We shouldn't pass the struct hostent returned from gethostbyname as
[wine/multimedia.git] / dlls / wininet / http.c
blobdbc71e29b7fe85d5a3961026705a0f76406373eb
1 /*
2 * Wininet - Http Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
9 * Ulrich Czekalla
10 * Aric Stewart
11 * David Hammerton
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with this library; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #include "config.h"
29 #include "wine/port.h"
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_SOCKET_H
33 # include <sys/socket.h>
34 #endif
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41 #include <errno.h>
42 #include <string.h>
43 #include <time.h>
44 #include <assert.h>
46 #include "windef.h"
47 #include "winbase.h"
48 #include "wininet.h"
49 #include "winreg.h"
50 #include "winerror.h"
51 #define NO_SHLWAPI_STREAM
52 #include "shlwapi.h"
54 #include "internet.h"
55 #include "wine/debug.h"
56 #include "wine/unicode.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
60 static const WCHAR g_szHttp[] = {' ','H','T','T','P','/','1','.','0',0 };
61 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
62 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
63 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
64 static const WCHAR g_szHost[] = {'H','o','s','t',0};
67 #define HTTPHEADER g_szHttp
68 #define MAXHOSTNAME 100
69 #define MAX_FIELD_VALUE_LEN 256
70 #define MAX_FIELD_LEN 256
72 #define HTTP_REFERER g_szReferer
73 #define HTTP_ACCEPT g_szAccept
74 #define HTTP_USERAGENT g_szUserAgent
76 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
77 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
78 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
79 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
80 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
81 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
82 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
85 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr);
86 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr);
87 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
88 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
89 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
90 static BOOL HTTP_ReplaceHeaderValue( LPHTTPHEADERW lphttpHdr, LPCWSTR lpsztmp );
91 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
92 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
93 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField);
94 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
97 /***********************************************************************
98 * HTTP_Tokenize (internal)
100 * Tokenize a string, allocating memory for the tokens.
102 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
104 LPWSTR * token_array;
105 int tokens = 0;
106 int i;
107 LPCWSTR next_token;
109 /* empty string has no tokens */
110 if (*string)
111 tokens++;
112 /* count tokens */
113 for (i = 0; string[i]; i++)
114 if (!strncmpW(string+i, token_string, strlenW(token_string)))
116 DWORD j;
117 tokens++;
118 /* we want to skip over separators, but not the null terminator */
119 for (j = 0; j < strlenW(token_string) - 1; j++)
120 if (!string[i+j])
121 break;
122 i += j;
125 /* add 1 for terminating NULL */
126 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
127 token_array[tokens] = NULL;
128 if (!tokens)
129 return token_array;
130 for (i = 0; i < tokens; i++)
132 int len;
133 next_token = strstrW(string, token_string);
134 if (!next_token) next_token = string+strlenW(string);
135 len = next_token - string;
136 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
137 memcpy(token_array[i], string, len*sizeof(WCHAR));
138 token_array[i][len] = '\0';
139 string = next_token+strlenW(token_string);
141 return token_array;
144 /***********************************************************************
145 * HTTP_FreeTokens (internal)
147 * Frees memory returned from HTTP_Tokenize.
149 static void HTTP_FreeTokens(LPWSTR * token_array)
151 int i;
152 for (i = 0; token_array[i]; i++)
153 HeapFree(GetProcessHeap(), 0, token_array[i]);
154 HeapFree(GetProcessHeap(), 0, token_array);
157 /***********************************************************************
158 * HTTP_HttpAddRequestHeadersW (internal)
160 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
161 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
163 LPWSTR lpszStart;
164 LPWSTR lpszEnd;
165 LPWSTR buffer;
166 BOOL bSuccess = FALSE;
167 DWORD len;
169 TRACE("copying header: %s\n", debugstr_w(lpszHeader));
171 if( dwHeaderLength == ~0U )
172 len = strlenW(lpszHeader);
173 else
174 len = dwHeaderLength;
175 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
176 lstrcpynW( buffer, lpszHeader, len + 1);
178 lpszStart = buffer;
182 LPWSTR * pFieldAndValue;
184 lpszEnd = lpszStart;
186 while (*lpszEnd != '\0')
188 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
189 break;
190 lpszEnd++;
193 if (*lpszStart == '\0')
194 break;
196 if (*lpszEnd == '\r')
198 *lpszEnd = '\0';
199 lpszEnd += 2; /* Jump over \r\n */
201 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
202 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
203 if (pFieldAndValue)
205 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
206 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
207 HTTP_FreeTokens(pFieldAndValue);
210 lpszStart = lpszEnd;
211 } while (bSuccess);
213 HeapFree(GetProcessHeap(), 0, buffer);
215 return bSuccess;
218 /***********************************************************************
219 * HttpAddRequestHeadersW (WININET.@)
221 * Adds one or more HTTP header to the request handler
223 * RETURNS
224 * TRUE on success
225 * FALSE on failure
228 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
229 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
231 BOOL bSuccess = FALSE;
232 LPWININETHTTPREQW lpwhr;
234 TRACE("%p, %s, %li, %li\n", hHttpRequest, debugstr_w(lpszHeader), dwHeaderLength,
235 dwModifier);
237 if (!lpszHeader)
238 return TRUE;
240 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
241 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
243 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
244 goto lend;
246 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
247 lend:
248 if( lpwhr )
249 WININET_Release( &lpwhr->hdr );
251 return bSuccess;
254 /***********************************************************************
255 * HttpAddRequestHeadersA (WININET.@)
257 * Adds one or more HTTP header to the request handler
259 * RETURNS
260 * TRUE on success
261 * FALSE on failure
264 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
265 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
267 DWORD len;
268 LPWSTR hdr;
269 BOOL r;
271 TRACE("%p, %s, %li, %li\n", hHttpRequest, debugstr_a(lpszHeader), dwHeaderLength,
272 dwModifier);
274 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
275 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
276 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
277 if( dwHeaderLength != ~0U )
278 dwHeaderLength = len;
280 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
282 HeapFree( GetProcessHeap(), 0, hdr );
284 return r;
287 /***********************************************************************
288 * HttpEndRequestA (WININET.@)
290 * Ends an HTTP request that was started by HttpSendRequestEx
292 * RETURNS
293 * TRUE if successful
294 * FALSE on failure
297 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest, LPINTERNET_BUFFERSA lpBuffersOut,
298 DWORD dwFlags, DWORD dwContext)
300 FIXME("stub\n");
301 return FALSE;
304 /***********************************************************************
305 * HttpEndRequestW (WININET.@)
307 * Ends an HTTP request that was started by HttpSendRequestEx
309 * RETURNS
310 * TRUE if successful
311 * FALSE on failure
314 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest, LPINTERNET_BUFFERSW lpBuffersOut,
315 DWORD dwFlags, DWORD dwContext)
317 FIXME("stub\n");
318 return FALSE;
321 /***********************************************************************
322 * HttpOpenRequestW (WININET.@)
324 * Open a HTTP request handle
326 * RETURNS
327 * HINTERNET a HTTP request handle on success
328 * NULL on failure
331 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
332 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
333 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
334 DWORD dwFlags, DWORD dwContext)
336 LPWININETHTTPSESSIONW lpwhs;
337 HINTERNET handle = NULL;
339 TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08lx)\n", hHttpSession,
340 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
341 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
342 dwFlags, dwContext);
343 if(lpszAcceptTypes!=NULL)
345 int i;
346 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
347 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
350 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
351 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
353 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
354 goto lend;
358 * My tests seem to show that the windows version does not
359 * become asynchronous until after this point. And anyhow
360 * if this call was asynchronous then how would you get the
361 * necessary HINTERNET pointer returned by this function.
364 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
365 lpszVersion, lpszReferrer, lpszAcceptTypes,
366 dwFlags, dwContext);
367 lend:
368 if( lpwhs )
369 WININET_Release( &lpwhs->hdr );
370 TRACE("returning %p\n", handle);
371 return handle;
375 /***********************************************************************
376 * HttpOpenRequestA (WININET.@)
378 * Open a HTTP request handle
380 * RETURNS
381 * HINTERNET a HTTP request handle on success
382 * NULL on failure
385 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
386 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
387 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
388 DWORD dwFlags, DWORD dwContext)
390 LPWSTR szVerb = NULL, szObjectName = NULL;
391 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
392 INT len;
393 INT acceptTypesCount;
394 HINTERNET rc = FALSE;
395 TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08lx)\n", hHttpSession,
396 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
397 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
398 dwFlags, dwContext);
400 if (lpszVerb)
402 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
403 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
404 if ( !szVerb )
405 goto end;
406 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
409 if (lpszObjectName)
411 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
412 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
413 if ( !szObjectName )
414 goto end;
415 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
418 if (lpszVersion)
420 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
421 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
422 if ( !szVersion )
423 goto end;
424 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
427 if (lpszReferrer)
429 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
430 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
431 if ( !szReferrer )
432 goto end;
433 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
436 acceptTypesCount = 0;
437 if (lpszAcceptTypes)
439 /* find out how many there are */
440 while (lpszAcceptTypes[acceptTypesCount])
441 acceptTypesCount++;
442 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
443 acceptTypesCount = 0;
444 while (lpszAcceptTypes[acceptTypesCount])
446 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
447 -1, NULL, 0 );
448 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
449 if (!szAcceptTypes[acceptTypesCount] )
450 goto end;
451 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
452 -1, szAcceptTypes[acceptTypesCount], len );
453 acceptTypesCount++;
455 szAcceptTypes[acceptTypesCount] = NULL;
457 else szAcceptTypes = 0;
459 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
460 szVersion, szReferrer,
461 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
463 end:
464 if (szAcceptTypes)
466 acceptTypesCount = 0;
467 while (szAcceptTypes[acceptTypesCount])
469 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
470 acceptTypesCount++;
472 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
474 HeapFree(GetProcessHeap(), 0, szReferrer);
475 HeapFree(GetProcessHeap(), 0, szVersion);
476 HeapFree(GetProcessHeap(), 0, szObjectName);
477 HeapFree(GetProcessHeap(), 0, szVerb);
479 return rc;
482 /***********************************************************************
483 * HTTP_Base64
485 static UINT HTTP_Base64( LPCWSTR bin, LPWSTR base64 )
487 UINT n = 0, x;
488 static LPCSTR HTTP_Base64Enc =
489 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
491 while( bin[0] )
493 /* first 6 bits, all from bin[0] */
494 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
495 x = (bin[0] & 3) << 4;
497 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
498 if( !bin[1] )
500 base64[n++] = HTTP_Base64Enc[x];
501 base64[n++] = '=';
502 base64[n++] = '=';
503 break;
505 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
506 x = ( bin[1] & 0x0f ) << 2;
508 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
509 if( !bin[2] )
511 base64[n++] = HTTP_Base64Enc[x];
512 base64[n++] = '=';
513 break;
515 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
517 /* last 6 bits, all from bin [2] */
518 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
519 bin += 3;
521 base64[n] = 0;
522 return n;
525 /***********************************************************************
526 * HTTP_EncodeBasicAuth
528 * Encode the basic authentication string for HTTP 1.1
530 static LPWSTR HTTP_EncodeBasicAuth( LPCWSTR username, LPCWSTR password)
532 UINT len;
533 LPWSTR in, out;
534 static const WCHAR szBasic[] = {'B','a','s','i','c',' ',0};
535 static const WCHAR szColon[] = {':',0};
537 len = lstrlenW( username ) + 1 + lstrlenW ( password ) + 1;
538 in = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
539 if( !in )
540 return NULL;
542 len = lstrlenW(szBasic) +
543 (lstrlenW( username ) + 1 + lstrlenW ( password ))*2 + 1 + 1;
544 out = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
545 if( out )
547 lstrcpyW( in, username );
548 lstrcatW( in, szColon );
549 lstrcatW( in, password );
550 lstrcpyW( out, szBasic );
551 HTTP_Base64( in, &out[strlenW(out)] );
553 HeapFree( GetProcessHeap(), 0, in );
555 return out;
558 /***********************************************************************
559 * HTTP_InsertProxyAuthorization
561 * Insert the basic authorization field in the request header
563 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr,
564 LPCWSTR username, LPCWSTR password )
566 HTTPHEADERW hdr;
567 INT index;
568 static const WCHAR szProxyAuthorization[] = {
569 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
571 hdr.lpszValue = HTTP_EncodeBasicAuth( username, password );
572 hdr.lpszField = (WCHAR *)szProxyAuthorization;
573 hdr.wFlags = HDR_ISREQUEST;
574 hdr.wCount = 0;
575 if( !hdr.lpszValue )
576 return FALSE;
578 TRACE("Inserting %s = %s\n",
579 debugstr_w( hdr.lpszField ), debugstr_w( hdr.lpszValue ) );
581 /* remove the old proxy authorization header */
582 index = HTTP_GetCustomHeaderIndex( lpwhr, hdr.lpszField );
583 if( index >=0 )
584 HTTP_DeleteCustomHeader( lpwhr, index );
586 HTTP_InsertCustomHeader(lpwhr, &hdr);
587 HeapFree( GetProcessHeap(), 0, hdr.lpszValue );
589 return TRUE;
592 /***********************************************************************
593 * HTTP_DealWithProxy
595 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
596 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
598 WCHAR buf[MAXHOSTNAME];
599 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
600 WCHAR* url;
601 static const WCHAR szNul[] = { 0 };
602 URL_COMPONENTSW UrlComponents;
603 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
604 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
605 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
606 int len;
608 memset( &UrlComponents, 0, sizeof UrlComponents );
609 UrlComponents.dwStructSize = sizeof UrlComponents;
610 UrlComponents.lpszHostName = buf;
611 UrlComponents.dwHostNameLength = MAXHOSTNAME;
613 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
614 buf,strlenW(szHttp),szHttp,strlenW(szHttp)) )
615 sprintfW(proxy, szFormat1, hIC->lpszProxy);
616 else
617 strcpyW(proxy,buf);
618 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
619 return FALSE;
620 if( UrlComponents.dwHostNameLength == 0 )
621 return FALSE;
623 if( !lpwhr->lpszPath )
624 lpwhr->lpszPath = (LPWSTR)szNul;
625 TRACE("server='%s' path='%s'\n",
626 debugstr_w(lpwhs->lpszServerName), debugstr_w(lpwhr->lpszPath));
627 /* for constant 15 see above */
628 len = strlenW(lpwhs->lpszServerName) + strlenW(lpwhr->lpszPath) + 15;
629 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
631 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
632 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
634 sprintfW(url, szFormat2, lpwhs->lpszServerName, lpwhs->nServerPort);
636 if( lpwhr->lpszPath[0] != '/' )
637 strcatW( url, szSlash );
638 strcatW(url, lpwhr->lpszPath);
639 if(lpwhr->lpszPath != szNul)
640 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
641 lpwhr->lpszPath = url;
642 /* FIXME: Do I have to free lpwhs->lpszServerName here ? */
643 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
644 lpwhs->nServerPort = UrlComponents.nPort;
646 return TRUE;
649 /***********************************************************************
650 * HTTP_HttpOpenRequestW (internal)
652 * Open a HTTP request handle
654 * RETURNS
655 * HINTERNET a HTTP request handle on success
656 * NULL on failure
659 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
660 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
661 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
662 DWORD dwFlags, DWORD dwContext)
664 LPWININETAPPINFOW hIC = NULL;
665 LPWININETHTTPREQW lpwhr;
666 LPWSTR lpszCookies;
667 LPWSTR lpszUrl = NULL;
668 DWORD nCookieSize;
669 HINTERNET handle = NULL;
670 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
671 DWORD len;
673 TRACE("-->\n");
675 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
676 hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
678 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
679 if (NULL == lpwhr)
681 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
682 goto lend;
684 lpwhr->hdr.htype = WH_HHTTPREQ;
685 lpwhr->hdr.lpwhparent = WININET_AddRef( &lpwhs->hdr );
686 lpwhr->hdr.dwFlags = dwFlags;
687 lpwhr->hdr.dwContext = dwContext;
688 lpwhr->hdr.dwRefCount = 1;
689 lpwhr->hdr.destroy = HTTP_CloseHTTPRequestHandle;
690 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
692 handle = WININET_AllocHandle( &lpwhr->hdr );
693 if (NULL == handle)
695 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
696 goto lend;
699 NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE);
701 if (NULL != lpszObjectName && strlenW(lpszObjectName)) {
702 HRESULT rc;
704 len = 0;
705 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
706 if (rc != E_POINTER)
707 len = strlenW(lpszObjectName)+1;
708 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
709 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
710 URL_ESCAPE_SPACES_ONLY);
711 if (rc)
713 ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(lpszObjectName),rc);
714 strcpyW(lpwhr->lpszPath,lpszObjectName);
718 if (NULL != lpszReferrer && strlenW(lpszReferrer))
719 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDHDR_FLAG_COALESCE);
721 if(lpszAcceptTypes!=NULL)
723 int i;
724 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
725 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i], HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_REQ|HTTP_ADDHDR_FLAG_ADD_IF_NEW);
728 if (NULL == lpszVerb)
730 static const WCHAR szGet[] = {'G','E','T',0};
731 lpwhr->lpszVerb = WININET_strdupW(szGet);
733 else if (strlenW(lpszVerb))
734 lpwhr->lpszVerb = WININET_strdupW(lpszVerb);
736 if (NULL != lpszReferrer && strlenW(lpszReferrer))
738 WCHAR buf[MAXHOSTNAME];
739 URL_COMPONENTSW UrlComponents;
741 memset( &UrlComponents, 0, sizeof UrlComponents );
742 UrlComponents.dwStructSize = sizeof UrlComponents;
743 UrlComponents.lpszHostName = buf;
744 UrlComponents.dwHostNameLength = MAXHOSTNAME;
746 InternetCrackUrlW(lpszReferrer, 0, 0, &UrlComponents);
747 if (strlenW(UrlComponents.lpszHostName))
748 HTTP_ProcessHeader(lpwhr, g_szHost, UrlComponents.lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
750 else
751 HTTP_ProcessHeader(lpwhr, g_szHost, lpwhs->lpszServerName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
753 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
754 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
755 INTERNET_DEFAULT_HTTPS_PORT :
756 INTERNET_DEFAULT_HTTP_PORT);
758 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
759 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
761 if (hIC->lpszAgent)
763 WCHAR *agent_header;
764 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
766 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
767 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
768 sprintfW(agent_header, user_agent, hIC->lpszAgent );
770 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
771 HTTP_ADDREQ_FLAG_ADD);
772 HeapFree(GetProcessHeap(), 0, agent_header);
775 len = strlenW(lpwhr->StdHeaders[HTTP_QUERY_HOST].lpszValue) + strlenW(szUrlForm);
776 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
777 sprintfW( lpszUrl, szUrlForm, lpwhr->StdHeaders[HTTP_QUERY_HOST].lpszValue );
779 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
780 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
782 int cnt = 0;
783 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
784 static const WCHAR szcrlf[] = {'\r','\n',0};
786 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
788 cnt += sprintfW(lpszCookies, szCookie);
789 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
790 strcatW(lpszCookies, szcrlf);
792 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
793 HTTP_ADDREQ_FLAG_ADD);
794 HeapFree(GetProcessHeap(), 0, lpszCookies);
796 HeapFree(GetProcessHeap(), 0, lpszUrl);
799 SendAsyncCallback(&lpwhs->hdr, dwContext,
800 INTERNET_STATUS_HANDLE_CREATED, &handle,
801 sizeof(handle));
804 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
808 * According to my tests. The name is not resolved until a request is Opened
810 SendAsyncCallback(&lpwhr->hdr, dwContext,
811 INTERNET_STATUS_RESOLVING_NAME,
812 lpwhs->lpszServerName,
813 strlenW(lpwhs->lpszServerName)+1);
815 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
816 &lpwhs->socketAddress))
818 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
819 InternetCloseHandle( handle );
820 handle = NULL;
821 goto lend;
824 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
825 INTERNET_STATUS_NAME_RESOLVED,
826 &(lpwhs->socketAddress),
827 sizeof(struct sockaddr_in));
829 lend:
830 if( lpwhr )
831 WININET_Release( &lpwhr->hdr );
833 TRACE("<-- %p (%p)\n", handle, lpwhr);
834 return handle;
837 /***********************************************************************
838 * HTTP_HttpQueryInfoW (internal)
840 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
841 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
843 LPHTTPHEADERW lphttpHdr = NULL;
844 BOOL bSuccess = FALSE;
846 /* Find requested header structure */
847 if ((dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK) == HTTP_QUERY_CUSTOM)
849 INT index = HTTP_GetCustomHeaderIndex(lpwhr, (LPWSTR)lpBuffer);
851 if (index < 0)
852 return bSuccess;
854 lphttpHdr = &lpwhr->pCustHeaders[index];
856 else
858 INT index = dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK;
860 if (index == HTTP_QUERY_RAW_HEADERS_CRLF)
862 DWORD len = strlenW(lpwhr->lpszRawHeaders);
863 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
865 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
866 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
867 return FALSE;
869 memcpy(lpBuffer, lpwhr->lpszRawHeaders, (len+1)*sizeof(WCHAR));
870 *lpdwBufferLength = len * sizeof(WCHAR);
872 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
874 return TRUE;
876 else if (index == HTTP_QUERY_RAW_HEADERS)
878 static const WCHAR szCrLf[] = {'\r','\n',0};
879 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
880 DWORD i, size = 0;
881 LPWSTR pszString = (WCHAR*)lpBuffer;
883 for (i = 0; ppszRawHeaderLines[i]; i++)
884 size += strlenW(ppszRawHeaderLines[i]) + 1;
886 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
888 HTTP_FreeTokens(ppszRawHeaderLines);
889 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
890 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
891 return FALSE;
894 for (i = 0; ppszRawHeaderLines[i]; i++)
896 DWORD len = strlenW(ppszRawHeaderLines[i]);
897 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
898 pszString += len+1;
900 *pszString = '\0';
902 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
904 *lpdwBufferLength = size * sizeof(WCHAR);
905 HTTP_FreeTokens(ppszRawHeaderLines);
907 return TRUE;
909 else if (index >= 0 && index <= HTTP_QUERY_MAX && lpwhr->StdHeaders[index].lpszValue)
911 lphttpHdr = &lpwhr->StdHeaders[index];
913 else
915 SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
916 return bSuccess;
920 /* Ensure header satisifies requested attributes */
921 if ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
922 (~lphttpHdr->wFlags & HDR_ISREQUEST))
924 SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
925 return bSuccess;
928 /* coalesce value to reuqested type */
929 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
931 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
932 bSuccess = TRUE;
934 TRACE(" returning number : %d\n", *(int *)lpBuffer);
936 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
938 time_t tmpTime;
939 struct tm tmpTM;
940 SYSTEMTIME *STHook;
942 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
944 tmpTM = *gmtime(&tmpTime);
945 STHook = (SYSTEMTIME *) lpBuffer;
946 if(STHook==NULL)
947 return bSuccess;
949 STHook->wDay = tmpTM.tm_mday;
950 STHook->wHour = tmpTM.tm_hour;
951 STHook->wMilliseconds = 0;
952 STHook->wMinute = tmpTM.tm_min;
953 STHook->wDayOfWeek = tmpTM.tm_wday;
954 STHook->wMonth = tmpTM.tm_mon + 1;
955 STHook->wSecond = tmpTM.tm_sec;
956 STHook->wYear = tmpTM.tm_year;
958 bSuccess = TRUE;
960 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
961 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
962 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
964 else if (dwInfoLevel & HTTP_QUERY_FLAG_COALESCE)
966 if (*lpdwIndex >= lphttpHdr->wCount)
968 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
970 else
972 /* Copy strncpyW(lpBuffer, lphttpHdr[*lpdwIndex], len); */
973 (*lpdwIndex)++;
976 else
978 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
980 if (len > *lpdwBufferLength)
982 *lpdwBufferLength = len;
983 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
984 return bSuccess;
987 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
988 *lpdwBufferLength = len - sizeof(WCHAR);
989 bSuccess = TRUE;
991 TRACE(" returning string : '%s'\n", debugstr_w(lpBuffer));
993 return bSuccess;
996 /***********************************************************************
997 * HttpQueryInfoW (WININET.@)
999 * Queries for information about an HTTP request
1001 * RETURNS
1002 * TRUE on success
1003 * FALSE on failure
1006 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1007 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1009 BOOL bSuccess = FALSE;
1010 LPWININETHTTPREQW lpwhr;
1012 if (TRACE_ON(wininet)) {
1013 #define FE(x) { x, #x }
1014 static const wininet_flag_info query_flags[] = {
1015 FE(HTTP_QUERY_MIME_VERSION),
1016 FE(HTTP_QUERY_CONTENT_TYPE),
1017 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1018 FE(HTTP_QUERY_CONTENT_ID),
1019 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1020 FE(HTTP_QUERY_CONTENT_LENGTH),
1021 FE(HTTP_QUERY_CONTENT_LANGUAGE),
1022 FE(HTTP_QUERY_ALLOW),
1023 FE(HTTP_QUERY_PUBLIC),
1024 FE(HTTP_QUERY_DATE),
1025 FE(HTTP_QUERY_EXPIRES),
1026 FE(HTTP_QUERY_LAST_MODIFIED),
1027 FE(HTTP_QUERY_MESSAGE_ID),
1028 FE(HTTP_QUERY_URI),
1029 FE(HTTP_QUERY_DERIVED_FROM),
1030 FE(HTTP_QUERY_COST),
1031 FE(HTTP_QUERY_LINK),
1032 FE(HTTP_QUERY_PRAGMA),
1033 FE(HTTP_QUERY_VERSION),
1034 FE(HTTP_QUERY_STATUS_CODE),
1035 FE(HTTP_QUERY_STATUS_TEXT),
1036 FE(HTTP_QUERY_RAW_HEADERS),
1037 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1038 FE(HTTP_QUERY_CONNECTION),
1039 FE(HTTP_QUERY_ACCEPT),
1040 FE(HTTP_QUERY_ACCEPT_CHARSET),
1041 FE(HTTP_QUERY_ACCEPT_ENCODING),
1042 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1043 FE(HTTP_QUERY_AUTHORIZATION),
1044 FE(HTTP_QUERY_CONTENT_ENCODING),
1045 FE(HTTP_QUERY_FORWARDED),
1046 FE(HTTP_QUERY_FROM),
1047 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1048 FE(HTTP_QUERY_LOCATION),
1049 FE(HTTP_QUERY_ORIG_URI),
1050 FE(HTTP_QUERY_REFERER),
1051 FE(HTTP_QUERY_RETRY_AFTER),
1052 FE(HTTP_QUERY_SERVER),
1053 FE(HTTP_QUERY_TITLE),
1054 FE(HTTP_QUERY_USER_AGENT),
1055 FE(HTTP_QUERY_WWW_AUTHENTICATE),
1056 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1057 FE(HTTP_QUERY_ACCEPT_RANGES),
1058 FE(HTTP_QUERY_SET_COOKIE),
1059 FE(HTTP_QUERY_COOKIE),
1060 FE(HTTP_QUERY_REQUEST_METHOD),
1061 FE(HTTP_QUERY_REFRESH),
1062 FE(HTTP_QUERY_CONTENT_DISPOSITION),
1063 FE(HTTP_QUERY_AGE),
1064 FE(HTTP_QUERY_CACHE_CONTROL),
1065 FE(HTTP_QUERY_CONTENT_BASE),
1066 FE(HTTP_QUERY_CONTENT_LOCATION),
1067 FE(HTTP_QUERY_CONTENT_MD5),
1068 FE(HTTP_QUERY_CONTENT_RANGE),
1069 FE(HTTP_QUERY_ETAG),
1070 FE(HTTP_QUERY_HOST),
1071 FE(HTTP_QUERY_IF_MATCH),
1072 FE(HTTP_QUERY_IF_NONE_MATCH),
1073 FE(HTTP_QUERY_IF_RANGE),
1074 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
1075 FE(HTTP_QUERY_MAX_FORWARDS),
1076 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
1077 FE(HTTP_QUERY_RANGE),
1078 FE(HTTP_QUERY_TRANSFER_ENCODING),
1079 FE(HTTP_QUERY_UPGRADE),
1080 FE(HTTP_QUERY_VARY),
1081 FE(HTTP_QUERY_VIA),
1082 FE(HTTP_QUERY_WARNING),
1083 FE(HTTP_QUERY_CUSTOM)
1085 static const wininet_flag_info modifier_flags[] = {
1086 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
1087 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
1088 FE(HTTP_QUERY_FLAG_NUMBER),
1089 FE(HTTP_QUERY_FLAG_COALESCE)
1091 #undef FE
1092 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
1093 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
1094 DWORD i;
1096 TRACE("(%p, 0x%08lx)--> %ld\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
1097 TRACE(" Attribute:");
1098 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
1099 if (query_flags[i].val == info) {
1100 TRACE(" %s", query_flags[i].name);
1101 break;
1104 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
1105 TRACE(" Unknown (%08lx)", info);
1108 TRACE(" Modifier:");
1109 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
1110 if (modifier_flags[i].val & info_mod) {
1111 TRACE(" %s", modifier_flags[i].name);
1112 info_mod &= ~ modifier_flags[i].val;
1116 if (info_mod) {
1117 TRACE(" Unknown (%08lx)", info_mod);
1119 TRACE("\n");
1122 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1123 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1125 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1126 goto lend;
1129 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
1130 lpBuffer, lpdwBufferLength, lpdwIndex);
1132 lend:
1133 if( lpwhr )
1134 WININET_Release( &lpwhr->hdr );
1136 TRACE("%d <--\n", bSuccess);
1137 return bSuccess;
1140 /***********************************************************************
1141 * HttpQueryInfoA (WININET.@)
1143 * Queries for information about an HTTP request
1145 * RETURNS
1146 * TRUE on success
1147 * FALSE on failure
1150 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1151 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1153 BOOL result;
1154 DWORD len;
1155 WCHAR* bufferW;
1157 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
1158 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
1160 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
1161 lpdwBufferLength, lpdwIndex );
1164 len = (*lpdwBufferLength)*sizeof(WCHAR);
1165 bufferW = HeapAlloc( GetProcessHeap(), 0, len );
1166 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
1167 &len, lpdwIndex );
1168 if( result )
1170 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
1171 lpBuffer, *lpdwBufferLength, NULL, NULL );
1172 *lpdwBufferLength = len - 1;
1174 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
1176 else
1177 /* since the strings being returned from HttpQueryInfoW should be
1178 * only ASCII characters, it is reasonable to assume that all of
1179 * the Unicode characters can be reduced to a single byte */
1180 *lpdwBufferLength = len / sizeof(WCHAR);
1182 HeapFree(GetProcessHeap(), 0, bufferW );
1184 return result;
1187 /***********************************************************************
1188 * HttpSendRequestExA (WININET.@)
1190 * Sends the specified request to the HTTP server and allows chunked
1191 * transfers
1193 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
1194 LPINTERNET_BUFFERSA lpBuffersIn,
1195 LPINTERNET_BUFFERSA lpBuffersOut,
1196 DWORD dwFlags, DWORD dwContext)
1198 FIXME("(%p, %p, %p, %08lx, %08lx): stub\n", hRequest, lpBuffersIn,
1199 lpBuffersOut, dwFlags, dwContext);
1200 return FALSE;
1203 /***********************************************************************
1204 * HttpSendRequestExW (WININET.@)
1206 * Sends the specified request to the HTTP server and allows chunked
1207 * transfers
1209 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
1210 LPINTERNET_BUFFERSW lpBuffersIn,
1211 LPINTERNET_BUFFERSW lpBuffersOut,
1212 DWORD dwFlags, DWORD dwContext)
1214 FIXME("(%p, %p, %p, %08lx, %08lx): stub\n", hRequest, lpBuffersIn,
1215 lpBuffersOut, dwFlags, dwContext);
1216 return FALSE;
1219 /***********************************************************************
1220 * HttpSendRequestW (WININET.@)
1222 * Sends the specified request to the HTTP server
1224 * RETURNS
1225 * TRUE on success
1226 * FALSE on failure
1229 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
1230 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1232 LPWININETHTTPREQW lpwhr;
1233 LPWININETHTTPSESSIONW lpwhs = NULL;
1234 LPWININETAPPINFOW hIC = NULL;
1235 BOOL r;
1237 TRACE("%p, %p (%s), %li, %p, %li)\n", hHttpRequest,
1238 lpszHeaders, debugstr_w(lpszHeaders), dwHeaderLength, lpOptional, dwOptionalLength);
1240 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1241 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1243 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1244 r = FALSE;
1245 goto lend;
1248 lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
1249 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
1251 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1252 r = FALSE;
1253 goto lend;
1256 hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1257 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
1259 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1260 r = FALSE;
1261 goto lend;
1264 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1266 WORKREQUEST workRequest;
1267 struct WORKREQ_HTTPSENDREQUESTW *req;
1269 workRequest.asyncall = HTTPSENDREQUESTW;
1270 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
1271 req = &workRequest.u.HttpSendRequestW;
1272 if (lpszHeaders)
1273 req->lpszHeader = WININET_strdupW(lpszHeaders);
1274 else
1275 req->lpszHeader = 0;
1276 req->dwHeaderLength = dwHeaderLength;
1277 req->lpOptional = lpOptional;
1278 req->dwOptionalLength = dwOptionalLength;
1280 INTERNET_AsyncCall(&workRequest);
1282 * This is from windows.
1284 SetLastError(ERROR_IO_PENDING);
1285 r = FALSE;
1287 else
1289 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
1290 dwHeaderLength, lpOptional, dwOptionalLength);
1292 lend:
1293 if( lpwhr )
1294 WININET_Release( &lpwhr->hdr );
1295 return r;
1298 /***********************************************************************
1299 * HttpSendRequestA (WININET.@)
1301 * Sends the specified request to the HTTP server
1303 * RETURNS
1304 * TRUE on success
1305 * FALSE on failure
1308 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
1309 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1311 BOOL result;
1312 LPWSTR szHeaders=NULL;
1313 DWORD nLen=dwHeaderLength;
1314 if(lpszHeaders!=NULL)
1316 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
1317 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
1318 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
1320 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
1321 HeapFree(GetProcessHeap(),0,szHeaders);
1322 return result;
1325 /***********************************************************************
1326 * HTTP_HandleRedirect (internal)
1328 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl, LPCWSTR lpszHeaders,
1329 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength)
1331 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
1332 LPWININETAPPINFOW hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1333 WCHAR path[2048];
1335 if(lpszUrl[0]=='/')
1337 /* if it's an absolute path, keep the same session info */
1338 strcpyW(path,lpszUrl);
1340 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1342 TRACE("Redirect through proxy\n");
1343 strcpyW(path,lpszUrl);
1345 else
1347 URL_COMPONENTSW urlComponents;
1348 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
1349 WCHAR password[1024], extra[1024];
1350 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
1351 urlComponents.lpszScheme = protocol;
1352 urlComponents.dwSchemeLength = 32;
1353 urlComponents.lpszHostName = hostName;
1354 urlComponents.dwHostNameLength = MAXHOSTNAME;
1355 urlComponents.lpszUserName = userName;
1356 urlComponents.dwUserNameLength = 1024;
1357 urlComponents.lpszPassword = password;
1358 urlComponents.dwPasswordLength = 1024;
1359 urlComponents.lpszUrlPath = path;
1360 urlComponents.dwUrlPathLength = 2048;
1361 urlComponents.lpszExtraInfo = extra;
1362 urlComponents.dwExtraInfoLength = 1024;
1363 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
1364 return FALSE;
1366 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1367 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1369 #if 0
1371 * This upsets redirects to binary files on sourceforge.net
1372 * and gives an html page instead of the target file
1373 * Examination of the HTTP request sent by native wininet.dll
1374 * reveals that it doesn't send a referrer in that case.
1375 * Maybe there's a flag that enables this, or maybe a referrer
1376 * shouldn't be added in case of a redirect.
1379 /* consider the current host as the referrer */
1380 if (NULL != lpwhs->lpszServerName && strlenW(lpwhs->lpszServerName))
1381 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
1382 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
1383 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
1384 #endif
1386 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1387 lpwhs->lpszServerName = WININET_strdupW(hostName);
1388 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
1389 lpwhs->lpszUserName = WININET_strdupW(userName);
1390 lpwhs->nServerPort = urlComponents.nPort;
1392 HTTP_ProcessHeader(lpwhr, g_szHost, hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1394 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1395 INTERNET_STATUS_RESOLVING_NAME,
1396 lpwhs->lpszServerName,
1397 strlenW(lpwhs->lpszServerName)+1);
1399 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1400 &lpwhs->socketAddress))
1402 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1403 return FALSE;
1406 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1407 INTERNET_STATUS_NAME_RESOLVED,
1408 &(lpwhs->socketAddress),
1409 sizeof(struct sockaddr_in));
1413 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1414 lpwhr->lpszPath=NULL;
1415 if (strlenW(path))
1417 DWORD needed = 0;
1418 HRESULT rc;
1420 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
1421 if (rc != E_POINTER)
1422 needed = strlenW(path)+1;
1423 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
1424 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
1425 URL_ESCAPE_SPACES_ONLY);
1426 if (rc)
1428 ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(path),rc);
1429 strcpyW(lpwhr->lpszPath,path);
1433 return HTTP_HttpSendRequestW(lpwhr, lpszHeaders, dwHeaderLength, lpOptional, dwOptionalLength);
1436 /***********************************************************************
1437 * HTTP_build_req (internal)
1439 * concatenate all the strings in the request together
1441 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
1443 LPCWSTR *t;
1444 LPWSTR str;
1446 for( t = list; *t ; t++ )
1447 len += strlenW( *t );
1448 len++;
1450 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1451 *str = 0;
1453 for( t = list; *t ; t++ )
1454 strcatW( str, *t );
1456 return str;
1459 /***********************************************************************
1460 * HTTP_HttpSendRequestW (internal)
1462 * Sends the specified request to the HTTP server
1464 * RETURNS
1465 * TRUE on success
1466 * FALSE on failure
1469 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
1470 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1472 INT cnt;
1473 DWORD i;
1474 BOOL bSuccess = FALSE;
1475 LPWSTR requestString = NULL;
1476 INT responseLen;
1477 LPWININETHTTPSESSIONW lpwhs = NULL;
1478 LPWININETAPPINFOW hIC = NULL;
1479 BOOL loop_next = FALSE;
1480 int CustHeaderIndex;
1481 INTERNET_ASYNC_RESULT iar;
1483 TRACE("--> %p\n", lpwhr);
1485 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
1487 lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
1488 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
1490 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1491 return FALSE;
1494 hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1495 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
1497 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1498 return FALSE;
1501 /* Clear any error information */
1502 INTERNET_SetLastError(0);
1505 /* if the verb is NULL default to GET */
1506 if (NULL == lpwhr->lpszVerb)
1508 static const WCHAR szGET[] = { 'G','E','T', 0 };
1509 lpwhr->lpszVerb = WININET_strdupW(szGET);
1512 /* if we are using optional stuff, we must add the fixed header of that option length */
1513 if (lpOptional && dwOptionalLength)
1515 static const WCHAR szContentLength[] = {
1516 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0};
1517 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \n\r */ + 20 /* int */ ];
1518 sprintfW(contentLengthStr, szContentLength, dwOptionalLength);
1519 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD);
1524 static const WCHAR szSlash[] = { '/',0 };
1525 static const WCHAR szSpace[] = { ' ',0 };
1526 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
1527 static const WCHAR szcrlf[] = {'\r','\n', 0};
1528 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
1529 static const WCHAR szSetCookie[] = {'S','e','t','-','C','o','o','k','i','e',0 };
1530 static const WCHAR szColon[] = { ':',' ',0 };
1531 LPCWSTR *req;
1532 LPWSTR p;
1533 DWORD len, n;
1534 char *ascii_req;
1536 TRACE("Going to url %s %s\n", debugstr_w(lpwhr->StdHeaders[HTTP_QUERY_HOST].lpszValue), debugstr_w(lpwhr->lpszPath));
1537 loop_next = FALSE;
1539 /* If we don't have a path we set it to root */
1540 if (NULL == lpwhr->lpszPath)
1541 lpwhr->lpszPath = WININET_strdupW(szSlash);
1542 else /* remove \r and \n*/
1544 int nLen = strlenW(lpwhr->lpszPath);
1545 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
1547 nLen--;
1548 lpwhr->lpszPath[nLen]='\0';
1550 /* Replace '\' with '/' */
1551 while (nLen>0) {
1552 nLen--;
1553 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
1557 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1558 lpwhr->lpszPath, strlenW(szHttp), szHttp, strlenW(szHttp) )
1559 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
1561 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
1562 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
1563 *fixurl = '/';
1564 strcpyW(fixurl + 1, lpwhr->lpszPath);
1565 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
1566 lpwhr->lpszPath = fixurl;
1569 /* add the headers the caller supplied */
1570 if( lpszHeaders && dwHeaderLength )
1572 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
1573 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
1576 /* if there's a proxy username and password, add it to the headers */
1577 if (hIC && (hIC->lpszProxyUsername || hIC->lpszProxyPassword ))
1578 HTTP_InsertProxyAuthorization(lpwhr, hIC->lpszProxyUsername, hIC->lpszProxyPassword);
1580 /* allocate space for an array of all the string pointers to be added */
1581 len = (HTTP_QUERY_MAX + lpwhr->nCustHeaders)*4 + 9;
1582 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
1584 /* add the verb, path and HTTP/1.0 */
1585 n = 0;
1586 req[n++] = lpwhr->lpszVerb;
1587 req[n++] = szSpace;
1588 req[n++] = lpwhr->lpszPath;
1589 req[n++] = HTTPHEADER;
1591 /* Append standard request headers */
1592 for (i = 0; i <= HTTP_QUERY_MAX; i++)
1594 if (lpwhr->StdHeaders[i].wFlags & HDR_ISREQUEST)
1596 req[n++] = szcrlf;
1597 req[n++] = lpwhr->StdHeaders[i].lpszField;
1598 req[n++] = szColon;
1599 req[n++] = lpwhr->StdHeaders[i].lpszValue;
1601 TRACE("Adding header %s (%s)\n",
1602 debugstr_w(lpwhr->StdHeaders[i].lpszField),
1603 debugstr_w(lpwhr->StdHeaders[i].lpszValue));
1607 /* Append custom request heades */
1608 for (i = 0; i < lpwhr->nCustHeaders; i++)
1610 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
1612 req[n++] = szcrlf;
1613 req[n++] = lpwhr->pCustHeaders[i].lpszField;
1614 req[n++] = szColon;
1615 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
1617 TRACE("Adding custom header %s (%s)\n",
1618 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
1619 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
1623 if( n >= len )
1624 ERR("oops. buffer overrun\n");
1626 req[n] = NULL;
1627 requestString = HTTP_build_req( req, 4 );
1628 HeapFree( GetProcessHeap(), 0, req );
1631 * Set (header) termination string for request
1632 * Make sure there's exactly two new lines at the end of the request
1634 p = &requestString[strlenW(requestString)-1];
1635 while ( (*p == '\n') || (*p == '\r') )
1636 p--;
1637 strcpyW( p+1, sztwocrlf );
1639 TRACE("Request header -> %s\n", debugstr_w(requestString) );
1641 /* Send the request and store the results */
1642 if (!HTTP_OpenConnection(lpwhr))
1643 goto lend;
1645 /* send the request as ASCII, tack on the optional data */
1646 if( !lpOptional )
1647 dwOptionalLength = 0;
1648 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
1649 NULL, 0, NULL, NULL );
1650 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
1651 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
1652 ascii_req, len, NULL, NULL );
1653 if( lpOptional )
1654 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
1655 len = (len + dwOptionalLength - 1);
1656 ascii_req[len] = 0;
1657 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
1659 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1660 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1662 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
1663 HeapFree( GetProcessHeap(), 0, ascii_req );
1665 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1666 INTERNET_STATUS_REQUEST_SENT,
1667 &len,sizeof(DWORD));
1669 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1670 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1672 if (cnt < 0)
1673 goto lend;
1675 responseLen = HTTP_GetResponseHeaders(lpwhr);
1676 if (responseLen)
1677 bSuccess = TRUE;
1679 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1680 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
1681 sizeof(DWORD));
1683 /* process headers here. Is this right? */
1684 CustHeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSetCookie);
1685 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && (CustHeaderIndex >= 0))
1687 LPHTTPHEADERW setCookieHeader;
1688 int nPosStart = 0, nPosEnd = 0, len;
1689 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
1691 setCookieHeader = &lpwhr->pCustHeaders[CustHeaderIndex];
1693 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
1695 LPWSTR buf_cookie, cookie_name, cookie_data;
1696 LPWSTR buf_url;
1697 LPWSTR domain = NULL;
1698 int nEqualPos = 0;
1699 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
1700 setCookieHeader->lpszValue[nPosEnd] != '\0')
1702 nPosEnd++;
1704 if (setCookieHeader->lpszValue[nPosEnd] == ';')
1706 /* fixme: not case sensitive, strcasestr is gnu only */
1707 int nDomainPosEnd = 0;
1708 int nDomainPosStart = 0, nDomainLength = 0;
1709 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
1710 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
1711 if (lpszDomain)
1712 { /* they have specified their own domain, lets use it */
1713 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
1714 lpszDomain[nDomainPosEnd] != '\0')
1716 nDomainPosEnd++;
1718 nDomainPosStart = strlenW(szDomain);
1719 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
1720 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
1721 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
1724 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
1725 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
1726 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
1727 TRACE("%s\n", debugstr_w(buf_cookie));
1728 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
1730 nEqualPos++;
1732 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
1734 HeapFree(GetProcessHeap(), 0, buf_cookie);
1735 break;
1738 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
1739 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
1740 cookie_data = &buf_cookie[nEqualPos + 1];
1743 len = strlenW((domain ? domain : lpwhr->StdHeaders[HTTP_QUERY_HOST].lpszValue)) +
1744 strlenW(lpwhr->lpszPath) + 9;
1745 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1746 sprintfW(buf_url, szFmt, (domain ? domain : lpwhr->StdHeaders[HTTP_QUERY_HOST].lpszValue)); /* FIXME PATH!!! */
1747 InternetSetCookieW(buf_url, cookie_name, cookie_data);
1749 HeapFree(GetProcessHeap(), 0, buf_url);
1750 HeapFree(GetProcessHeap(), 0, buf_cookie);
1751 HeapFree(GetProcessHeap(), 0, cookie_name);
1752 HeapFree(GetProcessHeap(), 0, domain);
1753 nPosStart = nPosEnd;
1757 while (loop_next);
1759 lend:
1761 HeapFree(GetProcessHeap(), 0, requestString);
1763 /* TODO: send notification for P3P header */
1765 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
1767 DWORD dwCode,dwCodeLength=sizeof(DWORD),dwIndex=0;
1768 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,&dwIndex) &&
1769 (dwCode==302 || dwCode==301))
1771 WCHAR szNewLocation[2048];
1772 DWORD dwBufferSize=2048;
1773 dwIndex=0;
1774 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,&dwIndex))
1776 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1777 INTERNET_STATUS_REDIRECT, szNewLocation,
1778 dwBufferSize);
1779 return HTTP_HandleRedirect(lpwhr, szNewLocation, lpszHeaders,
1780 dwHeaderLength, lpOptional, dwOptionalLength);
1786 iar.dwResult = (DWORD)bSuccess;
1787 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1789 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1790 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1791 sizeof(INTERNET_ASYNC_RESULT));
1793 TRACE("<--\n");
1794 return bSuccess;
1798 /***********************************************************************
1799 * HTTP_Connect (internal)
1801 * Create http session handle
1803 * RETURNS
1804 * HINTERNET a session handle on success
1805 * NULL on failure
1808 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
1809 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
1810 LPCWSTR lpszPassword, DWORD dwFlags, DWORD dwContext,
1811 DWORD dwInternalFlags)
1813 BOOL bSuccess = FALSE;
1814 LPWININETHTTPSESSIONW lpwhs = NULL;
1815 HINTERNET handle = NULL;
1817 TRACE("-->\n");
1819 assert( hIC->hdr.htype == WH_HINIT );
1821 hIC->hdr.dwContext = dwContext;
1823 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
1824 if (NULL == lpwhs)
1826 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1827 goto lerror;
1831 * According to my tests. The name is not resolved until a request is sent
1834 lpwhs->hdr.htype = WH_HHTTPSESSION;
1835 lpwhs->hdr.lpwhparent = WININET_AddRef( &hIC->hdr );
1836 lpwhs->hdr.dwFlags = dwFlags;
1837 lpwhs->hdr.dwContext = dwContext;
1838 lpwhs->hdr.dwInternalFlags = dwInternalFlags;
1839 lpwhs->hdr.dwRefCount = 1;
1840 lpwhs->hdr.destroy = HTTP_CloseHTTPSessionHandle;
1841 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
1843 handle = WININET_AllocHandle( &lpwhs->hdr );
1844 if (NULL == handle)
1846 ERR("Failed to alloc handle\n");
1847 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1848 goto lerror;
1851 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
1852 if(strchrW(hIC->lpszProxy, ' '))
1853 FIXME("Several proxies not implemented.\n");
1854 if(hIC->lpszProxyBypass)
1855 FIXME("Proxy bypass is ignored.\n");
1857 if (NULL != lpszServerName)
1858 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
1859 if (NULL != lpszUserName)
1860 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
1861 lpwhs->nServerPort = nServerPort;
1863 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
1864 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
1866 SendAsyncCallback(&hIC->hdr, dwContext,
1867 INTERNET_STATUS_HANDLE_CREATED, &handle,
1868 sizeof(handle));
1871 bSuccess = TRUE;
1873 lerror:
1874 if( lpwhs )
1875 WININET_Release( &lpwhs->hdr );
1878 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
1879 * windows
1882 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
1883 return handle;
1887 /***********************************************************************
1888 * HTTP_OpenConnection (internal)
1890 * Connect to a web server
1892 * RETURNS
1894 * TRUE on success
1895 * FALSE on failure
1897 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
1899 BOOL bSuccess = FALSE;
1900 LPWININETHTTPSESSIONW lpwhs;
1901 LPWININETAPPINFOW hIC = NULL;
1903 TRACE("-->\n");
1906 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1908 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1909 goto lend;
1912 lpwhs = (LPWININETHTTPSESSIONW)lpwhr->hdr.lpwhparent;
1914 hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1915 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1916 INTERNET_STATUS_CONNECTING_TO_SERVER,
1917 &(lpwhs->socketAddress),
1918 sizeof(struct sockaddr_in));
1920 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
1921 SOCK_STREAM, 0))
1923 WARN("Socket creation failed\n");
1924 goto lend;
1927 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
1928 sizeof(lpwhs->socketAddress)))
1930 WARN("Unable to connect to host (%s)\n", strerror(errno));
1931 goto lend;
1934 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1935 INTERNET_STATUS_CONNECTED_TO_SERVER,
1936 &(lpwhs->socketAddress),
1937 sizeof(struct sockaddr_in));
1939 bSuccess = TRUE;
1941 lend:
1942 TRACE("%d <--\n", bSuccess);
1943 return bSuccess;
1947 /***********************************************************************
1948 * HTTP_clear_response_headers (internal)
1950 * clear out any old response headers
1952 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
1954 DWORD i;
1956 for( i=0; i<=HTTP_QUERY_MAX; i++ )
1958 if( !lpwhr->StdHeaders[i].lpszField )
1959 continue;
1960 if( !lpwhr->StdHeaders[i].lpszValue )
1961 continue;
1962 if ( lpwhr->StdHeaders[i].wFlags & HDR_ISREQUEST )
1963 continue;
1964 HTTP_ReplaceHeaderValue( &lpwhr->StdHeaders[i], NULL );
1965 HeapFree( GetProcessHeap(), 0, lpwhr->StdHeaders[i].lpszField );
1966 lpwhr->StdHeaders[i].lpszField = NULL;
1968 for( i=0; i<lpwhr->nCustHeaders; i++)
1970 if( !lpwhr->pCustHeaders[i].lpszField )
1971 continue;
1972 if( !lpwhr->pCustHeaders[i].lpszValue )
1973 continue;
1974 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
1975 continue;
1976 HTTP_DeleteCustomHeader( lpwhr, i );
1977 i--;
1981 /***********************************************************************
1982 * HTTP_GetResponseHeaders (internal)
1984 * Read server response
1986 * RETURNS
1988 * TRUE on success
1989 * FALSE on error
1991 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
1993 INT cbreaks = 0;
1994 WCHAR buffer[MAX_REPLY_LEN];
1995 DWORD buflen = MAX_REPLY_LEN;
1996 BOOL bSuccess = FALSE;
1997 INT rc = 0;
1998 static const WCHAR szCrLf[] = {'\r','\n',0};
1999 char bufferA[MAX_REPLY_LEN];
2000 LPWSTR status_code, status_text;
2001 DWORD cchMaxRawHeaders = 1024;
2002 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2003 DWORD cchRawHeaders = 0;
2005 TRACE("-->\n");
2007 /* clear old response headers (eg. from a redirect response) */
2008 HTTP_clear_response_headers( lpwhr );
2010 if (!NETCON_connected(&lpwhr->netConnection))
2011 goto lend;
2014 * HACK peek at the buffer
2016 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
2019 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
2021 buflen = MAX_REPLY_LEN;
2022 memset(buffer, 0, MAX_REPLY_LEN);
2023 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
2024 goto lend;
2025 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
2027 /* regenerate raw headers */
2028 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
2030 cchMaxRawHeaders *= 2;
2031 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2033 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
2034 cchRawHeaders += (buflen-1);
2035 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
2036 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
2037 lpszRawHeaders[cchRawHeaders] = '\0';
2039 /* split the version from the status code */
2040 status_code = strchrW( buffer, ' ' );
2041 if( !status_code )
2042 goto lend;
2043 *status_code++=0;
2045 /* split the status code from the status text */
2046 status_text = strchrW( status_code, ' ' );
2047 if( !status_text )
2048 goto lend;
2049 *status_text++=0;
2051 TRACE("version [%s] status code [%s] status text [%s]\n",
2052 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
2053 HTTP_ReplaceHeaderValue( &lpwhr->StdHeaders[HTTP_QUERY_VERSION], buffer );
2054 HTTP_ReplaceHeaderValue( &lpwhr->StdHeaders[HTTP_QUERY_STATUS_CODE], status_code );
2055 HTTP_ReplaceHeaderValue( &lpwhr->StdHeaders[HTTP_QUERY_STATUS_TEXT], status_text );
2057 /* Parse each response line */
2060 buflen = MAX_REPLY_LEN;
2061 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
2063 LPWSTR * pFieldAndValue;
2065 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
2066 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
2068 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
2070 cchMaxRawHeaders *= 2;
2071 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2073 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
2074 cchRawHeaders += (buflen-1);
2075 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
2076 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
2077 lpszRawHeaders[cchRawHeaders] = '\0';
2079 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
2080 if (!pFieldAndValue)
2081 break;
2083 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
2084 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
2086 HTTP_FreeTokens(pFieldAndValue);
2088 else
2090 cbreaks++;
2091 if (cbreaks >= 2)
2092 break;
2094 }while(1);
2096 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
2097 lpwhr->lpszRawHeaders = lpszRawHeaders;
2098 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
2099 bSuccess = TRUE;
2101 lend:
2103 TRACE("<--\n");
2104 if (bSuccess)
2105 return rc;
2106 else
2107 return FALSE;
2111 static void strip_spaces(LPWSTR start)
2113 LPWSTR str = start;
2114 LPWSTR end;
2116 while (*str == ' ' && *str != '\0')
2117 str++;
2119 if (str != start)
2120 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
2122 end = start + strlenW(start) - 1;
2123 while (end >= start && *end == ' ')
2125 *end = '\0';
2126 end--;
2131 /***********************************************************************
2132 * HTTP_InterpretHttpHeader (internal)
2134 * Parse server response
2136 * RETURNS
2138 * Pointer to array of field, value, NULL on success.
2139 * NULL on error.
2141 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
2143 LPWSTR * pTokenPair;
2144 LPWSTR pszColon;
2145 INT len;
2147 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
2149 pszColon = strchrW(buffer, ':');
2150 /* must have two tokens */
2151 if (!pszColon)
2153 HTTP_FreeTokens(pTokenPair);
2154 if (buffer[0])
2155 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
2156 return NULL;
2159 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
2160 if (!pTokenPair[0])
2162 HTTP_FreeTokens(pTokenPair);
2163 return NULL;
2165 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
2166 pTokenPair[0][pszColon - buffer] = '\0';
2168 /* skip colon */
2169 pszColon++;
2170 len = strlenW(pszColon);
2171 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2172 if (!pTokenPair[1])
2174 HTTP_FreeTokens(pTokenPair);
2175 return NULL;
2177 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
2179 strip_spaces(pTokenPair[0]);
2180 strip_spaces(pTokenPair[1]);
2182 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
2183 return pTokenPair;
2186 typedef enum {REQUEST_HDR = 1, RESPONSE_HDR = 2, REQ_RESP_HDR = 3} std_hdr_type;
2188 typedef struct std_hdr_data
2190 const WCHAR* hdrStr;
2191 INT hdrIndex;
2192 std_hdr_type hdrType;
2193 } std_hdr_data;
2195 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2196 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2197 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2198 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2199 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2200 static const WCHAR szAge[] = { 'A','g','e',0 };
2201 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2202 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
2203 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2204 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2205 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2206 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2207 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2208 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2209 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2210 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2211 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2212 static const WCHAR szContent_Transfer_Encoding[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2213 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2214 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2215 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2216 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2217 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2218 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2219 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2220 static const WCHAR szHost[] = { 'H','o','s','t',0 };
2221 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2222 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2223 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2224 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2225 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2226 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2227 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2228 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2229 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2230 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2231 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2232 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
2233 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2234 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2235 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2236 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2237 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2238 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2239 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
2240 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2241 static const WCHAR szUnless_Modified_Since[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2242 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2243 static const WCHAR szURI[] = { 'U','R','I',0 };
2244 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2245 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2246 static const WCHAR szVia[] = { 'V','i','a',0 };
2247 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2248 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2250 /* Note: Must be kept sorted! */
2251 const std_hdr_data SORTED_STANDARD_HEADERS[] = {
2252 {szAccept_Charset, HTTP_QUERY_ACCEPT_CHARSET, REQUEST_HDR,},
2253 {szAccept_Encoding, HTTP_QUERY_ACCEPT_ENCODING, REQUEST_HDR,},
2254 {szAccept, HTTP_QUERY_ACCEPT, REQUEST_HDR,},
2255 {szAccept_Language, HTTP_QUERY_ACCEPT_LANGUAGE, REQUEST_HDR,},
2256 {szAccept_Ranges, HTTP_QUERY_ACCEPT_RANGES, RESPONSE_HDR,},
2257 {szAge, HTTP_QUERY_AGE, RESPONSE_HDR,},
2258 {szAllow, HTTP_QUERY_ALLOW, REQ_RESP_HDR,},
2259 {szAuthorization, HTTP_QUERY_AUTHORIZATION, REQUEST_HDR,},
2260 {szCache_Control, HTTP_QUERY_CACHE_CONTROL, REQ_RESP_HDR,},
2261 {szConnection, HTTP_QUERY_CONNECTION, REQ_RESP_HDR,},
2262 {szContent_Base, HTTP_QUERY_CONTENT_BASE, REQ_RESP_HDR,},
2263 {szContent_Encoding, HTTP_QUERY_CONTENT_ENCODING, REQ_RESP_HDR,},
2264 {szContent_Language, HTTP_QUERY_CONTENT_LANGUAGE, REQ_RESP_HDR,},
2265 {szContent_Length, HTTP_QUERY_CONTENT_LENGTH, REQ_RESP_HDR,},
2266 {szContent_Location, HTTP_QUERY_CONTENT_LOCATION, REQ_RESP_HDR,},
2267 {szContent_MD5, HTTP_QUERY_CONTENT_MD5, REQ_RESP_HDR,},
2268 {szContent_Range, HTTP_QUERY_CONTENT_RANGE, REQ_RESP_HDR,},
2269 {szContent_Transfer_Encoding,HTTP_QUERY_CONTENT_TRANSFER_ENCODING, REQ_RESP_HDR,},
2270 {szContent_Type, HTTP_QUERY_CONTENT_TYPE, REQ_RESP_HDR,},
2271 {szCookie, HTTP_QUERY_COOKIE, REQUEST_HDR,},
2272 {szDate, HTTP_QUERY_DATE, REQ_RESP_HDR,},
2273 {szETag, HTTP_QUERY_ETAG, REQ_RESP_HDR,},
2274 {szExpect, HTTP_QUERY_EXPECT, REQUEST_HDR,},
2275 {szExpires, HTTP_QUERY_EXPIRES, REQ_RESP_HDR,},
2276 {szFrom, HTTP_QUERY_DERIVED_FROM, REQUEST_HDR,},
2277 {szHost, HTTP_QUERY_HOST, REQUEST_HDR,},
2278 {szIf_Match, HTTP_QUERY_IF_MATCH, REQUEST_HDR,},
2279 {szIf_Modified_Since, HTTP_QUERY_IF_MODIFIED_SINCE, REQUEST_HDR,},
2280 {szIf_None_Match, HTTP_QUERY_IF_NONE_MATCH, REQUEST_HDR,},
2281 {szIf_Range, HTTP_QUERY_IF_RANGE, REQUEST_HDR,},
2282 {szIf_Unmodified_Since, HTTP_QUERY_IF_UNMODIFIED_SINCE, REQUEST_HDR,},
2283 {szLast_Modified, HTTP_QUERY_LAST_MODIFIED, REQ_RESP_HDR,},
2284 {szLocation, HTTP_QUERY_CONTENT_LOCATION, REQ_RESP_HDR,},
2285 {szMax_Forwards, HTTP_QUERY_MAX_FORWARDS, REQUEST_HDR,},
2286 {szMime_Version, HTTP_QUERY_MIME_VERSION, REQ_RESP_HDR,},
2287 {szPragma, HTTP_QUERY_PRAGMA, REQ_RESP_HDR,},
2288 {szProxy_Authenticate, HTTP_QUERY_PROXY_AUTHENTICATE, RESPONSE_HDR,},
2289 {szProxy_Authorization, HTTP_QUERY_PROXY_AUTHORIZATION, REQUEST_HDR,},
2290 {szPublic, HTTP_QUERY_PUBLIC, RESPONSE_HDR,},
2291 {szRange, HTTP_QUERY_RANGE, REQUEST_HDR,},
2292 {szReferer, HTTP_QUERY_REFERER, REQUEST_HDR,},
2293 {szRetry_After, HTTP_QUERY_RETRY_AFTER, RESPONSE_HDR,},
2294 {szServer, HTTP_QUERY_SERVER, RESPONSE_HDR,},
2295 {szSet_Cookie, HTTP_QUERY_SET_COOKIE, RESPONSE_HDR,},
2296 {szStatus, HTTP_QUERY_STATUS_CODE, RESPONSE_HDR,},
2297 {szTransfer_Encoding, HTTP_QUERY_TRANSFER_ENCODING, REQ_RESP_HDR,},
2298 {szUnless_Modified_Since, HTTP_QUERY_UNLESS_MODIFIED_SINCE, REQUEST_HDR,},
2299 {szUpgrade, HTTP_QUERY_UPGRADE, REQ_RESP_HDR,},
2300 {szURI, HTTP_QUERY_URI, REQ_RESP_HDR,},
2301 {szUser_Agent, HTTP_QUERY_USER_AGENT, REQUEST_HDR,},
2302 {szVary, HTTP_QUERY_VARY, RESPONSE_HDR,},
2303 {szVia, HTTP_QUERY_VIA, REQ_RESP_HDR,},
2304 {szWarning, HTTP_QUERY_WARNING, RESPONSE_HDR,},
2305 {szWWW_Authenticate, HTTP_QUERY_WWW_AUTHENTICATE, RESPONSE_HDR},
2308 /***********************************************************************
2309 * HTTP_GetStdHeaderIndex (internal)
2311 * Lookup field index in standard http header array
2313 * FIXME: Add support for HeaderType to avoid inadvertant assignments of
2314 * response headers to requests and looking for request headers
2315 * in responses
2318 static INT HTTP_GetStdHeaderIndex(LPCWSTR lpszField)
2320 INT lo = 0;
2321 INT hi = sizeof(SORTED_STANDARD_HEADERS) / sizeof(std_hdr_data) -1;
2322 INT mid, inx;
2324 while (lo <= hi) {
2325 mid = (int) (lo + hi) / 2;
2326 inx = lstrcmpiW(lpszField, SORTED_STANDARD_HEADERS[mid].hdrStr);
2327 if (!inx)
2328 return SORTED_STANDARD_HEADERS[mid].hdrIndex;
2329 if (inx < 0)
2330 hi = mid - 1;
2331 else
2332 lo = mid+1;
2334 FIXME("Couldn't find %s in standard header table\n", debugstr_w(lpszField));
2335 return -1;
2338 /***********************************************************************
2339 * HTTP_ReplaceHeaderValue (internal)
2341 static BOOL HTTP_ReplaceHeaderValue( LPHTTPHEADERW lphttpHdr, LPCWSTR value )
2343 INT len = 0;
2345 HeapFree( GetProcessHeap(), 0, lphttpHdr->lpszValue );
2346 lphttpHdr->lpszValue = NULL;
2348 if( value )
2349 len = strlenW(value);
2350 if (len)
2352 lphttpHdr->lpszValue = HeapAlloc(GetProcessHeap(), 0,
2353 (len+1)*sizeof(WCHAR));
2354 strcpyW(lphttpHdr->lpszValue, value);
2356 return TRUE;
2359 /***********************************************************************
2360 * HTTP_ProcessHeader (internal)
2362 * Stuff header into header tables according to <dwModifier>
2366 #define COALESCEFLASG (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
2368 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
2370 LPHTTPHEADERW lphttpHdr = NULL;
2371 BOOL bSuccess = FALSE;
2372 INT index;
2374 TRACE("--> %s: %s - 0x%08lx\n", debugstr_w(field), debugstr_w(value), dwModifier);
2376 /* Adjust modifier flags */
2377 if (dwModifier & COALESCEFLASG)
2378 dwModifier |= HTTP_ADDHDR_FLAG_ADD;
2380 /* Try to get index into standard header array */
2381 index = HTTP_GetStdHeaderIndex(field);
2382 /* Don't let applications add Connection header to request */
2383 if ((index == HTTP_QUERY_CONNECTION) && (dwModifier & HTTP_ADDHDR_FLAG_REQ))
2384 return TRUE;
2385 else if (index >= 0)
2387 lphttpHdr = &lpwhr->StdHeaders[index];
2389 else /* Find or create new custom header */
2391 index = HTTP_GetCustomHeaderIndex(lpwhr, field);
2392 if (index >= 0)
2394 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
2396 return FALSE;
2398 lphttpHdr = &lpwhr->pCustHeaders[index];
2400 else
2402 HTTPHEADERW hdr;
2404 hdr.lpszField = (LPWSTR)field;
2405 hdr.lpszValue = (LPWSTR)value;
2406 hdr.wFlags = hdr.wCount = 0;
2408 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2409 hdr.wFlags |= HDR_ISREQUEST;
2411 return HTTP_InsertCustomHeader(lpwhr, &hdr);
2415 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2416 lphttpHdr->wFlags |= HDR_ISREQUEST;
2417 else
2418 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
2420 if (!lphttpHdr->lpszValue && (dwModifier & (HTTP_ADDHDR_FLAG_ADD|HTTP_ADDHDR_FLAG_ADD_IF_NEW)))
2422 INT slen;
2424 if (!lpwhr->StdHeaders[index].lpszField)
2426 lphttpHdr->lpszField = WININET_strdupW(field);
2428 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2429 lphttpHdr->wFlags |= HDR_ISREQUEST;
2432 slen = strlenW(value) + 1;
2433 lphttpHdr->lpszValue = HeapAlloc(GetProcessHeap(), 0, slen*sizeof(WCHAR));
2434 if (lphttpHdr->lpszValue)
2436 strcpyW(lphttpHdr->lpszValue, value);
2437 bSuccess = TRUE;
2439 else
2441 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2444 else if (lphttpHdr->lpszValue)
2446 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
2447 bSuccess = HTTP_ReplaceHeaderValue( lphttpHdr, value );
2448 else if (dwModifier & COALESCEFLASG)
2450 LPWSTR lpsztmp;
2451 WCHAR ch = 0;
2452 INT len = 0;
2453 INT origlen = strlenW(lphttpHdr->lpszValue);
2454 INT valuelen = strlenW(value);
2456 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
2458 ch = ',';
2459 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
2461 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
2463 ch = ';';
2464 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
2467 len = origlen + valuelen + ((ch > 0) ? 1 : 0);
2469 lpsztmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
2470 if (lpsztmp)
2472 lphttpHdr->lpszValue = lpsztmp;
2473 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
2474 if (ch > 0)
2476 lphttpHdr->lpszValue[origlen] = ch;
2477 origlen++;
2480 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
2481 lphttpHdr->lpszValue[len] = '\0';
2482 bSuccess = TRUE;
2484 else
2486 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
2487 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2491 TRACE("<-- %d\n",bSuccess);
2492 return bSuccess;
2496 /***********************************************************************
2497 * HTTP_CloseConnection (internal)
2499 * Close socket connection
2502 static VOID HTTP_CloseConnection(LPWININETHTTPREQW lpwhr)
2504 LPWININETHTTPSESSIONW lpwhs = NULL;
2505 LPWININETAPPINFOW hIC = NULL;
2507 TRACE("%p\n",lpwhr);
2509 lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
2510 hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
2512 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2513 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2515 if (NETCON_connected(&lpwhr->netConnection))
2517 NETCON_close(&lpwhr->netConnection);
2520 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2521 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2525 /***********************************************************************
2526 * HTTP_CloseHTTPRequestHandle (internal)
2528 * Deallocate request handle
2531 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr)
2533 DWORD i;
2534 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
2536 TRACE("\n");
2538 if (NETCON_connected(&lpwhr->netConnection))
2539 HTTP_CloseConnection(lpwhr);
2541 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2542 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
2543 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
2545 for (i = 0; i <= HTTP_QUERY_MAX; i++)
2547 HeapFree(GetProcessHeap(), 0, lpwhr->StdHeaders[i].lpszField);
2548 HeapFree(GetProcessHeap(), 0, lpwhr->StdHeaders[i].lpszValue);
2551 for (i = 0; i < lpwhr->nCustHeaders; i++)
2553 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
2554 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
2557 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
2558 HeapFree(GetProcessHeap(), 0, lpwhr);
2562 /***********************************************************************
2563 * HTTP_CloseHTTPSessionHandle (internal)
2565 * Deallocate session handle
2568 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr)
2570 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
2572 TRACE("%p\n", lpwhs);
2574 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2575 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2576 HeapFree(GetProcessHeap(), 0, lpwhs);
2580 /***********************************************************************
2581 * HTTP_GetCustomHeaderIndex (internal)
2583 * Return index of custom header from header array
2586 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField)
2588 DWORD index;
2590 TRACE("%s\n", debugstr_w(lpszField));
2592 for (index = 0; index < lpwhr->nCustHeaders; index++)
2594 if (!strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
2595 break;
2599 if (index >= lpwhr->nCustHeaders)
2600 index = -1;
2602 TRACE("Return: %ld\n", index);
2603 return index;
2607 /***********************************************************************
2608 * HTTP_InsertCustomHeader (internal)
2610 * Insert header into array
2613 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
2615 INT count;
2616 LPHTTPHEADERW lph = NULL;
2617 BOOL r = FALSE;
2619 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
2620 count = lpwhr->nCustHeaders + 1;
2621 if (count > 1)
2622 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
2623 else
2624 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
2626 if (NULL != lph)
2628 lpwhr->pCustHeaders = lph;
2629 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
2630 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
2631 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
2632 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
2633 lpwhr->nCustHeaders++;
2634 r = TRUE;
2636 else
2638 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2641 return r;
2645 /***********************************************************************
2646 * HTTP_DeleteCustomHeader (internal)
2648 * Delete header from array
2649 * If this function is called, the indexs may change.
2651 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
2653 if( lpwhr->nCustHeaders <= 0 )
2654 return FALSE;
2655 if( index >= lpwhr->nCustHeaders )
2656 return FALSE;
2657 lpwhr->nCustHeaders--;
2659 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
2660 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
2661 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
2663 return TRUE;
2666 /***********************************************************************
2667 * IsHostInProxyBypassList (@)
2669 * Undocumented
2672 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
2674 FIXME("STUB: flags=%ld host=%s length=%ld\n",flags,szHost,length);
2675 return FALSE;