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