2 * $Logfile: /Freespace2/code/Inetfile/Chttpget.cpp $
7 * HTTP Client class (get only)
10 * Revision 1.1 2002/05/03 03:28:09 root
14 * 5 8/24/99 1:49a Dave
15 * Fixed client-side afterburner stuttering. Added checkbox for no version
16 * checking on PXO join. Made button info passing more friendly between
19 * 4 8/22/99 1:19p Dave
20 * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
21 * which d3d cards are detected.
23 * 21 8/21/99 6:33p Kevin
26 * 20 8/21/99 6:48a Jeff
29 * 19 8/20/99 3:01p Kevin
30 * Added support for Proxies (I hope!)
32 * 18 8/15/99 6:38p Jeff
35 * 17 8/15/99 6:26p Kevin
37 * 16 4/14/99 1:20a Jeff
38 * fixed case mismatched #includes
40 * 15 3/03/99 12:28a Nate
41 * sped up something or other when the connection is done
43 * 14 2/03/99 4:20p Kevin
44 * Got multiplayer working with .mn3 files, and setup autodownloading
46 * 13 1/27/99 5:49p Kevin
48 * 12 1/27/99 5:38p Kevin
50 * 11 12/30/98 12:15p Kevin
51 * Auto Mission Download system
53 * 10 10/12/98 4:59p Kevin
54 * Added delay to thread when cancelled...
56 * 9 10/12/98 4:49p Nate
59 * 8 10/12/98 1:54p Nate
62 * 7 10/12/98 11:30a Kevin
65 * 6 10/08/98 12:59p Nate
68 * 5 10/08/98 9:57a Kevin
69 * made transfer cancellable
71 * 4 7/31/98 12:19p Nate
72 * Fixed http abort problem.
74 * 3 7/31/98 11:57a Kevin
75 * Added new functions for getting state
77 * 2 6/01/98 10:10a Kevin
78 * Added DLL connection interface and auto update DLL
80 * 1 5/27/98 9:52a Kevin
82 * 1 5/25/98 5:31p Kevin
99 #include "inetgetfile.h"
100 #include "chttpget.h"
104 inline void Sleep(int millis)
108 tv.tv_usec = millis*1000;
109 select(0,NULL,NULL,NULL,&tv);
113 #define NW_AGHBN_CANCEL 1
114 #define NW_AGHBN_LOOKUP 2
115 #define NW_AGHBN_READ 3
118 void __cdecl http_gethostbynameworker(void *parm);
120 void *http_gethostbynameworker(void *parm);
123 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname);
126 void HTTPObjThread( void * obj )
128 void *HTTPObjThread( void * obj )
131 ((ChttpGet *)obj)->WorkerThread();
132 ((ChttpGet *)obj)->m_Aborted = true;
133 //OutputDebugString("http transfer exiting....\n");
140 void ChttpGet::AbortGet()
143 OutputDebugString("Aborting....\n");
146 while(!m_Aborted) Sleep(50); //Wait for the thread to end
148 OutputDebugString("Aborted....\n");
152 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
154 m_ProxyEnabled = true;
156 m_ProxyPort = proxyport;
157 GetFile(URL,localfile);
160 ChttpGet::ChttpGet(char *URL,char *localfile)
162 m_ProxyEnabled = false;
163 GetFile(URL,localfile);
167 void ChttpGet::GetFile(char *URL,char *localfile)
169 m_DataSock = INVALID_SOCKET;
172 m_State = HTTP_STATE_STARTUP;;
176 strncpy(m_URL,URL,MAX_URL_LEN-1);
177 m_URL[MAX_URL_LEN-1] = 0;
179 LOCALFILE = fopen(localfile,"wb");
180 if(NULL == LOCALFILE)
182 m_State = HTTP_STATE_CANT_WRITE_FILE;
185 m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
186 if(INVALID_SOCKET == m_DataSock)
188 m_State = HTTP_STATE_SOCKET_ERROR;
195 ioctlsocket( m_DataSock, FIONBIO, &arg );
197 ioctl( m_DataSock, FIONBIO, &arg );
201 if(strnicmp(URL,"http:",5)==0)
209 //There shouldn't be any : in this string
212 m_State = HTTP_STATE_URL_PARSING_ERROR;
215 //read the filename by searching backwards for a /
216 //then keep reading until you find the first /
217 //when you found it, you have the host and dir
218 char *filestart = NULL;
219 char *dirstart = NULL;
220 for(int i = strlen(pURL);i>=0;i--)
226 filestart = pURL+i+1;
228 strcpy(m_szFilename,filestart);
236 if((dirstart==NULL) || (filestart==NULL))
238 m_State = HTTP_STATE_URL_PARSING_ERROR;
243 strcpy(m_szDir,dirstart);//,(filestart-dirstart));
244 //m_szDir[(filestart-dirstart)] = NULL;
245 strncpy(m_szHost,pURL,(dirstart-pURL));
246 m_szHost[(dirstart-pURL)-1] = '\0';
249 if(NULL==_beginthread(HTTPObjThread,0,this))
251 m_State = HTTP_STATE_INTERNAL_ERROR;
255 #elif defined(__LINUX__)
257 if(!inet_LoadThreadLib())
259 m_State = HTTP_STATE_INTERNAL_ERROR;
262 if(df_pthread_create(&thread,NULL,HTTPObjThread,this)!=0)
264 m_State = HTTP_STATE_INTERNAL_ERROR;
272 ChttpGet::~ChttpGet()
274 if(m_DataSock != INVALID_SOCKET)
276 shutdown(m_DataSock,2);
278 closesocket(m_DataSock);
285 int ChttpGet::GetStatus()
290 unsigned int ChttpGet::GetBytesIn()
295 unsigned int ChttpGet::GetTotalBytes()
297 return m_iBytesTotal;
301 void ChttpGet::WorkerThread()
303 char szCommand[1000];
312 if(m_State != HTTP_STATE_CONNECTED)
317 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);
318 send(m_DataSock,szCommand,strlen(szCommand),0);
320 if(strnicmp("HTTP/",p,5)==0)
323 pcode = strchr(p,' ')+1;
326 m_State = HTTP_STATE_UNKNOWN_ERROR;
336 m_State = HTTP_STATE_UNKNOWN_ERROR;
348 m_State = HTTP_STATE_UNKNOWN_ERROR;
357 if(strnicmp(p,"Content-Length:",strlen("Content-Length:"))==0)
359 char *s = strchr(p,' ')+1;
371 m_iBytesTotal = atoi(p);
381 m_State = HTTP_STATE_FILE_NOT_FOUND;
387 m_State = HTTP_STATE_UNKNOWN_ERROR;
393 int ChttpGet::ConnectSocket()
398 SOCKADDR_IN hostaddr;
403 ip = inet_addr((const char *)m_szHost);
408 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);
413 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
416 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
424 m_State = HTTP_STATE_HOST_NOT_FOUND;
430 se = getservbyname("http", NULL);
435 hostaddr.sin_port = htons(80);
439 hostaddr.sin_port = se->s_port;
441 hostaddr.sin_family = AF_INET;
443 memcpy(&hostaddr.sin_addr,&ip,4);
447 //This is on a proxy, so we need to make sure to connect to the proxy machine
448 ip = inet_addr((const char *)m_ProxyIP);
452 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
458 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
461 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
469 m_State = HTTP_STATE_HOST_NOT_FOUND;
474 //Use either the proxy port or 80 if none specified
475 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
476 //Copy the proxy address...
477 memcpy(&hostaddr.sin_addr,&ip,4);
480 //Now we will connect to the host
486 int serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
487 int cerr = WSAGetLastError();
490 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
493 FD_SET( m_DataSock, &wfds );
494 if(select(0,NULL,&wfds,NULL,&timeout))
501 serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
504 cerr = WSAGetLastError();
516 m_State = HTTP_STATE_CANT_CONNECT;
519 m_State = HTTP_STATE_CONNECTED;
523 char *ChttpGet::GetHTTPLine()
525 unsigned int iBytesRead;
527 unsigned int igotcrlf = 0;
528 memset(recv_buffer,0,1000);
532 bool gotdata = false;
535 iBytesRead = recv(m_DataSock,chunk,1,0);
537 if(SOCKET_ERROR == iBytesRead)
539 int error = WSAGetLastError();
540 if(WSAEWOULDBLOCK==error)
558 //This should always read a 0x0a
561 iBytesRead = recv(m_DataSock,chunk,1,0);
563 if(SOCKET_ERROR == iBytesRead)
565 int error = WSAGetLastError();
566 if(WSAEWOULDBLOCK==error)
585 strcat(recv_buffer,chunk);
593 unsigned int ChttpGet::ReadDataChannel()
595 char sDataBuffer[4096]; // Data-storage buffer for the data channel
596 int nBytesRecv = 0; // Bytes received from the data channel
602 timeout.tv_usec = 500;
604 m_State = HTTP_STATE_RECEIVING;
608 FD_SET( m_DataSock, &wfds );
610 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
614 select(0,&wfds,NULL,NULL,&timeout);
620 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
626 if(SOCKET_ERROR == nBytesRecv)
628 int error = WSAGetLastError();
629 if(WSAEWOULDBLOCK==error)
635 m_iBytesIn += nBytesRecv;
638 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
639 //Write sDataBuffer, nBytesRecv
643 }while (nBytesRecv > 0);
645 // Close the file and check for error returns.
646 if (nBytesRecv == SOCKET_ERROR)
648 //Ok, we got a socket error -- xfer aborted?
649 m_State = HTTP_STATE_RECV_FAILED;
654 //OutputDebugString("HTTP File complete!\n");
656 m_State = HTTP_STATE_FILE_RECEIVED;
662 typedef struct _async_dns_lookup
664 unsigned int ip; //resolved host. Write only to worker thread.
665 char * host;//host name to resolve. read only to worker thread
666 bool done; //write only to the worker thread. Signals that the operation is complete
667 bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
668 bool abort; //read only to worker thread. If this is set, don't fill in the struct.
671 async_dns_lookup httpaslu;
672 async_dns_lookup *http_lastaslu = NULL;
675 void __cdecl http_gethostbynameworker(void *parm);
677 void *http_gethostbynameworker(void *parm);
680 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
683 if(command==NW_AGHBN_LOOKUP)
686 http_lastaslu->abort = true;
688 async_dns_lookup *newaslu;
689 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
690 memset(&newaslu->ip,0,sizeof(unsigned int));
691 newaslu->host = hostname;
692 newaslu->done = false;
693 newaslu->error = false;
694 newaslu->abort = false;
695 http_lastaslu = newaslu;
696 httpaslu.done = false;
699 _beginthread(http_gethostbynameworker,0,newaslu);
701 #elif defined(__LINUX__)
703 if(!inet_LoadThreadLib())
708 df_pthread_create(&thread,NULL,http_gethostbynameworker,newaslu);
713 else if(command==NW_AGHBN_CANCEL)
716 http_lastaslu->abort = true;
717 http_lastaslu = NULL;
719 else if(command==NW_AGHBN_READ)
725 //free(http_lastaslu);
726 http_lastaslu = NULL;
727 memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
730 else if(httpaslu.error)
733 http_lastaslu = NULL;
742 // This is the worker thread which does the lookup.
744 void __cdecl http_gethostbynameworker(void *parm)
746 void *http_gethostbynameworker(void *parm)
750 df_pthread_detach(df_pthread_self());
752 async_dns_lookup *lookup = (async_dns_lookup *)parm;
753 HOSTENT *he = gethostbyname(lookup->host);
756 lookup->error = true;
763 else if(!lookup->abort)
765 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
767 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));