]> icculus.org git repositories - taylor/freespace2.git/blob - src/inetfile/chttpget.cpp
safer strings using SDL string functions
[taylor/freespace2.git] / src / inetfile / chttpget.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/Chttpget.cpp $
11 * $Revision$
12 * $Date$
13 * $Author$
14 *
15 * HTTP Client class (get only)
16 *
17 * $Log$
18 * Revision 1.8  2002/06/21 03:04:12  relnev
19 * nothing important
20 *
21 * Revision 1.7  2002/06/17 06:33:09  relnev
22 * ryan's struct patch for gcc 2.95
23 *
24 * Revision 1.6  2002/06/09 04:41:21  relnev
25 * added copyright header
26 *
27 * Revision 1.5  2002/06/02 04:26:34  relnev
28 * warning cleanup
29 *
30 * Revision 1.4  2002/05/26 20:32:24  theoddone33
31 * Fix some minor stuff
32 *
33 * Revision 1.3  2002/05/26 20:20:54  relnev
34 * unix.h: updated
35 *
36 * inetfile/: complete
37 *
38 * Revision 1.2  2002/05/07 03:16:45  theoddone33
39 * The Great Newline Fix
40 *
41 * Revision 1.1.1.1  2002/05/03 03:28:09  root
42 * Initial import.
43 *
44  * 
45  * 5     8/24/99 1:49a Dave
46  * Fixed client-side afterburner stuttering. Added checkbox for no version
47  * checking on PXO join. Made button info passing more friendly between
48  * client and server.
49  * 
50  * 4     8/22/99 1:19p Dave
51  * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
52  * which d3d cards are detected.
53  * 
54  * 21    8/21/99 6:33p Kevin
55  * Fixed Proxy Stuff
56  * 
57  * 20    8/21/99 6:48a Jeff
58  * Linux port
59  * 
60  * 19    8/20/99 3:01p Kevin
61  * Added support for Proxies (I hope!)
62  * 
63  * 18    8/15/99 6:38p Jeff
64  * fixed compile error
65  * 
66  * 17    8/15/99 6:26p Kevin
67  * 
68  * 16    4/14/99 1:20a Jeff
69  * fixed case mismatched #includes
70  * 
71  * 15    3/03/99 12:28a Nate
72  * sped up something or other when the connection is done
73  * 
74  * 14    2/03/99 4:20p Kevin
75  * Got multiplayer working with .mn3 files, and setup autodownloading
76  * 
77  * 13    1/27/99 5:49p Kevin
78  * 
79  * 12    1/27/99 5:38p Kevin
80  * 
81  * 11    12/30/98 12:15p Kevin
82  * Auto Mission Download system
83  * 
84  * 10    10/12/98 4:59p Kevin
85  * Added delay to thread when cancelled...
86  * 
87  * 9     10/12/98 4:49p Nate
88  * More fixes
89  * 
90  * 8     10/12/98 1:54p Nate
91  * Fixed bug
92  * 
93  * 7     10/12/98 11:30a Kevin
94  * More memory stuff
95  * 
96  * 6     10/08/98 12:59p Nate
97  * fixed cancel
98  * 
99  * 5     10/08/98 9:57a Kevin
100  * made transfer cancellable
101  * 
102  * 4     7/31/98 12:19p Nate
103  * Fixed http abort problem.
104  * 
105  * 3     7/31/98 11:57a Kevin
106  * Added new functions for getting state
107  * 
108  * 2     6/01/98 10:10a Kevin
109  * Added DLL connection interface and auto update DLL
110  * 
111  * 1     5/27/98 9:52a Kevin
112  * 
113  * 1     5/25/98 5:31p Kevin
114  * Initial version
115 *
116 * $NoKeywords: $
117 */
118
119
120 #ifndef PLAT_UNIX
121 #include <windows.h>
122 #include <process.h>
123 #else
124 #include <sys/types.h>
125 #include <sys/socket.h>
126 #include <netinet/in.h>
127 #include <arpa/inet.h>
128 #include <netdb.h>
129 #include <sys/ioctl.h>
130 #include <errno.h>
131 #include <sys/time.h>
132 #include <unistd.h>
133 #endif
134
135 #include <string.h>
136 #include <stdio.h>
137 #include <stdlib.h>
138 #include <ctype.h>
139
140 #include "pstypes.h"
141 #include "inetgetfile.h"
142 #include "chttpget.h"
143
144
145
146 #define NW_AGHBN_CANCEL         1
147 #define NW_AGHBN_LOOKUP         2
148 #define NW_AGHBN_READ           3
149
150 int http_gethostbynameworker(void *parm);
151
152
153 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname);
154
155 int HTTPObjThread( void * obj )
156 {
157         ((ChttpGet *)obj)->WorkerThread();
158         ((ChttpGet *)obj)->m_Aborted = true;
159
160         return ((ChttpGet *)obj)->GetStatus();
161 }
162
163 void ChttpGet::AbortGet()
164 {
165         m_Aborting = true;
166         while(!m_Aborted) SDL_Delay(10); //Wait for the thread to end
167 }
168
169 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
170 {
171         m_ProxyEnabled = true;
172         m_ProxyIP = proxyip;
173         m_ProxyPort = proxyport;
174         GetFile(URL,localfile);
175 }
176
177 ChttpGet::ChttpGet(char *URL,char *localfile)
178 {
179         m_ProxyEnabled = false;
180         GetFile(URL,localfile);
181 }
182
183
184 void ChttpGet::GetFile(char *URL,char *localfile)
185 {
186         m_DataSock = INVALID_SOCKET;
187         m_iBytesIn = 0;
188         m_iBytesTotal = 0;
189         m_State = HTTP_STATE_STARTUP;;
190         m_Aborting = false;
191         m_Aborted = false;
192
193         SDL_strlcpy(m_URL, URL, sizeof(m_URL));
194
195         LOCALFILE = fopen(localfile,"wb");
196         if(NULL == LOCALFILE)
197         {
198                 m_State = HTTP_STATE_CANT_WRITE_FILE;
199                 m_Aborted = true;
200                 return;
201         }
202         m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
203         if(INVALID_SOCKET == m_DataSock)
204         {
205                 m_State = HTTP_STATE_SOCKET_ERROR;
206                 m_Aborted = true;
207                 return;
208         }
209         unsigned long arg;
210
211         arg = true;
212
213         ioctlsocket( m_DataSock, FIONBIO, &arg );
214
215         char *pURL = URL;
216         if(SDL_strncasecmp(URL,"http:",5)==0)
217         {
218                 pURL +=5;
219                 while(*pURL == '/')
220                 {
221                         pURL++;
222                 }
223         }
224         //There shouldn't be any : in this string
225         if(SDL_strchr(pURL,':'))
226         {
227                 m_State = HTTP_STATE_URL_PARSING_ERROR;
228                 m_Aborted = true;
229                 return;
230         }
231         //read the filename by searching backwards for a /
232         //then keep reading until you find the first /
233         //when you found it, you have the host and dir
234         char *filestart = NULL;
235         char *dirstart = NULL;
236         for(int i = strlen(pURL);i>=0;i--)
237         {
238                 if(pURL[i]== '/')
239                 {
240                         if(!filestart)
241                         {
242                                 filestart = pURL+i+1;
243                                 dirstart = pURL+i+1;
244                                 SDL_strlcpy(m_szFilename, filestart, sizeof(m_szFilename));
245                         }
246                         else
247                         {
248                                 dirstart = pURL+i+1;
249                         }
250                 }
251         }
252         if((dirstart==NULL) || (filestart==NULL))
253         {
254                 m_State = HTTP_STATE_URL_PARSING_ERROR;
255                 m_Aborted = true;
256                 return;
257         }
258         else
259         {
260                 SDL_strlcpy(m_szDir, dirstart, sizeof(m_szDir));//,(filestart-dirstart));
261                 int len = min((dirstart-pURL), sizeof(m_szHost));
262                 SDL_strlcpy(m_szHost, pURL, len);
263         }
264
265         SDL_Thread *thread = SDL_CreateThread(HTTPObjThread, "HTTPObjThread", this);
266
267         if(thread == NULL)
268         {
269                 m_State = HTTP_STATE_INTERNAL_ERROR;
270                 m_Aborted = true;
271                 return;
272         }
273         else
274         {
275                 int ret_val = 0;
276                 SDL_WaitThread(thread, &ret_val);
277         }
278 }
279
280
281 ChttpGet::~ChttpGet()
282 {
283         if(m_DataSock != INVALID_SOCKET)
284         {
285                 shutdown(m_DataSock,2);
286                 closesocket(m_DataSock);
287         }
288
289         if(LOCALFILE != NULL)
290         {
291                 fclose(LOCALFILE);
292         }
293 }
294
295 int ChttpGet::GetStatus()
296 {
297         return m_State;
298 }
299
300 unsigned int ChttpGet::GetBytesIn()
301 {
302         return m_iBytesIn;
303 }
304
305 unsigned int ChttpGet::GetTotalBytes()
306 {
307         return m_iBytesTotal;
308 }
309
310
311 void ChttpGet::WorkerThread()
312 {
313         char szCommand[1000];
314         char *p;
315         int irsp = 0;
316         ConnectSocket();
317         if(m_Aborting)
318         {
319                 fclose(LOCALFILE);
320                 LOCALFILE = NULL;
321                 return;
322         }
323         if(m_State != HTTP_STATE_CONNECTED)
324         {
325                 fclose(LOCALFILE);
326                 LOCALFILE = NULL;
327                 return;
328         }
329         SDL_snprintf(szCommand,sizeof(szCommand),"GET %s%s HTTP/1.1\nAccept: */*\nAccept-Encoding: deflate\nHost: %s\n\n\n",m_ProxyEnabled?"":"/",m_ProxyEnabled?m_URL:m_szDir,m_szHost);
330         send(m_DataSock,szCommand,strlen(szCommand),0);
331         p = GetHTTPLine();
332         if(SDL_strncasecmp("HTTP/",p,5)==0)
333         {
334                 char *pcode;
335                 pcode = SDL_strchr(p,' ')+1;
336                 if(!pcode)
337                 {
338                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
339                         fclose(LOCALFILE);
340                         LOCALFILE = NULL;
341                         return;
342
343                 }
344                 pcode[3] = '\0';
345                 irsp = atoi(pcode);
346
347                 if(irsp == 0)
348                 {
349                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
350                         fclose(LOCALFILE);
351                         LOCALFILE = NULL;
352                         return;
353                 }
354                 if(irsp==200)
355                 {
356                         int idataready=0;
357                         do
358                         {
359                                 p = GetHTTPLine();
360                                 if(p==NULL)
361                                 {
362                                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
363                                         fclose(LOCALFILE);
364                                         LOCALFILE = NULL;
365                                         return;
366                                 }
367                                 if(*p=='\0')
368                                 {
369                                         idataready = 1;
370                                         break;
371                                 }
372                                 if(SDL_strncasecmp(p,"Content-Length:",strlen("Content-Length:"))==0)
373                                 {
374                                         char *s = SDL_strchr(p,' ')+1;
375                                         p = s;
376                                         if(s)
377                                         {
378                                                 while(*s)
379                                                 {
380                                                         if(!isdigit(*s))
381                                                         {
382                                                                 *s='\0';
383                                                         }
384                                                         s++;
385                                                 };
386                                                 m_iBytesTotal = atoi(p);
387                                         }
388
389                                 }
390
391                                 SDL_Delay(1);
392                         }while(!idataready);
393                 ReadDataChannel();
394                 return;
395                 }
396                 m_State = HTTP_STATE_FILE_NOT_FOUND;
397                 fclose(LOCALFILE);
398                 LOCALFILE = NULL;
399                 return;
400         }
401         else
402         {
403                 m_State = HTTP_STATE_UNKNOWN_ERROR;
404                 fclose(LOCALFILE);
405                 LOCALFILE = NULL;
406                 return;
407         }
408 }
409
410 int ChttpGet::ConnectSocket()
411 {
412         //HOSTENT *he;
413         unsigned int ip;
414         SERVENT *se;
415         SOCKADDR_IN hostaddr;
416         if(m_Aborting){
417                 return 0;
418         }
419         
420         ip = inet_addr((const char *)m_szHost);
421
422         int rcode = 0;
423         if(ip==INADDR_NONE)
424         {
425                 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);          
426                 do
427                 {       
428                         if(m_Aborting)
429                         {
430                                 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
431                                 return 0;
432                         }
433                         rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
434
435                         SDL_Delay(1);
436                 }while(rcode==0);
437         }
438         
439         if(rcode == -1)
440         {
441                 m_State = HTTP_STATE_HOST_NOT_FOUND;
442                 return 0;
443         }
444         //m_ControlSock
445         if(m_Aborting)
446                 return 0;
447         se = getservbyname("http", NULL);
448         if(m_Aborting)
449                 return 0;
450         if(se == NULL)
451         {
452                 hostaddr.sin_port = htons(80);
453         }
454         else
455         {
456                 hostaddr.sin_port = se->s_port;
457         }
458         hostaddr.sin_family = AF_INET;          
459         //ip = htonl(ip);
460         memcpy(&hostaddr.sin_addr,&ip,4);
461
462         if(m_ProxyEnabled)
463         {
464                 //This is on a proxy, so we need to make sure to connect to the proxy machine
465                 ip = inet_addr((const char *)m_ProxyIP);
466                                 
467                 if(ip==INADDR_NONE)
468                 {
469                         http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
470                         rcode = 0;
471                         do
472                         {       
473                                 if(m_Aborting)
474                                 {
475                                         http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
476                                         return 0;
477                                 }
478                                 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
479
480                                 SDL_Delay(1);
481                         }while(rcode==0);
482                         
483                         
484                         if(rcode == -1)
485                         {
486                                 m_State = HTTP_STATE_HOST_NOT_FOUND;
487                                 return 0;
488                         }
489
490                 }
491                 //Use either the proxy port or 80 if none specified
492                 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
493                 //Copy the proxy address...
494                 memcpy(&hostaddr.sin_addr,&ip,4);
495
496         }
497         //Now we will connect to the host                                       
498         fd_set  wfds;
499
500         timeval timeout;
501         timeout.tv_sec = 0;
502         timeout.tv_usec = 0;
503         int serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
504         int cerr = WSAGetLastError();
505         if(serr)
506         {
507                 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
508                 {
509                         FD_ZERO(&wfds);
510                         FD_SET( m_DataSock, &wfds );
511                         if(select(0,NULL,&wfds,NULL,&timeout))
512                         {
513                                 serr = 0;
514                                 break;
515                         }
516                         if(m_Aborting)
517                                 return 0;
518                         serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
519                         if(serr == 0)
520                                 break;
521                         cerr = WSAGetLastError();
522                         if(cerr==WSAEISCONN)
523                         {
524                                 serr = 0;
525                                 break;
526                         }
527
528                         SDL_Delay(1);
529                 };
530         }
531         if(serr)
532         {
533                 m_State = HTTP_STATE_CANT_CONNECT;
534                 return 0;
535         }
536         m_State = HTTP_STATE_CONNECTED;
537         return 1;
538 }
539
540 char *ChttpGet::GetHTTPLine()
541 {
542         int iBytesRead;
543         char chunk[2];
544         unsigned int igotcrlf = 0;
545         memset(recv_buffer,0,1000);
546         do
547         {
548                 chunk[0]='\0';
549                 bool gotdata = false;
550                 do
551                 {
552                         iBytesRead = recv(m_DataSock,chunk,1,0);
553
554                         if(SOCKET_ERROR == iBytesRead)
555                         {       
556                                 int error = WSAGetLastError();
557                                 if(WSAEWOULDBLOCK==error)
558                                 {
559                                         gotdata = false;
560                                         continue;
561                                 }
562                                 else
563                                         return NULL;
564                         }
565                         else
566                         {
567                                 gotdata = true;
568                         }
569
570                         SDL_Delay(1);
571                 }while(!gotdata);
572                 
573                 if(chunk[0]==0x0d)
574                 {
575                         //This should always read a 0x0a
576                         do
577                         {
578                                 iBytesRead = recv(m_DataSock,chunk,1,0);
579
580                                 if(SOCKET_ERROR == iBytesRead)
581                                 {       
582                                         int error = WSAGetLastError();
583                                         if(WSAEWOULDBLOCK==error)
584                                         {
585                                                 gotdata = false;
586                                                 continue;
587                                         }
588                                         else
589                                                 return NULL;
590                                 }
591                                 else
592                                 {
593                                         gotdata = true;
594                                 }
595
596                                 SDL_Delay(1);
597                         }while(!gotdata);
598                         igotcrlf = 1;   
599                 }
600                 else
601                 {       chunk[1] = '\0';
602                         SDL_strlcat(recv_buffer, chunk, sizeof(recv_buffer));
603                 }
604                 
605                 SDL_Delay(1);
606         }while(igotcrlf==0);
607         return recv_buffer;     
608 }
609
610 unsigned int ChttpGet::ReadDataChannel()
611 {
612         char sDataBuffer[4096];         // Data-storage buffer for the data channel
613         int nBytesRecv = 0;                                             // Bytes received from the data channel
614
615         fd_set  wfds;
616
617         timeval timeout;
618         timeout.tv_sec = 0;
619         timeout.tv_usec = 500;
620
621         m_State = HTTP_STATE_RECEIVING;                 
622    do   
623    {
624                 FD_ZERO(&wfds);
625                 FD_SET( m_DataSock, &wfds );
626
627                 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
628                 {
629                         break;
630                 }
631                 select(0,&wfds,NULL,NULL,&timeout);
632         if(m_Aborting)
633                 {
634                         fclose(LOCALFILE);
635                         return 0;               
636                 }
637                 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
638         if(m_Aborting)
639                 {
640                         fclose(LOCALFILE);
641                         return 0;
642                 }
643                 if(SOCKET_ERROR == nBytesRecv)
644                 {       
645                         int error = WSAGetLastError();
646                         if(WSAEWOULDBLOCK==error)
647                         {
648                                 nBytesRecv = 1;
649                                 continue;
650                         }
651                 }
652                 m_iBytesIn += nBytesRecv;
653                 if (nBytesRecv > 0 )
654                 {
655                         fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
656                         //Write sDataBuffer, nBytesRecv
657         }
658                 
659                 SDL_Delay(1);
660         }while (nBytesRecv > 0);
661         fclose(LOCALFILE);                                                      
662         // Close the file and check for error returns.
663         if (nBytesRecv == SOCKET_ERROR)
664         { 
665                 //Ok, we got a socket error -- xfer aborted?
666                 m_State = HTTP_STATE_RECV_FAILED;
667                 return 0;
668         }
669         else
670         {
671                 //OutputDebugString("HTTP File complete!\n");
672                 //done!
673                 m_State = HTTP_STATE_FILE_RECEIVED;
674                 return 1;
675         }
676 }       
677
678
679 typedef struct _async_dns_lookup
680 {
681         unsigned int ip;        //resolved host. Write only to worker thread.
682         char * host;//host name to resolve. read only to worker thread
683         bool done;      //write only to the worker thread. Signals that the operation is complete
684         bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
685         bool abort;     //read only to worker thread. If this is set, don't fill in the struct.
686 }async_dns_lookup;
687
688 async_dns_lookup httpaslu;
689 async_dns_lookup *http_lastaslu = NULL;
690
691 int http_gethostbynameworker(void *parm);
692
693 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
694 {
695         
696         if(command==NW_AGHBN_LOOKUP)
697         {
698                 if(http_lastaslu)
699                         http_lastaslu->abort = true;
700
701                 async_dns_lookup *newaslu;
702                 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
703                 memset(&newaslu->ip,0,sizeof(unsigned int));
704                 newaslu->host = hostname;
705                 newaslu->done = false;
706                 newaslu->error = false;
707                 newaslu->abort = false;
708                 http_lastaslu = newaslu;
709                 httpaslu.done = false;
710
711                 SDL_CreateThread(http_gethostbynameworker, "GetHostByNameWorker", newaslu);
712
713                 return 1;
714         }
715         else if(command==NW_AGHBN_CANCEL)
716         {
717                 if(http_lastaslu)
718                         http_lastaslu->abort = true;
719                 http_lastaslu = NULL;
720         }
721         else if(command==NW_AGHBN_READ)
722         {
723                 if(!http_lastaslu)
724                         return -1;
725                 if(httpaslu.done)
726                 {
727                         //free(http_lastaslu);
728                         http_lastaslu = NULL;
729                         memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
730                         return 1;
731                 }
732                 else if(httpaslu.error)
733                 {
734                         free(http_lastaslu);
735                         http_lastaslu = NULL;
736                         return -1;
737                 }
738                 else return 0;
739         }
740         return -2;
741
742 }
743
744 // This is the worker thread which does the lookup.
745 int http_gethostbynameworker(void *parm)
746 {
747         async_dns_lookup *lookup = (async_dns_lookup *)parm;
748         HOSTENT *he = gethostbyname(lookup->host);
749         if(he==NULL)
750         {
751                 lookup->error = true;
752                 return 1;
753         }
754         else if(!lookup->abort)
755         {
756                 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
757                 lookup->done = true;
758                 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));
759         }
760         free(lookup);
761
762         return 0;
763 }