2 * $Logfile: /Freespace2/code/Inetfile/Chttpget.cpp $
7 * HTTP Client class (get only)
10 * Revision 1.2 2002/05/07 03:16:45 theoddone33
11 * The Great Newline Fix
13 * Revision 1.1.1.1 2002/05/03 03:28:09 root
17 * 5 8/24/99 1:49a Dave
18 * Fixed client-side afterburner stuttering. Added checkbox for no version
19 * checking on PXO join. Made button info passing more friendly between
22 * 4 8/22/99 1:19p Dave
23 * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
24 * which d3d cards are detected.
26 * 21 8/21/99 6:33p Kevin
29 * 20 8/21/99 6:48a Jeff
32 * 19 8/20/99 3:01p Kevin
33 * Added support for Proxies (I hope!)
35 * 18 8/15/99 6:38p Jeff
38 * 17 8/15/99 6:26p Kevin
40 * 16 4/14/99 1:20a Jeff
41 * fixed case mismatched #includes
43 * 15 3/03/99 12:28a Nate
44 * sped up something or other when the connection is done
46 * 14 2/03/99 4:20p Kevin
47 * Got multiplayer working with .mn3 files, and setup autodownloading
49 * 13 1/27/99 5:49p Kevin
51 * 12 1/27/99 5:38p Kevin
53 * 11 12/30/98 12:15p Kevin
54 * Auto Mission Download system
56 * 10 10/12/98 4:59p Kevin
57 * Added delay to thread when cancelled...
59 * 9 10/12/98 4:49p Nate
62 * 8 10/12/98 1:54p Nate
65 * 7 10/12/98 11:30a Kevin
68 * 6 10/08/98 12:59p Nate
71 * 5 10/08/98 9:57a Kevin
72 * made transfer cancellable
74 * 4 7/31/98 12:19p Nate
75 * Fixed http abort problem.
77 * 3 7/31/98 11:57a Kevin
78 * Added new functions for getting state
80 * 2 6/01/98 10:10a Kevin
81 * Added DLL connection interface and auto update DLL
83 * 1 5/27/98 9:52a Kevin
85 * 1 5/25/98 5:31p Kevin
102 #include "inetgetfile.h"
103 #include "chttpget.h"
107 inline void Sleep(int millis)
111 tv.tv_usec = millis*1000;
112 select(0,NULL,NULL,NULL,&tv);
116 #define NW_AGHBN_CANCEL 1
117 #define NW_AGHBN_LOOKUP 2
118 #define NW_AGHBN_READ 3
121 void __cdecl http_gethostbynameworker(void *parm);
123 void *http_gethostbynameworker(void *parm);
126 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname);
129 void HTTPObjThread( void * obj )
131 void *HTTPObjThread( void * obj )
134 ((ChttpGet *)obj)->WorkerThread();
135 ((ChttpGet *)obj)->m_Aborted = true;
136 //OutputDebugString("http transfer exiting....\n");
143 void ChttpGet::AbortGet()
146 OutputDebugString("Aborting....\n");
149 while(!m_Aborted) Sleep(50); //Wait for the thread to end
151 OutputDebugString("Aborted....\n");
155 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
157 m_ProxyEnabled = true;
159 m_ProxyPort = proxyport;
160 GetFile(URL,localfile);
163 ChttpGet::ChttpGet(char *URL,char *localfile)
165 m_ProxyEnabled = false;
166 GetFile(URL,localfile);
170 void ChttpGet::GetFile(char *URL,char *localfile)
172 m_DataSock = INVALID_SOCKET;
175 m_State = HTTP_STATE_STARTUP;;
179 strncpy(m_URL,URL,MAX_URL_LEN-1);
180 m_URL[MAX_URL_LEN-1] = 0;
182 LOCALFILE = fopen(localfile,"wb");
183 if(NULL == LOCALFILE)
185 m_State = HTTP_STATE_CANT_WRITE_FILE;
188 m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
189 if(INVALID_SOCKET == m_DataSock)
191 m_State = HTTP_STATE_SOCKET_ERROR;
198 ioctlsocket( m_DataSock, FIONBIO, &arg );
200 ioctl( m_DataSock, FIONBIO, &arg );
204 if(strnicmp(URL,"http:",5)==0)
212 //There shouldn't be any : in this string
215 m_State = HTTP_STATE_URL_PARSING_ERROR;
218 //read the filename by searching backwards for a /
219 //then keep reading until you find the first /
220 //when you found it, you have the host and dir
221 char *filestart = NULL;
222 char *dirstart = NULL;
223 for(int i = strlen(pURL);i>=0;i--)
229 filestart = pURL+i+1;
231 strcpy(m_szFilename,filestart);
239 if((dirstart==NULL) || (filestart==NULL))
241 m_State = HTTP_STATE_URL_PARSING_ERROR;
246 strcpy(m_szDir,dirstart);//,(filestart-dirstart));
247 //m_szDir[(filestart-dirstart)] = NULL;
248 strncpy(m_szHost,pURL,(dirstart-pURL));
249 m_szHost[(dirstart-pURL)-1] = '\0';
252 if(NULL==_beginthread(HTTPObjThread,0,this))
254 m_State = HTTP_STATE_INTERNAL_ERROR;
258 #elif defined(__LINUX__)
260 if(!inet_LoadThreadLib())
262 m_State = HTTP_STATE_INTERNAL_ERROR;
265 if(df_pthread_create(&thread,NULL,HTTPObjThread,this)!=0)
267 m_State = HTTP_STATE_INTERNAL_ERROR;
275 ChttpGet::~ChttpGet()
277 if(m_DataSock != INVALID_SOCKET)
279 shutdown(m_DataSock,2);
281 closesocket(m_DataSock);
288 int ChttpGet::GetStatus()
293 unsigned int ChttpGet::GetBytesIn()
298 unsigned int ChttpGet::GetTotalBytes()
300 return m_iBytesTotal;
304 void ChttpGet::WorkerThread()
306 char szCommand[1000];
315 if(m_State != HTTP_STATE_CONNECTED)
320 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);
321 send(m_DataSock,szCommand,strlen(szCommand),0);
323 if(strnicmp("HTTP/",p,5)==0)
326 pcode = strchr(p,' ')+1;
329 m_State = HTTP_STATE_UNKNOWN_ERROR;
339 m_State = HTTP_STATE_UNKNOWN_ERROR;
351 m_State = HTTP_STATE_UNKNOWN_ERROR;
360 if(strnicmp(p,"Content-Length:",strlen("Content-Length:"))==0)
362 char *s = strchr(p,' ')+1;
374 m_iBytesTotal = atoi(p);
384 m_State = HTTP_STATE_FILE_NOT_FOUND;
390 m_State = HTTP_STATE_UNKNOWN_ERROR;
396 int ChttpGet::ConnectSocket()
401 SOCKADDR_IN hostaddr;
406 ip = inet_addr((const char *)m_szHost);
411 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);
416 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
419 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
427 m_State = HTTP_STATE_HOST_NOT_FOUND;
433 se = getservbyname("http", NULL);
438 hostaddr.sin_port = htons(80);
442 hostaddr.sin_port = se->s_port;
444 hostaddr.sin_family = AF_INET;
446 memcpy(&hostaddr.sin_addr,&ip,4);
450 //This is on a proxy, so we need to make sure to connect to the proxy machine
451 ip = inet_addr((const char *)m_ProxyIP);
455 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
461 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
464 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
472 m_State = HTTP_STATE_HOST_NOT_FOUND;
477 //Use either the proxy port or 80 if none specified
478 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
479 //Copy the proxy address...
480 memcpy(&hostaddr.sin_addr,&ip,4);
483 //Now we will connect to the host
489 int serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
490 int cerr = WSAGetLastError();
493 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
496 FD_SET( m_DataSock, &wfds );
497 if(select(0,NULL,&wfds,NULL,&timeout))
504 serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
507 cerr = WSAGetLastError();
519 m_State = HTTP_STATE_CANT_CONNECT;
522 m_State = HTTP_STATE_CONNECTED;
526 char *ChttpGet::GetHTTPLine()
528 unsigned int iBytesRead;
530 unsigned int igotcrlf = 0;
531 memset(recv_buffer,0,1000);
535 bool gotdata = false;
538 iBytesRead = recv(m_DataSock,chunk,1,0);
540 if(SOCKET_ERROR == iBytesRead)
542 int error = WSAGetLastError();
543 if(WSAEWOULDBLOCK==error)
561 //This should always read a 0x0a
564 iBytesRead = recv(m_DataSock,chunk,1,0);
566 if(SOCKET_ERROR == iBytesRead)
568 int error = WSAGetLastError();
569 if(WSAEWOULDBLOCK==error)
588 strcat(recv_buffer,chunk);
596 unsigned int ChttpGet::ReadDataChannel()
598 char sDataBuffer[4096]; // Data-storage buffer for the data channel
599 int nBytesRecv = 0; // Bytes received from the data channel
605 timeout.tv_usec = 500;
607 m_State = HTTP_STATE_RECEIVING;
611 FD_SET( m_DataSock, &wfds );
613 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
617 select(0,&wfds,NULL,NULL,&timeout);
623 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
629 if(SOCKET_ERROR == nBytesRecv)
631 int error = WSAGetLastError();
632 if(WSAEWOULDBLOCK==error)
638 m_iBytesIn += nBytesRecv;
641 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
642 //Write sDataBuffer, nBytesRecv
646 }while (nBytesRecv > 0);
648 // Close the file and check for error returns.
649 if (nBytesRecv == SOCKET_ERROR)
651 //Ok, we got a socket error -- xfer aborted?
652 m_State = HTTP_STATE_RECV_FAILED;
657 //OutputDebugString("HTTP File complete!\n");
659 m_State = HTTP_STATE_FILE_RECEIVED;
665 typedef struct _async_dns_lookup
667 unsigned int ip; //resolved host. Write only to worker thread.
668 char * host;//host name to resolve. read only to worker thread
669 bool done; //write only to the worker thread. Signals that the operation is complete
670 bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
671 bool abort; //read only to worker thread. If this is set, don't fill in the struct.
674 async_dns_lookup httpaslu;
675 async_dns_lookup *http_lastaslu = NULL;
678 void __cdecl http_gethostbynameworker(void *parm);
680 void *http_gethostbynameworker(void *parm);
683 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
686 if(command==NW_AGHBN_LOOKUP)
689 http_lastaslu->abort = true;
691 async_dns_lookup *newaslu;
692 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
693 memset(&newaslu->ip,0,sizeof(unsigned int));
694 newaslu->host = hostname;
695 newaslu->done = false;
696 newaslu->error = false;
697 newaslu->abort = false;
698 http_lastaslu = newaslu;
699 httpaslu.done = false;
702 _beginthread(http_gethostbynameworker,0,newaslu);
704 #elif defined(__LINUX__)
706 if(!inet_LoadThreadLib())
711 df_pthread_create(&thread,NULL,http_gethostbynameworker,newaslu);
716 else if(command==NW_AGHBN_CANCEL)
719 http_lastaslu->abort = true;
720 http_lastaslu = NULL;
722 else if(command==NW_AGHBN_READ)
728 //free(http_lastaslu);
729 http_lastaslu = NULL;
730 memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
733 else if(httpaslu.error)
736 http_lastaslu = NULL;
745 // This is the worker thread which does the lookup.
747 void __cdecl http_gethostbynameworker(void *parm)
749 void *http_gethostbynameworker(void *parm)
753 df_pthread_detach(df_pthread_self());
755 async_dns_lookup *lookup = (async_dns_lookup *)parm;
756 HOSTENT *he = gethostbyname(lookup->host);
759 lookup->error = true;
766 else if(!lookup->abort)
768 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
770 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));