Fixed definitions of TTTOOLINFOA/W_V1_SIZE and
[wine] / dlls / wininet / http.c
1 /*
2  * Wininet - Http Implementation
3  *
4  * Copyright 1999 Corel Corporation
5  * Copyright 2002 CodeWeavers Inc.
6  * Copyright 2002 TransGaming Technologies Inc.
7  *
8  * Ulrich Czekalla
9  * Aric Stewart
10  * David Hammerton
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26
27 #include "config.h"
28
29 #include <sys/types.h>
30 #ifdef HAVE_SYS_SOCKET_H
31 # include <sys/socket.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #include <errno.h>
40 #include <string.h>
41 #include <time.h>
42
43 #include "windef.h"
44 #include "winbase.h"
45 #include "wininet.h"
46 #include "winreg.h"
47 #include "winerror.h"
48 #define NO_SHLWAPI_STREAM
49 #include "shlwapi.h"
50
51 #include "internet.h"
52 #include "wine/debug.h"
53 #include "wine/unicode.h"
54
55 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
56
57 #define HTTPHEADER " HTTP/1.0"
58 #define HTTPHOSTHEADER "\r\nHost: "
59 #define MAXHOSTNAME 100
60 #define MAX_FIELD_VALUE_LEN 256
61 #define MAX_FIELD_LEN 256
62
63
64 #define HTTP_REFERER    "Referer"
65 #define HTTP_ACCEPT     "Accept"
66 #define HTTP_USERAGENT  "User-Agent"
67
68 #define HTTP_ADDHDR_FLAG_ADD                            0x20000000
69 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW                     0x10000000
70 #define HTTP_ADDHDR_FLAG_COALESCE                       0x40000000
71 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA            0x40000000
72 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON        0x01000000
73 #define HTTP_ADDHDR_FLAG_REPLACE                        0x80000000
74 #define HTTP_ADDHDR_FLAG_REQ                            0x02000000
75
76
77 BOOL HTTP_OpenConnection(LPWININETHTTPREQA lpwhr);
78 int HTTP_WriteDataToStream(LPWININETHTTPREQA lpwhr,
79         void *Buffer, int BytesToWrite);
80 int HTTP_ReadDataFromStream(LPWININETHTTPREQA lpwhr,
81         void *Buffer, int BytesToRead);
82 BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQA lpwhr);
83 BOOL HTTP_ProcessHeader(LPWININETHTTPREQA lpwhr, LPCSTR field, LPCSTR value, DWORD dwModifier);
84 void HTTP_CloseConnection(LPWININETHTTPREQA lpwhr);
85 BOOL HTTP_InterpretHttpHeader(LPSTR buffer, LPSTR field, INT fieldlen, LPSTR value, INT valuelen);
86 INT HTTP_GetStdHeaderIndex(LPCSTR lpszField);
87 BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQA lpwhr, LPHTTPHEADERA lpHdr);
88 INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQA lpwhr, LPCSTR lpszField);
89 BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQA lpwhr, INT index);
90
91 inline static LPSTR HTTP_strdup( LPCSTR str )
92 {
93     LPSTR ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
94     if (ret) strcpy( ret, str );
95     return ret;
96 }
97
98 /***********************************************************************
99  *           HttpAddRequestHeadersA (WININET.@)
100  *
101  * Adds one or more HTTP header to the request handler
102  *
103  * RETURNS
104  *    TRUE  on success
105  *    FALSE on failure
106  *
107  */
108 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
109         LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
110 {
111     LPSTR lpszStart;
112     LPSTR lpszEnd;
113     LPSTR buffer;
114     CHAR value[MAX_FIELD_VALUE_LEN], field[MAX_FIELD_LEN];
115     BOOL bSuccess = FALSE;
116     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hHttpRequest;
117
118     TRACE("%p, %s, %li, %li\n", hHttpRequest, lpszHeader, dwHeaderLength,
119           dwModifier);
120
121
122     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
123     {
124         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
125         return FALSE;
126     }
127
128     if (!lpszHeader) 
129       return TRUE;
130
131     TRACE("copying header: %s\n", lpszHeader);
132     buffer = HTTP_strdup(lpszHeader);
133     lpszStart = buffer;
134
135     do
136     {
137         lpszEnd = lpszStart;
138
139         while (*lpszEnd != '\0')
140         {
141             if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
142                  break;
143             lpszEnd++;
144         }
145
146         if (*lpszEnd == '\0')
147             break;
148
149         *lpszEnd = '\0';
150
151         TRACE("interpreting header %s\n", debugstr_a(lpszStart));
152         if (HTTP_InterpretHttpHeader(lpszStart, field, MAX_FIELD_LEN, value, MAX_FIELD_VALUE_LEN))
153             bSuccess = HTTP_ProcessHeader(lpwhr, field, value, dwModifier | HTTP_ADDHDR_FLAG_REQ);
154
155         lpszStart = lpszEnd + 2; /* Jump over \0\n */
156
157     } while (bSuccess);
158
159     HeapFree(GetProcessHeap(), 0, buffer);
160     return bSuccess;
161 }
162
163 /***********************************************************************
164  *           HttpEndRequestA (WININET.@)
165  *
166  * Ends an HTTP request that was started by HttpSendRequestEx
167  *
168  * RETURNS
169  *    TRUE      if successful
170  *    FALSE     on failure
171  *
172  */
173 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest, LPINTERNET_BUFFERSA lpBuffersOut, 
174           DWORD dwFlags, DWORD dwContext)
175 {
176   FIXME("stub\n");
177   return FALSE;
178 }
179
180 /***********************************************************************
181  *           HttpEndRequestW (WININET.@)
182  *
183  * Ends an HTTP request that was started by HttpSendRequestEx
184  *
185  * RETURNS
186  *    TRUE      if successful
187  *    FALSE     on failure
188  *
189  */
190 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest, LPINTERNET_BUFFERSW lpBuffersOut, 
191           DWORD dwFlags, DWORD dwContext)
192 {
193   FIXME("stub\n");
194   return FALSE;
195 }
196
197 /***********************************************************************
198  *           HttpOpenRequestA (WININET.@)
199  *
200  * Open a HTTP request handle
201  *
202  * RETURNS
203  *    HINTERNET  a HTTP request handle on success
204  *    NULL       on failure
205  *
206  */
207 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
208         LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
209         LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
210         DWORD dwFlags, DWORD dwContext)
211 {
212     LPWININETHTTPSESSIONA lpwhs = (LPWININETHTTPSESSIONA) hHttpSession;
213     LPWININETAPPINFOA hIC = NULL;
214
215     TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08lx)\n", hHttpSession,
216           debugstr_a(lpszVerb), lpszObjectName,
217           debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
218           dwFlags, dwContext);
219     if(lpszAcceptTypes!=NULL)
220     {
221         int i;
222         for(i=0;lpszAcceptTypes[i]!=NULL;i++)
223             TRACE("\taccept type: %s\n",lpszAcceptTypes[i]);
224     }    
225
226     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
227     {
228         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
229         return FALSE;
230     }
231     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
232
233     /*
234      * My tests seem to show that the windows version does not
235      * become asynchronous until after this point. And anyhow
236      * if this call was asynchronous then how would you get the
237      * necessary HINTERNET pointer returned by this function.
238      *
239      * I am leaving this here just in case I am wrong
240      *
241      * if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
242      */
243     if (0)
244     {
245         WORKREQUEST workRequest;
246
247         workRequest.asyncall = HTTPOPENREQUESTA;
248         workRequest.HFTPSESSION = (DWORD)hHttpSession;
249         workRequest.LPSZVERB = (DWORD)HTTP_strdup(lpszVerb);
250         workRequest.LPSZOBJECTNAME = (DWORD)HTTP_strdup(lpszObjectName);
251         if (lpszVersion)
252             workRequest.LPSZVERSION = (DWORD)HTTP_strdup(lpszVersion);
253         else
254             workRequest.LPSZVERSION = 0;
255         if (lpszReferrer)
256             workRequest.LPSZREFERRER = (DWORD)HTTP_strdup(lpszReferrer);
257         else
258             workRequest.LPSZREFERRER = 0;
259         workRequest.LPSZACCEPTTYPES = (DWORD)lpszAcceptTypes;
260         workRequest.DWFLAGS = dwFlags;
261         workRequest.DWCONTEXT = dwContext;
262
263         INTERNET_AsyncCall(&workRequest);
264         TRACE ("returning NULL\n");
265         return NULL;
266     }
267     else
268     {
269         HINTERNET rec = HTTP_HttpOpenRequestA(hHttpSession, lpszVerb, lpszObjectName,
270                                               lpszVersion, lpszReferrer, lpszAcceptTypes,
271                                               dwFlags, dwContext);
272         TRACE("returning %p\n", rec);
273         return rec;
274     }
275 }
276
277
278 /***********************************************************************
279  *           HttpOpenRequestW (WININET.@)
280  *
281  * Open a HTTP request handle
282  *
283  * RETURNS
284  *    HINTERNET  a HTTP request handle on success
285  *    NULL       on failure
286  *
287  * FIXME: This should be the other way around (A should call W)
288  */
289 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
290         LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
291         LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
292         DWORD dwFlags, DWORD dwContext)
293 {
294     CHAR *szVerb = NULL, *szObjectName = NULL;
295     CHAR *szVersion = NULL, *szReferrer = NULL, **szAcceptTypes = NULL;
296     INT len;
297     INT acceptTypesCount;
298     HINTERNET rc = FALSE;
299     TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08lx)\n", hHttpSession,
300           debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
301           debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
302           dwFlags, dwContext);
303
304     if (lpszVerb)
305     {
306         len = WideCharToMultiByte(CP_ACP, 0, lpszVerb, -1, NULL, 0, NULL, NULL);
307         szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(CHAR) );
308         if ( !szVerb )
309             goto end;
310         WideCharToMultiByte(CP_ACP, 0, lpszVerb, -1, szVerb, len, NULL, NULL);
311     }
312
313     if (lpszObjectName)
314     {
315         len = WideCharToMultiByte(CP_ACP, 0, lpszObjectName, -1, NULL, 0, NULL, NULL);
316         szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(CHAR) );
317         if ( !szObjectName )
318             goto end;
319         WideCharToMultiByte(CP_ACP, 0, lpszObjectName, -1, szObjectName, len, NULL, NULL);
320     }
321
322     if (lpszVersion)
323     {
324         len = WideCharToMultiByte(CP_ACP, 0, lpszVersion, -1, NULL, 0, NULL, NULL);
325         szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(CHAR));
326         if ( !szVersion )
327             goto end;
328         WideCharToMultiByte(CP_ACP, 0, lpszVersion, -1, szVersion, len, NULL, NULL);
329     }
330
331     if (lpszReferrer)
332     {
333         len = WideCharToMultiByte(CP_ACP, 0, lpszReferrer, -1, NULL, 0, NULL, NULL);
334         szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(CHAR));
335         if ( !szReferrer )
336             goto end;
337         WideCharToMultiByte(CP_ACP, 0, lpszReferrer, -1, szReferrer, len, NULL, NULL);
338     }
339
340     acceptTypesCount = 0;
341     if (lpszAcceptTypes)
342     {
343         while (lpszAcceptTypes[acceptTypesCount]) { acceptTypesCount++; } /* find out how many there are */
344         szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(CHAR *) * acceptTypesCount);
345         acceptTypesCount = 0;
346         while (lpszAcceptTypes[acceptTypesCount])
347         {
348             len = WideCharToMultiByte(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
349                                 -1, NULL, 0, NULL, NULL);
350             szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(CHAR));
351             if (!szAcceptTypes[acceptTypesCount] )
352                 goto end;
353             WideCharToMultiByte(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
354                                 -1, szAcceptTypes[acceptTypesCount], len, NULL, NULL);
355             acceptTypesCount++;
356         }
357     }
358     else szAcceptTypes = 0;
359
360     rc = HttpOpenRequestA(hHttpSession, (LPCSTR)szVerb, (LPCSTR)szObjectName,
361                           (LPCSTR)szVersion, (LPCSTR)szReferrer,
362                           (LPCSTR *)szAcceptTypes, dwFlags, dwContext);
363
364 end:
365     if (szAcceptTypes)
366     {
367         acceptTypesCount = 0;
368         while (szAcceptTypes[acceptTypesCount])
369         {
370             HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
371             acceptTypesCount++;
372         }
373         HeapFree(GetProcessHeap(), 0, szAcceptTypes);
374     }
375     if (szReferrer) HeapFree(GetProcessHeap(), 0, szReferrer);
376     if (szVersion) HeapFree(GetProcessHeap(), 0, szVersion);
377     if (szObjectName) HeapFree(GetProcessHeap(), 0, szObjectName);
378     if (szVerb) HeapFree(GetProcessHeap(), 0, szVerb);
379
380     return rc;
381 }
382
383 /***********************************************************************
384  *  HTTP_Base64
385  */
386 static UINT HTTP_Base64( LPCSTR bin, LPSTR base64 )
387 {
388     UINT n = 0, x;
389     static LPSTR HTTP_Base64Enc = 
390         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
391
392     while( bin[0] )
393     {
394         /* first 6 bits, all from bin[0] */
395         base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
396         x = (bin[0] & 3) << 4;
397
398         /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
399         if( !bin[1] )
400         {
401             base64[n++] = HTTP_Base64Enc[x];
402             base64[n++] = '=';
403             base64[n++] = '=';
404             break;
405         }
406         base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
407         x = ( bin[1] & 0x0f ) << 2;
408
409         /* next 6 bits 4 from bin[1] and 2 from bin[2] */
410         if( !bin[2] )
411         {
412             base64[n++] = HTTP_Base64Enc[x];
413             base64[n++] = '=';
414             break;
415         }
416         base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
417
418         /* last 6 bits, all from bin [2] */
419         base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
420         bin += 3;
421     }
422     base64[n] = 0;
423     return n;
424 }
425
426 /***********************************************************************
427  *  HTTP_EncodeBasicAuth
428  *
429  *  Encode the basic authentication string for HTTP 1.1
430  */
431 static LPSTR HTTP_EncodeBasicAuth( LPCSTR username, LPCSTR password)
432 {
433     UINT len;
434     LPSTR in, out, szBasic = "Basic ";
435
436     len = strlen( username ) + 1 + strlen ( password ) + 1;
437     in = HeapAlloc( GetProcessHeap(), 0, len );
438     if( !in )
439         return NULL;
440
441     len = strlen(szBasic) +
442           (strlen( username ) + 1 + strlen ( password ))*2 + 1 + 1;
443     out = HeapAlloc( GetProcessHeap(), 0, len );
444     if( out )
445     {
446         strcpy( in, username );
447         strcat( in, ":" );
448         strcat( in, password );
449         strcpy( out, szBasic );
450         HTTP_Base64( in, &out[strlen(out)] );
451     }
452     HeapFree( GetProcessHeap(), 0, in );
453
454     return out;
455 }
456
457 /***********************************************************************
458  *  HTTP_InsertProxyAuthorization
459  *
460  *   Insert the basic authorization field in the request header
461  */
462 BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQA lpwhr,
463                        LPCSTR username, LPCSTR password )
464 {
465     HTTPHEADERA hdr;
466     INT index;
467
468     hdr.lpszField = "Proxy-Authorization";
469     hdr.lpszValue = HTTP_EncodeBasicAuth( username, password );
470     hdr.wFlags = HDR_ISREQUEST;
471     hdr.wCount = 0;
472     if( !hdr.lpszValue )
473         return FALSE;
474
475     TRACE("Inserting %s = %s\n",
476           debugstr_a( hdr.lpszField ), debugstr_a( hdr.lpszValue ) );
477
478     /* remove the old proxy authorization header */
479     index = HTTP_GetCustomHeaderIndex( lpwhr, hdr.lpszField );
480     if( index >=0 )
481         HTTP_DeleteCustomHeader( lpwhr, index );
482     
483     HTTP_InsertCustomHeader(lpwhr, &hdr);
484     HeapFree( GetProcessHeap(), 0, hdr.lpszValue );
485     
486     return TRUE;
487 }
488
489 /***********************************************************************
490  *           HTTP_DealWithProxy
491  */
492 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOA hIC,
493     LPWININETHTTPSESSIONA lpwhs, LPWININETHTTPREQA lpwhr)
494 {
495     char buf[MAXHOSTNAME];
496     char proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
497     char* url, *szNul = "";
498     URL_COMPONENTSA UrlComponents;
499
500     memset( &UrlComponents, 0, sizeof UrlComponents );
501     UrlComponents.dwStructSize = sizeof UrlComponents;
502     UrlComponents.lpszHostName = buf;
503     UrlComponents.dwHostNameLength = MAXHOSTNAME;
504
505     sprintf(proxy, "http://%s/", hIC->lpszProxy);
506     if( !InternetCrackUrlA(proxy, 0, 0, &UrlComponents) )
507         return FALSE;
508     if( UrlComponents.dwHostNameLength == 0 )
509         return FALSE;
510
511     if( !lpwhr->lpszPath )
512         lpwhr->lpszPath = szNul;
513     TRACE("server='%s' path='%s'\n",
514           lpwhs->lpszServerName, lpwhr->lpszPath);
515     /* for constant 15 see above */
516     url = HeapAlloc(GetProcessHeap(), 0,
517         strlen(lpwhs->lpszServerName) + strlen(lpwhr->lpszPath) + 15);
518
519     if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
520         UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
521
522     sprintf(url, "http://%s:%d", lpwhs->lpszServerName,
523             lpwhs->nServerPort);
524     if( lpwhr->lpszPath[0] != '/' )
525         strcat( url, "/" );
526     strcat(url, lpwhr->lpszPath);
527     if(lpwhr->lpszPath != szNul)
528         HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
529     lpwhr->lpszPath = url;
530     /* FIXME: Do I have to free lpwhs->lpszServerName here ? */
531     lpwhs->lpszServerName = HTTP_strdup(UrlComponents.lpszHostName);
532     lpwhs->nServerPort = UrlComponents.nPort;
533
534     return TRUE;
535 }
536
537 /***********************************************************************
538  *           HTTP_HttpOpenRequestA (internal)
539  *
540  * Open a HTTP request handle
541  *
542  * RETURNS
543  *    HINTERNET  a HTTP request handle on success
544  *    NULL       on failure
545  *
546  */
547 HINTERNET WINAPI HTTP_HttpOpenRequestA(HINTERNET hHttpSession,
548         LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
549         LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
550         DWORD dwFlags, DWORD dwContext)
551 {
552     LPWININETHTTPSESSIONA lpwhs = (LPWININETHTTPSESSIONA) hHttpSession;
553     LPWININETAPPINFOA hIC = NULL;
554     LPWININETHTTPREQA lpwhr;
555     LPSTR lpszCookies;
556     LPSTR lpszUrl = NULL;
557     DWORD nCookieSize;
558
559     TRACE("--> \n");
560
561     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
562     {
563         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
564         return FALSE;
565     }
566
567     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
568
569     lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQA));
570     if (NULL == lpwhr)
571     {
572         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
573         return (HINTERNET) NULL;
574     }
575
576     lpwhr->hdr.htype = WH_HHTTPREQ;
577     lpwhr->hdr.lpwhparent = hHttpSession;
578     lpwhr->hdr.dwFlags = dwFlags;
579     lpwhr->hdr.dwContext = dwContext;
580     NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE);
581
582     if (NULL != lpszObjectName && strlen(lpszObjectName)) {
583         DWORD needed = 0;
584         HRESULT rc;
585         rc = UrlEscapeA(lpszObjectName, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
586         if (rc != E_POINTER)
587             needed = strlen(lpszObjectName)+1;
588         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed);
589         rc = UrlEscapeA(lpszObjectName, lpwhr->lpszPath, &needed,
590                    URL_ESCAPE_SPACES_ONLY);
591         if (rc)
592         {
593             ERR("Unable to escape string!(%s) (%ld)\n",lpszObjectName,rc);
594             strcpy(lpwhr->lpszPath,lpszObjectName);
595         }
596     }
597
598     if (NULL != lpszReferrer && strlen(lpszReferrer))
599         HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDHDR_FLAG_COALESCE);
600
601     if(lpszAcceptTypes!=NULL)
602     {
603         int i;
604         for(i=0;lpszAcceptTypes[i]!=NULL;i++)
605             HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i], HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_REQ|HTTP_ADDHDR_FLAG_ADD_IF_NEW);
606     }
607
608     if (NULL == lpszVerb)
609         lpwhr->lpszVerb = HTTP_strdup("GET");
610     else if (strlen(lpszVerb))
611         lpwhr->lpszVerb = HTTP_strdup(lpszVerb);
612
613     if (NULL != lpszReferrer && strlen(lpszReferrer))
614     {
615         char buf[MAXHOSTNAME];
616         URL_COMPONENTSA UrlComponents;
617
618         memset( &UrlComponents, 0, sizeof UrlComponents );
619         UrlComponents.dwStructSize = sizeof UrlComponents;
620         UrlComponents.lpszHostName = buf;
621         UrlComponents.dwHostNameLength = MAXHOSTNAME;
622
623         InternetCrackUrlA(lpszReferrer, 0, 0, &UrlComponents);
624         if (strlen(UrlComponents.lpszHostName))
625             lpwhr->lpszHostName = HTTP_strdup(UrlComponents.lpszHostName);
626     } else {
627         lpwhr->lpszHostName = HTTP_strdup(lpwhs->lpszServerName);
628     }
629     if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
630         HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
631
632     if (hIC->lpszAgent)
633     {
634         char *agent_header = HeapAlloc(GetProcessHeap(), 0, strlen(hIC->lpszAgent) + 1 + 14);
635         sprintf(agent_header, "User-Agent: %s\r\n", hIC->lpszAgent);
636         HttpAddRequestHeadersA((HINTERNET)lpwhr, agent_header, strlen(agent_header),
637                                HTTP_ADDREQ_FLAG_ADD);
638         HeapFree(GetProcessHeap(), 0, agent_header);
639     }
640
641     lpszUrl = HeapAlloc(GetProcessHeap(), 0, strlen(lpwhr->lpszHostName) + 1 + 7);
642     sprintf(lpszUrl, "http://%s", lpwhr->lpszHostName);
643     if (InternetGetCookieA(lpszUrl, NULL, NULL, &nCookieSize))
644     {
645         int cnt = 0;
646
647         lpszCookies = HeapAlloc(GetProcessHeap(), 0, nCookieSize + 1 + 8);
648
649         cnt += sprintf(lpszCookies, "Cookie: ");
650         InternetGetCookieA(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
651         cnt += nCookieSize - 1;
652         sprintf(lpszCookies + cnt, "\r\n");
653
654         HttpAddRequestHeadersA((HINTERNET)lpwhr, lpszCookies, strlen(lpszCookies),
655                                HTTP_ADDREQ_FLAG_ADD);
656         HeapFree(GetProcessHeap(), 0, lpszCookies);
657     }
658     HeapFree(GetProcessHeap(), 0, lpszUrl);
659
660
661
662     if (hIC->lpfnStatusCB)
663     {
664         INTERNET_ASYNC_RESULT iar;
665
666         iar.dwResult = (DWORD)lpwhr;
667         iar.dwError = ERROR_SUCCESS;
668
669         SendAsyncCallback(hIC, hHttpSession, dwContext,
670                       INTERNET_STATUS_HANDLE_CREATED, &iar,
671                       sizeof(INTERNET_ASYNC_RESULT));
672     }
673
674     /*
675      * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
676      */
677
678     /*
679      * According to my tests. The name is not resolved until a request is Opened
680      */
681     SendAsyncCallback(hIC, hHttpSession, dwContext,
682                       INTERNET_STATUS_RESOLVING_NAME,
683                       lpwhs->lpszServerName,
684                       strlen(lpwhs->lpszServerName)+1);
685     if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
686                     &lpwhs->phostent, &lpwhs->socketAddress))
687     {
688         INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
689         return FALSE;
690     }
691
692     SendAsyncCallback(hIC, hHttpSession, lpwhr->hdr.dwContext,
693                       INTERNET_STATUS_NAME_RESOLVED,
694                       &(lpwhs->socketAddress),
695                       sizeof(struct sockaddr_in));
696
697     TRACE("<--\n");
698     return (HINTERNET) lpwhr;
699 }
700
701
702 /***********************************************************************
703  *           HttpQueryInfoA (WININET.@)
704  *
705  * Queries for information about an HTTP request
706  *
707  * RETURNS
708  *    TRUE  on success
709  *    FALSE on failure
710  *
711  */
712 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
713         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
714 {
715     LPHTTPHEADERA lphttpHdr = NULL;
716     BOOL bSuccess = FALSE;
717     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hHttpRequest;
718
719     TRACE("(0x%08lx)--> %ld\n", dwInfoLevel, dwInfoLevel);
720
721     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
722     {
723         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
724         return FALSE;
725     }
726
727     /* Find requested header structure */
728     if ((dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK) == HTTP_QUERY_CUSTOM)
729     {
730         INT index = HTTP_GetCustomHeaderIndex(lpwhr, (LPSTR)lpBuffer);
731
732         if (index < 0)
733             goto lend;
734
735         lphttpHdr = &lpwhr->pCustHeaders[index];
736     }
737     else
738     {
739         INT index = dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK;
740
741         if (index == HTTP_QUERY_RAW_HEADERS_CRLF || index == HTTP_QUERY_RAW_HEADERS)
742         {
743             INT i, delim, size = 0, cnt = 0;
744
745             delim = index == HTTP_QUERY_RAW_HEADERS_CRLF ? 2 : 1;
746
747            /* Calculate length of custom reuqest headers */
748            for (i = 0; i < lpwhr->nCustHeaders; i++)
749            {
750                if ((~lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST) && lpwhr->pCustHeaders[i].lpszField &&
751                    lpwhr->pCustHeaders[i].lpszValue)
752                {
753                   size += strlen(lpwhr->pCustHeaders[i].lpszField) +
754                        strlen(lpwhr->pCustHeaders[i].lpszValue) + delim + 2;
755                }
756            }
757
758            /* Calculate the length of stadard request headers */
759            for (i = 0; i <= HTTP_QUERY_MAX; i++)
760            {
761               if ((~lpwhr->StdHeaders[i].wFlags & HDR_ISREQUEST) && lpwhr->StdHeaders[i].lpszField &&
762                    lpwhr->StdHeaders[i].lpszValue)
763               {
764                  size += strlen(lpwhr->StdHeaders[i].lpszField) +
765                     strlen(lpwhr->StdHeaders[i].lpszValue) + delim + 2;
766               }
767            }
768            size += delim;
769
770            if (size + 1 > *lpdwBufferLength)
771            {
772               *lpdwBufferLength = size + 1;
773               INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
774               goto lend;
775            }
776
777            /* Append standard request heades */
778            for (i = 0; i <= HTTP_QUERY_MAX; i++)
779            {
780                if ((~lpwhr->StdHeaders[i].wFlags & HDR_ISREQUEST) &&
781                                            lpwhr->StdHeaders[i].lpszField &&
782                                            lpwhr->StdHeaders[i].lpszValue)
783                {
784                    cnt += sprintf((char*)lpBuffer + cnt, "%s: %s%s", lpwhr->StdHeaders[i].lpszField, lpwhr->StdHeaders[i].lpszValue,
785                           index == HTTP_QUERY_RAW_HEADERS_CRLF ? "\r\n" : "\0");
786                }
787             }
788
789             /* Append custom request heades */
790             for (i = 0; i < lpwhr->nCustHeaders; i++)
791             {
792                 if ((~lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST) &&
793                                                 lpwhr->pCustHeaders[i].lpszField &&
794                                                 lpwhr->pCustHeaders[i].lpszValue)
795                 {
796                    cnt += sprintf((char*)lpBuffer + cnt, "%s: %s%s",
797                     lpwhr->pCustHeaders[i].lpszField, lpwhr->pCustHeaders[i].lpszValue,
798                                         index == HTTP_QUERY_RAW_HEADERS_CRLF ? "\r\n" : "\0");
799                 }
800             }
801
802             strcpy((char*)lpBuffer + cnt, index == HTTP_QUERY_RAW_HEADERS_CRLF ? "\r\n" : "");
803
804            *lpdwBufferLength = cnt + delim;
805            bSuccess = TRUE;
806                 goto lend;
807         }
808         else if (index >= 0 && index <= HTTP_QUERY_MAX && lpwhr->StdHeaders[index].lpszValue)
809         {
810             lphttpHdr = &lpwhr->StdHeaders[index];
811         }
812         else
813             goto lend;
814     }
815
816     /* Ensure header satisifies requested attributes */
817     if ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
818             (~lphttpHdr->wFlags & HDR_ISREQUEST))
819         goto lend;
820
821     /* coalesce value to reuqested type */
822     if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
823     {
824        *(int *)lpBuffer = atoi(lphttpHdr->lpszValue);
825            bSuccess = TRUE;
826     }
827     else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
828     {
829         time_t tmpTime;
830         struct tm tmpTM;
831         SYSTEMTIME *STHook;
832
833         tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
834
835         tmpTM = *gmtime(&tmpTime);
836         STHook = (SYSTEMTIME *) lpBuffer;
837         if(STHook==NULL)
838             goto lend;
839
840             STHook->wDay = tmpTM.tm_mday;
841             STHook->wHour = tmpTM.tm_hour;
842             STHook->wMilliseconds = 0;
843             STHook->wMinute = tmpTM.tm_min;
844             STHook->wDayOfWeek = tmpTM.tm_wday;
845             STHook->wMonth = tmpTM.tm_mon + 1;
846             STHook->wSecond = tmpTM.tm_sec;
847             STHook->wYear = tmpTM.tm_year;
848
849             bSuccess = TRUE;
850     }
851     else if (dwInfoLevel & HTTP_QUERY_FLAG_COALESCE)
852     {
853             if (*lpdwIndex >= lphttpHdr->wCount)
854                 {
855                 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
856                 }
857             else
858             {
859             /* Copy strncpy(lpBuffer, lphttpHdr[*lpdwIndex], len); */
860             (*lpdwIndex)++;
861             }
862     }
863     else
864     {
865         INT len = strlen(lphttpHdr->lpszValue);
866
867         if (len + 1 > *lpdwBufferLength)
868         {
869             *lpdwBufferLength = len + 1;
870             INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
871             goto lend;
872         }
873
874         strncpy(lpBuffer, lphttpHdr->lpszValue, len);
875         ((char*)lpBuffer)[len]=0;
876         *lpdwBufferLength = len;
877         bSuccess = TRUE;
878     }
879
880 lend:
881     TRACE("%d <--\n", bSuccess);
882     return bSuccess;
883 }
884
885 /***********************************************************************
886  *           HttpQueryInfoW (WININET.@)
887  *
888  * Queries for information about an HTTP request
889  *
890  * RETURNS
891  *    TRUE  on success
892  *    FALSE on failure
893  *
894  */
895 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
896         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
897 {
898     BOOL result;
899     DWORD charLen=*lpdwBufferLength;
900     char* tempBuffer=HeapAlloc(GetProcessHeap(), 0, charLen);
901     result=HttpQueryInfoA(hHttpRequest, dwInfoLevel, tempBuffer, &charLen, lpdwIndex);
902     if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
903        (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
904     {
905         memcpy(lpBuffer,tempBuffer,charLen);
906     }
907     else
908     {
909         int nChars=MultiByteToWideChar(CP_ACP,0, tempBuffer,charLen,lpBuffer,*lpdwBufferLength);
910         *lpdwBufferLength=nChars;
911     }
912     HeapFree(GetProcessHeap(), 0, tempBuffer);
913     return result;
914 }
915
916 /***********************************************************************
917  *           HttpSendRequestExA (WININET.@)
918  *
919  * Sends the specified request to the HTTP server and allows chunked
920  * transfers
921  */
922 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
923                                LPINTERNET_BUFFERSA lpBuffersIn,
924                                LPINTERNET_BUFFERSA lpBuffersOut,
925                                DWORD dwFlags, DWORD dwContext)
926 {
927   FIXME("(%p, %p, %p, %08lx, %08lx): stub\n", hRequest, lpBuffersIn,
928         lpBuffersOut, dwFlags, dwContext);
929   return FALSE;
930 }
931
932 /***********************************************************************
933  *           HttpSendRequestA (WININET.@)
934  *
935  * Sends the specified request to the HTTP server
936  *
937  * RETURNS
938  *    TRUE  on success
939  *    FALSE on failure
940  *
941  */
942 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
943         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
944 {
945     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hHttpRequest;
946     LPWININETHTTPSESSIONA lpwhs = NULL;
947     LPWININETAPPINFOA hIC = NULL;
948
949     TRACE("(0x%08lx, %p (%s), %li, %p, %li)\n", (unsigned long)hHttpRequest,
950             lpszHeaders, debugstr_a(lpszHeaders), dwHeaderLength, lpOptional, dwOptionalLength);
951
952     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
953     {
954         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
955         return FALSE;
956     }
957
958     lpwhs = (LPWININETHTTPSESSIONA) lpwhr->hdr.lpwhparent;
959     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
960     {
961         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
962         return FALSE;
963     }
964
965     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
966     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT)
967     {
968         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
969         return FALSE;
970     }
971
972     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
973     {
974         WORKREQUEST workRequest;
975
976         workRequest.asyncall = HTTPSENDREQUESTA;
977         workRequest.HFTPSESSION = (DWORD)hHttpRequest;
978         if (lpszHeaders)
979             workRequest.LPSZHEADER = (DWORD)HTTP_strdup(lpszHeaders);
980         else
981             workRequest.LPSZHEADER = 0;
982         workRequest.DWHEADERLENGTH = dwHeaderLength;
983         workRequest.LPOPTIONAL = (DWORD)lpOptional;
984         workRequest.DWOPTIONALLENGTH = dwOptionalLength;
985
986         INTERNET_AsyncCall(&workRequest);
987         /*
988          * This is from windows.
989          */
990         SetLastError(ERROR_IO_PENDING);
991         return 0;
992     }
993     else
994     {
995         return HTTP_HttpSendRequestA(hHttpRequest, lpszHeaders,
996                 dwHeaderLength, lpOptional, dwOptionalLength);
997     }
998 }
999
1000 /***********************************************************************
1001  *           HttpSendRequestW (WININET.@)
1002  *
1003  * Sends the specified request to the HTTP server
1004  *
1005  * RETURNS
1006  *    TRUE  on success
1007  *    FALSE on failure
1008  *
1009  */
1010 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
1011         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1012 {
1013     BOOL result;
1014     char* szHeaders=NULL;
1015     DWORD nLen=dwHeaderLength;
1016     if(lpszHeaders!=NULL)
1017     {
1018         nLen=WideCharToMultiByte(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0,NULL,NULL);
1019         szHeaders=HeapAlloc(GetProcessHeap(),0,nLen);
1020         WideCharToMultiByte(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen,NULL,NULL);
1021     }
1022     result=HttpSendRequestA(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
1023     if(szHeaders!=NULL)
1024         HeapFree(GetProcessHeap(),0,szHeaders);
1025     return result;
1026 }
1027
1028 /***********************************************************************
1029  *           HTTP_HandleRedirect (internal)
1030  */
1031 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQA lpwhr, LPCSTR lpszUrl, LPCSTR lpszHeaders,
1032                                 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength)
1033 {
1034     LPWININETHTTPSESSIONA lpwhs = (LPWININETHTTPSESSIONA) lpwhr->hdr.lpwhparent;
1035     LPWININETAPPINFOA hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
1036     char path[2048];
1037     if(lpszUrl[0]=='/')
1038     {
1039         /* if it's an absolute path, keep the same session info */
1040         strcpy(path,lpszUrl);
1041     }
1042     else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1043     {
1044         TRACE("Redirect through proxy\n");
1045         strcpy(path,lpszUrl);
1046     }
1047     else
1048     {
1049         URL_COMPONENTSA urlComponents;
1050         char protocol[32], hostName[MAXHOSTNAME], userName[1024];
1051         char password[1024], extra[1024];
1052         urlComponents.dwStructSize = sizeof(URL_COMPONENTSA);
1053         urlComponents.lpszScheme = protocol;
1054         urlComponents.dwSchemeLength = 32;
1055         urlComponents.lpszHostName = hostName;
1056         urlComponents.dwHostNameLength = MAXHOSTNAME;
1057         urlComponents.lpszUserName = userName;
1058         urlComponents.dwUserNameLength = 1024;
1059         urlComponents.lpszPassword = password;
1060         urlComponents.dwPasswordLength = 1024;
1061         urlComponents.lpszUrlPath = path;
1062         urlComponents.dwUrlPathLength = 2048;
1063         urlComponents.lpszExtraInfo = extra;
1064         urlComponents.dwExtraInfoLength = 1024;
1065         if(!InternetCrackUrlA(lpszUrl, strlen(lpszUrl), 0, &urlComponents))
1066             return FALSE;
1067         
1068         if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1069             urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1070
1071 #if 0
1072         /*
1073          * This upsets redirects to binary files on sourceforge.net 
1074          * and gives an html page instead of the target file
1075          * Examination of the HTTP request sent by native wininet.dll
1076          * reveals that it doesn't send a referrer in that case.
1077          * Maybe there's a flag that enables this, or maybe a referrer
1078          * shouldn't be added in case of a redirect.
1079          */
1080
1081         /* consider the current host as the referrer */
1082         if (NULL != lpwhs->lpszServerName && strlen(lpwhs->lpszServerName))
1083             HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
1084                            HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
1085                            HTTP_ADDHDR_FLAG_ADD_IF_NEW);
1086 #endif
1087         
1088         if (NULL != lpwhs->lpszServerName)
1089             HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1090         lpwhs->lpszServerName = HTTP_strdup(hostName);
1091         if (NULL != lpwhs->lpszUserName)
1092             HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
1093         lpwhs->lpszUserName = HTTP_strdup(userName);
1094         lpwhs->nServerPort = urlComponents.nPort;
1095
1096         if (NULL != lpwhr->lpszHostName)
1097             HeapFree(GetProcessHeap(), 0, lpwhr->lpszHostName);
1098         lpwhr->lpszHostName=HTTP_strdup(hostName);
1099
1100         SendAsyncCallback(hIC, lpwhs, lpwhr->hdr.dwContext,
1101                       INTERNET_STATUS_RESOLVING_NAME,
1102                       lpwhs->lpszServerName,
1103                       strlen(lpwhs->lpszServerName)+1);
1104
1105         if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1106                     &lpwhs->phostent, &lpwhs->socketAddress))
1107         {
1108             INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1109             return FALSE;
1110         }
1111
1112         SendAsyncCallback(hIC, lpwhs, lpwhr->hdr.dwContext,
1113                       INTERNET_STATUS_NAME_RESOLVED,
1114                       &(lpwhs->socketAddress),
1115                       sizeof(struct sockaddr_in));
1116
1117     }
1118
1119     if(lpwhr->lpszPath)
1120         HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1121     lpwhr->lpszPath=NULL;
1122     if (strlen(path))
1123     {
1124         DWORD needed = 0;
1125         HRESULT rc;
1126         rc = UrlEscapeA(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
1127         if (rc != E_POINTER)
1128             needed = strlen(path)+1;
1129         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed);
1130         rc = UrlEscapeA(path, lpwhr->lpszPath, &needed,
1131                         URL_ESCAPE_SPACES_ONLY);
1132         if (rc)
1133         {
1134             ERR("Unable to escape string!(%s) (%ld)\n",path,rc);
1135             strcpy(lpwhr->lpszPath,path);
1136         }
1137     }
1138
1139     return HttpSendRequestA((HINTERNET)lpwhr, lpszHeaders, dwHeaderLength, lpOptional, dwOptionalLength);
1140 }
1141
1142 /***********************************************************************
1143  *           HTTP_HttpSendRequestA (internal)
1144  *
1145  * Sends the specified request to the HTTP server
1146  *
1147  * RETURNS
1148  *    TRUE  on success
1149  *    FALSE on failure
1150  *
1151  */
1152 BOOL WINAPI HTTP_HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
1153         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1154 {
1155     INT cnt;
1156     INT i;
1157     BOOL bSuccess = FALSE;
1158     LPSTR requestString = NULL;
1159     INT requestStringLen;
1160     INT responseLen;
1161     INT headerLength = 0;
1162     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hHttpRequest;
1163     LPWININETHTTPSESSIONA lpwhs = NULL;
1164     LPWININETAPPINFOA hIC = NULL;
1165     BOOL loop_next = FALSE;
1166     int CustHeaderIndex;
1167
1168     TRACE("--> 0x%08lx\n", (ULONG)hHttpRequest);
1169
1170     /* Verify our tree of internet handles */
1171     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
1172     {
1173         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1174         return FALSE;
1175     }
1176
1177     lpwhs = (LPWININETHTTPSESSIONA) lpwhr->hdr.lpwhparent;
1178     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
1179     {
1180         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1181         return FALSE;
1182     }
1183
1184     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
1185     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT)
1186     {
1187         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1188         return FALSE;
1189     }
1190
1191     /* Clear any error information */
1192     INTERNET_SetLastError(0);
1193
1194
1195     /* We must have a verb */
1196     if (NULL == lpwhr->lpszVerb)
1197     {
1198             goto lend;
1199     }
1200
1201     /* if we are using optional stuff, we must add the fixed header of that option length */
1202     if (lpOptional && dwOptionalLength)
1203     {
1204         char contentLengthStr[sizeof("Content-Length: ") + 20 /* int */ + 2 /* \n\r */];
1205         sprintf(contentLengthStr, "Content-Length: %li\r\n", dwOptionalLength);
1206         HttpAddRequestHeadersA(hHttpRequest, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD);
1207     }
1208
1209     do
1210     {
1211         TRACE("Going to url %s %s\n", debugstr_a(lpwhr->lpszHostName), debugstr_a(lpwhr->lpszPath));
1212         loop_next = FALSE;
1213
1214         /* If we don't have a path we set it to root */
1215         if (NULL == lpwhr->lpszPath)
1216             lpwhr->lpszPath = HTTP_strdup("/");
1217
1218         if(strncmp(lpwhr->lpszPath, "http://", sizeof("http://") -1) != 0
1219            && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
1220         {
1221             char *fixurl = HeapAlloc(GetProcessHeap(), 0, strlen(lpwhr->lpszPath) + 2);
1222             *fixurl = '/';
1223             strcpy(fixurl + 1, lpwhr->lpszPath);
1224             HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
1225             lpwhr->lpszPath = fixurl;
1226         }
1227
1228         /* Calculate length of request string */
1229         requestStringLen =
1230             strlen(lpwhr->lpszVerb) +
1231             strlen(lpwhr->lpszPath) +
1232             strlen(HTTPHEADER) +
1233             5; /* " \r\n\r\n" */
1234
1235         /* Add length of passed headers */
1236         if (lpszHeaders)
1237         {
1238             headerLength = -1 == dwHeaderLength ?  strlen(lpszHeaders) : dwHeaderLength;
1239             requestStringLen += headerLength +  2; /* \r\n */
1240         }
1241
1242
1243         /* if there isa proxy username and password, add it to the headers */
1244         if( hIC && (hIC->lpszProxyUsername || hIC->lpszProxyPassword ) )
1245         {
1246             HTTP_InsertProxyAuthorization( lpwhr, hIC->lpszProxyUsername, hIC->lpszProxyPassword );
1247         }
1248
1249         /* Calculate length of custom request headers */
1250         for (i = 0; i < lpwhr->nCustHeaders; i++)
1251         {
1252             if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
1253             {
1254                 requestStringLen += strlen(lpwhr->pCustHeaders[i].lpszField) +
1255                     strlen(lpwhr->pCustHeaders[i].lpszValue) + 4; /*: \r\n */
1256             }
1257         }
1258
1259         /* Calculate the length of standard request headers */
1260         for (i = 0; i <= HTTP_QUERY_MAX; i++)
1261         {
1262             if (lpwhr->StdHeaders[i].wFlags & HDR_ISREQUEST)
1263             {
1264                 requestStringLen += strlen(lpwhr->StdHeaders[i].lpszField) +
1265                     strlen(lpwhr->StdHeaders[i].lpszValue) + 4; /*: \r\n */
1266             }
1267         }
1268
1269         if (lpwhr->lpszHostName)
1270             requestStringLen += (strlen(HTTPHOSTHEADER) + strlen(lpwhr->lpszHostName));
1271
1272         /* if there is optional data to send, add the length */
1273         if (lpOptional)
1274         {
1275             requestStringLen += dwOptionalLength;
1276         }
1277
1278         /* Allocate string to hold entire request */
1279         requestString = HeapAlloc(GetProcessHeap(), 0, requestStringLen + 1);
1280         if (NULL == requestString)
1281         {
1282             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1283             goto lend;
1284         }
1285
1286         /* Build request string */
1287         cnt = sprintf(requestString, "%s %s%s",
1288                       lpwhr->lpszVerb,
1289                       lpwhr->lpszPath,
1290                       HTTPHEADER);
1291
1292         /* Append standard request headers */
1293         for (i = 0; i <= HTTP_QUERY_MAX; i++)
1294         {
1295             if (lpwhr->StdHeaders[i].wFlags & HDR_ISREQUEST)
1296             {
1297                 cnt += sprintf(requestString + cnt, "\r\n%s: %s",
1298                                lpwhr->StdHeaders[i].lpszField, lpwhr->StdHeaders[i].lpszValue);
1299                 TRACE("Adding header %s (%s)\n",lpwhr->StdHeaders[i].lpszField,lpwhr->StdHeaders[i].lpszValue);
1300             }
1301         }
1302
1303         /* Append custom request heades */
1304         for (i = 0; i < lpwhr->nCustHeaders; i++)
1305         {
1306             if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
1307             {
1308                 cnt += sprintf(requestString + cnt, "\r\n%s: %s",
1309                                lpwhr->pCustHeaders[i].lpszField, lpwhr->pCustHeaders[i].lpszValue);
1310                 TRACE("Adding custom header %s (%s)\n",lpwhr->pCustHeaders[i].lpszField,lpwhr->pCustHeaders[i].lpszValue);
1311             }
1312         }
1313
1314         if (lpwhr->lpszHostName)
1315             cnt += sprintf(requestString + cnt, "%s%s", HTTPHOSTHEADER, lpwhr->lpszHostName);
1316
1317         /* Append passed request headers */
1318         if (lpszHeaders)
1319         {
1320             strcpy(requestString + cnt, "\r\n");
1321             cnt += 2;
1322             strcpy(requestString + cnt, lpszHeaders);
1323             cnt += headerLength;
1324         }
1325
1326         /* Set (header) termination string for request */
1327         if (memcmp((requestString + cnt) - 4, "\r\n\r\n", 4) != 0)
1328         { /* only add it if the request string doesn't already
1329              have the thing.. (could happen if the custom header
1330              added it */
1331                 strcpy(requestString + cnt, "\r\n");
1332                 cnt += 2;
1333         }
1334         else
1335             requestStringLen -= 2;
1336  
1337         /* if optional data, append it */
1338         if (lpOptional)
1339         {
1340             memcpy(requestString + cnt, lpOptional, dwOptionalLength);
1341             cnt += dwOptionalLength;
1342             /* we also have to decrease the expected string length by two,
1343              * since we won't be adding on those following \r\n's */
1344             requestStringLen -= 2;
1345         }
1346         else
1347         { /* if there is no optional data, add on another \r\n just to be safe */
1348                 /* termination for request */
1349                 strcpy(requestString + cnt, "\r\n");
1350                 cnt += 2;
1351         }
1352
1353         TRACE("(%s) len(%d)\n", requestString, requestStringLen);
1354         /* Send the request and store the results */
1355         if (!HTTP_OpenConnection(lpwhr))
1356             goto lend;
1357
1358         SendAsyncCallback(hIC, hHttpRequest, lpwhr->hdr.dwContext,
1359                           INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1360
1361         NETCON_send(&lpwhr->netConnection, requestString, requestStringLen,
1362                     0, &cnt);
1363
1364
1365         SendAsyncCallback(hIC, hHttpRequest, lpwhr->hdr.dwContext,
1366                           INTERNET_STATUS_REQUEST_SENT,
1367                           &requestStringLen,sizeof(DWORD));
1368
1369         SendAsyncCallback(hIC, hHttpRequest, lpwhr->hdr.dwContext,
1370                           INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1371
1372         if (cnt < 0)
1373             goto lend;
1374
1375         responseLen = HTTP_GetResponseHeaders(lpwhr);
1376         if (responseLen)
1377             bSuccess = TRUE;
1378
1379         SendAsyncCallback(hIC, hHttpRequest, lpwhr->hdr.dwContext,
1380                           INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
1381                           sizeof(DWORD));
1382
1383         /* process headers here. Is this right? */
1384         CustHeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, "Set-Cookie");
1385         if (CustHeaderIndex >= 0)
1386         {
1387             LPHTTPHEADERA setCookieHeader;
1388             int nPosStart = 0, nPosEnd = 0;
1389
1390             setCookieHeader = &lpwhr->pCustHeaders[CustHeaderIndex];
1391
1392             while (setCookieHeader->lpszValue[nPosEnd] != '\0')
1393             {
1394                 LPSTR buf_cookie, cookie_name, cookie_data;
1395                 LPSTR buf_url;
1396                 LPSTR domain = NULL;
1397                 int nEqualPos = 0;
1398                 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
1399                        setCookieHeader->lpszValue[nPosEnd] != '\0')
1400                 {
1401                     nPosEnd++;
1402                 }
1403                 if (setCookieHeader->lpszValue[nPosEnd] == ';')
1404                 {
1405                     /* fixme: not case sensitive, strcasestr is gnu only */
1406                     int nDomainPosEnd = 0;
1407                     int nDomainPosStart = 0, nDomainLength = 0;
1408                     LPSTR lpszDomain = strstr(&setCookieHeader->lpszValue[nPosEnd], "domain=");
1409                     if (lpszDomain)
1410                     { /* they have specified their own domain, lets use it */
1411                         while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
1412                                lpszDomain[nDomainPosEnd] != '\0')
1413                         {
1414                             nDomainPosEnd++;
1415                         }
1416                         nDomainPosStart = strlen("domain=");
1417                         nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
1418                         domain = HeapAlloc(GetProcessHeap(), 0, nDomainLength + 1);
1419                         strncpy(domain, &lpszDomain[nDomainPosStart], nDomainLength);
1420                         domain[nDomainLength] = '\0';
1421                     }
1422                 }
1423                 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
1424                 buf_cookie = HeapAlloc(GetProcessHeap(), 0, (nPosEnd - nPosStart) + 1);
1425                 strncpy(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart));
1426                 buf_cookie[(nPosEnd - nPosStart)] = '\0';
1427                 TRACE("%s\n", buf_cookie);
1428                 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
1429                 {
1430                     nEqualPos++;
1431                 }
1432                 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
1433                 {
1434                     HeapFree(GetProcessHeap(), 0, buf_cookie);
1435                     break;
1436                 }
1437
1438                 cookie_name = HeapAlloc(GetProcessHeap(), 0, nEqualPos + 1);
1439                 strncpy(cookie_name, buf_cookie, nEqualPos);
1440                 cookie_name[nEqualPos] = '\0';
1441                 cookie_data = &buf_cookie[nEqualPos + 1];
1442
1443
1444                 buf_url = HeapAlloc(GetProcessHeap(), 0, strlen((domain ? domain : lpwhr->lpszHostName)) + strlen(lpwhr->lpszPath) + 9);
1445                 sprintf(buf_url, "http://%s/", (domain ? domain : lpwhr->lpszHostName)); /* FIXME PATH!!! */
1446                 InternetSetCookieA(buf_url, cookie_name, cookie_data);
1447
1448                 HeapFree(GetProcessHeap(), 0, buf_url);
1449                 HeapFree(GetProcessHeap(), 0, buf_cookie);
1450                 HeapFree(GetProcessHeap(), 0, cookie_name);
1451                 if (domain) HeapFree(GetProcessHeap(), 0, domain);
1452                 nPosStart = nPosEnd;
1453             }
1454         }
1455     }
1456     while (loop_next);
1457
1458 lend:
1459
1460     if (requestString)
1461         HeapFree(GetProcessHeap(), 0, requestString);
1462
1463     /* TODO: send notification for P3P header */
1464     
1465     if(!(hIC->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
1466     {
1467         DWORD dwCode,dwCodeLength=sizeof(DWORD),dwIndex=0;
1468         if(HttpQueryInfoA(hHttpRequest,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,&dwIndex) &&
1469             (dwCode==302 || dwCode==301))
1470         {
1471             char szNewLocation[2048];
1472             DWORD dwBufferSize=2048;
1473             dwIndex=0;
1474             if(HttpQueryInfoA(hHttpRequest,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,&dwIndex))
1475             {
1476                 SendAsyncCallback(hIC, hHttpRequest, lpwhr->hdr.dwContext,
1477                       INTERNET_STATUS_REDIRECT, szNewLocation,
1478                       dwBufferSize);
1479                 return HTTP_HandleRedirect(lpwhr, szNewLocation, lpszHeaders,
1480                                            dwHeaderLength, lpOptional, dwOptionalLength);
1481             }
1482         }
1483     }
1484
1485     if (hIC->lpfnStatusCB)
1486     {
1487         INTERNET_ASYNC_RESULT iar;
1488
1489         iar.dwResult = (DWORD)bSuccess;
1490         iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1491
1492         SendAsyncCallback(hIC, hHttpRequest, lpwhr->hdr.dwContext,
1493                       INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1494                       sizeof(INTERNET_ASYNC_RESULT));
1495     }
1496
1497     TRACE("<--\n");
1498     return bSuccess;
1499 }
1500
1501
1502 /***********************************************************************
1503  *           HTTP_Connect  (internal)
1504  *
1505  * Create http session handle
1506  *
1507  * RETURNS
1508  *   HINTERNET a session handle on success
1509  *   NULL on failure
1510  *
1511  */
1512 HINTERNET HTTP_Connect(HINTERNET hInternet, LPCSTR lpszServerName,
1513         INTERNET_PORT nServerPort, LPCSTR lpszUserName,
1514         LPCSTR lpszPassword, DWORD dwFlags, DWORD dwContext)
1515 {
1516     BOOL bSuccess = FALSE;
1517     LPWININETAPPINFOA hIC = NULL;
1518     LPWININETHTTPSESSIONA lpwhs = NULL;
1519
1520     TRACE("-->\n");
1521
1522     if (((LPWININETHANDLEHEADER)hInternet)->htype != WH_HINIT)
1523         goto lerror;
1524
1525     hIC = (LPWININETAPPINFOA) hInternet;
1526     hIC->hdr.dwContext = dwContext;
1527     
1528     lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONA));
1529     if (NULL == lpwhs)
1530     {
1531         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1532         goto lerror;
1533     }
1534
1535    /*
1536     * According to my tests. The name is not resolved until a request is sent
1537     */
1538
1539     if (nServerPort == INTERNET_INVALID_PORT_NUMBER)
1540         nServerPort = INTERNET_DEFAULT_HTTP_PORT;
1541
1542     lpwhs->hdr.htype = WH_HHTTPSESSION;
1543     lpwhs->hdr.lpwhparent = (LPWININETHANDLEHEADER)hInternet;
1544     lpwhs->hdr.dwFlags = dwFlags;
1545     lpwhs->hdr.dwContext = dwContext;
1546     if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
1547         if(strchr(hIC->lpszProxy, ' '))
1548             FIXME("Several proxies not implemented.\n");
1549         if(hIC->lpszProxyBypass)
1550             FIXME("Proxy bypass is ignored.\n");
1551     }
1552     if (NULL != lpszServerName)
1553         lpwhs->lpszServerName = HTTP_strdup(lpszServerName);
1554     if (NULL != lpszUserName)
1555         lpwhs->lpszUserName = HTTP_strdup(lpszUserName);
1556     lpwhs->nServerPort = nServerPort;
1557
1558     if (hIC->lpfnStatusCB)
1559     {
1560         INTERNET_ASYNC_RESULT iar;
1561
1562         iar.dwResult = (DWORD)lpwhs;
1563         iar.dwError = ERROR_SUCCESS;
1564
1565         SendAsyncCallback(hIC, hInternet, dwContext,
1566                       INTERNET_STATUS_HANDLE_CREATED, &iar,
1567                       sizeof(INTERNET_ASYNC_RESULT));
1568     }
1569
1570     bSuccess = TRUE;
1571
1572 lerror:
1573     if (!bSuccess && lpwhs)
1574     {
1575         HeapFree(GetProcessHeap(), 0, lpwhs);
1576         lpwhs = NULL;
1577     }
1578
1579 /*
1580  * a INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
1581  * windows
1582  */
1583
1584     TRACE("%p -->\n", hInternet);
1585     return (HINTERNET)lpwhs;
1586 }
1587
1588
1589 /***********************************************************************
1590  *           HTTP_OpenConnection (internal)
1591  *
1592  * Connect to a web server
1593  *
1594  * RETURNS
1595  *
1596  *   TRUE  on success
1597  *   FALSE on failure
1598  */
1599 BOOL HTTP_OpenConnection(LPWININETHTTPREQA lpwhr)
1600 {
1601     BOOL bSuccess = FALSE;
1602     LPWININETHTTPSESSIONA lpwhs;
1603     LPWININETAPPINFOA hIC = NULL;
1604
1605     TRACE("-->\n");
1606
1607
1608     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
1609     {
1610         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1611         goto lend;
1612     }
1613
1614     lpwhs = (LPWININETHTTPSESSIONA)lpwhr->hdr.lpwhparent;
1615
1616     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
1617     SendAsyncCallback(hIC, lpwhr, lpwhr->hdr.dwContext,
1618                       INTERNET_STATUS_CONNECTING_TO_SERVER,
1619                       &(lpwhs->socketAddress),
1620                        sizeof(struct sockaddr_in));
1621
1622     if (!NETCON_create(&lpwhr->netConnection, lpwhs->phostent->h_addrtype,
1623                          SOCK_STREAM, 0))
1624     {
1625         WARN("Socket creation failed\n");
1626         goto lend;
1627     }
1628
1629     if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
1630                       sizeof(lpwhs->socketAddress)))
1631     {
1632        WARN("Unable to connect to host (%s)\n", strerror(errno));
1633        goto lend;
1634     }
1635
1636     SendAsyncCallback(hIC, lpwhr, lpwhr->hdr.dwContext,
1637                       INTERNET_STATUS_CONNECTED_TO_SERVER,
1638                       &(lpwhs->socketAddress),
1639                        sizeof(struct sockaddr_in));
1640
1641     bSuccess = TRUE;
1642
1643 lend:
1644     TRACE("%d <--\n", bSuccess);
1645     return bSuccess;
1646 }
1647
1648
1649 /***********************************************************************
1650  *           HTTP_GetResponseHeaders (internal)
1651  *
1652  * Read server response
1653  *
1654  * RETURNS
1655  *
1656  *   TRUE  on success
1657  *   FALSE on error
1658  */
1659 BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQA lpwhr)
1660 {
1661     INT cbreaks = 0;
1662     CHAR buffer[MAX_REPLY_LEN];
1663     DWORD buflen = MAX_REPLY_LEN;
1664     BOOL bSuccess = FALSE;
1665     INT  rc = 0;
1666     CHAR value[MAX_FIELD_VALUE_LEN], field[MAX_FIELD_LEN];
1667
1668     TRACE("-->\n");
1669
1670     if (!NETCON_connected(&lpwhr->netConnection))
1671         goto lend;
1672
1673     /*
1674      * HACK peek at the buffer
1675      */
1676     NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
1677
1678     /*
1679      * We should first receive 'HTTP/1.x nnn' where nnn is the status code.
1680      */
1681     buflen = MAX_REPLY_LEN;
1682     memset(buffer, 0, MAX_REPLY_LEN);
1683     if (!NETCON_getNextLine(&lpwhr->netConnection, buffer, &buflen))
1684         goto lend;
1685
1686     if (strncmp(buffer, "HTTP", 4) != 0)
1687         goto lend;
1688
1689     buffer[12]='\0';
1690     HTTP_ProcessHeader(lpwhr, "Status", buffer+9, (HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE));
1691
1692     /* Parse each response line */
1693     do
1694     {
1695         buflen = MAX_REPLY_LEN;
1696         if (NETCON_getNextLine(&lpwhr->netConnection, buffer, &buflen))
1697         {
1698             TRACE("got line %s, now interpretting\n", debugstr_a(buffer));
1699             if (!HTTP_InterpretHttpHeader(buffer, field, MAX_FIELD_LEN, value, MAX_FIELD_VALUE_LEN))
1700                 break;
1701
1702             HTTP_ProcessHeader(lpwhr, field, value, (HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE));
1703         }
1704         else
1705         {
1706             cbreaks++;
1707             if (cbreaks >= 2)
1708                break;
1709         }
1710     }while(1);
1711
1712     bSuccess = TRUE;
1713
1714 lend:
1715
1716     TRACE("<--\n");
1717     if (bSuccess)
1718         return rc;
1719     else
1720         return FALSE;
1721 }
1722
1723
1724 /***********************************************************************
1725  *           HTTP_InterpretHttpHeader (internal)
1726  *
1727  * Parse server response
1728  *
1729  * RETURNS
1730  *
1731  *   TRUE  on success
1732  *   FALSE on error
1733  */
1734 INT stripSpaces(LPCSTR lpszSrc, LPSTR lpszStart, INT *len)
1735 {
1736     LPCSTR lpsztmp;
1737     INT srclen;
1738
1739     srclen = 0;
1740
1741     while (*lpszSrc == ' ' && *lpszSrc != '\0')
1742         lpszSrc++;
1743
1744     lpsztmp = lpszSrc;
1745     while(*lpsztmp != '\0')
1746     {
1747         if (*lpsztmp != ' ')
1748             srclen = lpsztmp - lpszSrc + 1;
1749
1750         lpsztmp++;
1751     }
1752
1753     *len = min(*len, srclen);
1754     strncpy(lpszStart, lpszSrc, *len);
1755     lpszStart[*len] = '\0';
1756
1757     return *len;
1758 }
1759
1760
1761 BOOL HTTP_InterpretHttpHeader(LPSTR buffer, LPSTR field, INT fieldlen, LPSTR value, INT valuelen)
1762 {
1763     CHAR *pd;
1764     BOOL bSuccess = FALSE;
1765
1766     TRACE("\n");
1767
1768     *field = '\0';
1769     *value = '\0';
1770
1771     pd = strchr(buffer, ':');
1772     if (pd)
1773     {
1774         *pd = '\0';
1775         if (stripSpaces(buffer, field, &fieldlen) > 0)
1776         {
1777             if (stripSpaces(pd+1, value, &valuelen) > 0)
1778                 bSuccess = TRUE;
1779         }
1780     }
1781
1782     TRACE("%d: field(%s) Value(%s)\n", bSuccess, field, value);
1783     return bSuccess;
1784 }
1785
1786
1787 /***********************************************************************
1788  *           HTTP_GetStdHeaderIndex (internal)
1789  *
1790  * Lookup field index in standard http header array
1791  *
1792  * FIXME: This should be stuffed into a hash table
1793  */
1794 INT HTTP_GetStdHeaderIndex(LPCSTR lpszField)
1795 {
1796     INT index = -1;
1797
1798     if (!strcasecmp(lpszField, "Content-Length"))
1799         index = HTTP_QUERY_CONTENT_LENGTH;
1800     else if (!strcasecmp(lpszField,"Status"))
1801         index = HTTP_QUERY_STATUS_CODE;
1802     else if (!strcasecmp(lpszField,"Content-Type"))
1803         index = HTTP_QUERY_CONTENT_TYPE;
1804     else if (!strcasecmp(lpszField,"Last-Modified"))
1805         index = HTTP_QUERY_LAST_MODIFIED;
1806     else if (!strcasecmp(lpszField,"Location"))
1807         index = HTTP_QUERY_LOCATION;
1808     else if (!strcasecmp(lpszField,"Accept"))
1809         index = HTTP_QUERY_ACCEPT;
1810     else if (!strcasecmp(lpszField,"Referer"))
1811         index = HTTP_QUERY_REFERER;
1812     else if (!strcasecmp(lpszField,"Content-Transfer-Encoding"))
1813         index = HTTP_QUERY_CONTENT_TRANSFER_ENCODING;
1814     else if (!strcasecmp(lpszField,"Date"))
1815         index = HTTP_QUERY_DATE;
1816     else if (!strcasecmp(lpszField,"Server"))
1817         index = HTTP_QUERY_SERVER;
1818     else if (!strcasecmp(lpszField,"Connection"))
1819         index = HTTP_QUERY_CONNECTION;
1820     else if (!strcasecmp(lpszField,"ETag"))
1821         index = HTTP_QUERY_ETAG;
1822     else if (!strcasecmp(lpszField,"Accept-Ranges"))
1823         index = HTTP_QUERY_ACCEPT_RANGES;
1824     else if (!strcasecmp(lpszField,"Expires"))
1825         index = HTTP_QUERY_EXPIRES;
1826     else if (!strcasecmp(lpszField,"Mime-Version"))
1827         index = HTTP_QUERY_MIME_VERSION;
1828     else if (!strcasecmp(lpszField,"Pragma"))
1829         index = HTTP_QUERY_PRAGMA;
1830     else if (!strcasecmp(lpszField,"Cache-Control"))
1831         index = HTTP_QUERY_CACHE_CONTROL;
1832     else if (!strcasecmp(lpszField,"Content-Length"))
1833         index = HTTP_QUERY_CONTENT_LENGTH;
1834     else if (!strcasecmp(lpszField,"User-Agent"))
1835         index = HTTP_QUERY_USER_AGENT;
1836     else if (!strcasecmp(lpszField,"Proxy-Authenticate"))
1837         index = HTTP_QUERY_PROXY_AUTHENTICATE;
1838     else
1839     {
1840        TRACE("Couldn't find %s in standard header table\n", lpszField);
1841     }
1842
1843     return index;
1844 }
1845
1846
1847 /***********************************************************************
1848  *           HTTP_ProcessHeader (internal)
1849  *
1850  * Stuff header into header tables according to <dwModifier>
1851  *
1852  */
1853
1854 #define COALESCEFLASG (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
1855
1856 BOOL HTTP_ProcessHeader(LPWININETHTTPREQA lpwhr, LPCSTR field, LPCSTR value, DWORD dwModifier)
1857 {
1858     LPHTTPHEADERA lphttpHdr = NULL;
1859     BOOL bSuccess = FALSE;
1860     INT index;
1861
1862     TRACE("--> %s: %s - 0x%08x\n", field, value, (unsigned int)dwModifier);
1863
1864     /* Adjust modifier flags */
1865     if (dwModifier & COALESCEFLASG)
1866         dwModifier |= HTTP_ADDHDR_FLAG_ADD;
1867
1868     /* Try to get index into standard header array */
1869     index = HTTP_GetStdHeaderIndex(field);
1870     if (index >= 0)
1871     {
1872         lphttpHdr = &lpwhr->StdHeaders[index];
1873     }
1874     else /* Find or create new custom header */
1875     {
1876         index = HTTP_GetCustomHeaderIndex(lpwhr, field);
1877         if (index >= 0)
1878         {
1879             if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
1880             {
1881                 return FALSE;
1882             }
1883             lphttpHdr = &lpwhr->pCustHeaders[index];
1884         }
1885         else
1886         {
1887             HTTPHEADERA hdr;
1888
1889             hdr.lpszField = (LPSTR)field;
1890             hdr.lpszValue = (LPSTR)value;
1891             hdr.wFlags = hdr.wCount = 0;
1892
1893             if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
1894                 hdr.wFlags |= HDR_ISREQUEST;
1895
1896             return HTTP_InsertCustomHeader(lpwhr, &hdr);
1897         }
1898     }
1899
1900     if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
1901         lphttpHdr->wFlags |= HDR_ISREQUEST;
1902     else
1903         lphttpHdr->wFlags &= ~HDR_ISREQUEST;
1904
1905     if (!lphttpHdr->lpszValue && (dwModifier & (HTTP_ADDHDR_FLAG_ADD|HTTP_ADDHDR_FLAG_ADD_IF_NEW)))
1906     {
1907         INT slen;
1908
1909         if (!lpwhr->StdHeaders[index].lpszField)
1910         {
1911             lphttpHdr->lpszField = HTTP_strdup(field);
1912
1913             if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
1914                 lphttpHdr->wFlags |= HDR_ISREQUEST;
1915         }
1916
1917         slen = strlen(value) + 1;
1918         lphttpHdr->lpszValue = HeapAlloc(GetProcessHeap(), 0, slen);
1919         if (lphttpHdr->lpszValue)
1920         {
1921             memcpy(lphttpHdr->lpszValue, value, slen);
1922             bSuccess = TRUE;
1923         }
1924         else
1925         {
1926             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1927         }
1928     }
1929     else if (lphttpHdr->lpszValue)
1930     {
1931         if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
1932         {
1933             LPSTR lpsztmp;
1934             INT len;
1935
1936             len = strlen(value);
1937
1938             if (len <= 0)
1939             {
1940                 /* if custom header delete from array */
1941                 HeapFree(GetProcessHeap(), 0, lphttpHdr->lpszValue);
1942                 lphttpHdr->lpszValue = NULL;
1943                 bSuccess = TRUE;
1944             }
1945             else
1946             {
1947                 lpsztmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,  lphttpHdr->lpszValue, len+1);
1948                 if (lpsztmp)
1949                 {
1950                     lphttpHdr->lpszValue = lpsztmp;
1951                     strcpy(lpsztmp, value);
1952                     bSuccess = TRUE;
1953                 }
1954                 else
1955                 {
1956                     WARN("HeapReAlloc (%d bytes) failed\n",len+1);
1957                     INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1958                 }
1959             }
1960         }
1961         else if (dwModifier & COALESCEFLASG)
1962         {
1963             LPSTR lpsztmp;
1964             CHAR ch = 0;
1965             INT len = 0;
1966             INT origlen = strlen(lphttpHdr->lpszValue);
1967             INT valuelen = strlen(value);
1968
1969             if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
1970             {
1971                 ch = ',';
1972                 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
1973             }
1974             else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
1975             {
1976                 ch = ';';
1977                 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
1978             }
1979
1980             len = origlen + valuelen + ((ch > 0) ? 1 : 0);
1981
1982             lpsztmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,  lphttpHdr->lpszValue, len+1);
1983             if (lpsztmp)
1984             {
1985                 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
1986                 if (ch > 0)
1987                 {
1988                     lphttpHdr->lpszValue[origlen] = ch;
1989                     origlen++;
1990                 }
1991
1992                 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen);
1993                 lphttpHdr->lpszValue[len] = '\0';
1994                 bSuccess = TRUE;
1995             }
1996             else
1997             {
1998                 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
1999                 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2000             }
2001         }
2002     }
2003     TRACE("<-- %d\n",bSuccess);
2004     return bSuccess;
2005 }
2006
2007
2008 /***********************************************************************
2009  *           HTTP_CloseConnection (internal)
2010  *
2011  * Close socket connection
2012  *
2013  */
2014 VOID HTTP_CloseConnection(LPWININETHTTPREQA lpwhr)
2015 {
2016
2017
2018     LPWININETHTTPSESSIONA lpwhs = NULL;
2019     LPWININETAPPINFOA hIC = NULL;
2020
2021     TRACE("%p\n",lpwhr);
2022
2023     lpwhs = (LPWININETHTTPSESSIONA) lpwhr->hdr.lpwhparent;
2024     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
2025
2026     SendAsyncCallback(hIC, lpwhr, lpwhr->hdr.dwContext,
2027                       INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2028
2029     if (NETCON_connected(&lpwhr->netConnection))
2030     {
2031         NETCON_close(&lpwhr->netConnection);
2032     }
2033
2034     SendAsyncCallback(hIC, lpwhr, lpwhr->hdr.dwContext,
2035                       INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2036 }
2037
2038
2039 /***********************************************************************
2040  *           HTTP_CloseHTTPRequestHandle (internal)
2041  *
2042  * Deallocate request handle
2043  *
2044  */
2045 void HTTP_CloseHTTPRequestHandle(LPWININETHTTPREQA lpwhr)
2046 {
2047     int i;
2048     LPWININETHTTPSESSIONA lpwhs = NULL;
2049     LPWININETAPPINFOA hIC = NULL;
2050
2051     TRACE("\n");
2052
2053     if (NETCON_connected(&lpwhr->netConnection))
2054         HTTP_CloseConnection(lpwhr);
2055
2056     lpwhs = (LPWININETHTTPSESSIONA) lpwhr->hdr.lpwhparent;
2057     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
2058
2059     SendAsyncCallback(hIC, lpwhr, lpwhr->hdr.dwContext,
2060                       INTERNET_STATUS_HANDLE_CLOSING, lpwhr,
2061                       sizeof(HINTERNET));
2062
2063     if (lpwhr->lpszPath)
2064         HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2065     if (lpwhr->lpszVerb)
2066         HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
2067     if (lpwhr->lpszHostName)
2068         HeapFree(GetProcessHeap(), 0, lpwhr->lpszHostName);
2069
2070     for (i = 0; i <= HTTP_QUERY_MAX; i++)
2071     {
2072            if (lpwhr->StdHeaders[i].lpszField)
2073             HeapFree(GetProcessHeap(), 0, lpwhr->StdHeaders[i].lpszField);
2074            if (lpwhr->StdHeaders[i].lpszValue)
2075             HeapFree(GetProcessHeap(), 0, lpwhr->StdHeaders[i].lpszValue);
2076     }
2077
2078     for (i = 0; i < lpwhr->nCustHeaders; i++)
2079     {
2080            if (lpwhr->pCustHeaders[i].lpszField)
2081             HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
2082            if (lpwhr->pCustHeaders[i].lpszValue)
2083             HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
2084     }
2085
2086     HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
2087     HeapFree(GetProcessHeap(), 0, lpwhr);
2088 }
2089
2090
2091 /***********************************************************************
2092  *           HTTP_CloseHTTPSessionHandle (internal)
2093  *
2094  * Deallocate session handle
2095  *
2096  */
2097 void HTTP_CloseHTTPSessionHandle(LPWININETHTTPSESSIONA lpwhs)
2098 {
2099     LPWININETAPPINFOA hIC = NULL;
2100     TRACE("%p\n", lpwhs);
2101
2102     hIC = (LPWININETAPPINFOA) lpwhs->hdr.lpwhparent;
2103
2104     SendAsyncCallback(hIC, lpwhs, lpwhs->hdr.dwContext,
2105                       INTERNET_STATUS_HANDLE_CLOSING, lpwhs,
2106                       sizeof(HINTERNET));
2107
2108     if (lpwhs->lpszServerName)
2109         HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2110     if (lpwhs->lpszUserName)
2111         HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2112     HeapFree(GetProcessHeap(), 0, lpwhs);
2113 }
2114
2115
2116 /***********************************************************************
2117  *           HTTP_GetCustomHeaderIndex (internal)
2118  *
2119  * Return index of custom header from header array
2120  *
2121  */
2122 INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQA lpwhr, LPCSTR lpszField)
2123 {
2124     INT index;
2125
2126     TRACE("%s\n", lpszField);
2127
2128     for (index = 0; index < lpwhr->nCustHeaders; index++)
2129     {
2130         if (!strcasecmp(lpwhr->pCustHeaders[index].lpszField, lpszField))
2131             break;
2132
2133     }
2134
2135     if (index >= lpwhr->nCustHeaders)
2136         index = -1;
2137
2138     TRACE("Return: %d\n", index);
2139     return index;
2140 }
2141
2142
2143 /***********************************************************************
2144  *           HTTP_InsertCustomHeader (internal)
2145  *
2146  * Insert header into array
2147  *
2148  */
2149 BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQA lpwhr, LPHTTPHEADERA lpHdr)
2150 {
2151     INT count;
2152     LPHTTPHEADERA lph = NULL;
2153     BOOL r = FALSE;
2154
2155     TRACE("--> %s: %s\n", lpHdr->lpszField, lpHdr->lpszValue);
2156     count = lpwhr->nCustHeaders + 1;
2157     if (count > 1)
2158         lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERA) * count);
2159     else
2160         lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERA) * count);
2161
2162     if (NULL != lph)
2163     {
2164         lpwhr->pCustHeaders = lph;
2165         lpwhr->pCustHeaders[count-1].lpszField = HTTP_strdup(lpHdr->lpszField);
2166         lpwhr->pCustHeaders[count-1].lpszValue = HTTP_strdup(lpHdr->lpszValue);
2167         lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
2168         lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
2169         lpwhr->nCustHeaders++;
2170         r = TRUE;
2171     }
2172     else
2173     {
2174         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2175     }
2176
2177     return r;
2178 }
2179
2180
2181 /***********************************************************************
2182  *           HTTP_DeleteCustomHeader (internal)
2183  *
2184  * Delete header from array
2185  *  If this function is called, the indexs may change.
2186  */
2187 BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQA lpwhr, INT index)
2188 {
2189     if( lpwhr->nCustHeaders <= 0 )
2190         return FALSE;
2191     if( lpwhr->nCustHeaders >= index )
2192         return FALSE;
2193     lpwhr->nCustHeaders--;
2194
2195     memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
2196              (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERA) );
2197     memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERA) );
2198
2199     return TRUE;
2200 }
2201
2202 /***********************************************************************
2203  *          IsHostInProxyBypassList (@)
2204  *
2205  * Undocumented
2206  *
2207  */
2208 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
2209 {
2210    FIXME("STUB: flags=%ld host=%s length=%ld\n",flags,szHost,length);
2211    return FALSE;
2212 }