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 = min((filestart-dirstart)+1, (int)SDL_arraysize(m_szDir));
236 SDL_strlcpy(m_szDir, dirstart, len);
237 len = 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;
253 SDL_WaitThread(thread, &ret_val);
255 m_State = FTP_STATE_CONNECTING;
262 if(m_ListenSock != INVALID_SOCKET)
264 shutdown(m_ListenSock,2);
265 closesocket(m_ListenSock);
267 if(m_DataSock != INVALID_SOCKET)
269 shutdown(m_DataSock,2);
270 closesocket(m_DataSock);
272 if(m_ControlSock != INVALID_SOCKET)
274 shutdown(m_ControlSock,2);
275 closesocket(m_ControlSock);
277 if(LOCALFILE != NULL)
283 //Returns a value to specify the status (ie. connecting/connected/transferring/done)
284 int CFtpGet::GetStatus()
289 unsigned int CFtpGet::GetBytesIn()
294 unsigned int CFtpGet::GetTotalBytes()
297 return m_iBytesTotal;
300 //This function does all the work -- connects on a blocking socket
301 //then sends the appropriate user and password commands
302 //and then the cwd command, the port command then get and finally the quit
303 void CFtpGet::WorkerThread()
305 ConnectControlSocket();
306 if(m_State != FTP_STATE_LOGGING_IN)
311 if(m_State != FTP_STATE_LOGGED_IN)
317 //We are all done now, and state has the current state.
323 unsigned int CFtpGet::GetFile()
325 //Start off by changing into the proper dir.
326 char szCommandString[200];
329 SDL_strlcpy(szCommandString, "TYPE I\r\n", SDL_arraysize(szCommandString));
330 rcode = SendFTPCommand(szCommandString);
333 m_State = FTP_STATE_UNKNOWN_ERROR;
340 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "CWD %s\r\n", m_szDir);
341 rcode = SendFTPCommand(szCommandString);
344 m_State = FTP_STATE_DIRECTORY_INVALID;
352 m_State = FTP_STATE_UNKNOWN_ERROR;
357 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "RETR %s\r\n", m_szFilename);
358 rcode = SendFTPCommand(szCommandString);
361 m_State = FTP_STATE_FILE_NOT_FOUND;
366 //Now we will try to determine the file size...
368 p = SDL_strchr(recv_buffer,'(');
372 s = SDL_strchr(p,' ');
374 m_iBytesTotal = atoi(p);
379 m_DataSock = accept(m_ListenSock, NULL,NULL);//(struct sockaddr *)&sockaddr,&iAddrLength);
380 // Close the listen socket
381 closesocket(m_ListenSock);
382 if (m_DataSock == INVALID_SOCKET)
384 // int iWinsockErr = WSAGetLastError();
385 m_State = FTP_STATE_SOCKET_ERROR;
392 m_State = FTP_STATE_FILE_RECEIVED;
396 unsigned int CFtpGet::IssuePort()
399 char szCommandString[200];
400 struct sockaddr_in listenaddr; // Socket address structure
402 int iLength; // Length of the address structure
406 uint nLocalPort; // Local port for listening
407 uint nReplyCode; // FTP server reply code
410 // Get the address for the hListenSocket
411 iLength = sizeof(listenaddr);
412 if (getsockname(m_ListenSock, (struct sockaddr*)&listenaddr, &iLength) == SOCKET_ERROR)
414 // int iWinsockErr = WSAGetLastError();
415 m_State = FTP_STATE_SOCKET_ERROR;
419 // Extract the local port from the hListenSocket
420 nLocalPort = listenaddr.sin_port;
422 // Now, reuse the socket address structure to
423 // get the IP address from the control socket.
424 if (getsockname(m_ControlSock, (struct sockaddr*)&listenaddr, &iLength) == SOCKET_ERROR)
426 // int iWinsockErr = WSAGetLastError();
427 m_State = FTP_STATE_SOCKET_ERROR;
431 // Format the PORT command with the correct numbers.
432 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "PORT %d,%d,%d,%d,%d,%d\r\n",
433 (listenaddr.sin_addr.s_addr >> 0) & 0xFF,
434 (listenaddr.sin_addr.s_addr >> 8) & 0xFF,
435 (listenaddr.sin_addr.s_addr >> 16) & 0xFF,
436 (listenaddr.sin_addr.s_addr >> 24) & 0xFF,
440 // Tell the server which port to use for data.
441 nReplyCode = SendFTPCommand(szCommandString);
442 if (nReplyCode != 200)
444 // int iWinsockErr = WSAGetLastError();
445 m_State = FTP_STATE_SOCKET_ERROR;
451 int CFtpGet::ConnectControlSocket()
455 struct sockaddr_in hostaddr;
456 he = gethostbyname(m_szHost);
459 m_State = FTP_STATE_HOST_NOT_FOUND;
465 se = getservbyname("ftp", NULL);
469 hostaddr.sin_port = htons(21);
473 hostaddr.sin_port = se->s_port;
475 hostaddr.sin_family = AF_INET;
476 hostaddr.sin_addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;
479 //Now we will connect to the host
480 if(connect(m_ControlSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr)))
482 // int iWinsockErr = WSAGetLastError();
483 m_State = FTP_STATE_CANT_CONNECT;
486 m_State = FTP_STATE_LOGGING_IN;
491 int CFtpGet::LoginHost()
493 char szLoginString[200];
496 SDL_snprintf(szLoginString, SDL_arraysize(szLoginString), "USER %s\r\n" ,m_szUserName);
497 rcode = SendFTPCommand(szLoginString);
500 m_State = FTP_STATE_LOGIN_ERROR;
503 SDL_snprintf(szLoginString, SDL_arraysize(szLoginString), "PASS %s\r\n" ,m_szPassword);
504 rcode = SendFTPCommand(szLoginString);
507 m_State = FTP_STATE_LOGIN_ERROR;
511 m_State = FTP_STATE_LOGGED_IN;
516 unsigned int CFtpGet::SendFTPCommand(char *command)
519 FlushControlChannel();
520 // Send the FTP command
521 if (SOCKET_ERROR ==(send(m_ControlSock,command,strlen(command), 0)))
523 // int iWinsockErr = WSAGetLastError();
524 // Return 999 to indicate an error has occurred
528 // Read the server's reply and return the reply code as an integer
529 return(ReadFTPServerReply());
534 unsigned int CFtpGet::ReadFTPServerReply()
540 unsigned int igotcrlf = 0;
541 memset(recv_buffer,0,1000);
545 iBytesRead = recv(m_ControlSock,chunk,1,0);
547 if (iBytesRead == SOCKET_ERROR)
549 // int iWinsockErr = WSAGetLastError();
550 // Return 999 to indicate an error has occurred
554 if((chunk[0]==0x0a) || (chunk[0]==0x0d))
556 if(recv_buffer[0]!=0)
563 SDL_strlcat(recv_buffer, chunk, SDL_arraysize(recv_buffer));
569 if(recv_buffer[3] == '-')
571 //Hack -- must be a MOTD
572 return ReadFTPServerReply();
574 if(recv_buffer[3] != ' ')
576 //We should have 3 numbers then a space
579 memcpy(szcode,recv_buffer,3);
581 rcode = atoi(szcode);
582 // Extract the reply code from the server reply and return as an integer
587 unsigned int CFtpGet::ReadDataChannel()
589 char sDataBuffer[4096]; // Data-storage buffer for the data channel
590 int nBytesRecv; // Bytes received from the data channel
591 m_State = FTP_STATE_RECEIVING;
598 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
600 m_iBytesIn += nBytesRecv;
603 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
604 //Write sDataBuffer, nBytesRecv
608 }while (nBytesRecv > 0);
610 // Close the file and check for error returns.
611 if (nBytesRecv == SOCKET_ERROR)
613 //Ok, we got a socket error -- xfer aborted?
614 m_State = FTP_STATE_RECV_FAILED;
620 m_State = FTP_STATE_FILE_RECEIVED;
626 void CFtpGet::FlushControlChannel()
629 struct timeval timeout;
636 FD_SET(m_ControlSock,&read_fds);
638 while(select(m_ControlSock+1,&read_fds,NULL,NULL,&timeout))
640 recv(m_ControlSock,flushbuff,1,0);