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.9 2002/06/17 06:33:09 relnev
19 * ryan's struct patch for gcc 2.95
21 * Revision 1.8 2002/06/09 04:41:21 relnev
22 * added copyright header
24 * Revision 1.7 2002/06/02 04:26:34 relnev
27 * Revision 1.6 2002/05/26 21:06:44 relnev
30 * Revision 1.5 2002/05/26 20:32:24 theoddone33
31 * Fix some minor stuff
33 * Revision 1.4 2002/05/26 20:20:53 relnev
38 * Revision 1.3 2002/05/26 19:55:20 relnev
39 * unix.h: winsock defines
41 * cftp.cpp: now compiles!
43 * Revision 1.2 2002/05/07 03:16:45 theoddone33
44 * The Great Newline Fix
46 * Revision 1.1.1.1 2002/05/03 03:28:09 root
50 * 3 5/04/99 7:34p Dave
51 * Fixed slow HTTP get problem.
53 * 2 4/20/99 6:39p Dave
54 * Almost done with artillery targeting. Added support for downloading
55 * images on the PXO screen.
57 * 1 4/20/99 4:37p Dave
68 #include <sys/types.h>
69 #include <sys/socket.h>
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
76 #include "unix.h" // unix.h
85 void FTPObjThread( void * obj )
87 ((CFtpGet *)obj)->WorkerThread();
90 void CFtpGet::AbortGet()
93 while(!m_Aborted) ; //Wait for the thread to end
97 CFtpGet::CFtpGet(char *URL,char *localfile,char *Username,char *Password)
99 SOCKADDR_IN listensockaddr;
100 m_State = FTP_STATE_STARTUP;
102 m_ListenSock = INVALID_SOCKET;
103 m_DataSock = INVALID_SOCKET;
104 m_ControlSock = INVALID_SOCKET;
110 LOCALFILE = fopen(localfile,"wb");
111 if(NULL == LOCALFILE)
113 m_State = FTP_STATE_CANT_WRITE_FILE;
119 strcpy(m_szUserName,Username);
123 strcpy(m_szUserName,"anonymous");
127 strcpy(m_szPassword,Password);
131 strcpy(m_szPassword,"pxouser@pxo.net");
133 m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
134 if(INVALID_SOCKET == m_ListenSock)
136 // vint iWinsockErr = WSAGetLastError();
137 m_State = FTP_STATE_SOCKET_ERROR;
142 listensockaddr.sin_family = AF_INET;
143 listensockaddr.sin_port = 0;
144 listensockaddr.sin_addr.s_addr = INADDR_ANY;
146 // Bind the listen socket
147 if (bind(m_ListenSock, (SOCKADDR *)&listensockaddr, sizeof(SOCKADDR)))
149 //Couldn't bind the socket
150 // int iWinsockErr = WSAGetLastError();
151 m_State = FTP_STATE_SOCKET_ERROR;
155 // Listen for the server connection
156 if (listen(m_ListenSock, 1))
158 //Couldn't listen on the socket
159 // int iWinsockErr = WSAGetLastError();
160 m_State = FTP_STATE_SOCKET_ERROR;
164 m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
165 if(INVALID_SOCKET == m_ControlSock)
167 m_State = FTP_STATE_SOCKET_ERROR;
171 //Get rid of any extra ftp:// stuff
173 if(_strnicmp(URL,"ftp:",4)==0)
181 //There shouldn't be any : in this string
184 m_State = FTP_STATE_URL_PARSING_ERROR;
187 //read the filename by searching backwards for a /
188 //then keep reading until you find the first /
189 //when you found it, you have the host and dir
190 char *filestart = NULL;
191 char *dirstart = NULL;
192 for(int i = strlen(pURL);i>=0;i--)
198 filestart = pURL+i+1;
200 strcpy(m_szFilename,filestart);
208 if((dirstart==NULL) || (filestart==NULL))
210 m_State = FTP_STATE_URL_PARSING_ERROR;
215 strncpy(m_szDir,dirstart,(filestart-dirstart));
216 m_szDir[(filestart-dirstart)] = 0;
217 strncpy(m_szHost,pURL,(dirstart-pURL));
218 m_szHost[(dirstart-pURL)-1] = 0;
220 //At this point we should have a nice host,dir and filename
222 //if(NULL==CreateThread(NULL,0,ObjThread,this,0,&m_dwThreadId))
223 if(NULL==_beginthread(FTPObjThread,0,this))
225 m_State = FTP_STATE_INTERNAL_ERROR;
228 m_State = FTP_STATE_CONNECTING;
235 if(m_ListenSock != INVALID_SOCKET)
237 shutdown(m_ListenSock,2);
238 closesocket(m_ListenSock);
240 if(m_DataSock != INVALID_SOCKET)
242 shutdown(m_DataSock,2);
243 closesocket(m_DataSock);
245 if(m_ControlSock != INVALID_SOCKET)
247 shutdown(m_ControlSock,2);
248 closesocket(m_ControlSock);
254 //Returns a value to specify the status (ie. connecting/connected/transferring/done)
255 int CFtpGet::GetStatus()
260 unsigned int CFtpGet::GetBytesIn()
265 unsigned int CFtpGet::GetTotalBytes()
268 return m_iBytesTotal;
271 //This function does all the work -- connects on a blocking socket
272 //then sends the appropriate user and password commands
273 //and then the cwd command, the port command then get and finally the quit
274 void CFtpGet::WorkerThread()
276 ConnectControlSocket();
277 if(m_State != FTP_STATE_LOGGING_IN)
282 if(m_State != FTP_STATE_LOGGED_IN)
288 //We are all done now, and state has the current state.
294 unsigned int CFtpGet::GetFile()
296 //Start off by changing into the proper dir.
297 char szCommandString[200];
300 sprintf(szCommandString,"TYPE I\r\n");
301 rcode = SendFTPCommand(szCommandString);
304 m_State = FTP_STATE_UNKNOWN_ERROR;
311 sprintf(szCommandString,"CWD %s\r\n",m_szDir);
312 rcode = SendFTPCommand(szCommandString);
315 m_State = FTP_STATE_DIRECTORY_INVALID;
323 m_State = FTP_STATE_UNKNOWN_ERROR;
328 sprintf(szCommandString,"RETR %s\r\n",m_szFilename);
329 rcode = SendFTPCommand(szCommandString);
332 m_State = FTP_STATE_FILE_NOT_FOUND;
337 //Now we will try to determine the file size...
339 p = strchr(recv_buffer,'(');
345 m_iBytesTotal = atoi(p);
350 m_DataSock = accept(m_ListenSock, NULL,NULL);//(SOCKADDR *)&sockaddr,&iAddrLength);
351 // Close the listen socket
352 closesocket(m_ListenSock);
353 if (m_DataSock == INVALID_SOCKET)
355 // int iWinsockErr = WSAGetLastError();
356 m_State = FTP_STATE_SOCKET_ERROR;
363 m_State = FTP_STATE_FILE_RECEIVED;
367 unsigned int CFtpGet::IssuePort()
370 char szCommandString[200];
371 SOCKADDR_IN listenaddr; // Socket address structure
373 int iLength; // Length of the address structure
377 UINT nLocalPort; // Local port for listening
378 UINT nReplyCode; // FTP server reply code
381 // Get the address for the hListenSocket
382 iLength = sizeof(listenaddr);
383 if (getsockname(m_ListenSock, (LPSOCKADDR)&listenaddr,&iLength) == SOCKET_ERROR)
385 // int iWinsockErr = WSAGetLastError();
386 m_State = FTP_STATE_SOCKET_ERROR;
390 // Extract the local port from the hListenSocket
391 nLocalPort = listenaddr.sin_port;
393 // Now, reuse the socket address structure to
394 // get the IP address from the control socket.
395 if (getsockname(m_ControlSock, (LPSOCKADDR)&listenaddr,&iLength) == SOCKET_ERROR)
397 // int iWinsockErr = WSAGetLastError();
398 m_State = FTP_STATE_SOCKET_ERROR;
402 // Format the PORT command with the correct numbers.
404 sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n",
405 listenaddr.sin_addr.S_un.S_un_b.s_b1,
406 listenaddr.sin_addr.S_un.S_un_b.s_b2,
407 listenaddr.sin_addr.S_un.S_un_b.s_b3,
408 listenaddr.sin_addr.S_un.S_un_b.s_b4,
412 sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n",
413 (listenaddr.sin_addr.s_addr >> 0) & 0xFF,
414 (listenaddr.sin_addr.s_addr >> 8) & 0xFF,
415 (listenaddr.sin_addr.s_addr >> 16) & 0xFF,
416 (listenaddr.sin_addr.s_addr >> 24) & 0xFF,
421 // Tell the server which port to use for data.
422 nReplyCode = SendFTPCommand(szCommandString);
423 if (nReplyCode != 200)
425 // int iWinsockErr = WSAGetLastError();
426 m_State = FTP_STATE_SOCKET_ERROR;
432 int CFtpGet::ConnectControlSocket()
436 SOCKADDR_IN hostaddr;
437 he = gethostbyname(m_szHost);
440 m_State = FTP_STATE_HOST_NOT_FOUND;
446 se = getservbyname("ftp", NULL);
450 hostaddr.sin_port = htons(21);
454 hostaddr.sin_port = se->s_port;
456 hostaddr.sin_family = AF_INET;
457 memcpy(&hostaddr.sin_addr,he->h_addr_list[0],4);
460 //Now we will connect to the host
461 if(connect(m_ControlSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR)))
463 // int iWinsockErr = WSAGetLastError();
464 m_State = FTP_STATE_CANT_CONNECT;
467 m_State = FTP_STATE_LOGGING_IN;
472 int CFtpGet::LoginHost()
474 char szLoginString[200];
477 sprintf(szLoginString,"USER %s\r\n",m_szUserName);
478 rcode = SendFTPCommand(szLoginString);
481 m_State = FTP_STATE_LOGIN_ERROR;
484 sprintf(szLoginString,"PASS %s\r\n",m_szPassword);
485 rcode = SendFTPCommand(szLoginString);
488 m_State = FTP_STATE_LOGIN_ERROR;
492 m_State = FTP_STATE_LOGGED_IN;
497 unsigned int CFtpGet::SendFTPCommand(char *command)
500 FlushControlChannel();
501 // Send the FTP command
502 if (SOCKET_ERROR ==(send(m_ControlSock,command,strlen(command), 0)))
504 // int iWinsockErr = WSAGetLastError();
505 // Return 999 to indicate an error has occurred
509 // Read the server's reply and return the reply code as an integer
510 return(ReadFTPServerReply());
515 unsigned int CFtpGet::ReadFTPServerReply()
521 unsigned int igotcrlf = 0;
522 memset(recv_buffer,0,1000);
526 iBytesRead = recv(m_ControlSock,chunk,1,0);
528 if (iBytesRead == SOCKET_ERROR)
530 // int iWinsockErr = WSAGetLastError();
531 // Return 999 to indicate an error has occurred
535 if((chunk[0]==0x0a) || (chunk[0]==0x0d))
537 if(recv_buffer[0]!=0)
544 strcat(recv_buffer,chunk);
550 if(recv_buffer[3] == '-')
552 //Hack -- must be a MOTD
553 return ReadFTPServerReply();
555 if(recv_buffer[3] != ' ')
557 //We should have 3 numbers then a space
560 memcpy(szcode,recv_buffer,3);
562 rcode = atoi(szcode);
563 // Extract the reply code from the server reply and return as an integer
568 unsigned int CFtpGet::ReadDataChannel()
570 char sDataBuffer[4096]; // Data-storage buffer for the data channel
571 int nBytesRecv; // Bytes received from the data channel
572 m_State = FTP_STATE_RECEIVING;
579 nBytesRecv = recv(m_DataSock, (LPSTR)&sDataBuffer,sizeof(sDataBuffer), 0);
581 m_iBytesIn += nBytesRecv;
584 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
585 //Write sDataBuffer, nBytesRecv
589 }while (nBytesRecv > 0);
591 // Close the file and check for error returns.
592 if (nBytesRecv == SOCKET_ERROR)
594 //Ok, we got a socket error -- xfer aborted?
595 m_State = FTP_STATE_RECV_FAILED;
601 m_State = FTP_STATE_FILE_RECEIVED;
607 void CFtpGet::FlushControlChannel()
617 FD_SET(m_ControlSock,&read_fds);
619 while(select(0,&read_fds,NULL,NULL,&timeout))
621 recv(m_ControlSock,flushbuff,1,0);