]> icculus.org git repositories - taylor/freespace2.git/blob - src/inetfile/cftp.cpp
use a better multi_sw_ok_to_commit() check
[taylor/freespace2.git] / src / inetfile / cftp.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
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
6  * the source.
7  */
8
9  /*
10  * $Logfile: /Freespace2/code/Inetfile/CFtp.cpp $
11  * $Revision$
12  * $Date$
13  *  $Author$
14  *
15  * FTP Client class (get only)
16  *
17  * $Log$
18  * Revision 1.11  2002/06/21 03:04:12  relnev
19  * nothing important
20  *
21  * Revision 1.10  2002/06/19 04:52:45  relnev
22  * MacOS X updates (Ryan)
23  *
24  * Revision 1.9  2002/06/17 06:33:09  relnev
25  * ryan's struct patch for gcc 2.95
26  *
27  * Revision 1.8  2002/06/09 04:41:21  relnev
28  * added copyright header
29  *
30  * Revision 1.7  2002/06/02 04:26:34  relnev
31  * warning cleanup
32  *
33  * Revision 1.6  2002/05/26 21:06:44  relnev
34  * oops
35  *
36  * Revision 1.5  2002/05/26 20:32:24  theoddone33
37  * Fix some minor stuff
38  *
39  * Revision 1.4  2002/05/26 20:20:53  relnev
40  * unix.h: updated
41  *
42  * inetfile/: complete
43  *
44  * Revision 1.3  2002/05/26 19:55:20  relnev
45  * unix.h: winsock defines
46  *
47  * cftp.cpp: now compiles!
48  *
49  * Revision 1.2  2002/05/07 03:16:45  theoddone33
50  * The Great Newline Fix
51  *
52  * Revision 1.1.1.1  2002/05/03 03:28:09  root
53  * Initial import.
54  *
55  * 
56  * 3     5/04/99 7:34p Dave
57  * Fixed slow HTTP get problem.
58  * 
59  * 2     4/20/99 6:39p Dave
60  * Almost done with artillery targeting. Added support for downloading
61  * images on the PXO screen.
62  * 
63  * 1     4/20/99 4:37p Dave
64  * 
65  * Initial version
66  *
67  * $NoKeywords: $
68  */
69
70
71 #ifndef PLAT_UNIX
72 #include <winsock2.h>
73 #else
74 #include <sys/types.h>
75 #include <sys/socket.h>
76 #include <netinet/in.h>
77 #include <arpa/inet.h>
78 #include <netdb.h>
79 #include <sys/time.h>
80 #include <unistd.h>
81 #endif
82
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86
87 #include "pstypes.h"
88 #include "cftp.h"
89
90
91 int FTPObjThread( void * obj )
92 {
93         ((CFtpGet *)obj)->WorkerThread();
94
95         return ((CFtpGet *)obj)->GetStatus();
96 }
97
98 void CFtpGet::AbortGet()
99 {
100         m_Aborting = true;
101         while(!m_Aborted) SDL_Delay(10); //Wait for the thread to end
102
103         if(LOCALFILE != NULL)
104         {
105                 fclose(LOCALFILE);
106                 LOCALFILE = NULL;
107         }
108 }
109
110 CFtpGet::CFtpGet(char *URL,char *localfile,char *Username,char *Password)
111 {
112         struct sockaddr_in listensockaddr;
113         m_State = FTP_STATE_STARTUP;
114
115         m_ListenSock = INVALID_SOCKET;
116         m_DataSock = INVALID_SOCKET;
117         m_ControlSock = INVALID_SOCKET;
118         m_iBytesIn = 0;
119         m_iBytesTotal = 0;
120         m_Aborting = false;
121         m_Aborted = false;
122
123         LOCALFILE = fopen(localfile,"wb");
124         if(NULL == LOCALFILE)
125         {
126                 m_State = FTP_STATE_CANT_WRITE_FILE;
127                 m_Aborted = true;
128                 return;
129         }
130
131         if(Username)
132         {
133                 SDL_strlcpy(m_szUserName, Username, SDL_arraysize(m_szUserName));
134         }
135         else
136         {
137                 SDL_strlcpy(m_szUserName, "anonymous", SDL_arraysize(m_szUserName));
138         }
139         if(Password)
140         {
141                 SDL_strlcpy(m_szPassword, Password, SDL_arraysize(m_szPassword));
142         }
143         else
144         {
145                 SDL_strlcpy(m_szPassword, "pxouser@pxo.net", SDL_arraysize(m_szPassword));
146         }
147         m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
148         if(INVALID_SOCKET == m_ListenSock)
149         {
150                 // vint iWinsockErr = WSAGetLastError();
151                 m_State = FTP_STATE_SOCKET_ERROR;
152                 m_Aborted = true;
153                 return;
154         }
155         else
156         {
157                 listensockaddr.sin_family = AF_INET;            
158                 listensockaddr.sin_port = 0;
159                 listensockaddr.sin_addr.s_addr = INADDR_ANY;
160                                                         
161                 // Bind the listen socket
162                 if (bind(m_ListenSock, (struct sockaddr *)&listensockaddr, sizeof(struct sockaddr)))
163                 {
164                         //Couldn't bind the socket
165                         // int iWinsockErr = WSAGetLastError();
166                         m_State = FTP_STATE_SOCKET_ERROR;
167                         m_Aborted = true;
168                         return;
169                 }
170
171                 // Listen for the server connection
172                 if (listen(m_ListenSock, 1))    
173                 {
174                         //Couldn't listen on the socket
175                         // int iWinsockErr = WSAGetLastError();
176                         m_State = FTP_STATE_SOCKET_ERROR;
177                         m_Aborted = true;
178                         return;
179                 }
180         }
181         m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
182         if(INVALID_SOCKET == m_ControlSock)
183         {
184                 m_State = FTP_STATE_SOCKET_ERROR;
185                 m_Aborted = true;
186                 return;
187         }
188         //Parse the URL
189         //Get rid of any extra ftp:// stuff
190         char *pURL = URL;
191         if(SDL_strncasecmp(URL,"ftp:",4)==0)
192         {
193                 pURL +=4;
194                 while(*pURL == '/')
195                 {
196                         pURL++;
197                 }
198         }
199         //There shouldn't be any : in this string
200         if(SDL_strchr(pURL,':'))
201         {
202                 m_State = FTP_STATE_URL_PARSING_ERROR;
203                 m_Aborted = true;
204                 return;
205         }
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--)
212         {
213                 if(pURL[i]== '/')
214                 {
215                         if(!filestart)
216                         {
217                                 filestart = pURL+i+1;
218                                 dirstart = pURL+i+1;
219                                 SDL_strlcpy(m_szFilename, filestart, SDL_arraysize(m_szFilename));
220                         }
221                         else
222                         {
223                                 dirstart = pURL+i+1;
224                         }
225                 }
226         }
227         if((dirstart==NULL) || (filestart==NULL))
228         {
229                 m_State = FTP_STATE_URL_PARSING_ERROR;
230                 m_Aborted = true;
231                 return;
232         }
233         else
234         {
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);
239         }
240         //At this point we should have a nice host,dir and filename
241
242         SDL_Thread *thread = SDL_CreateThread(FTPObjThread, "FTPObjThread", this);
243
244         if(thread == NULL)
245         {
246                 m_State = FTP_STATE_INTERNAL_ERROR;
247                 m_Aborted = true;
248                 return;
249         }
250         else
251         {
252                 SDL_DetachThread(thread);
253         }
254         m_State = FTP_STATE_CONNECTING;
255 }
256
257
258
259 CFtpGet::~CFtpGet()
260 {
261         if(m_ListenSock != INVALID_SOCKET)
262         {
263                 shutdown(m_ListenSock,2);
264                 closesocket(m_ListenSock);
265         }
266         if(m_DataSock != INVALID_SOCKET)
267         {
268                 shutdown(m_DataSock,2);
269                 closesocket(m_DataSock);
270         }
271         if(m_ControlSock != INVALID_SOCKET)
272         {
273                 shutdown(m_ControlSock,2);
274                 closesocket(m_ControlSock);
275         }
276         if(LOCALFILE != NULL)
277         {
278                 fclose(LOCALFILE);
279         }
280 }
281
282 //Returns a value to specify the status (ie. connecting/connected/transferring/done)
283 int CFtpGet::GetStatus()
284 {
285         return m_State;
286 }
287
288 unsigned int CFtpGet::GetBytesIn()
289 {
290         return m_iBytesIn;
291 }
292
293 unsigned int CFtpGet::GetTotalBytes()
294 {
295
296         return m_iBytesTotal;
297 }
298
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()
303 {
304         ConnectControlSocket();
305         if(m_State != FTP_STATE_LOGGING_IN)
306         {
307                 return;
308         }
309         LoginHost();
310         if(m_State != FTP_STATE_LOGGED_IN)
311         {
312                 return;
313         }
314         GetFile();
315
316         //We are all done now, and state has the current state.
317         m_Aborted = true;
318         
319
320 }
321
322 unsigned int CFtpGet::GetFile()
323 {
324         //Start off by changing into the proper dir.
325         char szCommandString[200];
326         int rcode;
327         
328         SDL_strlcpy(szCommandString, "TYPE I\r\n", SDL_arraysize(szCommandString));
329         rcode = SendFTPCommand(szCommandString);
330         if(rcode >=400)
331         {
332                 m_State = FTP_STATE_UNKNOWN_ERROR;      
333                 return 0;
334         }
335         if(m_Aborting)
336                 return 0;
337         if(m_szDir[0])
338         {
339                 SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "CWD %s\r\n", m_szDir);
340                 rcode = SendFTPCommand(szCommandString);
341                 if(rcode >=400)
342                 {
343                         m_State = FTP_STATE_DIRECTORY_INVALID;  
344                         return 0;
345                 }
346         }
347         if(m_Aborting)
348                 return 0;
349         if(!IssuePort())
350         {
351                 m_State = FTP_STATE_UNKNOWN_ERROR;
352                 return 0;
353         }
354         if(m_Aborting)
355                 return 0;
356         SDL_snprintf(szCommandString, SDL_arraysize(szCommandString), "RETR %s\r\n", m_szFilename);
357         rcode = SendFTPCommand(szCommandString);
358         if(rcode >=400)
359         {
360                 m_State = FTP_STATE_FILE_NOT_FOUND;     
361                 return 0;
362         }
363         if(m_Aborting)
364                 return 0;
365         //Now we will try to determine the file size...
366         char *p,*s;
367         p = SDL_strchr(recv_buffer,'(');
368         p++;
369         if(p)
370         {
371                 s = SDL_strchr(p,' ');
372                 *s = 0;
373                 m_iBytesTotal = atoi(p);
374         }
375         if(m_Aborting)
376                 return 0;
377
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)
382         {
383                 // int iWinsockErr = WSAGetLastError();
384                 m_State = FTP_STATE_SOCKET_ERROR;
385                 return 0;
386         }
387         if(m_Aborting)
388                 return 0;
389         ReadDataChannel();
390         
391         m_State = FTP_STATE_FILE_RECEIVED;
392         return 1;
393 }
394
395 unsigned int CFtpGet::IssuePort()
396 {
397
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
403
404
405    // Get the address for the hListenSocket
406         iLength = sizeof(listenaddr);
407         if (getsockname(m_ListenSock, (struct sockaddr*)&listenaddr, &iLength) == SOCKET_ERROR)
408         {
409                 // int iWinsockErr = WSAGetLastError();
410                 m_State = FTP_STATE_SOCKET_ERROR;
411                 return 0;
412         }
413
414         // Extract the local port from the hListenSocket
415         nLocalPort = listenaddr.sin_port;
416                                                         
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)
420         {
421                 // int iWinsockErr = WSAGetLastError();
422                 m_State = FTP_STATE_SOCKET_ERROR;
423                 return 0;
424         }
425                                 
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,
432                                 nLocalPort & 0xFF,
433                                 nLocalPort >> 8);
434                                                                                                                 
435         // Tell the server which port to use for data.
436         nReplyCode = SendFTPCommand(szCommandString);
437         if (nReplyCode != 200)
438         {
439                 // int iWinsockErr = WSAGetLastError();
440                 m_State = FTP_STATE_SOCKET_ERROR;
441                 return 0;
442         }
443         return 1;
444 }
445
446 int CFtpGet::ConnectControlSocket()
447 {
448         struct hostent *he;
449         struct servent *se;
450         struct sockaddr_in hostaddr;
451         he = gethostbyname(m_szHost);
452         if(he == NULL)
453         {
454                 m_State = FTP_STATE_HOST_NOT_FOUND;
455                 return 0;
456         }
457         //m_ControlSock
458         if(m_Aborting)
459                 return 0;
460         se = getservbyname("ftp", NULL);
461
462         if(se == NULL)
463         {
464                 hostaddr.sin_port = htons(21);
465         }
466         else
467         {
468                 hostaddr.sin_port = se->s_port;
469         }
470         hostaddr.sin_family = AF_INET;          
471         hostaddr.sin_addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;
472         if(m_Aborting)
473                 return 0;
474         //Now we will connect to the host                                       
475         if(connect(m_ControlSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr)))
476         {
477                 // int iWinsockErr = WSAGetLastError();
478                 m_State = FTP_STATE_CANT_CONNECT;
479                 return 0;
480         }
481         m_State = FTP_STATE_LOGGING_IN;
482         return 1;
483 }
484
485
486 int CFtpGet::LoginHost()
487 {
488         char szLoginString[200];
489         int rcode;
490         
491         SDL_snprintf(szLoginString, SDL_arraysize(szLoginString), "USER %s\r\n" ,m_szUserName);
492         rcode = SendFTPCommand(szLoginString);
493         if(rcode >=400)
494         {
495                 m_State = FTP_STATE_LOGIN_ERROR;        
496                 return 0;
497         }
498         SDL_snprintf(szLoginString, SDL_arraysize(szLoginString), "PASS %s\r\n" ,m_szPassword);
499         rcode = SendFTPCommand(szLoginString);
500         if(rcode >=400)
501         {
502                 m_State = FTP_STATE_LOGIN_ERROR;        
503                 return 0;
504         }
505
506         m_State = FTP_STATE_LOGGED_IN;
507         return 1;
508 }
509
510
511 unsigned int CFtpGet::SendFTPCommand(char *command)
512 {
513
514         FlushControlChannel();
515         // Send the FTP command
516         if (SOCKET_ERROR ==(send(m_ControlSock,command,strlen(command), 0)))
517                 {
518                         // int iWinsockErr = WSAGetLastError();
519                   // Return 999 to indicate an error has occurred
520                         return(999);
521                 } 
522                 
523         // Read the server's reply and return the reply code as an integer
524         return(ReadFTPServerReply());               
525 }       
526
527
528
529 unsigned int CFtpGet::ReadFTPServerReply()
530 {
531         unsigned int rcode;
532         int iBytesRead;
533         char chunk[2];
534         char szcode[5];
535         unsigned int igotcrlf = 0;
536         memset(recv_buffer,0,1000);
537         do
538         {
539                 chunk[0]=0;
540                 iBytesRead = recv(m_ControlSock,chunk,1,0);
541
542                 if (iBytesRead == SOCKET_ERROR)
543                 {
544                         // int iWinsockErr = WSAGetLastError();
545                   // Return 999 to indicate an error has occurred
546                         return(999);
547                 }
548                 
549                 if((chunk[0]==0x0a) || (chunk[0]==0x0d))
550                 {
551                         if(recv_buffer[0]!=0) 
552                         {
553                                 igotcrlf = 1;   
554                         }
555                 }
556                 else
557                 {       chunk[1] = 0;
558                         SDL_strlcat(recv_buffer, chunk, SDL_arraysize(recv_buffer));
559                 }
560                 
561                 SDL_Delay(1);
562         }while(igotcrlf==0);
563                                         
564         if(recv_buffer[3] == '-')
565         {
566                 //Hack -- must be a MOTD
567                 return ReadFTPServerReply();
568         }
569         if(recv_buffer[3] != ' ')
570         {
571                 //We should have 3 numbers then a space
572                 return 999;
573         }
574         memcpy(szcode,recv_buffer,3);
575         szcode[3] = 0;
576         rcode = atoi(szcode);
577     // Extract the reply code from the server reply and return as an integer
578         return(rcode);              
579 }       
580
581
582 unsigned int CFtpGet::ReadDataChannel()
583 {
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;                  
587    if(m_Aborting)
588                 return 0;
589         do      
590    {
591                 if(m_Aborting)
592                         return 0;
593                 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
594                                         
595                 m_iBytesIn += nBytesRecv;
596                 if (nBytesRecv > 0 )
597                 {
598                         fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
599                         //Write sDataBuffer, nBytesRecv
600         }
601
602                 SDL_Delay(1);
603         }while (nBytesRecv > 0);
604         fclose(LOCALFILE);                                                      
605         // Close the file and check for error returns.
606         if (nBytesRecv == SOCKET_ERROR)
607         { 
608                 //Ok, we got a socket error -- xfer aborted?
609                 m_State = FTP_STATE_RECV_FAILED;
610                 return 0;
611         }
612         else
613         {
614                 //done!
615                 m_State = FTP_STATE_FILE_RECEIVED;
616                 return 1;
617         }
618 }       
619
620
621 void CFtpGet::FlushControlChannel()
622 {
623         fd_set read_fds;                   
624         struct timeval timeout;
625         char flushbuff[3];
626
627         timeout.tv_sec=0;            
628         timeout.tv_usec=0;
629         
630         FD_ZERO(&read_fds);
631         FD_SET(m_ControlSock,&read_fds);    
632         
633         while(select(m_ControlSock+1,&read_fds,NULL,NULL,&timeout))
634         {
635                 recv(m_ControlSock,flushbuff,1,0);
636
637                 SDL_Delay(1);
638         }
639 }