]> icculus.org git repositories - taylor/freespace2.git/blob - src/inetfile/chttpget.cpp
fix compile errors post rebase
[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, SDL_arraysize(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, SDL_arraysize(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, SDL_arraysize(m_szDir));//,(filestart-dirstart));
261                 int len = min((dirstart-pURL), (int)SDL_arraysize(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         }
272         else
273         {
274                 int ret_val = 0;
275                 SDL_WaitThread(thread, &ret_val);
276         }
277 }
278
279
280 ChttpGet::~ChttpGet()
281 {
282         if(m_DataSock != INVALID_SOCKET)
283         {
284                 shutdown(m_DataSock,2);
285                 closesocket(m_DataSock);
286         }
287
288         if(LOCALFILE != NULL)
289         {
290                 fclose(LOCALFILE);
291         }
292 }
293
294 int ChttpGet::GetStatus()
295 {
296         return m_State;
297 }
298
299 unsigned int ChttpGet::GetBytesIn()
300 {
301         return m_iBytesIn;
302 }
303
304 unsigned int ChttpGet::GetTotalBytes()
305 {
306         return m_iBytesTotal;
307 }
308
309
310 void ChttpGet::WorkerThread()
311 {
312         char szCommand[1000];
313         char *p;
314         int irsp = 0;
315         ConnectSocket();
316         if(m_Aborting)
317         {
318                 fclose(LOCALFILE);
319                 LOCALFILE = NULL;
320                 return;
321         }
322         if(m_State != HTTP_STATE_CONNECTED)
323         {
324                 fclose(LOCALFILE);
325                 LOCALFILE = NULL;
326                 return;
327         }
328         SDL_snprintf(szCommand,SDL_arraysize(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);
329         send(m_DataSock,szCommand,strlen(szCommand),0);
330         p = GetHTTPLine();
331         if(SDL_strncasecmp("HTTP/",p,5)==0)
332         {
333                 char *pcode;
334                 pcode = SDL_strchr(p,' ')+1;
335                 if(!pcode)
336                 {
337                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
338                         fclose(LOCALFILE);
339                         LOCALFILE = NULL;
340                         return;
341
342                 }
343                 pcode[3] = '\0';
344                 irsp = atoi(pcode);
345
346                 if(irsp == 0)
347                 {
348                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
349                         fclose(LOCALFILE);
350                         LOCALFILE = NULL;
351                         return;
352                 }
353                 if(irsp==200)
354                 {
355                         int idataready=0;
356                         do
357                         {
358                                 p = GetHTTPLine();
359                                 if(p==NULL)
360                                 {
361                                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
362                                         fclose(LOCALFILE);
363                                         LOCALFILE = NULL;
364                                         return;
365                                 }
366                                 if(*p=='\0')
367                                 {
368                                         idataready = 1;
369                                         break;
370                                 }
371                                 if(SDL_strncasecmp(p,"Content-Length:",strlen("Content-Length:"))==0)
372                                 {
373                                         char *s = SDL_strchr(p,' ')+1;
374                                         p = s;
375                                         if(s)
376                                         {
377                                                 while(*s)
378                                                 {
379                                                         if(!isdigit(*s))
380                                                         {
381                                                                 *s='\0';
382                                                         }
383                                                         s++;
384                                                 };
385                                                 m_iBytesTotal = atoi(p);
386                                         }
387
388                                 }
389
390                                 SDL_Delay(1);
391                         }while(!idataready);
392                 ReadDataChannel();
393                 return;
394                 }
395                 m_State = HTTP_STATE_FILE_NOT_FOUND;
396                 fclose(LOCALFILE);
397                 LOCALFILE = NULL;
398                 return;
399         }
400         else
401         {
402                 m_State = HTTP_STATE_UNKNOWN_ERROR;
403                 fclose(LOCALFILE);
404                 LOCALFILE = NULL;
405                 return;
406         }
407 }
408
409 int ChttpGet::ConnectSocket()
410 {
411         unsigned int ip;
412         struct servent *se;
413         struct sockaddr_in hostaddr;
414         if(m_Aborting){
415                 return 0;
416         }
417         
418         ip = inet_addr((const char *)m_szHost);
419
420         int rcode = 0;
421         if(ip==INADDR_NONE)
422         {
423                 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);          
424                 do
425                 {       
426                         if(m_Aborting)
427                         {
428                                 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
429                                 return 0;
430                         }
431                         rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
432
433                         SDL_Delay(1);
434                 }while(rcode==0);
435         }
436         
437         if(rcode == -1)
438         {
439                 m_State = HTTP_STATE_HOST_NOT_FOUND;
440                 return 0;
441         }
442         //m_ControlSock
443         if(m_Aborting)
444                 return 0;
445         se = getservbyname("http", NULL);
446         if(m_Aborting)
447                 return 0;
448         if(se == NULL)
449         {
450                 hostaddr.sin_port = htons(80);
451         }
452         else
453         {
454                 hostaddr.sin_port = se->s_port;
455         }
456         hostaddr.sin_family = AF_INET;          
457         //ip = htonl(ip);
458         memcpy(&hostaddr.sin_addr,&ip,4);
459
460         if(m_ProxyEnabled)
461         {
462                 //This is on a proxy, so we need to make sure to connect to the proxy machine
463                 ip = inet_addr((const char *)m_ProxyIP);
464                                 
465                 if(ip==INADDR_NONE)
466                 {
467                         http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
468                         rcode = 0;
469                         do
470                         {       
471                                 if(m_Aborting)
472                                 {
473                                         http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
474                                         return 0;
475                                 }
476                                 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
477
478                                 SDL_Delay(1);
479                         }while(rcode==0);
480                         
481                         
482                         if(rcode == -1)
483                         {
484                                 m_State = HTTP_STATE_HOST_NOT_FOUND;
485                                 return 0;
486                         }
487
488                 }
489                 //Use either the proxy port or 80 if none specified
490                 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
491                 //Copy the proxy address...
492                 memcpy(&hostaddr.sin_addr,&ip,4);
493
494         }
495         //Now we will connect to the host                                       
496         fd_set  wfds;
497
498         timeval timeout;
499         timeout.tv_sec = 0;
500         timeout.tv_usec = 0;
501         int serr = connect(m_DataSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr));
502         int cerr = WSAGetLastError();
503         if(serr)
504         {
505                 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
506                 {
507                         FD_ZERO(&wfds);
508                         FD_SET( m_DataSock, &wfds );
509                         if(select(0,NULL,&wfds,NULL,&timeout))
510                         {
511                                 serr = 0;
512                                 break;
513                         }
514                         if(m_Aborting)
515                                 return 0;
516                         serr = connect(m_DataSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr));
517                         if(serr == 0)
518                                 break;
519                         cerr = WSAGetLastError();
520                         if(cerr==WSAEISCONN)
521                         {
522                                 serr = 0;
523                                 break;
524                         }
525
526                         SDL_Delay(1);
527                 };
528         }
529         if(serr)
530         {
531                 m_State = HTTP_STATE_CANT_CONNECT;
532                 return 0;
533         }
534         m_State = HTTP_STATE_CONNECTED;
535         return 1;
536 }
537
538 char *ChttpGet::GetHTTPLine()
539 {
540         int iBytesRead;
541         char chunk[2];
542         unsigned int igotcrlf = 0;
543         memset(recv_buffer,0,1000);
544         do
545         {
546                 chunk[0]='\0';
547                 bool gotdata = false;
548                 do
549                 {
550                         iBytesRead = recv(m_DataSock,chunk,1,0);
551
552                         if(SOCKET_ERROR == iBytesRead)
553                         {       
554                                 int error = WSAGetLastError();
555                                 if(WSAEWOULDBLOCK==error)
556                                 {
557                                         gotdata = false;
558                                         continue;
559                                 }
560                                 else
561                                         return NULL;
562                         }
563                         else
564                         {
565                                 gotdata = true;
566                         }
567
568                         SDL_Delay(1);
569                 }while(!gotdata);
570                 
571                 if(chunk[0]==0x0d)
572                 {
573                         //This should always read a 0x0a
574                         do
575                         {
576                                 iBytesRead = recv(m_DataSock,chunk,1,0);
577
578                                 if(SOCKET_ERROR == iBytesRead)
579                                 {       
580                                         int error = WSAGetLastError();
581                                         if(WSAEWOULDBLOCK==error)
582                                         {
583                                                 gotdata = false;
584                                                 continue;
585                                         }
586                                         else
587                                                 return NULL;
588                                 }
589                                 else
590                                 {
591                                         gotdata = true;
592                                 }
593
594                                 SDL_Delay(1);
595                         }while(!gotdata);
596                         igotcrlf = 1;   
597                 }
598                 else
599                 {       chunk[1] = '\0';
600                         SDL_strlcat(recv_buffer, chunk, SDL_arraysize(recv_buffer));
601                 }
602                 
603                 SDL_Delay(1);
604         }while(igotcrlf==0);
605         return recv_buffer;     
606 }
607
608 unsigned int ChttpGet::ReadDataChannel()
609 {
610         char sDataBuffer[4096];         // Data-storage buffer for the data channel
611         int nBytesRecv = 0;                                             // Bytes received from the data channel
612
613         fd_set  wfds;
614
615         timeval timeout;
616         timeout.tv_sec = 0;
617         timeout.tv_usec = 500;
618
619         m_State = HTTP_STATE_RECEIVING;                 
620    do   
621    {
622                 FD_ZERO(&wfds);
623                 FD_SET( m_DataSock, &wfds );
624
625                 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
626                 {
627                         break;
628                 }
629                 select(0,&wfds,NULL,NULL,&timeout);
630         if(m_Aborting)
631                 {
632                         fclose(LOCALFILE);
633                         return 0;               
634                 }
635                 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
636         if(m_Aborting)
637                 {
638                         fclose(LOCALFILE);
639                         return 0;
640                 }
641                 if(SOCKET_ERROR == nBytesRecv)
642                 {       
643                         int error = WSAGetLastError();
644                         if(WSAEWOULDBLOCK==error)
645                         {
646                                 nBytesRecv = 1;
647                                 continue;
648                         }
649                 }
650                 m_iBytesIn += nBytesRecv;
651                 if (nBytesRecv > 0 )
652                 {
653                         fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
654                         //Write sDataBuffer, nBytesRecv
655         }
656                 
657                 SDL_Delay(1);
658         }while (nBytesRecv > 0);
659         fclose(LOCALFILE);                                                      
660         // Close the file and check for error returns.
661         if (nBytesRecv == SOCKET_ERROR)
662         { 
663                 //Ok, we got a socket error -- xfer aborted?
664                 m_State = HTTP_STATE_RECV_FAILED;
665                 return 0;
666         }
667         else
668         {
669                 //OutputDebugString("HTTP File complete!\n");
670                 //done!
671                 m_State = HTTP_STATE_FILE_RECEIVED;
672                 return 1;
673         }
674 }       
675
676
677 typedef struct _async_dns_lookup
678 {
679         unsigned int ip;        //resolved host. Write only to worker thread.
680         char * host;//host name to resolve. read only to worker thread
681         bool done;      //write only to the worker thread. Signals that the operation is complete
682         bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
683         bool abort;     //read only to worker thread. If this is set, don't fill in the struct.
684 }async_dns_lookup;
685
686 async_dns_lookup httpaslu;
687 async_dns_lookup *http_lastaslu = NULL;
688
689 int http_gethostbynameworker(void *parm);
690
691 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
692 {
693         
694         if(command==NW_AGHBN_LOOKUP)
695         {
696                 if(http_lastaslu)
697                         http_lastaslu->abort = true;
698
699                 async_dns_lookup *newaslu;
700                 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
701                 memset(&newaslu->ip,0,sizeof(unsigned int));
702                 newaslu->host = hostname;
703                 newaslu->done = false;
704                 newaslu->error = false;
705                 newaslu->abort = false;
706                 http_lastaslu = newaslu;
707                 httpaslu.done = false;
708
709                 SDL_CreateThread(http_gethostbynameworker, "GetHostByNameWorker", newaslu);
710
711                 return 1;
712         }
713         else if(command==NW_AGHBN_CANCEL)
714         {
715                 if(http_lastaslu)
716                         http_lastaslu->abort = true;
717                 http_lastaslu = NULL;
718         }
719         else if(command==NW_AGHBN_READ)
720         {
721                 if(!http_lastaslu)
722                         return -1;
723                 if(httpaslu.done)
724                 {
725                         //free(http_lastaslu);
726                         http_lastaslu = NULL;
727                         memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
728                         return 1;
729                 }
730                 else if(httpaslu.error)
731                 {
732                         free(http_lastaslu);
733                         http_lastaslu = NULL;
734                         return -1;
735                 }
736                 else return 0;
737         }
738         return -2;
739
740 }
741
742 // This is the worker thread which does the lookup.
743 int http_gethostbynameworker(void *parm)
744 {
745         async_dns_lookup *lookup = (async_dns_lookup *)parm;
746         struct hostent *he = gethostbyname(lookup->host);
747         if(he==NULL)
748         {
749                 lookup->error = true;
750                 return 1;
751         }
752         else if(!lookup->abort)
753         {
754                 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
755                 lookup->done = true;
756                 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));
757         }
758         free(lookup);
759
760         return 0;
761 }