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.8 2002/06/09 04:41:21 relnev
19 * added copyright header
21 * Revision 1.7 2002/06/02 04:26:34 relnev
24 * Revision 1.6 2002/05/26 21:06:44 relnev
27 * Revision 1.5 2002/05/26 20:32:24 theoddone33
28 * Fix some minor stuff
30 * Revision 1.4 2002/05/26 20:20:53 relnev
35 * Revision 1.3 2002/05/26 19:55:20 relnev
36 * unix.h: winsock defines
38 * cftp.cpp: now compiles!
40 * Revision 1.2 2002/05/07 03:16:45 theoddone33
41 * The Great Newline Fix
43 * Revision 1.1.1.1 2002/05/03 03:28:09 root
47 * 3 5/04/99 7:34p Dave
48 * Fixed slow HTTP get problem.
50 * 2 4/20/99 6:39p Dave
51 * Almost done with artillery targeting. Added support for downloading
52 * images on the PXO screen.
54 * 1 4/20/99 4:37p Dave
65 #include <sys/types.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
71 #include "unix.h" // unix.h
80 void FTPObjThread( void * obj )
82 ((CFtpGet *)obj)->WorkerThread();
85 void CFtpGet::AbortGet()
88 while(!m_Aborted) ; //Wait for the thread to end
92 CFtpGet::CFtpGet(char *URL,char *localfile,char *Username,char *Password)
94 SOCKADDR_IN listensockaddr;
95 m_State = FTP_STATE_STARTUP;
97 m_ListenSock = INVALID_SOCKET;
98 m_DataSock = INVALID_SOCKET;
99 m_ControlSock = INVALID_SOCKET;
105 LOCALFILE = fopen(localfile,"wb");
106 if(NULL == LOCALFILE)
108 m_State = FTP_STATE_CANT_WRITE_FILE;
114 strcpy(m_szUserName,Username);
118 strcpy(m_szUserName,"anonymous");
122 strcpy(m_szPassword,Password);
126 strcpy(m_szPassword,"pxouser@pxo.net");
128 m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
129 if(INVALID_SOCKET == m_ListenSock)
131 // vint iWinsockErr = WSAGetLastError();
132 m_State = FTP_STATE_SOCKET_ERROR;
137 listensockaddr.sin_family = AF_INET;
138 listensockaddr.sin_port = 0;
139 listensockaddr.sin_addr.s_addr = INADDR_ANY;
141 // Bind the listen socket
142 if (bind(m_ListenSock, (SOCKADDR *)&listensockaddr, sizeof(SOCKADDR)))
144 //Couldn't bind the socket
145 // int iWinsockErr = WSAGetLastError();
146 m_State = FTP_STATE_SOCKET_ERROR;
150 // Listen for the server connection
151 if (listen(m_ListenSock, 1))
153 //Couldn't listen on the socket
154 // int iWinsockErr = WSAGetLastError();
155 m_State = FTP_STATE_SOCKET_ERROR;
159 m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
160 if(INVALID_SOCKET == m_ControlSock)
162 m_State = FTP_STATE_SOCKET_ERROR;
166 //Get rid of any extra ftp:// stuff
168 if(_strnicmp(URL,"ftp:",4)==0)
176 //There shouldn't be any : in this string
179 m_State = FTP_STATE_URL_PARSING_ERROR;
182 //read the filename by searching backwards for a /
183 //then keep reading until you find the first /
184 //when you found it, you have the host and dir
185 char *filestart = NULL;
186 char *dirstart = NULL;
187 for(int i = strlen(pURL);i>=0;i--)
193 filestart = pURL+i+1;
195 strcpy(m_szFilename,filestart);
203 if((dirstart==NULL) || (filestart==NULL))
205 m_State = FTP_STATE_URL_PARSING_ERROR;
210 strncpy(m_szDir,dirstart,(filestart-dirstart));
211 m_szDir[(filestart-dirstart)] = 0;
212 strncpy(m_szHost,pURL,(dirstart-pURL));
213 m_szHost[(dirstart-pURL)-1] = 0;
215 //At this point we should have a nice host,dir and filename
217 //if(NULL==CreateThread(NULL,0,ObjThread,this,0,&m_dwThreadId))
218 if(NULL==_beginthread(FTPObjThread,0,this))
220 m_State = FTP_STATE_INTERNAL_ERROR;
223 m_State = FTP_STATE_CONNECTING;
230 if(m_ListenSock != INVALID_SOCKET)
232 shutdown(m_ListenSock,2);
233 closesocket(m_ListenSock);
235 if(m_DataSock != INVALID_SOCKET)
237 shutdown(m_DataSock,2);
238 closesocket(m_DataSock);
240 if(m_ControlSock != INVALID_SOCKET)
242 shutdown(m_ControlSock,2);
243 closesocket(m_ControlSock);
249 //Returns a value to specify the status (ie. connecting/connected/transferring/done)
250 int CFtpGet::GetStatus()
255 unsigned int CFtpGet::GetBytesIn()
260 unsigned int CFtpGet::GetTotalBytes()
263 return m_iBytesTotal;
266 //This function does all the work -- connects on a blocking socket
267 //then sends the appropriate user and password commands
268 //and then the cwd command, the port command then get and finally the quit
269 void CFtpGet::WorkerThread()
271 ConnectControlSocket();
272 if(m_State != FTP_STATE_LOGGING_IN)
277 if(m_State != FTP_STATE_LOGGED_IN)
283 //We are all done now, and state has the current state.
289 unsigned int CFtpGet::GetFile()
291 //Start off by changing into the proper dir.
292 char szCommandString[200];
295 sprintf(szCommandString,"TYPE I\r\n");
296 rcode = SendFTPCommand(szCommandString);
299 m_State = FTP_STATE_UNKNOWN_ERROR;
306 sprintf(szCommandString,"CWD %s\r\n",m_szDir);
307 rcode = SendFTPCommand(szCommandString);
310 m_State = FTP_STATE_DIRECTORY_INVALID;
318 m_State = FTP_STATE_UNKNOWN_ERROR;
323 sprintf(szCommandString,"RETR %s\r\n",m_szFilename);
324 rcode = SendFTPCommand(szCommandString);
327 m_State = FTP_STATE_FILE_NOT_FOUND;
332 //Now we will try to determine the file size...
334 p = strchr(recv_buffer,'(');
340 m_iBytesTotal = atoi(p);
345 m_DataSock = accept(m_ListenSock, NULL,NULL);//(SOCKADDR *)&sockaddr,&iAddrLength);
346 // Close the listen socket
347 closesocket(m_ListenSock);
348 if (m_DataSock == INVALID_SOCKET)
350 // int iWinsockErr = WSAGetLastError();
351 m_State = FTP_STATE_SOCKET_ERROR;
358 m_State = FTP_STATE_FILE_RECEIVED;
362 unsigned int CFtpGet::IssuePort()
365 char szCommandString[200];
366 SOCKADDR_IN listenaddr; // Socket address structure
368 int iLength; // Length of the address structure
372 UINT nLocalPort; // Local port for listening
373 UINT nReplyCode; // FTP server reply code
376 // Get the address for the hListenSocket
377 iLength = sizeof(listenaddr);
378 if (getsockname(m_ListenSock, (LPSOCKADDR)&listenaddr,&iLength) == SOCKET_ERROR)
380 // int iWinsockErr = WSAGetLastError();
381 m_State = FTP_STATE_SOCKET_ERROR;
385 // Extract the local port from the hListenSocket
386 nLocalPort = listenaddr.sin_port;
388 // Now, reuse the socket address structure to
389 // get the IP address from the control socket.
390 if (getsockname(m_ControlSock, (LPSOCKADDR)&listenaddr,&iLength) == SOCKET_ERROR)
392 // int iWinsockErr = WSAGetLastError();
393 m_State = FTP_STATE_SOCKET_ERROR;
397 // Format the PORT command with the correct numbers.
399 sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n",
400 listenaddr.sin_addr.S_un.S_un_b.s_b1,
401 listenaddr.sin_addr.S_un.S_un_b.s_b2,
402 listenaddr.sin_addr.S_un.S_un_b.s_b3,
403 listenaddr.sin_addr.S_un.S_un_b.s_b4,
407 sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n",
408 (listenaddr.sin_addr.s_addr >> 0) & 0xFF,
409 (listenaddr.sin_addr.s_addr >> 8) & 0xFF,
410 (listenaddr.sin_addr.s_addr >> 16) & 0xFF,
411 (listenaddr.sin_addr.s_addr >> 24) & 0xFF,
416 // Tell the server which port to use for data.
417 nReplyCode = SendFTPCommand(szCommandString);
418 if (nReplyCode != 200)
420 // int iWinsockErr = WSAGetLastError();
421 m_State = FTP_STATE_SOCKET_ERROR;
427 int CFtpGet::ConnectControlSocket()
431 SOCKADDR_IN hostaddr;
432 he = gethostbyname(m_szHost);
435 m_State = FTP_STATE_HOST_NOT_FOUND;
441 se = getservbyname("ftp", NULL);
445 hostaddr.sin_port = htons(21);
449 hostaddr.sin_port = se->s_port;
451 hostaddr.sin_family = AF_INET;
452 memcpy(&hostaddr.sin_addr,he->h_addr_list[0],4);
455 //Now we will connect to the host
456 if(connect(m_ControlSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR)))
458 // int iWinsockErr = WSAGetLastError();
459 m_State = FTP_STATE_CANT_CONNECT;
462 m_State = FTP_STATE_LOGGING_IN;
467 int CFtpGet::LoginHost()
469 char szLoginString[200];
472 sprintf(szLoginString,"USER %s\r\n",m_szUserName);
473 rcode = SendFTPCommand(szLoginString);
476 m_State = FTP_STATE_LOGIN_ERROR;
479 sprintf(szLoginString,"PASS %s\r\n",m_szPassword);
480 rcode = SendFTPCommand(szLoginString);
483 m_State = FTP_STATE_LOGIN_ERROR;
487 m_State = FTP_STATE_LOGGED_IN;
492 unsigned int CFtpGet::SendFTPCommand(char *command)
495 FlushControlChannel();
496 // Send the FTP command
497 if (SOCKET_ERROR ==(send(m_ControlSock,command,strlen(command), 0)))
499 // int iWinsockErr = WSAGetLastError();
500 // Return 999 to indicate an error has occurred
504 // Read the server's reply and return the reply code as an integer
505 return(ReadFTPServerReply());
510 unsigned int CFtpGet::ReadFTPServerReply()
516 unsigned int igotcrlf = 0;
517 memset(recv_buffer,0,1000);
521 iBytesRead = recv(m_ControlSock,chunk,1,0);
523 if (iBytesRead == SOCKET_ERROR)
525 // int iWinsockErr = WSAGetLastError();
526 // Return 999 to indicate an error has occurred
530 if((chunk[0]==0x0a) || (chunk[0]==0x0d))
532 if(recv_buffer[0]!=0)
539 strcat(recv_buffer,chunk);
545 if(recv_buffer[3] == '-')
547 //Hack -- must be a MOTD
548 return ReadFTPServerReply();
550 if(recv_buffer[3] != ' ')
552 //We should have 3 numbers then a space
555 memcpy(szcode,recv_buffer,3);
557 rcode = atoi(szcode);
558 // Extract the reply code from the server reply and return as an integer
563 unsigned int CFtpGet::ReadDataChannel()
565 char sDataBuffer[4096]; // Data-storage buffer for the data channel
566 int nBytesRecv; // Bytes received from the data channel
567 m_State = FTP_STATE_RECEIVING;
574 nBytesRecv = recv(m_DataSock, (LPSTR)&sDataBuffer,sizeof(sDataBuffer), 0);
576 m_iBytesIn += nBytesRecv;
579 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
580 //Write sDataBuffer, nBytesRecv
584 }while (nBytesRecv > 0);
586 // Close the file and check for error returns.
587 if (nBytesRecv == SOCKET_ERROR)
589 //Ok, we got a socket error -- xfer aborted?
590 m_State = FTP_STATE_RECV_FAILED;
596 m_State = FTP_STATE_FILE_RECEIVED;
602 void CFtpGet::FlushControlChannel()
612 FD_SET(m_ControlSock,&read_fds);
614 while(select(0,&read_fds,NULL,NULL,&timeout))
616 recv(m_ControlSock,flushbuff,1,0);