2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
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
10 * $Logfile: /Freespace2/code/Inetfile/Chttpget.cpp $
15 * HTTP Client class (get only)
18 * Revision 1.8 2002/06/21 03:04:12 relnev
21 * Revision 1.7 2002/06/17 06:33:09 relnev
22 * ryan's struct patch for gcc 2.95
24 * Revision 1.6 2002/06/09 04:41:21 relnev
25 * added copyright header
27 * Revision 1.5 2002/06/02 04:26:34 relnev
30 * Revision 1.4 2002/05/26 20:32:24 theoddone33
31 * Fix some minor stuff
33 * Revision 1.3 2002/05/26 20:20:54 relnev
38 * Revision 1.2 2002/05/07 03:16:45 theoddone33
39 * The Great Newline Fix
41 * Revision 1.1.1.1 2002/05/03 03:28:09 root
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
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.
54 * 21 8/21/99 6:33p Kevin
57 * 20 8/21/99 6:48a Jeff
60 * 19 8/20/99 3:01p Kevin
61 * Added support for Proxies (I hope!)
63 * 18 8/15/99 6:38p Jeff
66 * 17 8/15/99 6:26p Kevin
68 * 16 4/14/99 1:20a Jeff
69 * fixed case mismatched #includes
71 * 15 3/03/99 12:28a Nate
72 * sped up something or other when the connection is done
74 * 14 2/03/99 4:20p Kevin
75 * Got multiplayer working with .mn3 files, and setup autodownloading
77 * 13 1/27/99 5:49p Kevin
79 * 12 1/27/99 5:38p Kevin
81 * 11 12/30/98 12:15p Kevin
82 * Auto Mission Download system
84 * 10 10/12/98 4:59p Kevin
85 * Added delay to thread when cancelled...
87 * 9 10/12/98 4:49p Nate
90 * 8 10/12/98 1:54p Nate
93 * 7 10/12/98 11:30a Kevin
96 * 6 10/08/98 12:59p Nate
99 * 5 10/08/98 9:57a Kevin
100 * made transfer cancellable
102 * 4 7/31/98 12:19p Nate
103 * Fixed http abort problem.
105 * 3 7/31/98 11:57a Kevin
106 * Added new functions for getting state
108 * 2 6/01/98 10:10a Kevin
109 * Added DLL connection interface and auto update DLL
111 * 1 5/27/98 9:52a Kevin
113 * 1 5/25/98 5:31p Kevin
119 #ifndef PLAT_UNIX // this isn't working yet (really only needed by PXO anyway)
129 #include <sys/types.h>
130 #include <sys/socket.h>
131 #include <netinet/in.h>
132 #include <arpa/inet.h>
134 #include <sys/ioctl.h>
136 #include <sys/time.h>
148 #include "inetgetfile.h"
149 #include "chttpget.h"
153 inline void Sleep(int millis)
157 tv.tv_usec = millis*1000;
158 select(0,NULL,NULL,NULL,&tv);
162 #define NW_AGHBN_CANCEL 1
163 #define NW_AGHBN_LOOKUP 2
164 #define NW_AGHBN_READ 3
167 void __cdecl http_gethostbynameworker(void *parm);
169 void *http_gethostbynameworker(void *parm);
172 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname);
175 void HTTPObjThread( void * obj )
177 void *HTTPObjThread( void * obj )
180 ((ChttpGet *)obj)->WorkerThread();
181 ((ChttpGet *)obj)->m_Aborted = true;
182 //OutputDebugString("http transfer exiting....\n");
189 void ChttpGet::AbortGet()
192 OutputDebugString("Aborting....\n");
195 while(!m_Aborted) Sleep(50); //Wait for the thread to end
197 OutputDebugString("Aborted....\n");
201 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
203 m_ProxyEnabled = true;
205 m_ProxyPort = proxyport;
206 GetFile(URL,localfile);
209 ChttpGet::ChttpGet(char *URL,char *localfile)
211 m_ProxyEnabled = false;
212 GetFile(URL,localfile);
216 void ChttpGet::GetFile(char *URL,char *localfile)
218 m_DataSock = INVALID_SOCKET;
221 m_State = HTTP_STATE_STARTUP;;
225 strncpy(m_URL,URL,MAX_URL_LEN-1);
226 m_URL[MAX_URL_LEN-1] = 0;
228 LOCALFILE = fopen(localfile,"wb");
229 if(NULL == LOCALFILE)
231 m_State = HTTP_STATE_CANT_WRITE_FILE;
234 m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
235 if(INVALID_SOCKET == m_DataSock)
237 m_State = HTTP_STATE_SOCKET_ERROR;
245 ioctlsocket( m_DataSock, FIONBIO, &arg );
247 ioctl( m_DataSock, FIONBIO, &arg );
251 if(strnicmp(URL,"http:",5)==0)
259 //There shouldn't be any : in this string
262 m_State = HTTP_STATE_URL_PARSING_ERROR;
265 //read the filename by searching backwards for a /
266 //then keep reading until you find the first /
267 //when you found it, you have the host and dir
268 char *filestart = NULL;
269 char *dirstart = NULL;
270 for(int i = strlen(pURL);i>=0;i--)
276 filestart = pURL+i+1;
278 strcpy(m_szFilename,filestart);
286 if((dirstart==NULL) || (filestart==NULL))
288 m_State = HTTP_STATE_URL_PARSING_ERROR;
293 strcpy(m_szDir,dirstart);//,(filestart-dirstart));
294 //m_szDir[(filestart-dirstart)] = NULL;
295 strncpy(m_szHost,pURL,(dirstart-pURL));
296 m_szHost[(dirstart-pURL)-1] = '\0';
299 if(0==_beginthread(HTTPObjThread,0,this))
301 m_State = HTTP_STATE_INTERNAL_ERROR;
305 #elif defined(__LINUX__)
307 if(!inet_LoadThreadLib())
309 m_State = HTTP_STATE_INTERNAL_ERROR;
312 if(df_pthread_create(&thread,NULL,HTTPObjThread,this)!=0)
314 m_State = HTTP_STATE_INTERNAL_ERROR;
322 ChttpGet::~ChttpGet()
324 if(m_DataSock != INVALID_SOCKET)
326 shutdown(m_DataSock,2);
328 closesocket(m_DataSock);
335 int ChttpGet::GetStatus()
340 unsigned int ChttpGet::GetBytesIn()
345 unsigned int ChttpGet::GetTotalBytes()
347 return m_iBytesTotal;
351 void ChttpGet::WorkerThread()
353 char szCommand[1000];
362 if(m_State != HTTP_STATE_CONNECTED)
367 sprintf(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);
368 send(m_DataSock,szCommand,strlen(szCommand),0);
370 if(strnicmp("HTTP/",p,5)==0)
373 pcode = strchr(p,' ')+1;
376 m_State = HTTP_STATE_UNKNOWN_ERROR;
386 m_State = HTTP_STATE_UNKNOWN_ERROR;
398 m_State = HTTP_STATE_UNKNOWN_ERROR;
407 if(strnicmp(p,"Content-Length:",strlen("Content-Length:"))==0)
409 char *s = strchr(p,' ')+1;
421 m_iBytesTotal = atoi(p);
431 m_State = HTTP_STATE_FILE_NOT_FOUND;
437 m_State = HTTP_STATE_UNKNOWN_ERROR;
443 int ChttpGet::ConnectSocket()
448 SOCKADDR_IN hostaddr;
453 ip = inet_addr((const char *)m_szHost);
458 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);
463 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
466 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
474 m_State = HTTP_STATE_HOST_NOT_FOUND;
480 se = getservbyname("http", NULL);
485 hostaddr.sin_port = htons(80);
489 hostaddr.sin_port = se->s_port;
491 hostaddr.sin_family = AF_INET;
493 memcpy(&hostaddr.sin_addr,&ip,4);
497 //This is on a proxy, so we need to make sure to connect to the proxy machine
498 ip = inet_addr((const char *)m_ProxyIP);
502 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
508 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
511 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
519 m_State = HTTP_STATE_HOST_NOT_FOUND;
524 //Use either the proxy port or 80 if none specified
525 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
526 //Copy the proxy address...
527 memcpy(&hostaddr.sin_addr,&ip,4);
530 //Now we will connect to the host
536 int serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
537 int cerr = WSAGetLastError();
540 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
543 FD_SET( m_DataSock, &wfds );
544 if(select(0,NULL,&wfds,NULL,&timeout))
551 serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
554 cerr = WSAGetLastError();
566 m_State = HTTP_STATE_CANT_CONNECT;
569 m_State = HTTP_STATE_CONNECTED;
573 char *ChttpGet::GetHTTPLine()
577 unsigned int igotcrlf = 0;
578 memset(recv_buffer,0,1000);
582 bool gotdata = false;
585 iBytesRead = recv(m_DataSock,chunk,1,0);
587 if(SOCKET_ERROR == iBytesRead)
589 int error = WSAGetLastError();
590 if(WSAEWOULDBLOCK==error)
608 //This should always read a 0x0a
611 iBytesRead = recv(m_DataSock,chunk,1,0);
613 if(SOCKET_ERROR == iBytesRead)
615 int error = WSAGetLastError();
616 if(WSAEWOULDBLOCK==error)
635 strcat(recv_buffer,chunk);
643 unsigned int ChttpGet::ReadDataChannel()
645 char sDataBuffer[4096]; // Data-storage buffer for the data channel
646 int nBytesRecv = 0; // Bytes received from the data channel
652 timeout.tv_usec = 500;
654 m_State = HTTP_STATE_RECEIVING;
658 FD_SET( m_DataSock, &wfds );
660 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
664 select(0,&wfds,NULL,NULL,&timeout);
670 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
676 if(SOCKET_ERROR == nBytesRecv)
678 int error = WSAGetLastError();
679 if(WSAEWOULDBLOCK==error)
685 m_iBytesIn += nBytesRecv;
688 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
689 //Write sDataBuffer, nBytesRecv
693 }while (nBytesRecv > 0);
695 // Close the file and check for error returns.
696 if (nBytesRecv == SOCKET_ERROR)
698 //Ok, we got a socket error -- xfer aborted?
699 m_State = HTTP_STATE_RECV_FAILED;
704 //OutputDebugString("HTTP File complete!\n");
706 m_State = HTTP_STATE_FILE_RECEIVED;
712 typedef struct _async_dns_lookup
714 unsigned int ip; //resolved host. Write only to worker thread.
715 char * host;//host name to resolve. read only to worker thread
716 bool done; //write only to the worker thread. Signals that the operation is complete
717 bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
718 bool abort; //read only to worker thread. If this is set, don't fill in the struct.
721 async_dns_lookup httpaslu;
722 async_dns_lookup *http_lastaslu = NULL;
725 void __cdecl http_gethostbynameworker(void *parm);
727 void *http_gethostbynameworker(void *parm);
730 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
733 if(command==NW_AGHBN_LOOKUP)
736 http_lastaslu->abort = true;
738 async_dns_lookup *newaslu;
739 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
740 memset(&newaslu->ip,0,sizeof(unsigned int));
741 newaslu->host = hostname;
742 newaslu->done = false;
743 newaslu->error = false;
744 newaslu->abort = false;
745 http_lastaslu = newaslu;
746 httpaslu.done = false;
749 _beginthread(http_gethostbynameworker,0,newaslu);
751 #elif defined(__LINUX__)
753 if(!inet_LoadThreadLib())
758 df_pthread_create(&thread,NULL,http_gethostbynameworker,newaslu);
763 else if(command==NW_AGHBN_CANCEL)
766 http_lastaslu->abort = true;
767 http_lastaslu = NULL;
769 else if(command==NW_AGHBN_READ)
775 //free(http_lastaslu);
776 http_lastaslu = NULL;
777 memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
780 else if(httpaslu.error)
783 http_lastaslu = NULL;
792 // This is the worker thread which does the lookup.
794 void __cdecl http_gethostbynameworker(void *parm)
796 void *http_gethostbynameworker(void *parm)
800 df_pthread_detach(df_pthread_self());
802 async_dns_lookup *lookup = (async_dns_lookup *)parm;
803 HOSTENT *he = gethostbyname(lookup->host);
806 lookup->error = true;
813 else if(!lookup->abort)
815 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
817 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));