2 * $Logfile: /Freespace2/code/Inetfile/Chttpget.cpp $
7 * HTTP Client class (get only)
10 * Revision 1.4 2002/05/26 20:32:24 theoddone33
11 * Fix some minor stuff
13 * Revision 1.3 2002/05/26 20:20:54 relnev
18 * Revision 1.2 2002/05/07 03:16:45 theoddone33
19 * The Great Newline Fix
21 * Revision 1.1.1.1 2002/05/03 03:28:09 root
25 * 5 8/24/99 1:49a Dave
26 * Fixed client-side afterburner stuttering. Added checkbox for no version
27 * checking on PXO join. Made button info passing more friendly between
30 * 4 8/22/99 1:19p Dave
31 * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
32 * which d3d cards are detected.
34 * 21 8/21/99 6:33p Kevin
37 * 20 8/21/99 6:48a Jeff
40 * 19 8/20/99 3:01p Kevin
41 * Added support for Proxies (I hope!)
43 * 18 8/15/99 6:38p Jeff
46 * 17 8/15/99 6:26p Kevin
48 * 16 4/14/99 1:20a Jeff
49 * fixed case mismatched #includes
51 * 15 3/03/99 12:28a Nate
52 * sped up something or other when the connection is done
54 * 14 2/03/99 4:20p Kevin
55 * Got multiplayer working with .mn3 files, and setup autodownloading
57 * 13 1/27/99 5:49p Kevin
59 * 12 1/27/99 5:38p Kevin
61 * 11 12/30/98 12:15p Kevin
62 * Auto Mission Download system
64 * 10 10/12/98 4:59p Kevin
65 * Added delay to thread when cancelled...
67 * 9 10/12/98 4:49p Nate
70 * 8 10/12/98 1:54p Nate
73 * 7 10/12/98 11:30a Kevin
76 * 6 10/08/98 12:59p Nate
79 * 5 10/08/98 9:57a Kevin
80 * made transfer cancellable
82 * 4 7/31/98 12:19p Nate
83 * Fixed http abort problem.
85 * 3 7/31/98 11:57a Kevin
86 * Added new functions for getting state
88 * 2 6/01/98 10:10a Kevin
89 * Added DLL connection interface and auto update DLL
91 * 1 5/27/98 9:52a Kevin
93 * 1 5/25/98 5:31p Kevin
107 #include <sys/types.h>
108 #include <sys/socket.h>
109 #include <netinet/in.h>
110 #include <arpa/inet.h>
112 #include <sys/ioctl.h>
124 #include "inetgetfile.h"
125 #include "chttpget.h"
129 inline void Sleep(int millis)
133 tv.tv_usec = millis*1000;
134 select(0,NULL,NULL,NULL,&tv);
138 #define NW_AGHBN_CANCEL 1
139 #define NW_AGHBN_LOOKUP 2
140 #define NW_AGHBN_READ 3
143 void __cdecl http_gethostbynameworker(void *parm);
145 void *http_gethostbynameworker(void *parm);
148 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname);
151 void HTTPObjThread( void * obj )
153 void *HTTPObjThread( void * obj )
156 ((ChttpGet *)obj)->WorkerThread();
157 ((ChttpGet *)obj)->m_Aborted = true;
158 //OutputDebugString("http transfer exiting....\n");
165 void ChttpGet::AbortGet()
168 OutputDebugString("Aborting....\n");
171 while(!m_Aborted) Sleep(50); //Wait for the thread to end
173 OutputDebugString("Aborted....\n");
177 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
179 m_ProxyEnabled = true;
181 m_ProxyPort = proxyport;
182 GetFile(URL,localfile);
185 ChttpGet::ChttpGet(char *URL,char *localfile)
187 m_ProxyEnabled = false;
188 GetFile(URL,localfile);
192 void ChttpGet::GetFile(char *URL,char *localfile)
194 m_DataSock = INVALID_SOCKET;
197 m_State = HTTP_STATE_STARTUP;;
201 strncpy(m_URL,URL,MAX_URL_LEN-1);
202 m_URL[MAX_URL_LEN-1] = 0;
204 LOCALFILE = fopen(localfile,"wb");
205 if(NULL == LOCALFILE)
207 m_State = HTTP_STATE_CANT_WRITE_FILE;
210 m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
211 if(INVALID_SOCKET == m_DataSock)
213 m_State = HTTP_STATE_SOCKET_ERROR;
221 ioctlsocket( m_DataSock, FIONBIO, &arg );
223 ioctl( m_DataSock, FIONBIO, &arg );
227 if(strnicmp(URL,"http:",5)==0)
235 //There shouldn't be any : in this string
238 m_State = HTTP_STATE_URL_PARSING_ERROR;
241 //read the filename by searching backwards for a /
242 //then keep reading until you find the first /
243 //when you found it, you have the host and dir
244 char *filestart = NULL;
245 char *dirstart = NULL;
246 for(int i = strlen(pURL);i>=0;i--)
252 filestart = pURL+i+1;
254 strcpy(m_szFilename,filestart);
262 if((dirstart==NULL) || (filestart==NULL))
264 m_State = HTTP_STATE_URL_PARSING_ERROR;
269 strcpy(m_szDir,dirstart);//,(filestart-dirstart));
270 //m_szDir[(filestart-dirstart)] = NULL;
271 strncpy(m_szHost,pURL,(dirstart-pURL));
272 m_szHost[(dirstart-pURL)-1] = '\0';
275 if(NULL==_beginthread(HTTPObjThread,0,this))
277 m_State = HTTP_STATE_INTERNAL_ERROR;
281 #elif defined(__LINUX__)
283 if(!inet_LoadThreadLib())
285 m_State = HTTP_STATE_INTERNAL_ERROR;
288 if(df_pthread_create(&thread,NULL,HTTPObjThread,this)!=0)
290 m_State = HTTP_STATE_INTERNAL_ERROR;
298 ChttpGet::~ChttpGet()
300 if(m_DataSock != INVALID_SOCKET)
302 shutdown(m_DataSock,2);
304 closesocket(m_DataSock);
311 int ChttpGet::GetStatus()
316 unsigned int ChttpGet::GetBytesIn()
321 unsigned int ChttpGet::GetTotalBytes()
323 return m_iBytesTotal;
327 void ChttpGet::WorkerThread()
329 char szCommand[1000];
338 if(m_State != HTTP_STATE_CONNECTED)
343 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);
344 send(m_DataSock,szCommand,strlen(szCommand),0);
346 if(strnicmp("HTTP/",p,5)==0)
349 pcode = strchr(p,' ')+1;
352 m_State = HTTP_STATE_UNKNOWN_ERROR;
362 m_State = HTTP_STATE_UNKNOWN_ERROR;
374 m_State = HTTP_STATE_UNKNOWN_ERROR;
383 if(strnicmp(p,"Content-Length:",strlen("Content-Length:"))==0)
385 char *s = strchr(p,' ')+1;
397 m_iBytesTotal = atoi(p);
407 m_State = HTTP_STATE_FILE_NOT_FOUND;
413 m_State = HTTP_STATE_UNKNOWN_ERROR;
419 int ChttpGet::ConnectSocket()
424 SOCKADDR_IN hostaddr;
429 ip = inet_addr((const char *)m_szHost);
434 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);
439 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
442 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
450 m_State = HTTP_STATE_HOST_NOT_FOUND;
456 se = getservbyname("http", NULL);
461 hostaddr.sin_port = htons(80);
465 hostaddr.sin_port = se->s_port;
467 hostaddr.sin_family = AF_INET;
469 memcpy(&hostaddr.sin_addr,&ip,4);
473 //This is on a proxy, so we need to make sure to connect to the proxy machine
474 ip = inet_addr((const char *)m_ProxyIP);
478 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
484 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
487 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
495 m_State = HTTP_STATE_HOST_NOT_FOUND;
500 //Use either the proxy port or 80 if none specified
501 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
502 //Copy the proxy address...
503 memcpy(&hostaddr.sin_addr,&ip,4);
506 //Now we will connect to the host
512 int serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
513 int cerr = WSAGetLastError();
516 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
519 FD_SET( m_DataSock, &wfds );
520 if(select(0,NULL,&wfds,NULL,&timeout))
527 serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
530 cerr = WSAGetLastError();
542 m_State = HTTP_STATE_CANT_CONNECT;
545 m_State = HTTP_STATE_CONNECTED;
549 char *ChttpGet::GetHTTPLine()
551 unsigned int iBytesRead;
553 unsigned int igotcrlf = 0;
554 memset(recv_buffer,0,1000);
558 bool gotdata = false;
561 iBytesRead = recv(m_DataSock,chunk,1,0);
563 if(SOCKET_ERROR == iBytesRead)
565 int error = WSAGetLastError();
566 if(WSAEWOULDBLOCK==error)
584 //This should always read a 0x0a
587 iBytesRead = recv(m_DataSock,chunk,1,0);
589 if(SOCKET_ERROR == iBytesRead)
591 int error = WSAGetLastError();
592 if(WSAEWOULDBLOCK==error)
611 strcat(recv_buffer,chunk);
619 unsigned int ChttpGet::ReadDataChannel()
621 char sDataBuffer[4096]; // Data-storage buffer for the data channel
622 int nBytesRecv = 0; // Bytes received from the data channel
628 timeout.tv_usec = 500;
630 m_State = HTTP_STATE_RECEIVING;
634 FD_SET( m_DataSock, &wfds );
636 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
640 select(0,&wfds,NULL,NULL,&timeout);
646 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
652 if(SOCKET_ERROR == nBytesRecv)
654 int error = WSAGetLastError();
655 if(WSAEWOULDBLOCK==error)
661 m_iBytesIn += nBytesRecv;
664 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
665 //Write sDataBuffer, nBytesRecv
669 }while (nBytesRecv > 0);
671 // Close the file and check for error returns.
672 if (nBytesRecv == SOCKET_ERROR)
674 //Ok, we got a socket error -- xfer aborted?
675 m_State = HTTP_STATE_RECV_FAILED;
680 //OutputDebugString("HTTP File complete!\n");
682 m_State = HTTP_STATE_FILE_RECEIVED;
688 typedef struct _async_dns_lookup
690 unsigned int ip; //resolved host. Write only to worker thread.
691 char * host;//host name to resolve. read only to worker thread
692 bool done; //write only to the worker thread. Signals that the operation is complete
693 bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
694 bool abort; //read only to worker thread. If this is set, don't fill in the struct.
697 async_dns_lookup httpaslu;
698 async_dns_lookup *http_lastaslu = NULL;
701 void __cdecl http_gethostbynameworker(void *parm);
703 void *http_gethostbynameworker(void *parm);
706 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
709 if(command==NW_AGHBN_LOOKUP)
712 http_lastaslu->abort = true;
714 async_dns_lookup *newaslu;
715 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
716 memset(&newaslu->ip,0,sizeof(unsigned int));
717 newaslu->host = hostname;
718 newaslu->done = false;
719 newaslu->error = false;
720 newaslu->abort = false;
721 http_lastaslu = newaslu;
722 httpaslu.done = false;
725 _beginthread(http_gethostbynameworker,0,newaslu);
727 #elif defined(__LINUX__)
729 if(!inet_LoadThreadLib())
734 df_pthread_create(&thread,NULL,http_gethostbynameworker,newaslu);
739 else if(command==NW_AGHBN_CANCEL)
742 http_lastaslu->abort = true;
743 http_lastaslu = NULL;
745 else if(command==NW_AGHBN_READ)
751 //free(http_lastaslu);
752 http_lastaslu = NULL;
753 memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
756 else if(httpaslu.error)
759 http_lastaslu = NULL;
768 // This is the worker thread which does the lookup.
770 void __cdecl http_gethostbynameworker(void *parm)
772 void *http_gethostbynameworker(void *parm)
776 df_pthread_detach(df_pthread_self());
778 async_dns_lookup *lookup = (async_dns_lookup *)parm;
779 HOSTENT *he = gethostbyname(lookup->host);
782 lookup->error = true;
789 else if(!lookup->abort)
791 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
793 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));