]> icculus.org git repositories - taylor/freespace2.git/blob - src/inetfile/chttpget.cpp
platform and pstypes cleanup:
[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), (int)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         unsigned int ip;
413         struct servent *se;
414         struct sockaddr_in hostaddr;
415         if(m_Aborting){
416                 return 0;
417         }
418         
419         ip = inet_addr((const char *)m_szHost);
420
421         int rcode = 0;
422         if(ip==INADDR_NONE)
423         {
424                 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);          
425                 do
426                 {       
427                         if(m_Aborting)
428                         {
429                                 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
430                                 return 0;
431                         }
432                         rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
433
434                         SDL_Delay(1);
435                 }while(rcode==0);
436         }
437         
438         if(rcode == -1)
439         {
440                 m_State = HTTP_STATE_HOST_NOT_FOUND;
441                 return 0;
442         }
443         //m_ControlSock
444         if(m_Aborting)
445                 return 0;
446         se = getservbyname("http", NULL);
447         if(m_Aborting)
448                 return 0;
449         if(se == NULL)
450         {
451                 hostaddr.sin_port = htons(80);
452         }
453         else
454         {
455                 hostaddr.sin_port = se->s_port;
456         }
457         hostaddr.sin_family = AF_INET;          
458         //ip = htonl(ip);
459         memcpy(&hostaddr.sin_addr,&ip,4);
460
461         if(m_ProxyEnabled)
462         {
463                 //This is on a proxy, so we need to make sure to connect to the proxy machine
464                 ip = inet_addr((const char *)m_ProxyIP);
465                                 
466                 if(ip==INADDR_NONE)
467                 {
468                         http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
469                         rcode = 0;
470                         do
471                         {       
472                                 if(m_Aborting)
473                                 {
474                                         http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
475                                         return 0;
476                                 }
477                                 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
478
479                                 SDL_Delay(1);
480                         }while(rcode==0);
481                         
482                         
483                         if(rcode == -1)
484                         {
485                                 m_State = HTTP_STATE_HOST_NOT_FOUND;
486                                 return 0;
487                         }
488
489                 }
490                 //Use either the proxy port or 80 if none specified
491                 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
492                 //Copy the proxy address...
493                 memcpy(&hostaddr.sin_addr,&ip,4);
494
495         }
496         //Now we will connect to the host                                       
497         fd_set  wfds;
498
499         timeval timeout;
500         timeout.tv_sec = 0;
501         timeout.tv_usec = 0;
502         int serr = connect(m_DataSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr));
503         int cerr = WSAGetLastError();
504         if(serr)
505         {
506                 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
507                 {
508                         FD_ZERO(&wfds);
509                         FD_SET( m_DataSock, &wfds );
510                         if(select(0,NULL,&wfds,NULL,&timeout))
511                         {
512                                 serr = 0;
513                                 break;
514                         }
515                         if(m_Aborting)
516                                 return 0;
517                         serr = connect(m_DataSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr));
518                         if(serr == 0)
519                                 break;
520                         cerr = WSAGetLastError();
521                         if(cerr==WSAEISCONN)
522                         {
523                                 serr = 0;
524                                 break;
525                         }
526
527                         SDL_Delay(1);
528                 };
529         }
530         if(serr)
531         {
532                 m_State = HTTP_STATE_CANT_CONNECT;
533                 return 0;
534         }
535         m_State = HTTP_STATE_CONNECTED;
536         return 1;
537 }
538
539 char *ChttpGet::GetHTTPLine()
540 {
541         int iBytesRead;
542         char chunk[2];
543         unsigned int igotcrlf = 0;
544         memset(recv_buffer,0,1000);
545         do
546         {
547                 chunk[0]='\0';
548                 bool gotdata = false;
549                 do
550                 {
551                         iBytesRead = recv(m_DataSock,chunk,1,0);
552
553                         if(SOCKET_ERROR == iBytesRead)
554                         {       
555                                 int error = WSAGetLastError();
556                                 if(WSAEWOULDBLOCK==error)
557                                 {
558                                         gotdata = false;
559                                         continue;
560                                 }
561                                 else
562                                         return NULL;
563                         }
564                         else
565                         {
566                                 gotdata = true;
567                         }
568
569                         SDL_Delay(1);
570                 }while(!gotdata);
571                 
572                 if(chunk[0]==0x0d)
573                 {
574                         //This should always read a 0x0a
575                         do
576                         {
577                                 iBytesRead = recv(m_DataSock,chunk,1,0);
578
579                                 if(SOCKET_ERROR == iBytesRead)
580                                 {       
581                                         int error = WSAGetLastError();
582                                         if(WSAEWOULDBLOCK==error)
583                                         {
584                                                 gotdata = false;
585                                                 continue;
586                                         }
587                                         else
588                                                 return NULL;
589                                 }
590                                 else
591                                 {
592                                         gotdata = true;
593                                 }
594
595                                 SDL_Delay(1);
596                         }while(!gotdata);
597                         igotcrlf = 1;   
598                 }
599                 else
600                 {       chunk[1] = '\0';
601                         SDL_strlcat(recv_buffer, chunk, sizeof(recv_buffer));
602                 }
603                 
604                 SDL_Delay(1);
605         }while(igotcrlf==0);
606         return recv_buffer;     
607 }
608
609 unsigned int ChttpGet::ReadDataChannel()
610 {
611         char sDataBuffer[4096];         // Data-storage buffer for the data channel
612         int nBytesRecv = 0;                                             // Bytes received from the data channel
613
614         fd_set  wfds;
615
616         timeval timeout;
617         timeout.tv_sec = 0;
618         timeout.tv_usec = 500;
619
620         m_State = HTTP_STATE_RECEIVING;                 
621    do   
622    {
623                 FD_ZERO(&wfds);
624                 FD_SET( m_DataSock, &wfds );
625
626                 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
627                 {
628                         break;
629                 }
630                 select(0,&wfds,NULL,NULL,&timeout);
631         if(m_Aborting)
632                 {
633                         fclose(LOCALFILE);
634                         return 0;               
635                 }
636                 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
637         if(m_Aborting)
638                 {
639                         fclose(LOCALFILE);
640                         return 0;
641                 }
642                 if(SOCKET_ERROR == nBytesRecv)
643                 {       
644                         int error = WSAGetLastError();
645                         if(WSAEWOULDBLOCK==error)
646                         {
647                                 nBytesRecv = 1;
648                                 continue;
649                         }
650                 }
651                 m_iBytesIn += nBytesRecv;
652                 if (nBytesRecv > 0 )
653                 {
654                         fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
655                         //Write sDataBuffer, nBytesRecv
656         }
657                 
658                 SDL_Delay(1);
659         }while (nBytesRecv > 0);
660         fclose(LOCALFILE);                                                      
661         // Close the file and check for error returns.
662         if (nBytesRecv == SOCKET_ERROR)
663         { 
664                 //Ok, we got a socket error -- xfer aborted?
665                 m_State = HTTP_STATE_RECV_FAILED;
666                 return 0;
667         }
668         else
669         {
670                 //OutputDebugString("HTTP File complete!\n");
671                 //done!
672                 m_State = HTTP_STATE_FILE_RECEIVED;
673                 return 1;
674         }
675 }       
676
677
678 typedef struct _async_dns_lookup
679 {
680         unsigned int ip;        //resolved host. Write only to worker thread.
681         char * host;//host name to resolve. read only to worker thread
682         bool done;      //write only to the worker thread. Signals that the operation is complete
683         bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
684         bool abort;     //read only to worker thread. If this is set, don't fill in the struct.
685 }async_dns_lookup;
686
687 async_dns_lookup httpaslu;
688 async_dns_lookup *http_lastaslu = NULL;
689
690 int http_gethostbynameworker(void *parm);
691
692 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
693 {
694         
695         if(command==NW_AGHBN_LOOKUP)
696         {
697                 if(http_lastaslu)
698                         http_lastaslu->abort = true;
699
700                 async_dns_lookup *newaslu;
701                 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
702                 memset(&newaslu->ip,0,sizeof(unsigned int));
703                 newaslu->host = hostname;
704                 newaslu->done = false;
705                 newaslu->error = false;
706                 newaslu->abort = false;
707                 http_lastaslu = newaslu;
708                 httpaslu.done = false;
709
710                 SDL_CreateThread(http_gethostbynameworker, "GetHostByNameWorker", newaslu);
711
712                 return 1;
713         }
714         else if(command==NW_AGHBN_CANCEL)
715         {
716                 if(http_lastaslu)
717                         http_lastaslu->abort = true;
718                 http_lastaslu = NULL;
719         }
720         else if(command==NW_AGHBN_READ)
721         {
722                 if(!http_lastaslu)
723                         return -1;
724                 if(httpaslu.done)
725                 {
726                         //free(http_lastaslu);
727                         http_lastaslu = NULL;
728                         memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
729                         return 1;
730                 }
731                 else if(httpaslu.error)
732                 {
733                         free(http_lastaslu);
734                         http_lastaslu = NULL;
735                         return -1;
736                 }
737                 else return 0;
738         }
739         return -2;
740
741 }
742
743 // This is the worker thread which does the lookup.
744 int http_gethostbynameworker(void *parm)
745 {
746         async_dns_lookup *lookup = (async_dns_lookup *)parm;
747         struct hostent *he = gethostbyname(lookup->host);
748         if(he==NULL)
749         {
750                 lookup->error = true;
751                 return 1;
752         }
753         else if(!lookup->abort)
754         {
755                 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
756                 lookup->done = true;
757                 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));
758         }
759         free(lookup);
760
761         return 0;
762 }