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