2 * $Logfile: /Freespace2/code/Inetfile/Chttpget.cpp $
7 * HTTP Client class (get only)
10 * Revision 1.5 2002/06/02 04:26:34 relnev
13 * Revision 1.4 2002/05/26 20:32:24 theoddone33
14 * Fix some minor stuff
16 * Revision 1.3 2002/05/26 20:20:54 relnev
21 * Revision 1.2 2002/05/07 03:16:45 theoddone33
22 * The Great Newline Fix
24 * Revision 1.1.1.1 2002/05/03 03:28:09 root
28 * 5 8/24/99 1:49a Dave
29 * Fixed client-side afterburner stuttering. Added checkbox for no version
30 * checking on PXO join. Made button info passing more friendly between
33 * 4 8/22/99 1:19p Dave
34 * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
35 * which d3d cards are detected.
37 * 21 8/21/99 6:33p Kevin
40 * 20 8/21/99 6:48a Jeff
43 * 19 8/20/99 3:01p Kevin
44 * Added support for Proxies (I hope!)
46 * 18 8/15/99 6:38p Jeff
49 * 17 8/15/99 6:26p Kevin
51 * 16 4/14/99 1:20a Jeff
52 * fixed case mismatched #includes
54 * 15 3/03/99 12:28a Nate
55 * sped up something or other when the connection is done
57 * 14 2/03/99 4:20p Kevin
58 * Got multiplayer working with .mn3 files, and setup autodownloading
60 * 13 1/27/99 5:49p Kevin
62 * 12 1/27/99 5:38p Kevin
64 * 11 12/30/98 12:15p Kevin
65 * Auto Mission Download system
67 * 10 10/12/98 4:59p Kevin
68 * Added delay to thread when cancelled...
70 * 9 10/12/98 4:49p Nate
73 * 8 10/12/98 1:54p Nate
76 * 7 10/12/98 11:30a Kevin
79 * 6 10/08/98 12:59p Nate
82 * 5 10/08/98 9:57a Kevin
83 * made transfer cancellable
85 * 4 7/31/98 12:19p Nate
86 * Fixed http abort problem.
88 * 3 7/31/98 11:57a Kevin
89 * Added new functions for getting state
91 * 2 6/01/98 10:10a Kevin
92 * Added DLL connection interface and auto update DLL
94 * 1 5/27/98 9:52a Kevin
96 * 1 5/25/98 5:31p Kevin
110 #include <sys/types.h>
111 #include <sys/socket.h>
112 #include <netinet/in.h>
113 #include <arpa/inet.h>
115 #include <sys/ioctl.h>
127 #include "inetgetfile.h"
128 #include "chttpget.h"
132 inline void Sleep(int millis)
136 tv.tv_usec = millis*1000;
137 select(0,NULL,NULL,NULL,&tv);
141 #define NW_AGHBN_CANCEL 1
142 #define NW_AGHBN_LOOKUP 2
143 #define NW_AGHBN_READ 3
146 void __cdecl http_gethostbynameworker(void *parm);
148 void *http_gethostbynameworker(void *parm);
151 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname);
154 void HTTPObjThread( void * obj )
156 void *HTTPObjThread( void * obj )
159 ((ChttpGet *)obj)->WorkerThread();
160 ((ChttpGet *)obj)->m_Aborted = true;
161 //OutputDebugString("http transfer exiting....\n");
168 void ChttpGet::AbortGet()
171 OutputDebugString("Aborting....\n");
174 while(!m_Aborted) Sleep(50); //Wait for the thread to end
176 OutputDebugString("Aborted....\n");
180 ChttpGet::ChttpGet(char *URL,char *localfile,char *proxyip,unsigned short proxyport)
182 m_ProxyEnabled = true;
184 m_ProxyPort = proxyport;
185 GetFile(URL,localfile);
188 ChttpGet::ChttpGet(char *URL,char *localfile)
190 m_ProxyEnabled = false;
191 GetFile(URL,localfile);
195 void ChttpGet::GetFile(char *URL,char *localfile)
197 m_DataSock = INVALID_SOCKET;
200 m_State = HTTP_STATE_STARTUP;;
204 strncpy(m_URL,URL,MAX_URL_LEN-1);
205 m_URL[MAX_URL_LEN-1] = 0;
207 LOCALFILE = fopen(localfile,"wb");
208 if(NULL == LOCALFILE)
210 m_State = HTTP_STATE_CANT_WRITE_FILE;
213 m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
214 if(INVALID_SOCKET == m_DataSock)
216 m_State = HTTP_STATE_SOCKET_ERROR;
224 ioctlsocket( m_DataSock, FIONBIO, &arg );
226 ioctl( m_DataSock, FIONBIO, &arg );
230 if(strnicmp(URL,"http:",5)==0)
238 //There shouldn't be any : in this string
241 m_State = HTTP_STATE_URL_PARSING_ERROR;
244 //read the filename by searching backwards for a /
245 //then keep reading until you find the first /
246 //when you found it, you have the host and dir
247 char *filestart = NULL;
248 char *dirstart = NULL;
249 for(int i = strlen(pURL);i>=0;i--)
255 filestart = pURL+i+1;
257 strcpy(m_szFilename,filestart);
265 if((dirstart==NULL) || (filestart==NULL))
267 m_State = HTTP_STATE_URL_PARSING_ERROR;
272 strcpy(m_szDir,dirstart);//,(filestart-dirstart));
273 //m_szDir[(filestart-dirstart)] = NULL;
274 strncpy(m_szHost,pURL,(dirstart-pURL));
275 m_szHost[(dirstart-pURL)-1] = '\0';
278 if(NULL==_beginthread(HTTPObjThread,0,this))
280 m_State = HTTP_STATE_INTERNAL_ERROR;
284 #elif defined(__LINUX__)
286 if(!inet_LoadThreadLib())
288 m_State = HTTP_STATE_INTERNAL_ERROR;
291 if(df_pthread_create(&thread,NULL,HTTPObjThread,this)!=0)
293 m_State = HTTP_STATE_INTERNAL_ERROR;
301 ChttpGet::~ChttpGet()
303 if(m_DataSock != INVALID_SOCKET)
305 shutdown(m_DataSock,2);
307 closesocket(m_DataSock);
314 int ChttpGet::GetStatus()
319 unsigned int ChttpGet::GetBytesIn()
324 unsigned int ChttpGet::GetTotalBytes()
326 return m_iBytesTotal;
330 void ChttpGet::WorkerThread()
332 char szCommand[1000];
341 if(m_State != HTTP_STATE_CONNECTED)
346 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);
347 send(m_DataSock,szCommand,strlen(szCommand),0);
349 if(strnicmp("HTTP/",p,5)==0)
352 pcode = strchr(p,' ')+1;
355 m_State = HTTP_STATE_UNKNOWN_ERROR;
365 m_State = HTTP_STATE_UNKNOWN_ERROR;
377 m_State = HTTP_STATE_UNKNOWN_ERROR;
386 if(strnicmp(p,"Content-Length:",strlen("Content-Length:"))==0)
388 char *s = strchr(p,' ')+1;
400 m_iBytesTotal = atoi(p);
410 m_State = HTTP_STATE_FILE_NOT_FOUND;
416 m_State = HTTP_STATE_UNKNOWN_ERROR;
422 int ChttpGet::ConnectSocket()
427 SOCKADDR_IN hostaddr;
432 ip = inet_addr((const char *)m_szHost);
437 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_szHost);
442 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_szHost);
445 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_szHost);
453 m_State = HTTP_STATE_HOST_NOT_FOUND;
459 se = getservbyname("http", NULL);
464 hostaddr.sin_port = htons(80);
468 hostaddr.sin_port = se->s_port;
470 hostaddr.sin_family = AF_INET;
472 memcpy(&hostaddr.sin_addr,&ip,4);
476 //This is on a proxy, so we need to make sure to connect to the proxy machine
477 ip = inet_addr((const char *)m_ProxyIP);
481 http_Asyncgethostbyname(&ip,NW_AGHBN_LOOKUP,m_ProxyIP);
487 http_Asyncgethostbyname(&ip,NW_AGHBN_CANCEL,m_ProxyIP);
490 rcode = http_Asyncgethostbyname(&ip,NW_AGHBN_READ,m_ProxyIP);
498 m_State = HTTP_STATE_HOST_NOT_FOUND;
503 //Use either the proxy port or 80 if none specified
504 hostaddr.sin_port = htons((ushort)(m_ProxyPort ? m_ProxyPort : 80));
505 //Copy the proxy address...
506 memcpy(&hostaddr.sin_addr,&ip,4);
509 //Now we will connect to the host
515 int serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
516 int cerr = WSAGetLastError();
519 while((cerr==WSAEALREADY)||(cerr==WSAEINVAL)||(cerr==WSAEWOULDBLOCK))
522 FD_SET( m_DataSock, &wfds );
523 if(select(0,NULL,&wfds,NULL,&timeout))
530 serr = connect(m_DataSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR));
533 cerr = WSAGetLastError();
545 m_State = HTTP_STATE_CANT_CONNECT;
548 m_State = HTTP_STATE_CONNECTED;
552 char *ChttpGet::GetHTTPLine()
556 unsigned int igotcrlf = 0;
557 memset(recv_buffer,0,1000);
561 bool gotdata = false;
564 iBytesRead = recv(m_DataSock,chunk,1,0);
566 if(SOCKET_ERROR == iBytesRead)
568 int error = WSAGetLastError();
569 if(WSAEWOULDBLOCK==error)
587 //This should always read a 0x0a
590 iBytesRead = recv(m_DataSock,chunk,1,0);
592 if(SOCKET_ERROR == iBytesRead)
594 int error = WSAGetLastError();
595 if(WSAEWOULDBLOCK==error)
614 strcat(recv_buffer,chunk);
622 unsigned int ChttpGet::ReadDataChannel()
624 char sDataBuffer[4096]; // Data-storage buffer for the data channel
625 int nBytesRecv = 0; // Bytes received from the data channel
631 timeout.tv_usec = 500;
633 m_State = HTTP_STATE_RECEIVING;
637 FD_SET( m_DataSock, &wfds );
639 if((m_iBytesTotal)&&(m_iBytesIn==m_iBytesTotal))
643 select(0,&wfds,NULL,NULL,&timeout);
649 nBytesRecv = recv(m_DataSock, (char *)&sDataBuffer,sizeof(sDataBuffer), 0);
655 if(SOCKET_ERROR == nBytesRecv)
657 int error = WSAGetLastError();
658 if(WSAEWOULDBLOCK==error)
664 m_iBytesIn += nBytesRecv;
667 fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
668 //Write sDataBuffer, nBytesRecv
672 }while (nBytesRecv > 0);
674 // Close the file and check for error returns.
675 if (nBytesRecv == SOCKET_ERROR)
677 //Ok, we got a socket error -- xfer aborted?
678 m_State = HTTP_STATE_RECV_FAILED;
683 //OutputDebugString("HTTP File complete!\n");
685 m_State = HTTP_STATE_FILE_RECEIVED;
691 typedef struct _async_dns_lookup
693 unsigned int ip; //resolved host. Write only to worker thread.
694 char * host;//host name to resolve. read only to worker thread
695 bool done; //write only to the worker thread. Signals that the operation is complete
696 bool error; //write only to worker thread. Thread sets this if the name doesn't resolve
697 bool abort; //read only to worker thread. If this is set, don't fill in the struct.
700 async_dns_lookup httpaslu;
701 async_dns_lookup *http_lastaslu = NULL;
704 void __cdecl http_gethostbynameworker(void *parm);
706 void *http_gethostbynameworker(void *parm);
709 int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
712 if(command==NW_AGHBN_LOOKUP)
715 http_lastaslu->abort = true;
717 async_dns_lookup *newaslu;
718 newaslu = (async_dns_lookup *)malloc(sizeof(async_dns_lookup));
719 memset(&newaslu->ip,0,sizeof(unsigned int));
720 newaslu->host = hostname;
721 newaslu->done = false;
722 newaslu->error = false;
723 newaslu->abort = false;
724 http_lastaslu = newaslu;
725 httpaslu.done = false;
728 _beginthread(http_gethostbynameworker,0,newaslu);
730 #elif defined(__LINUX__)
732 if(!inet_LoadThreadLib())
737 df_pthread_create(&thread,NULL,http_gethostbynameworker,newaslu);
742 else if(command==NW_AGHBN_CANCEL)
745 http_lastaslu->abort = true;
746 http_lastaslu = NULL;
748 else if(command==NW_AGHBN_READ)
754 //free(http_lastaslu);
755 http_lastaslu = NULL;
756 memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
759 else if(httpaslu.error)
762 http_lastaslu = NULL;
771 // This is the worker thread which does the lookup.
773 void __cdecl http_gethostbynameworker(void *parm)
775 void *http_gethostbynameworker(void *parm)
779 df_pthread_detach(df_pthread_self());
781 async_dns_lookup *lookup = (async_dns_lookup *)parm;
782 HOSTENT *he = gethostbyname(lookup->host);
785 lookup->error = true;
792 else if(!lookup->abort)
794 memcpy(&lookup->ip,he->h_addr_list[0],sizeof(unsigned int));
796 memcpy(&httpaslu,lookup,sizeof(async_dns_lookup));