2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/Inetfile/CFtp.cpp $
15 * FTP Client class (get only)
18 * Revision 1.11 2002/06/21 03:04:12 relnev
21 * Revision 1.10 2002/06/19 04:52:45 relnev
22 * MacOS X updates (Ryan)
24 * Revision 1.9 2002/06/17 06:33:09 relnev
25 * ryan's struct patch for gcc 2.95
27 * Revision 1.8 2002/06/09 04:41:21 relnev
28 * added copyright header
30 * Revision 1.7 2002/06/02 04:26:34 relnev
33 * Revision 1.6 2002/05/26 21:06:44 relnev
36 * Revision 1.5 2002/05/26 20:32:24 theoddone33
37 * Fix some minor stuff
39 * Revision 1.4 2002/05/26 20:20:53 relnev
44 * Revision 1.3 2002/05/26 19:55:20 relnev
45 * unix.h: winsock defines
47 * cftp.cpp: now compiles!
49 * Revision 1.2 2002/05/07 03:16:45 theoddone33
50 * The Great Newline Fix
52 * Revision 1.1.1.1 2002/05/03 03:28:09 root
56 * 3 5/04/99 7:34p Dave
57 * Fixed slow HTTP get problem.
59 * 2 4/20/99 6:39p Dave
60 * Almost done with artillery targeting. Added support for downloading
61 * images on the PXO screen.
63 * 1 4/20/99 4:37p Dave
74 #include <sys/types.h>
75 #include <sys/socket.h>
76 #include <netinet/in.h>
77 #include <arpa/inet.h>
91 int FTPObjThread( void * obj )
93 ((CFtpGet *)obj)->WorkerThread();
95 return ((CFtpGet *)obj)->GetStatus();
98 void CFtpGet::AbortGet()
101 while(!m_Aborted) SDL_Delay(10); //Wait for the thread to end
103 if(LOCALFILE != NULL)
110 CFtpGet::CFtpGet(char *URL,char *localfile,char *Username,char *Password)
112 struct sockaddr_in listensockaddr;
113 m_State = FTP_STATE_STARTUP;
115 m_ListenSock = INVALID_SOCKET;
116 m_DataSock = INVALID_SOCKET;
117 m_ControlSock = INVALID_SOCKET;
123 LOCALFILE = fopen(localfile,"wb");
124 if(NULL == LOCALFILE)
126 m_State = FTP_STATE_CANT_WRITE_FILE;
133 SDL_strlcpy(m_szUserName, Username, SDL_arraysize(m_szUserName));
137 SDL_strlcpy(m_szUserName, "anonymous", SDL_arraysize(m_szUserName));
141 SDL_strlcpy(m_szPassword, Password, SDL_arraysize(m_szPassword));
145 SDL_strlcpy(m_szPassword, "pxouser@pxo.net", SDL_arraysize(m_szPassword));
147 m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
148 if(INVALID_SOCKET == m_ListenSock)
150 // vint iWinsockErr = WSAGetLastError();
151 m_State = FTP_STATE_SOCKET_ERROR;
157 listensockaddr.sin_family = AF_INET;
158 listensockaddr.sin_port = 0;
159 listensockaddr.sin_addr.s_addr = INADDR_ANY;
161 // Bind the listen socket
162 if (bind(m_ListenSock, (struct sockaddr *)&listensockaddr, sizeof(struct sockaddr)))
164 //Couldn't bind the socket
165 // int iWinsockErr = WSAGetLastError();
166 m_State = FTP_STATE_SOCKET_ERROR;
171 // Listen for the server connection
172 if (listen(m_ListenSock, 1))
174 //Couldn't listen on the socket
175 // int iWinsockErr = WSAGetLastError();
176 m_State = FTP_STATE_SOCKET_ERROR;
181 m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
182 if(INVALID_SOCKET == m_ControlSock)
184 m_State = FTP_STATE_SOCKET_ERROR;
189 //Get rid of any extra ftp:// stuff
191 if(SDL_strncasecmp(URL,"ftp:",4)==0)
199 //There shouldn't be any : in this string
200 if(SDL_strchr(pURL,':'))
202 m_State = FTP_STATE_URL_PARSING_ERROR;
206 //read the filename by searching backwards for a /
207 //then keep reading until you find the first /
208 //when you found it, you have the host and dir
209 char *filestart = NULL;
210 char *dirstart = NULL;
211 for(int i = strlen(pURL);i>=0;i--)
217 filestart = pURL+i+1;
219 SDL_strlcpy(m_szFilename, filestart, SDL_arraysize(m_szFilename));
227 if((dirstart==NULL) || (filestart==NULL))
229 m_State = FTP_STATE_URL_PARSING_ERROR;
235 int len = SDL_min((filestart-dirstart)+1, (int)SDL_arraysize(m_szDir));
236 SDL_strlcpy(m_szDir, dirstart, len);
237 len = SDL_min((dirstart-pURL), (int)SDL_arraysize(m_szHost));
238 SDL_strlcpy(m_szHost, pURL, len);
240 //At this point we should have a nice host,dir and filename
242 SDL_Thread *thread = SDL_CreateThread(FTPObjThread, "FTPObjThread", this);
246 m_State = FTP_STATE_INTERNAL_ERROR;
252 SDL_DetachThread(thread);
254 m_State = FTP_STATE_CONNECTING;
261 if(m_ListenSock != INVALID_SOCKET)
263 shutdown(m_ListenSock,2);
264 closesocket(m_ListenSock);
266 if(m_DataSock != INVALID_SOCKET)
268 shutdown(m_DataSock,2);
269 closesocket(m_DataSock);
271 if(m_ControlSock != INVALID_SOCKET)
273 shutdown(m_ControlSock,2);
274 closesocket(m_ControlSock);
276 if(LOCALFILE != NULL)
282 //Returns a value to specify the status (ie. connecting/connected/transferring/done)
283 int CFtpGet::GetStatus()
288 unsigned int CFtpGet::GetBytesIn()
293 unsigned int CFtpGet::GetTotalBytes()
296 return m_iBytesTotal;
299 //This function does all the work -- connects on a blocking socket
300 //then sends the appropriate user and password commands
301 //and then the cwd command, the port command then get and finally the quit
302 void CFtpGet::WorkerThread()
304 ConnectControlSocket();
305 if(m_State != FTP_STATE_LOGGING_IN)
310 if(m_State != FTP_STATE_LOGGED_IN)
316 //We are all done now, and state has the current state.
322 unsigned int CFtpGet::GetFile()
324 //Start off by changing into the proper dir.
325 char szCommandString[200];
328 SDL_strlcpy(szCommandString, "TYPE I\r\n", SDL_arraysize(szCommandString));
329 rcode = SendFTPCommand(szCommandString);
332 m_State = FTP_STATE_UNKNOWN_ERROR;
339 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "CWD %s\r\n", m_szDir);
340 rcode = SendFTPCommand(szCommandString);
343 m_State = FTP_STATE_DIRECTORY_INVALID;
351 m_State = FTP_STATE_UNKNOWN_ERROR;
356 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "RETR %s\r\n", m_szFilename);
357 rcode = SendFTPCommand(szCommandString);
360 m_State = FTP_STATE_FILE_NOT_FOUND;
365 //Now we will try to determine the file size...
367 p = SDL_strchr(recv_buffer,'(');
371 s = SDL_strchr(p,' ');
373 m_iBytesTotal = atoi(p);
378 m_DataSock = accept(m_ListenSock, NULL,NULL);//(struct sockaddr *)&sockaddr,&iAddrLength);
379 // Close the listen socket
380 closesocket(m_ListenSock);
381 if (m_DataSock == INVALID_SOCKET)
383 // int iWinsockErr = WSAGetLastError();
384 m_State = FTP_STATE_SOCKET_ERROR;
391 m_State = FTP_STATE_FILE_RECEIVED;
395 unsigned int CFtpGet::IssuePort()
398 char szCommandString[200];
399 struct sockaddr_in listenaddr; // Socket address structure
400 SOCKLEN_T iLength; // Length of the address structure
401 uint nLocalPort; // Local port for listening
402 uint nReplyCode; // FTP server reply code
405 // Get the address for the hListenSocket
406 iLength = sizeof(listenaddr);
407 if (getsockname(m_ListenSock, (struct sockaddr*)&listenaddr, &iLength) == SOCKET_ERROR)
409 // int iWinsockErr = WSAGetLastError();
410 m_State = FTP_STATE_SOCKET_ERROR;
414 // Extract the local port from the hListenSocket
415 nLocalPort = listenaddr.sin_port;
417 // Now, reuse the socket address structure to
418 // get the IP address from the control socket.
419 if (getsockname(m_ControlSock, (struct sockaddr*)&listenaddr, &iLength) == SOCKET_ERROR)
421 // int iWinsockErr = WSAGetLastError();
422 m_State = FTP_STATE_SOCKET_ERROR;
426 // Format the PORT command with the correct numbers.
427 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "PORT %d,%d,%d,%d,%d,%d\r\n",
428 (listenaddr.sin_addr.s_addr >> 0) & 0xFF,
429 (listenaddr.sin_addr.s_addr >> 8) & 0xFF,
430 (listenaddr.sin_addr.s_addr >> 16) & 0xFF,
431 (listenaddr.sin_addr.s_addr >> 24) & 0xFF,
435 // Tell the server which port to use for data.
436 nReplyCode = SendFTPCommand(szCommandString);
437 if (nReplyCode != 200)
439 // int iWinsockErr = WSAGetLastError();
440 m_State = FTP_STATE_SOCKET_ERROR;
446 int CFtpGet::ConnectControlSocket()
450 struct sockaddr_in hostaddr;
451 he = gethostbyname(m_szHost);
454 m_State = FTP_STATE_HOST_NOT_FOUND;
460 se = getservbyname("ftp", NULL);
464 hostaddr.sin_port = htons(21);
468 hostaddr.sin_port = se->s_port;
470 hostaddr.sin_family = AF_INET;
471 hostaddr.sin_addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;
474 //Now we will connect to the host
475 if(connect(m_ControlSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr)))
477 // int iWinsockErr = WSAGetLastError();
478 m_State = FTP_STATE_CANT_CONNECT;
481 m_State = FTP_STATE_LOGGING_IN;
486 int CFtpGet::LoginHost()
488 char szLoginString[200];
491 SDL_snprintf(szLoginString, SDL_arraysize(szLoginString), "USER %s\r\n" ,m_szUserName);
492 rcode = SendFTPCommand(szLoginString);
495 m_State = FTP_STATE_LOGIN_ERROR;
498 SDL_snprintf(szLoginString, SDL_arraysize(szLoginString), "PASS %s\r\n" ,m_szPassword);
499 rcode = SendFTPCommand(szLoginString);
502 m_State = FTP_STATE_LOGIN_ERROR;
506 m_State = FTP_STATE_LOGGED_IN;
511 unsigned int CFtpGet::SendFTPCommand(char *command)
514 FlushControlChannel();
515 // Send the FTP command
516 if (SOCKET_ERROR ==(send(m_ControlSock,command,strlen(command), 0)))
518 // int iWinsockErr = WSAGetLastError();
519 // Return 999 to indicate an error has occurred
523 // Read the server's reply and return the reply code as an integer
524 return(ReadFTPServerReply());
529 unsigned int CFtpGet::ReadFTPServerReply()
535 unsigned int igotcrlf = 0;
536 memset(recv_buffer,0,1000);
540 iBytesRead = recv(m_ControlSock,chunk,1,0);
542 if (iBytesRead == SOCKET_ERROR)
544 // int iWinsockErr = WSAGetLastError();
545 // Return 999 to indicate an error has occurred
549 if((chunk[0]==0x0a) || (chunk[0]==0x0d))
551 if(recv_buffer[0]!=0)
558 SDL_strlcat(recv_buffer, chunk, SDL_arraysize(recv_buffer));
564 if(recv_buffer[3] == '-')
566 //Hack -- must be a MOTD
567 return ReadFTPServerReply();
569 if(recv_buffer[3] != ' ')
571 //We should have 3 numbers then a space
574 memcpy(szcode,recv_buffer,3);
576 rcode = atoi(szcode);
577 // Extract the reply code from the server reply and return as an integer
582 unsigned int CFtpGet::ReadDataChannel()
584 char sDataBuffer[4096]; // Data-storage buffer for the data channel
585 int nBytesRecv; // Bytes received from the data channel
586 m_State = FTP_STATE_RECEIVING;
593 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
595 m_iBytesIn += nBytesRecv;
598 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
599 //Write sDataBuffer, nBytesRecv
603 }while (nBytesRecv > 0);
605 // Close the file and check for error returns.
606 if (nBytesRecv == SOCKET_ERROR)
608 //Ok, we got a socket error -- xfer aborted?
609 m_State = FTP_STATE_RECV_FAILED;
615 m_State = FTP_STATE_FILE_RECEIVED;
621 void CFtpGet::FlushControlChannel()
624 struct timeval timeout;
631 FD_SET(m_ControlSock,&read_fds);
633 while(select(m_ControlSock+1,&read_fds,NULL,NULL,&timeout))
635 recv(m_ControlSock,flushbuff,1,0);