]> icculus.org git repositories - taylor/freespace2.git/blob - src/inetfile/chttpget.cpp
clean up Windows #include's and use winsock2
[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 <winsock2.h>
122 #else
123 #include <sys/types.h>
124 #include <sys/socket.h>
125 #include <netinet/in.h>
126 #include <arpa/inet.h>
127 #include <netdb.h>
128 #include <sys/ioctl.h>
129 #include <errno.h>
130 #include <sys/time.h>
131 #include <unistd.h>
132 #endif
133
134 #include <string.h>
135 #include <stdio.h>
136 #include <stdlib.h>
137 #include <ctype.h>
138
139 #include "pstypes.h"
140 #include "inetgetfile.h"
141 #include "chttpget.h"
142
143
144
145 #define NW_AGHBN_CANCEL         1
146 #define NW_AGHBN_LOOKUP         2
147 #define NW_AGHBN_READ           3
148
149 int http_gethostbynameworker(void *parm);
150
151
152 int http_Asyncgethostbyname(in_addr_t *ip, int command, char *hostname);
153
154 int HTTPObjThread( void * obj )
155 {
156         ((ChttpGet *)obj)->WorkerThread();
157         ((ChttpGet *)obj)->m_Aborted = true;
158
159         return ((ChttpGet *)obj)->GetStatus();
160 }
161
162 void ChttpGet::AbortGet()
163 {
164         m_Aborting = true;
165         while(!m_Aborted) SDL_Delay(10); //Wait for the thread to end
166 }
167
168 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
169 {
170         m_ProxyEnabled = true;
171         m_ProxyIP = proxyip;
172         m_ProxyPort = proxyport;
173         GetFile(URL,localfile);
174 }
175
176 ChttpGet::ChttpGet(char *URL,char *localfile)
177 {
178         m_ProxyEnabled = false;
179         GetFile(URL,localfile);
180 }
181
182
183 void ChttpGet::GetFile(char *URL,char *localfile)
184 {
185         m_DataSock = INVALID_SOCKET;
186         m_iBytesIn = 0;
187         m_iBytesTotal = 0;
188         m_State = HTTP_STATE_STARTUP;;
189         m_Aborting = false;
190         m_Aborted = false;
191
192         SDL_strlcpy(m_URL, URL, SDL_arraysize(m_URL));
193
194         LOCALFILE = fopen(localfile,"wb");
195         if(NULL == LOCALFILE)
196         {
197                 m_State = HTTP_STATE_CANT_WRITE_FILE;
198                 m_Aborted = true;
199                 return;
200         }
201         m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
202         if(INVALID_SOCKET == m_DataSock)
203         {
204                 m_State = HTTP_STATE_SOCKET_ERROR;
205                 m_Aborted = true;
206                 return;
207         }
208         unsigned long arg;
209
210         arg = 1;
211
212         ioctlsocket( m_DataSock, FIONBIO, &arg );
213
214         char *pURL = URL;
215         if(SDL_strncasecmp(URL,"http:",5)==0)
216         {
217                 pURL +=5;
218                 while(*pURL == '/')
219                 {
220                         pURL++;
221                 }
222         }
223         //There shouldn't be any : in this string
224         if(SDL_strchr(pURL,':'))
225         {
226                 m_State = HTTP_STATE_URL_PARSING_ERROR;
227                 m_Aborted = true;
228                 return;
229         }
230         //read the filename by searching backwards for a /
231         //then keep reading until you find the first /
232         //when you found it, you have the host and dir
233         char *filestart = NULL;
234         char *dirstart = NULL;
235         for(int i = strlen(pURL);i>=0;i--)
236         {
237                 if(pURL[i]== '/')
238                 {
239                         if(!filestart)
240                         {
241                                 filestart = pURL+i+1;
242                                 dirstart = pURL+i+1;
243                                 SDL_strlcpy(m_szFilename, filestart, SDL_arraysize(m_szFilename));
244                         }
245                         else
246                         {
247                                 dirstart = pURL+i+1;
248                         }
249                 }
250         }
251         if((dirstart==NULL) || (filestart==NULL))
252         {
253                 m_State = HTTP_STATE_URL_PARSING_ERROR;
254                 m_Aborted = true;
255                 return;
256         }
257         else
258         {
259                 SDL_strlcpy(m_szDir, dirstart, SDL_arraysize(m_szDir));//,(filestart-dirstart));
260                 int len = min((dirstart-pURL), (int)SDL_arraysize(m_szHost));
261                 SDL_strlcpy(m_szHost, pURL, len);
262         }
263
264         SDL_Thread *thread = SDL_CreateThread(HTTPObjThread, "HTTPObjThread", this);
265
266         if(thread == NULL)
267         {
268                 m_State = HTTP_STATE_INTERNAL_ERROR;
269                 m_Aborted = true;
270         }
271         else
272         {
273                 int ret_val = 0;
274                 SDL_WaitThread(thread, &ret_val);
275         }
276 }
277
278
279 ChttpGet::~ChttpGet()
280 {
281         if(m_DataSock != INVALID_SOCKET)
282         {
283                 shutdown(m_DataSock,2);
284                 closesocket(m_DataSock);
285         }
286
287         if(LOCALFILE != NULL)
288         {
289                 fclose(LOCALFILE);
290         }
291 }
292
293 int ChttpGet::GetStatus()
294 {
295         return m_State;
296 }
297
298 unsigned int ChttpGet::GetBytesIn()
299 {
300         return m_iBytesIn;
301 }
302
303 unsigned int ChttpGet::GetTotalBytes()
304 {
305         return m_iBytesTotal;
306 }
307
308
309 void ChttpGet::WorkerThread()
310 {
311         char szCommand[1000];
312         char *p;
313         int irsp = 0;
314         ConnectSocket();
315         if(m_Aborting)
316         {
317                 fclose(LOCALFILE);
318                 LOCALFILE = NULL;
319                 return;
320         }
321         if(m_State != HTTP_STATE_CONNECTED)
322         {
323                 fclose(LOCALFILE);
324                 LOCALFILE = NULL;
325                 return;
326         }
327         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);
328         send(m_DataSock,szCommand,strlen(szCommand),0);
329         p = GetHTTPLine();
330         if(SDL_strncasecmp("HTTP/",p,5)==0)
331         {
332                 char *pcode;
333                 pcode = SDL_strchr(p,' ')+1;
334                 if(!pcode)
335                 {
336                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
337                         fclose(LOCALFILE);
338                         LOCALFILE = NULL;
339                         return;
340
341                 }
342                 pcode[3] = '\0';
343                 irsp = atoi(pcode);
344
345                 if(irsp == 0)
346                 {
347                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
348                         fclose(LOCALFILE);
349                         LOCALFILE = NULL;
350                         return;
351                 }
352                 if(irsp==200)
353                 {
354                         do
355                         {
356                                 p = GetHTTPLine();
357                                 if(p==NULL)
358                                 {
359                                         m_State = HTTP_STATE_UNKNOWN_ERROR;     
360                                         fclose(LOCALFILE);
361                                         LOCALFILE = NULL;
362                                         return;
363                                 }
364                                 if(*p=='\0')
365                                 {
366                                         break;
367                                 }
368                                 if(SDL_strncasecmp(p,"Content-Length:",strlen("Content-Length:"))==0)
369                                 {
370                                         char *s = SDL_strchr(p,' ')+1;
371                                         p = s;
372                                         if(s)
373                                         {
374                                                 while(*s)
375                                                 {
376                                                         if(!isdigit(*s))
377                                                         {
378                                                                 *s='\0';
379                                                         }
380                                                         s++;
381                                                 };
382                                                 m_iBytesTotal = atoi(p);
383                                         }
384
385                                 }
386
387                                 SDL_Delay(1);
388                         }while(true);
389                 ReadDataChannel();
390                 return;
391                 }
392                 m_State = HTTP_STATE_FILE_NOT_FOUND;
393                 fclose(LOCALFILE);
394                 LOCALFILE = NULL;
395                 return;
396         }
397         else
398         {
399                 m_State = HTTP_STATE_UNKNOWN_ERROR;
400                 fclose(LOCALFILE);
401                 LOCALFILE = NULL;
402                 return;
403         }
404 }
405
406 int ChttpGet::ConnectSocket()
407 {
408         in_addr_t ip;
409         struct servent *se;
410         struct sockaddr_in hostaddr;
411         if(m_Aborting){
412                 return 0;
413         }
414         
415         ip = inet_addr((const char *)m_szHost);
416
417         int rcode = 0;
418         if(ip==INADDR_NONE)
419         {
420                 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);          
421                 do
422                 {       
423                         if(m_Aborting)
424                         {
425                                 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
426                                 return 0;
427                         }
428                         rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
429
430                         SDL_Delay(1);
431                 }while(rcode==0);
432         }
433         
434         if(rcode == -1)
435         {
436                 m_State = HTTP_STATE_HOST_NOT_FOUND;
437                 return 0;
438         }
439         //m_ControlSock
440         if(m_Aborting)
441                 return 0;
442         se = getservbyname("http", NULL);
443         if(m_Aborting)
444                 return 0;
445         if(se == NULL)
446         {
447                 hostaddr.sin_port = htons(80);
448         }
449         else
450         {
451                 hostaddr.sin_port = se->s_port;
452         }
453         hostaddr.sin_family = AF_INET;          
454         //ip = htonl(ip);
455         hostaddr.sin_addr.s_addr = ip;
456
457         if(m_ProxyEnabled)
458         {
459                 //This is on a proxy, so we need to make sure to connect to the proxy machine
460                 ip = inet_addr((const char *)m_ProxyIP);
461                                 
462                 if(ip==INADDR_NONE)
463                 {
464                         http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
465
466                         do
467                         {       
468                                 if(m_Aborting)
469                                 {
470                                         http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
471                                         return 0;
472                                 }
473                                 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
474
475                                 SDL_Delay(1);
476                         }while(rcode==0);
477                         
478                         
479                         if(rcode == -1)
480                         {
481                                 m_State = HTTP_STATE_HOST_NOT_FOUND;
482                                 return 0;
483                         }
484
485                 }
486                 //Use either the proxy port or 80 if none specified
487                 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
488                 //Copy the proxy address...
489                 hostaddr.sin_addr.s_addr = ip;
490
491         }
492         //Now we will connect to the host                                       
493         fd_set  wfds;
494
495         timeval timeout;
496         timeout.tv_sec = 0;
497         timeout.tv_usec = 0;
498         int serr = connect(m_DataSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr));
499         int cerr = WSAGetLastError();
500         if(serr)
501         {
502                 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||NETCALL_WOULDBLOCK(cerr))
503                 {
504                         FD_ZERO(&wfds);
505                         FD_SET( m_DataSock, &wfds );
506                         if(select(m_DataSock+1,NULL,&wfds,NULL,&timeout))
507                         {
508                                 serr = 0;
509                                 break;
510                         }
511                         if(m_Aborting)
512                                 return 0;
513                         serr = connect(m_DataSock, (struct sockaddr *)&hostaddr, sizeof(struct sockaddr));
514                         if(serr == 0)
515                                 break;
516                         cerr = WSAGetLastError();
517                         if(cerr==WSAEISCONN)
518                         {
519                                 serr = 0;
520                                 break;
521                         }
522
523                         SDL_Delay(1);
524                 };
525         }
526         if(serr)
527         {
528                 m_State = HTTP_STATE_CANT_CONNECT;
529                 return 0;
530         }
531         m_State = HTTP_STATE_CONNECTED;
532         return 1;
533 }
534
535 char *ChttpGet::GetHTTPLine()
536 {
537         int iBytesRead;
538         char chunk[2];
539         unsigned int igotcrlf = 0;
540         memset(recv_buffer,0,1000);
541         do
542         {
543                 chunk[0]='\0';
544                 bool gotdata = false;
545                 do
546                 {
547                         iBytesRead = recv(m_DataSock,chunk,1,0);
548
549                         if(SOCKET_ERROR == iBytesRead)
550                         {       
551                                 int error = WSAGetLastError();
552                                 if(NETCALL_WOULDBLOCK(error))
553                                 {
554                                         gotdata = false;
555                                         continue;
556                                 }
557                                 else
558                                         return NULL;
559                         }
560                         else
561                         {
562                                 gotdata = true;
563                         }
564
565                         SDL_Delay(1);
566                 }while(!gotdata);
567                 
568                 if(chunk[0]==0x0d)
569                 {
570                         //This should always read a 0x0a
571                         do
572                         {
573                                 iBytesRead = recv(m_DataSock,chunk,1,0);
574
575                                 if(SOCKET_ERROR == iBytesRead)
576                                 {       
577                                         int error = WSAGetLastError();
578                                         if(NETCALL_WOULDBLOCK(error))
579                                         {
580                                                 gotdata = false;
581                                                 continue;
582                                         }
583                                         else
584                                                 return NULL;
585                                 }
586                                 else
587                                 {
588                                         gotdata = true;
589                                 }
590
591                                 SDL_Delay(1);
592                         }while(!gotdata);
593                         igotcrlf = 1;   
594                 }
595                 else
596                 {       chunk[1] = '\0';
597                         SDL_strlcat(recv_buffer, chunk, SDL_arraysize(recv_buffer));
598                 }
599                 
600                 SDL_Delay(1);
601         }while(igotcrlf==0);
602         return recv_buffer;     
603 }
604
605 unsigned int ChttpGet::ReadDataChannel()
606 {
607         char sDataBuffer[4096];         // Data-storage buffer for the data channel
608         int nBytesRecv = 0;                                             // Bytes received from the data channel
609
610         fd_set  wfds;
611
612         timeval timeout;
613         timeout.tv_sec = 0;
614         timeout.tv_usec = 500;
615
616         m_State = HTTP_STATE_RECEIVING;                 
617    do   
618    {
619                 FD_ZERO(&wfds);
620                 FD_SET( m_DataSock, &wfds );
621
622                 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
623                 {
624                         break;
625                 }
626                 select(m_DataSock+1,&wfds,NULL,NULL,&timeout);
627         if(m_Aborting)
628                 {
629                         fclose(LOCALFILE);
630                         LOCALFILE = NULL;
631                         return 0;               
632                 }
633                 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
634         if(m_Aborting)
635                 {
636                         fclose(LOCALFILE);
637                         LOCALFILE = NULL;
638                         return 0;
639                 }
640                 if(SOCKET_ERROR == nBytesRecv)
641                 {       
642                         int error = WSAGetLastError();
643                         if(NETCALL_WOULDBLOCK(error))
644                         {
645                                 nBytesRecv = 1;
646                                 continue;
647                         }
648                 }
649                 m_iBytesIn += nBytesRecv;
650                 if (nBytesRecv > 0 )
651                 {
652                         fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
653                         //Write sDataBuffer, nBytesRecv
654         }
655                 
656                 SDL_Delay(1);
657         }while (nBytesRecv > 0);
658         fclose(LOCALFILE);
659         LOCALFILE = NULL;
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         in_addr_t 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(in_addr_t *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                 newaslu->ip = 0;
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                         *ip = httpaslu.ip;
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                 lookup->ip = ((in_addr *)(he->h_addr))->s_addr;
755                 lookup->done = true;
756                 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));
757         }
758         free(lookup);
759
760         return 0;
761 }