wininet: Make a function for resolving the server name for an HTTP request
[wine.git] / dlls / wininet / http.c
blob8327b8b4216081975143f50a8163c475fbd4dd86
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
8 * Copyright 2005 Aric Stewart for CodeWeavers
10 * Ulrich Czekalla
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 #ifdef HAVE_ARPA_INET_H
36 # include <arpa/inet.h>
37 #endif
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #ifdef HAVE_UNISTD_H
42 # include <unistd.h>
43 #endif
44 #include <time.h>
45 #include <assert.h>
47 #include "windef.h"
48 #include "winbase.h"
49 #include "wininet.h"
50 #include "winreg.h"
51 #include "winerror.h"
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
56 #include "shlwapi.h"
58 #include "internet.h"
59 #include "wine/debug.h"
60 #include "wine/unicode.h"
62 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
64 static const WCHAR g_szHttp1_0[] = {' ','H','T','T','P','/','1','.','0',0 };
65 static const WCHAR g_szHttp1_1[] = {' ','H','T','T','P','/','1','.','1',0 };
66 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
67 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
68 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
69 static const WCHAR szHost[] = { 'H','o','s','t',0 };
70 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
73 #define MAXHOSTNAME 100
74 #define MAX_FIELD_VALUE_LEN 256
75 #define MAX_FIELD_LEN 256
77 #define HTTP_REFERER g_szReferer
78 #define HTTP_ACCEPT g_szAccept
79 #define HTTP_USERAGENT g_szUserAgent
81 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
82 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
83 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
84 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
85 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
86 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
87 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
90 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr);
91 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr);
92 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
93 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
94 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
95 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
96 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
97 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
98 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
99 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
100 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr,
101 LPCWSTR username, LPCWSTR password );
102 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
103 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
104 lpdwIndex);
105 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
108 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
110 int HeaderIndex = 0;
111 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
112 if (HeaderIndex == -1)
113 return NULL;
114 else
115 return &req->pCustHeaders[HeaderIndex];
118 /***********************************************************************
119 * HTTP_Tokenize (internal)
121 * Tokenize a string, allocating memory for the tokens.
123 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
125 LPWSTR * token_array;
126 int tokens = 0;
127 int i;
128 LPCWSTR next_token;
130 /* empty string has no tokens */
131 if (*string)
132 tokens++;
133 /* count tokens */
134 for (i = 0; string[i]; i++)
135 if (!strncmpW(string+i, token_string, strlenW(token_string)))
137 DWORD j;
138 tokens++;
139 /* we want to skip over separators, but not the null terminator */
140 for (j = 0; j < strlenW(token_string) - 1; j++)
141 if (!string[i+j])
142 break;
143 i += j;
146 /* add 1 for terminating NULL */
147 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
148 token_array[tokens] = NULL;
149 if (!tokens)
150 return token_array;
151 for (i = 0; i < tokens; i++)
153 int len;
154 next_token = strstrW(string, token_string);
155 if (!next_token) next_token = string+strlenW(string);
156 len = next_token - string;
157 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
158 memcpy(token_array[i], string, len*sizeof(WCHAR));
159 token_array[i][len] = '\0';
160 string = next_token+strlenW(token_string);
162 return token_array;
165 /***********************************************************************
166 * HTTP_FreeTokens (internal)
168 * Frees memory returned from HTTP_Tokenize.
170 static void HTTP_FreeTokens(LPWSTR * token_array)
172 int i;
173 for (i = 0; token_array[i]; i++)
174 HeapFree(GetProcessHeap(), 0, token_array[i]);
175 HeapFree(GetProcessHeap(), 0, token_array);
178 /* **********************************************************************
180 * Helper functions for the HttpSendRequest(Ex) functions
183 static void HTTP_FixVerb( LPWININETHTTPREQW lpwhr )
185 /* if the verb is NULL default to GET */
186 if (NULL == lpwhr->lpszVerb)
188 static const WCHAR szGET[] = { 'G','E','T', 0 };
189 lpwhr->lpszVerb = WININET_strdupW(szGET);
193 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
195 static const WCHAR szSlash[] = { '/',0 };
196 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
198 /* If we don't have a path we set it to root */
199 if (NULL == lpwhr->lpszPath)
200 lpwhr->lpszPath = WININET_strdupW(szSlash);
201 else /* remove \r and \n*/
203 int nLen = strlenW(lpwhr->lpszPath);
204 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
206 nLen--;
207 lpwhr->lpszPath[nLen]='\0';
209 /* Replace '\' with '/' */
210 while (nLen>0) {
211 nLen--;
212 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
216 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
217 lpwhr->lpszPath, strlenW(szHttp), szHttp, strlenW(szHttp) )
218 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
220 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
221 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
222 *fixurl = '/';
223 strcpyW(fixurl + 1, lpwhr->lpszPath);
224 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
225 lpwhr->lpszPath = fixurl;
229 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, BOOL http1_1 )
231 LPWSTR requestString;
232 DWORD len, n;
233 LPCWSTR *req;
234 INT i;
235 LPWSTR p;
237 static const WCHAR szSpace[] = { ' ',0 };
238 static const WCHAR szcrlf[] = {'\r','\n', 0};
239 static const WCHAR szColon[] = { ':',' ',0 };
240 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
242 /* allocate space for an array of all the string pointers to be added */
243 len = (lpwhr->nCustHeaders)*4 + 9;
244 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
246 /* add the verb, path and HTTP version string */
247 n = 0;
248 req[n++] = verb;
249 req[n++] = szSpace;
250 req[n++] = path;
251 req[n++] = http1_1 ? g_szHttp1_1 : g_szHttp1_0;
253 /* Append custom request heades */
254 for (i = 0; i < lpwhr->nCustHeaders; i++)
256 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
258 req[n++] = szcrlf;
259 req[n++] = lpwhr->pCustHeaders[i].lpszField;
260 req[n++] = szColon;
261 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
263 TRACE("Adding custom header %s (%s)\n",
264 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
265 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
269 if( n >= len )
270 ERR("oops. buffer overrun\n");
272 req[n] = NULL;
273 requestString = HTTP_build_req( req, 4 );
274 HeapFree( GetProcessHeap(), 0, req );
277 * Set (header) termination string for request
278 * Make sure there's exactly two new lines at the end of the request
280 p = &requestString[strlenW(requestString)-1];
281 while ( (*p == '\n') || (*p == '\r') )
282 p--;
283 strcpyW( p+1, sztwocrlf );
285 return requestString;
288 static void HTTP_ProcessHeaders( LPWININETHTTPREQW lpwhr )
290 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
291 int HeaderIndex;
292 LPHTTPHEADERW setCookieHeader;
294 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
295 if (HeaderIndex == -1)
296 return;
297 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
299 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
301 int nPosStart = 0, nPosEnd = 0, len;
302 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
304 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
306 LPWSTR buf_cookie, cookie_name, cookie_data;
307 LPWSTR buf_url;
308 LPWSTR domain = NULL;
309 LPHTTPHEADERW Host;
311 int nEqualPos = 0;
312 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
313 setCookieHeader->lpszValue[nPosEnd] != '\0')
315 nPosEnd++;
317 if (setCookieHeader->lpszValue[nPosEnd] == ';')
319 /* fixme: not case sensitive, strcasestr is gnu only */
320 int nDomainPosEnd = 0;
321 int nDomainPosStart = 0, nDomainLength = 0;
322 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
323 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
324 if (lpszDomain)
325 { /* they have specified their own domain, lets use it */
326 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
327 lpszDomain[nDomainPosEnd] != '\0')
329 nDomainPosEnd++;
331 nDomainPosStart = strlenW(szDomain);
332 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
333 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
334 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
337 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
338 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
339 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
340 TRACE("%s\n", debugstr_w(buf_cookie));
341 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
343 nEqualPos++;
345 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
347 HeapFree(GetProcessHeap(), 0, buf_cookie);
348 break;
351 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
352 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
353 cookie_data = &buf_cookie[nEqualPos + 1];
355 Host = HTTP_GetHeader(lpwhr,szHost);
356 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
357 strlenW(lpwhr->lpszPath) + 9;
358 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
359 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
360 InternetSetCookieW(buf_url, cookie_name, cookie_data);
362 HeapFree(GetProcessHeap(), 0, buf_url);
363 HeapFree(GetProcessHeap(), 0, buf_cookie);
364 HeapFree(GetProcessHeap(), 0, cookie_name);
365 HeapFree(GetProcessHeap(), 0, domain);
366 nPosStart = nPosEnd;
371 static void HTTP_AddProxyInfo( LPWININETHTTPREQW lpwhr )
373 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
374 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
376 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
377 assert(hIC->hdr.htype == WH_HINIT);
379 if (hIC && (hIC->lpszProxyUsername || hIC->lpszProxyPassword ))
380 HTTP_InsertProxyAuthorization(lpwhr, hIC->lpszProxyUsername,
381 hIC->lpszProxyPassword);
384 /***********************************************************************
385 * HTTP_HttpAddRequestHeadersW (internal)
387 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
388 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
390 LPWSTR lpszStart;
391 LPWSTR lpszEnd;
392 LPWSTR buffer;
393 BOOL bSuccess = FALSE;
394 DWORD len;
396 TRACE("copying header: %s\n", debugstr_w(lpszHeader));
398 if( dwHeaderLength == ~0U )
399 len = strlenW(lpszHeader);
400 else
401 len = dwHeaderLength;
402 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
403 lstrcpynW( buffer, lpszHeader, len + 1);
405 lpszStart = buffer;
409 LPWSTR * pFieldAndValue;
411 lpszEnd = lpszStart;
413 while (*lpszEnd != '\0')
415 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
416 break;
417 lpszEnd++;
420 if (*lpszStart == '\0')
421 break;
423 if (*lpszEnd == '\r')
425 *lpszEnd = '\0';
426 lpszEnd += 2; /* Jump over \r\n */
428 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
429 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
430 if (pFieldAndValue)
432 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
433 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
434 HTTP_FreeTokens(pFieldAndValue);
437 lpszStart = lpszEnd;
438 } while (bSuccess);
440 HeapFree(GetProcessHeap(), 0, buffer);
442 return bSuccess;
445 /***********************************************************************
446 * HttpAddRequestHeadersW (WININET.@)
448 * Adds one or more HTTP header to the request handler
450 * RETURNS
451 * TRUE on success
452 * FALSE on failure
455 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
456 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
458 BOOL bSuccess = FALSE;
459 LPWININETHTTPREQW lpwhr;
461 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_w(lpszHeader), dwHeaderLength,
462 dwModifier);
464 if (!lpszHeader)
465 return TRUE;
467 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
468 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
470 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
471 goto lend;
473 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
474 lend:
475 if( lpwhr )
476 WININET_Release( &lpwhr->hdr );
478 return bSuccess;
481 /***********************************************************************
482 * HttpAddRequestHeadersA (WININET.@)
484 * Adds one or more HTTP header to the request handler
486 * RETURNS
487 * TRUE on success
488 * FALSE on failure
491 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
492 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
494 DWORD len;
495 LPWSTR hdr;
496 BOOL r;
498 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_a(lpszHeader), dwHeaderLength,
499 dwModifier);
501 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
502 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
503 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
504 if( dwHeaderLength != ~0U )
505 dwHeaderLength = len;
507 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
509 HeapFree( GetProcessHeap(), 0, hdr );
511 return r;
514 /***********************************************************************
515 * HttpEndRequestA (WININET.@)
517 * Ends an HTTP request that was started by HttpSendRequestEx
519 * RETURNS
520 * TRUE if successful
521 * FALSE on failure
524 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
525 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD dwContext)
527 LPINTERNET_BUFFERSA ptr;
528 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
529 BOOL rc = FALSE;
531 TRACE("(%p, %p, %08x, %08x): stub\n", hRequest, lpBuffersOut, dwFlags,
532 dwContext);
534 ptr = lpBuffersOut;
535 if (ptr)
536 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
537 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
538 else
539 lpBuffersOutW = NULL;
541 ptrW = lpBuffersOutW;
542 while (ptr)
544 if (ptr->lpvBuffer && ptr->dwBufferLength)
545 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
546 ptrW->dwBufferLength = ptr->dwBufferLength;
547 ptrW->dwBufferTotal= ptr->dwBufferTotal;
549 if (ptr->Next)
550 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
551 sizeof(INTERNET_BUFFERSW));
553 ptr = ptr->Next;
554 ptrW = ptrW->Next;
557 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
559 if (lpBuffersOutW)
561 ptrW = lpBuffersOutW;
562 while (ptrW)
564 LPINTERNET_BUFFERSW ptrW2;
566 FIXME("Do we need to translate info out of these buffer?\n");
568 HeapFree(GetProcessHeap(),0,(LPVOID)ptrW->lpvBuffer);
569 ptrW2 = ptrW->Next;
570 HeapFree(GetProcessHeap(),0,ptrW);
571 ptrW = ptrW2;
575 return rc;
578 /***********************************************************************
579 * HttpEndRequestW (WININET.@)
581 * Ends an HTTP request that was started by HttpSendRequestEx
583 * RETURNS
584 * TRUE if successful
585 * FALSE on failure
588 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
589 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD dwContext)
591 BOOL rc = FALSE;
592 LPWININETHTTPREQW lpwhr;
593 INT responseLen;
595 TRACE("-->\n");
596 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
598 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
600 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
601 return FALSE;
604 lpwhr->hdr.dwFlags |= dwFlags;
605 lpwhr->hdr.dwContext = dwContext;
607 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
608 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
610 responseLen = HTTP_GetResponseHeaders(lpwhr);
611 if (responseLen)
612 rc = TRUE;
614 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
615 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
617 /* process headers here. Is this right? */
618 HTTP_ProcessHeaders(lpwhr);
620 /* We appear to do nothing with the buffer.. is that correct? */
622 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
624 DWORD dwCode,dwCodeLength=sizeof(DWORD),dwIndex=0;
625 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,&dwIndex) &&
626 (dwCode==302 || dwCode==301))
628 WCHAR szNewLocation[2048];
629 DWORD dwBufferSize=2048;
630 dwIndex=0;
631 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,&dwIndex))
633 static const WCHAR szGET[] = { 'G','E','T', 0 };
634 /* redirects are always GETs */
635 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
636 lpwhr->lpszVerb = WININET_strdupW(szGET);
637 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
638 if (rc)
639 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
644 TRACE("%i <--\n",rc);
645 return rc;
648 /***********************************************************************
649 * HttpOpenRequestW (WININET.@)
651 * Open a HTTP request handle
653 * RETURNS
654 * HINTERNET a HTTP request handle on success
655 * NULL on failure
658 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
659 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
660 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
661 DWORD dwFlags, DWORD dwContext)
663 LPWININETHTTPSESSIONW lpwhs;
664 HINTERNET handle = NULL;
666 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08x)\n", hHttpSession,
667 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
668 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
669 dwFlags, dwContext);
670 if(lpszAcceptTypes!=NULL)
672 int i;
673 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
674 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
677 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
678 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
680 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
681 goto lend;
685 * My tests seem to show that the windows version does not
686 * become asynchronous until after this point. And anyhow
687 * if this call was asynchronous then how would you get the
688 * necessary HINTERNET pointer returned by this function.
691 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
692 lpszVersion, lpszReferrer, lpszAcceptTypes,
693 dwFlags, dwContext);
694 lend:
695 if( lpwhs )
696 WININET_Release( &lpwhs->hdr );
697 TRACE("returning %p\n", handle);
698 return handle;
702 /***********************************************************************
703 * HttpOpenRequestA (WININET.@)
705 * Open a HTTP request handle
707 * RETURNS
708 * HINTERNET a HTTP request handle on success
709 * NULL on failure
712 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
713 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
714 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
715 DWORD dwFlags, DWORD dwContext)
717 LPWSTR szVerb = NULL, szObjectName = NULL;
718 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
719 INT len;
720 INT acceptTypesCount;
721 HINTERNET rc = FALSE;
722 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08x)\n", hHttpSession,
723 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
724 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
725 dwFlags, dwContext);
727 if (lpszVerb)
729 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
730 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
731 if ( !szVerb )
732 goto end;
733 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
736 if (lpszObjectName)
738 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
739 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
740 if ( !szObjectName )
741 goto end;
742 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
745 if (lpszVersion)
747 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
748 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
749 if ( !szVersion )
750 goto end;
751 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
754 if (lpszReferrer)
756 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
757 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
758 if ( !szReferrer )
759 goto end;
760 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
763 acceptTypesCount = 0;
764 if (lpszAcceptTypes)
766 /* find out how many there are */
767 while (lpszAcceptTypes[acceptTypesCount])
768 acceptTypesCount++;
769 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
770 acceptTypesCount = 0;
771 while (lpszAcceptTypes[acceptTypesCount])
773 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
774 -1, NULL, 0 );
775 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
776 if (!szAcceptTypes[acceptTypesCount] )
777 goto end;
778 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
779 -1, szAcceptTypes[acceptTypesCount], len );
780 acceptTypesCount++;
782 szAcceptTypes[acceptTypesCount] = NULL;
784 else szAcceptTypes = 0;
786 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
787 szVersion, szReferrer,
788 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
790 end:
791 if (szAcceptTypes)
793 acceptTypesCount = 0;
794 while (szAcceptTypes[acceptTypesCount])
796 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
797 acceptTypesCount++;
799 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
801 HeapFree(GetProcessHeap(), 0, szReferrer);
802 HeapFree(GetProcessHeap(), 0, szVersion);
803 HeapFree(GetProcessHeap(), 0, szObjectName);
804 HeapFree(GetProcessHeap(), 0, szVerb);
806 return rc;
809 /***********************************************************************
810 * HTTP_Base64
812 static UINT HTTP_Base64( LPCWSTR bin, LPWSTR base64 )
814 UINT n = 0, x;
815 static LPCSTR HTTP_Base64Enc =
816 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
818 while( bin[0] )
820 /* first 6 bits, all from bin[0] */
821 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
822 x = (bin[0] & 3) << 4;
824 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
825 if( !bin[1] )
827 base64[n++] = HTTP_Base64Enc[x];
828 base64[n++] = '=';
829 base64[n++] = '=';
830 break;
832 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
833 x = ( bin[1] & 0x0f ) << 2;
835 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
836 if( !bin[2] )
838 base64[n++] = HTTP_Base64Enc[x];
839 base64[n++] = '=';
840 break;
842 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
844 /* last 6 bits, all from bin [2] */
845 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
846 bin += 3;
848 base64[n] = 0;
849 return n;
852 /***********************************************************************
853 * HTTP_EncodeBasicAuth
855 * Encode the basic authentication string for HTTP 1.1
857 static LPWSTR HTTP_EncodeBasicAuth( LPCWSTR username, LPCWSTR password)
859 UINT len;
860 LPWSTR in, out;
861 static const WCHAR szBasic[] = {'B','a','s','i','c',' ',0};
862 static const WCHAR szColon[] = {':',0};
864 len = lstrlenW( username ) + 1 + lstrlenW ( password ) + 1;
865 in = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
866 if( !in )
867 return NULL;
869 len = lstrlenW(szBasic) +
870 (lstrlenW( username ) + 1 + lstrlenW ( password ))*2 + 1 + 1;
871 out = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
872 if( out )
874 lstrcpyW( in, username );
875 lstrcatW( in, szColon );
876 lstrcatW( in, password );
877 lstrcpyW( out, szBasic );
878 HTTP_Base64( in, &out[strlenW(out)] );
880 HeapFree( GetProcessHeap(), 0, in );
882 return out;
885 /***********************************************************************
886 * HTTP_InsertProxyAuthorization
888 * Insert the basic authorization field in the request header
890 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr,
891 LPCWSTR username, LPCWSTR password )
893 WCHAR *authorization = HTTP_EncodeBasicAuth( username, password );
894 BOOL ret = TRUE;
896 if (!authorization)
897 return FALSE;
899 TRACE( "Inserting authorization: %s\n", debugstr_w( authorization ) );
901 HTTP_ProcessHeader(lpwhr, szProxy_Authorization, authorization,
902 HTTP_ADDHDR_FLAG_REPLACE);
904 HeapFree( GetProcessHeap(), 0, authorization );
906 return ret;
909 /***********************************************************************
910 * HTTP_DealWithProxy
912 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
913 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
915 WCHAR buf[MAXHOSTNAME];
916 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
917 WCHAR* url;
918 static WCHAR szNul[] = { 0 };
919 URL_COMPONENTSW UrlComponents;
920 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
921 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
922 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
923 int len;
925 memset( &UrlComponents, 0, sizeof UrlComponents );
926 UrlComponents.dwStructSize = sizeof UrlComponents;
927 UrlComponents.lpszHostName = buf;
928 UrlComponents.dwHostNameLength = MAXHOSTNAME;
930 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
931 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
932 sprintfW(proxy, szFormat1, hIC->lpszProxy);
933 else
934 strcpyW(proxy, hIC->lpszProxy);
935 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
936 return FALSE;
937 if( UrlComponents.dwHostNameLength == 0 )
938 return FALSE;
940 if( !lpwhr->lpszPath )
941 lpwhr->lpszPath = szNul;
942 TRACE("server='%s' path='%s'\n",
943 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
944 /* for constant 15 see above */
945 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
946 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
948 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
949 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
951 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
953 if( lpwhr->lpszPath[0] != '/' )
954 strcatW( url, szSlash );
955 strcatW(url, lpwhr->lpszPath);
956 if(lpwhr->lpszPath != szNul)
957 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
958 lpwhr->lpszPath = url;
960 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
961 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
962 lpwhs->nServerPort = UrlComponents.nPort;
964 return TRUE;
967 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
969 char szaddr[32];
970 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
972 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
973 INTERNET_STATUS_RESOLVING_NAME,
974 lpwhs->lpszServerName,
975 strlenW(lpwhs->lpszServerName)+1);
977 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
978 &lpwhs->socketAddress))
980 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
981 return FALSE;
984 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
985 szaddr, sizeof(szaddr));
986 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
987 INTERNET_STATUS_NAME_RESOLVED,
988 szaddr, strlen(szaddr)+1);
989 return TRUE;
992 /***********************************************************************
993 * HTTP_HttpOpenRequestW (internal)
995 * Open a HTTP request handle
997 * RETURNS
998 * HINTERNET a HTTP request handle on success
999 * NULL on failure
1002 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1003 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1004 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1005 DWORD dwFlags, DWORD dwContext)
1007 LPWININETAPPINFOW hIC = NULL;
1008 LPWININETHTTPREQW lpwhr;
1009 LPWSTR lpszCookies;
1010 LPWSTR lpszUrl = NULL;
1011 DWORD nCookieSize;
1012 HINTERNET handle = NULL;
1013 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1014 DWORD len;
1015 LPHTTPHEADERW Host;
1017 TRACE("-->\n");
1019 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1020 hIC = lpwhs->lpAppInfo;
1022 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1023 if (NULL == lpwhr)
1025 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1026 goto lend;
1028 lpwhr->hdr.htype = WH_HHTTPREQ;
1029 lpwhr->hdr.dwFlags = dwFlags;
1030 lpwhr->hdr.dwContext = dwContext;
1031 lpwhr->hdr.dwRefCount = 1;
1032 lpwhr->hdr.destroy = HTTP_CloseHTTPRequestHandle;
1033 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1034 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1036 WININET_AddRef( &lpwhs->hdr );
1037 lpwhr->lpHttpSession = lpwhs;
1039 handle = WININET_AllocHandle( &lpwhr->hdr );
1040 if (NULL == handle)
1042 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1043 goto lend;
1046 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1048 InternetCloseHandle( handle );
1049 handle = NULL;
1050 goto lend;
1053 if (NULL != lpszObjectName && strlenW(lpszObjectName)) {
1054 HRESULT rc;
1056 len = 0;
1057 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1058 if (rc != E_POINTER)
1059 len = strlenW(lpszObjectName)+1;
1060 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1061 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1062 URL_ESCAPE_SPACES_ONLY);
1063 if (rc)
1065 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1066 strcpyW(lpwhr->lpszPath,lpszObjectName);
1070 if (NULL != lpszReferrer && strlenW(lpszReferrer))
1071 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDHDR_FLAG_COALESCE);
1073 if(lpszAcceptTypes!=NULL)
1075 int i;
1076 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
1077 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i], HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_REQ|HTTP_ADDHDR_FLAG_ADD_IF_NEW);
1080 if (NULL == lpszVerb)
1082 static const WCHAR szGet[] = {'G','E','T',0};
1083 lpwhr->lpszVerb = WININET_strdupW(szGet);
1085 else if (strlenW(lpszVerb))
1086 lpwhr->lpszVerb = WININET_strdupW(lpszVerb);
1088 if (NULL != lpszReferrer && strlenW(lpszReferrer))
1090 WCHAR buf[MAXHOSTNAME];
1091 URL_COMPONENTSW UrlComponents;
1093 memset( &UrlComponents, 0, sizeof UrlComponents );
1094 UrlComponents.dwStructSize = sizeof UrlComponents;
1095 UrlComponents.lpszHostName = buf;
1096 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1098 InternetCrackUrlW(lpszReferrer, 0, 0, &UrlComponents);
1099 if (strlenW(UrlComponents.lpszHostName))
1100 HTTP_ProcessHeader(lpwhr, szHost, UrlComponents.lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1102 else
1103 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1105 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1106 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1107 INTERNET_DEFAULT_HTTPS_PORT :
1108 INTERNET_DEFAULT_HTTP_PORT);
1109 lpwhs->nHostPort = lpwhs->nServerPort;
1111 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1112 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1114 if (hIC->lpszAgent)
1116 WCHAR *agent_header;
1117 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1119 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1120 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1121 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1123 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1124 HTTP_ADDREQ_FLAG_ADD);
1125 HeapFree(GetProcessHeap(), 0, agent_header);
1128 Host = HTTP_GetHeader(lpwhr,szHost);
1130 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1131 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1132 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1134 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1135 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1137 int cnt = 0;
1138 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1139 static const WCHAR szcrlf[] = {'\r','\n',0};
1141 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1143 cnt += sprintfW(lpszCookies, szCookie);
1144 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1145 strcatW(lpszCookies, szcrlf);
1147 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1148 HTTP_ADDREQ_FLAG_ADD);
1149 HeapFree(GetProcessHeap(), 0, lpszCookies);
1151 HeapFree(GetProcessHeap(), 0, lpszUrl);
1154 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1155 INTERNET_STATUS_HANDLE_CREATED, &handle,
1156 sizeof(handle));
1159 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1162 if (!HTTP_ResolveName(lpwhr))
1164 InternetCloseHandle( handle );
1165 handle = NULL;
1168 lend:
1169 if( lpwhr )
1170 WININET_Release( &lpwhr->hdr );
1172 TRACE("<-- %p (%p)\n", handle, lpwhr);
1173 return handle;
1176 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1177 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1178 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1179 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1180 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1181 static const WCHAR szAge[] = { 'A','g','e',0 };
1182 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1183 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
1184 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1185 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1186 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1187 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1188 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1189 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1190 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1191 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1192 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1193 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1194 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 };
1195 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1196 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1197 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1198 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1199 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1200 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1201 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1202 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1203 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1204 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1205 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1206 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1207 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1208 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1209 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1210 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1211 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1212 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1213 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1214 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1215 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1216 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1217 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1218 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1219 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1220 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1221 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 };
1222 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1223 static const WCHAR szURI[] = { 'U','R','I',0 };
1224 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1225 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1226 static const WCHAR szVia[] = { 'V','i','a',0 };
1227 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1228 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1230 static const LPCWSTR header_lookup[] = {
1231 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1232 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1233 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1234 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1235 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1236 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1237 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1238 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1239 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1240 szDate, /* HTTP_QUERY_DATE = 9 */
1241 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1242 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1243 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1244 szURI, /* HTTP_QUERY_URI = 13 */
1245 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1246 NULL, /* HTTP_QUERY_COST = 15 */
1247 NULL, /* HTTP_QUERY_LINK = 16 */
1248 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1249 NULL, /* HTTP_QUERY_VERSION = 18 */
1250 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1251 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1252 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1253 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1254 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1255 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1256 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1257 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1258 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1259 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1260 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1261 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1262 NULL, /* HTTP_QUERY_FROM = 31 */
1263 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1264 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1265 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1266 szReferer, /* HTTP_QUERY_REFERER = 35 */
1267 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1268 szServer, /* HTTP_QUERY_SERVER = 37 */
1269 NULL, /* HTTP_TITLE = 38 */
1270 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1271 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1272 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1273 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1274 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1275 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1276 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1277 NULL, /* HTTP_QUERY_REFRESH = 46 */
1278 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1279 szAge, /* HTTP_QUERY_AGE = 48 */
1280 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1281 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1282 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1283 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1284 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1285 szETag, /* HTTP_QUERY_ETAG = 54 */
1286 szHost, /* HTTP_QUERY_HOST = 55 */
1287 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1288 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1289 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1290 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1291 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1292 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1293 szRange, /* HTTP_QUERY_RANGE = 62 */
1294 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1295 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1296 szVary, /* HTTP_QUERY_VARY = 65 */
1297 szVia, /* HTTP_QUERY_VIA = 66 */
1298 szWarning, /* HTTP_QUERY_WARNING = 67 */
1299 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1300 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1301 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1304 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1306 /***********************************************************************
1307 * HTTP_HttpQueryInfoW (internal)
1309 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1310 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1312 LPHTTPHEADERW lphttpHdr = NULL;
1313 BOOL bSuccess = FALSE;
1314 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1315 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1316 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1317 INT index = -1;
1319 /* Find requested header structure */
1320 switch (level)
1322 case HTTP_QUERY_CUSTOM:
1323 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1324 break;
1326 case HTTP_QUERY_RAW_HEADERS_CRLF:
1328 DWORD len = strlenW(lpwhr->lpszRawHeaders);
1329 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1331 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1332 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1333 return FALSE;
1335 memcpy(lpBuffer, lpwhr->lpszRawHeaders, (len+1)*sizeof(WCHAR));
1336 *lpdwBufferLength = len * sizeof(WCHAR);
1338 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1340 return TRUE;
1342 case HTTP_QUERY_RAW_HEADERS:
1344 static const WCHAR szCrLf[] = {'\r','\n',0};
1345 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1346 DWORD i, size = 0;
1347 LPWSTR pszString = (WCHAR*)lpBuffer;
1349 for (i = 0; ppszRawHeaderLines[i]; i++)
1350 size += strlenW(ppszRawHeaderLines[i]) + 1;
1352 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1354 HTTP_FreeTokens(ppszRawHeaderLines);
1355 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1356 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1357 return FALSE;
1360 for (i = 0; ppszRawHeaderLines[i]; i++)
1362 DWORD len = strlenW(ppszRawHeaderLines[i]);
1363 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1364 pszString += len+1;
1366 *pszString = '\0';
1368 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1370 *lpdwBufferLength = size * sizeof(WCHAR);
1371 HTTP_FreeTokens(ppszRawHeaderLines);
1373 return TRUE;
1375 case HTTP_QUERY_STATUS_TEXT:
1376 if (lpwhr->lpszStatusText)
1378 DWORD len = strlenW(lpwhr->lpszStatusText);
1379 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1381 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1382 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1383 return FALSE;
1385 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1386 *lpdwBufferLength = len * sizeof(WCHAR);
1388 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1390 return TRUE;
1392 break;
1393 case HTTP_QUERY_VERSION:
1394 if (lpwhr->lpszVersion)
1396 DWORD len = strlenW(lpwhr->lpszVersion);
1397 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1399 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1400 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1401 return FALSE;
1403 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1404 *lpdwBufferLength = len * sizeof(WCHAR);
1406 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1408 return TRUE;
1410 break;
1411 default:
1412 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1414 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1415 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1416 requested_index,request_only);
1419 if (index >= 0)
1420 lphttpHdr = &lpwhr->pCustHeaders[index];
1422 /* Ensure header satisifies requested attributes */
1423 if (!lphttpHdr ||
1424 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1425 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1427 SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1428 return bSuccess;
1431 if (lpdwIndex)
1432 (*lpdwIndex)++;
1434 /* coalesce value to reuqested type */
1435 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1437 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1438 bSuccess = TRUE;
1440 TRACE(" returning number : %d\n", *(int *)lpBuffer);
1442 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1444 time_t tmpTime;
1445 struct tm tmpTM;
1446 SYSTEMTIME *STHook;
1448 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1450 tmpTM = *gmtime(&tmpTime);
1451 STHook = (SYSTEMTIME *) lpBuffer;
1452 if(STHook==NULL)
1453 return bSuccess;
1455 STHook->wDay = tmpTM.tm_mday;
1456 STHook->wHour = tmpTM.tm_hour;
1457 STHook->wMilliseconds = 0;
1458 STHook->wMinute = tmpTM.tm_min;
1459 STHook->wDayOfWeek = tmpTM.tm_wday;
1460 STHook->wMonth = tmpTM.tm_mon + 1;
1461 STHook->wSecond = tmpTM.tm_sec;
1462 STHook->wYear = tmpTM.tm_year;
1464 bSuccess = TRUE;
1466 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
1467 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1468 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1470 else if (lphttpHdr->lpszValue)
1472 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1474 if (len > *lpdwBufferLength)
1476 *lpdwBufferLength = len;
1477 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1478 return bSuccess;
1481 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1482 *lpdwBufferLength = len - sizeof(WCHAR);
1483 bSuccess = TRUE;
1485 TRACE(" returning string : '%s'\n", debugstr_w(lpBuffer));
1487 return bSuccess;
1490 /***********************************************************************
1491 * HttpQueryInfoW (WININET.@)
1493 * Queries for information about an HTTP request
1495 * RETURNS
1496 * TRUE on success
1497 * FALSE on failure
1500 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1501 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1503 BOOL bSuccess = FALSE;
1504 LPWININETHTTPREQW lpwhr;
1506 if (TRACE_ON(wininet)) {
1507 #define FE(x) { x, #x }
1508 static const wininet_flag_info query_flags[] = {
1509 FE(HTTP_QUERY_MIME_VERSION),
1510 FE(HTTP_QUERY_CONTENT_TYPE),
1511 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1512 FE(HTTP_QUERY_CONTENT_ID),
1513 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1514 FE(HTTP_QUERY_CONTENT_LENGTH),
1515 FE(HTTP_QUERY_CONTENT_LANGUAGE),
1516 FE(HTTP_QUERY_ALLOW),
1517 FE(HTTP_QUERY_PUBLIC),
1518 FE(HTTP_QUERY_DATE),
1519 FE(HTTP_QUERY_EXPIRES),
1520 FE(HTTP_QUERY_LAST_MODIFIED),
1521 FE(HTTP_QUERY_MESSAGE_ID),
1522 FE(HTTP_QUERY_URI),
1523 FE(HTTP_QUERY_DERIVED_FROM),
1524 FE(HTTP_QUERY_COST),
1525 FE(HTTP_QUERY_LINK),
1526 FE(HTTP_QUERY_PRAGMA),
1527 FE(HTTP_QUERY_VERSION),
1528 FE(HTTP_QUERY_STATUS_CODE),
1529 FE(HTTP_QUERY_STATUS_TEXT),
1530 FE(HTTP_QUERY_RAW_HEADERS),
1531 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1532 FE(HTTP_QUERY_CONNECTION),
1533 FE(HTTP_QUERY_ACCEPT),
1534 FE(HTTP_QUERY_ACCEPT_CHARSET),
1535 FE(HTTP_QUERY_ACCEPT_ENCODING),
1536 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1537 FE(HTTP_QUERY_AUTHORIZATION),
1538 FE(HTTP_QUERY_CONTENT_ENCODING),
1539 FE(HTTP_QUERY_FORWARDED),
1540 FE(HTTP_QUERY_FROM),
1541 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1542 FE(HTTP_QUERY_LOCATION),
1543 FE(HTTP_QUERY_ORIG_URI),
1544 FE(HTTP_QUERY_REFERER),
1545 FE(HTTP_QUERY_RETRY_AFTER),
1546 FE(HTTP_QUERY_SERVER),
1547 FE(HTTP_QUERY_TITLE),
1548 FE(HTTP_QUERY_USER_AGENT),
1549 FE(HTTP_QUERY_WWW_AUTHENTICATE),
1550 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1551 FE(HTTP_QUERY_ACCEPT_RANGES),
1552 FE(HTTP_QUERY_SET_COOKIE),
1553 FE(HTTP_QUERY_COOKIE),
1554 FE(HTTP_QUERY_REQUEST_METHOD),
1555 FE(HTTP_QUERY_REFRESH),
1556 FE(HTTP_QUERY_CONTENT_DISPOSITION),
1557 FE(HTTP_QUERY_AGE),
1558 FE(HTTP_QUERY_CACHE_CONTROL),
1559 FE(HTTP_QUERY_CONTENT_BASE),
1560 FE(HTTP_QUERY_CONTENT_LOCATION),
1561 FE(HTTP_QUERY_CONTENT_MD5),
1562 FE(HTTP_QUERY_CONTENT_RANGE),
1563 FE(HTTP_QUERY_ETAG),
1564 FE(HTTP_QUERY_HOST),
1565 FE(HTTP_QUERY_IF_MATCH),
1566 FE(HTTP_QUERY_IF_NONE_MATCH),
1567 FE(HTTP_QUERY_IF_RANGE),
1568 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
1569 FE(HTTP_QUERY_MAX_FORWARDS),
1570 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
1571 FE(HTTP_QUERY_RANGE),
1572 FE(HTTP_QUERY_TRANSFER_ENCODING),
1573 FE(HTTP_QUERY_UPGRADE),
1574 FE(HTTP_QUERY_VARY),
1575 FE(HTTP_QUERY_VIA),
1576 FE(HTTP_QUERY_WARNING),
1577 FE(HTTP_QUERY_CUSTOM)
1579 static const wininet_flag_info modifier_flags[] = {
1580 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
1581 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
1582 FE(HTTP_QUERY_FLAG_NUMBER),
1583 FE(HTTP_QUERY_FLAG_COALESCE)
1585 #undef FE
1586 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
1587 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
1588 DWORD i;
1590 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
1591 TRACE(" Attribute:");
1592 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
1593 if (query_flags[i].val == info) {
1594 TRACE(" %s", query_flags[i].name);
1595 break;
1598 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
1599 TRACE(" Unknown (%08x)", info);
1602 TRACE(" Modifier:");
1603 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
1604 if (modifier_flags[i].val & info_mod) {
1605 TRACE(" %s", modifier_flags[i].name);
1606 info_mod &= ~ modifier_flags[i].val;
1610 if (info_mod) {
1611 TRACE(" Unknown (%08x)", info_mod);
1613 TRACE("\n");
1616 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1617 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1619 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1620 goto lend;
1623 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
1624 lpBuffer, lpdwBufferLength, lpdwIndex);
1626 lend:
1627 if( lpwhr )
1628 WININET_Release( &lpwhr->hdr );
1630 TRACE("%d <--\n", bSuccess);
1631 return bSuccess;
1634 /***********************************************************************
1635 * HttpQueryInfoA (WININET.@)
1637 * Queries for information about an HTTP request
1639 * RETURNS
1640 * TRUE on success
1641 * FALSE on failure
1644 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1645 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1647 BOOL result;
1648 DWORD len;
1649 WCHAR* bufferW;
1651 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
1652 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
1654 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
1655 lpdwBufferLength, lpdwIndex );
1658 len = (*lpdwBufferLength)*sizeof(WCHAR);
1659 bufferW = HeapAlloc( GetProcessHeap(), 0, len );
1660 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
1661 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
1662 MultiByteToWideChar(CP_ACP,0,lpBuffer,-1,bufferW,len);
1663 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
1664 &len, lpdwIndex );
1665 if( result )
1667 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
1668 lpBuffer, *lpdwBufferLength, NULL, NULL );
1669 *lpdwBufferLength = len - 1;
1671 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
1673 else
1674 /* since the strings being returned from HttpQueryInfoW should be
1675 * only ASCII characters, it is reasonable to assume that all of
1676 * the Unicode characters can be reduced to a single byte */
1677 *lpdwBufferLength = len / sizeof(WCHAR);
1679 HeapFree(GetProcessHeap(), 0, bufferW );
1681 return result;
1684 /***********************************************************************
1685 * HttpSendRequestExA (WININET.@)
1687 * Sends the specified request to the HTTP server and allows chunked
1688 * transfers.
1690 * RETURNS
1691 * Success: TRUE
1692 * Failure: FALSE, call GetLastError() for more information.
1694 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
1695 LPINTERNET_BUFFERSA lpBuffersIn,
1696 LPINTERNET_BUFFERSA lpBuffersOut,
1697 DWORD dwFlags, DWORD dwContext)
1699 INTERNET_BUFFERSW BuffersInW;
1700 BOOL rc = FALSE;
1701 DWORD headerlen;
1702 LPWSTR header = NULL;
1704 TRACE("(%p, %p, %p, %08x, %08x): stub\n", hRequest, lpBuffersIn,
1705 lpBuffersOut, dwFlags, dwContext);
1707 if (lpBuffersIn)
1709 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
1710 if (lpBuffersIn->lpcszHeader)
1712 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
1713 lpBuffersIn->dwHeadersLength,0,0);
1714 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
1715 if (!(BuffersInW.lpcszHeader = header))
1717 SetLastError(ERROR_OUTOFMEMORY);
1718 return FALSE;
1720 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
1721 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
1722 header, headerlen);
1724 else
1725 BuffersInW.lpcszHeader = NULL;
1726 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
1727 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
1728 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
1729 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
1730 BuffersInW.Next = NULL;
1733 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
1735 HeapFree(GetProcessHeap(),0,header);
1737 return rc;
1740 /***********************************************************************
1741 * HttpSendRequestExW (WININET.@)
1743 * Sends the specified request to the HTTP server and allows chunked
1744 * transfers
1746 * RETURNS
1747 * Success: TRUE
1748 * Failure: FALSE, call GetLastError() for more information.
1750 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
1751 LPINTERNET_BUFFERSW lpBuffersIn,
1752 LPINTERNET_BUFFERSW lpBuffersOut,
1753 DWORD dwFlags, DWORD dwContext)
1755 BOOL ret;
1756 LPWININETHTTPREQW lpwhr;
1757 LPWININETHTTPSESSIONW lpwhs;
1758 LPWININETAPPINFOW hIC;
1760 TRACE("(%p, %p, %p, %08x, %08x)\n", hRequest, lpBuffersIn,
1761 lpBuffersOut, dwFlags, dwContext);
1763 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
1765 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1767 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1768 return FALSE;
1771 lpwhs = lpwhr->lpHttpSession;
1772 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
1773 hIC = lpwhs->lpAppInfo;
1774 assert(hIC->hdr.htype == WH_HINIT);
1776 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1778 WORKREQUEST workRequest;
1779 struct WORKREQ_HTTPSENDREQUESTW *req;
1781 workRequest.asyncall = HTTPSENDREQUESTW;
1782 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
1783 req = &workRequest.u.HttpSendRequestW;
1784 if (lpBuffersIn)
1786 if (lpBuffersIn->lpcszHeader)
1787 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
1788 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
1789 else
1790 req->lpszHeader = NULL;
1791 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
1792 req->lpOptional = lpBuffersIn->lpvBuffer;
1793 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
1794 req->dwContentLength = lpBuffersIn->dwBufferTotal;
1796 else
1798 req->lpszHeader = NULL;
1799 req->dwHeaderLength = 0;
1800 req->lpOptional = NULL;
1801 req->dwOptionalLength = 0;
1802 req->dwContentLength = 0;
1805 req->bEndRequest = FALSE;
1807 INTERNET_AsyncCall(&workRequest);
1809 * This is from windows.
1811 SetLastError(ERROR_IO_PENDING);
1812 ret = FALSE;
1814 else
1816 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
1817 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
1818 lpBuffersIn->dwBufferTotal, FALSE);
1821 WININET_Release(&lpwhr->hdr);
1822 TRACE("<---\n");
1823 return ret;
1826 /***********************************************************************
1827 * HttpSendRequestW (WININET.@)
1829 * Sends the specified request to the HTTP server
1831 * RETURNS
1832 * TRUE on success
1833 * FALSE on failure
1836 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
1837 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1839 LPWININETHTTPREQW lpwhr;
1840 LPWININETHTTPSESSIONW lpwhs = NULL;
1841 LPWININETAPPINFOW hIC = NULL;
1842 BOOL r;
1844 TRACE("%p, %p (%s), %i, %p, %i)\n", hHttpRequest,
1845 lpszHeaders, debugstr_w(lpszHeaders), dwHeaderLength, lpOptional, dwOptionalLength);
1847 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1848 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1850 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1851 r = FALSE;
1852 goto lend;
1855 lpwhs = lpwhr->lpHttpSession;
1856 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
1858 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1859 r = FALSE;
1860 goto lend;
1863 hIC = lpwhs->lpAppInfo;
1864 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
1866 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1867 r = FALSE;
1868 goto lend;
1871 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1873 WORKREQUEST workRequest;
1874 struct WORKREQ_HTTPSENDREQUESTW *req;
1876 workRequest.asyncall = HTTPSENDREQUESTW;
1877 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
1878 req = &workRequest.u.HttpSendRequestW;
1879 if (lpszHeaders)
1880 req->lpszHeader = WININET_strdupW(lpszHeaders);
1881 else
1882 req->lpszHeader = 0;
1883 req->dwHeaderLength = dwHeaderLength;
1884 req->lpOptional = lpOptional;
1885 req->dwOptionalLength = dwOptionalLength;
1886 req->dwContentLength = dwOptionalLength;
1887 req->bEndRequest = TRUE;
1889 INTERNET_AsyncCall(&workRequest);
1891 * This is from windows.
1893 SetLastError(ERROR_IO_PENDING);
1894 r = FALSE;
1896 else
1898 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
1899 dwHeaderLength, lpOptional, dwOptionalLength,
1900 dwOptionalLength, TRUE);
1902 lend:
1903 if( lpwhr )
1904 WININET_Release( &lpwhr->hdr );
1905 return r;
1908 /***********************************************************************
1909 * HttpSendRequestA (WININET.@)
1911 * Sends the specified request to the HTTP server
1913 * RETURNS
1914 * TRUE on success
1915 * FALSE on failure
1918 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
1919 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1921 BOOL result;
1922 LPWSTR szHeaders=NULL;
1923 DWORD nLen=dwHeaderLength;
1924 if(lpszHeaders!=NULL)
1926 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
1927 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
1928 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
1930 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
1931 HeapFree(GetProcessHeap(),0,szHeaders);
1932 return result;
1935 /***********************************************************************
1936 * HTTP_HandleRedirect (internal)
1938 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
1940 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1941 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
1942 WCHAR path[2048];
1944 if(lpszUrl[0]=='/')
1946 /* if it's an absolute path, keep the same session info */
1947 lstrcpynW(path, lpszUrl, 2048);
1949 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1951 TRACE("Redirect through proxy\n");
1952 lstrcpynW(path, lpszUrl, 2048);
1954 else
1956 URL_COMPONENTSW urlComponents;
1957 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
1958 static WCHAR szHttp[] = {'h','t','t','p',0};
1959 static WCHAR szHttps[] = {'h','t','t','p','s',0};
1960 DWORD url_length = 0;
1961 LPWSTR orig_url;
1962 LPWSTR combined_url;
1964 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
1965 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
1966 urlComponents.dwSchemeLength = 0;
1967 urlComponents.lpszHostName = lpwhs->lpszHostName;
1968 urlComponents.dwHostNameLength = 0;
1969 urlComponents.nPort = lpwhs->nHostPort;
1970 urlComponents.lpszUserName = lpwhs->lpszUserName;
1971 urlComponents.dwUserNameLength = 0;
1972 urlComponents.lpszPassword = NULL;
1973 urlComponents.dwPasswordLength = 0;
1974 urlComponents.lpszUrlPath = lpwhr->lpszPath;
1975 urlComponents.dwUrlPathLength = 0;
1976 urlComponents.lpszExtraInfo = NULL;
1977 urlComponents.dwExtraInfoLength = 0;
1979 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
1980 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
1981 return FALSE;
1983 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
1985 /* convert from bytes to characters */
1986 url_length = url_length / sizeof(WCHAR) - 1;
1987 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
1989 HeapFree(GetProcessHeap(), 0, orig_url);
1990 return FALSE;
1993 url_length = 0;
1994 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
1995 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
1997 HeapFree(GetProcessHeap(), 0, orig_url);
1998 return FALSE;
2000 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2002 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2004 HeapFree(GetProcessHeap(), 0, orig_url);
2005 HeapFree(GetProcessHeap(), 0, combined_url);
2006 return FALSE;
2008 HeapFree(GetProcessHeap(), 0, orig_url);
2010 userName[0] = 0;
2011 hostName[0] = 0;
2012 protocol[0] = 0;
2014 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2015 urlComponents.lpszScheme = protocol;
2016 urlComponents.dwSchemeLength = 32;
2017 urlComponents.lpszHostName = hostName;
2018 urlComponents.dwHostNameLength = MAXHOSTNAME;
2019 urlComponents.lpszUserName = userName;
2020 urlComponents.dwUserNameLength = 1024;
2021 urlComponents.lpszPassword = NULL;
2022 urlComponents.dwPasswordLength = 0;
2023 urlComponents.lpszUrlPath = path;
2024 urlComponents.dwUrlPathLength = 2048;
2025 urlComponents.lpszExtraInfo = NULL;
2026 urlComponents.dwExtraInfoLength = 0;
2027 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2029 HeapFree(GetProcessHeap(), 0, combined_url);
2030 return FALSE;
2032 HeapFree(GetProcessHeap(), 0, combined_url);
2034 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2035 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2037 TRACE("redirect from secure page to non-secure page\n");
2038 /* FIXME: warn about from secure redirect to non-secure page */
2039 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2041 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2042 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2044 TRACE("redirect from non-secure page to secure page\n");
2045 /* FIXME: notify about redirect to secure page */
2046 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2049 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2051 if (lstrlenW(protocol)>4) /*https*/
2052 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2053 else /*http*/
2054 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2057 #if 0
2059 * This upsets redirects to binary files on sourceforge.net
2060 * and gives an html page instead of the target file
2061 * Examination of the HTTP request sent by native wininet.dll
2062 * reveals that it doesn't send a referrer in that case.
2063 * Maybe there's a flag that enables this, or maybe a referrer
2064 * shouldn't be added in case of a redirect.
2067 /* consider the current host as the referrer */
2068 if (NULL != lpwhs->lpszServerName && strlenW(lpwhs->lpszServerName))
2069 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2070 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2071 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2072 #endif
2074 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2075 lpwhs->lpszServerName = WININET_strdupW(hostName);
2076 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2077 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2078 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2080 int len;
2081 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2082 len = lstrlenW(hostName);
2083 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2084 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2085 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2087 else
2088 lpwhs->lpszHostName = WININET_strdupW(hostName);
2090 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2093 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2094 lpwhs->lpszUserName = NULL;
2095 if (userName[0])
2096 lpwhs->lpszUserName = WININET_strdupW(userName);
2097 lpwhs->nServerPort = urlComponents.nPort;
2099 if (!HTTP_ResolveName(lpwhr))
2100 return FALSE;
2102 NETCON_close(&lpwhr->netConnection);
2104 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2105 return FALSE;
2108 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2109 lpwhr->lpszPath=NULL;
2110 if (strlenW(path))
2112 DWORD needed = 0;
2113 HRESULT rc;
2115 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2116 if (rc != E_POINTER)
2117 needed = strlenW(path)+1;
2118 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2119 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2120 URL_ESCAPE_SPACES_ONLY);
2121 if (rc)
2123 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2124 strcpyW(lpwhr->lpszPath,path);
2128 return TRUE;
2131 /***********************************************************************
2132 * HTTP_build_req (internal)
2134 * concatenate all the strings in the request together
2136 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2138 LPCWSTR *t;
2139 LPWSTR str;
2141 for( t = list; *t ; t++ )
2142 len += strlenW( *t );
2143 len++;
2145 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2146 *str = 0;
2148 for( t = list; *t ; t++ )
2149 strcatW( str, *t );
2151 return str;
2154 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2156 LPWSTR lpszPath;
2157 LPWSTR requestString;
2158 INT len;
2159 INT cnt;
2160 INT responseLen;
2161 char *ascii_req;
2162 BOOL ret;
2163 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2164 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2165 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2167 TRACE("\n");
2169 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2170 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2171 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, FALSE );
2172 HeapFree( GetProcessHeap(), 0, lpszPath );
2174 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2175 NULL, 0, NULL, NULL );
2176 len--; /* the nul terminator isn't needed */
2177 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2178 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2179 ascii_req, len, NULL, NULL );
2180 HeapFree( GetProcessHeap(), 0, requestString );
2182 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2184 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2185 HeapFree( GetProcessHeap(), 0, ascii_req );
2186 if (!ret || cnt < 0)
2187 return FALSE;
2189 responseLen = HTTP_GetResponseHeaders( lpwhr );
2190 if (!responseLen)
2191 return FALSE;
2193 return TRUE;
2196 /***********************************************************************
2197 * HTTP_HttpSendRequestW (internal)
2199 * Sends the specified request to the HTTP server
2201 * RETURNS
2202 * TRUE on success
2203 * FALSE on failure
2206 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2207 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2208 DWORD dwContentLength, BOOL bEndRequest)
2210 INT cnt;
2211 BOOL bSuccess = FALSE;
2212 LPWSTR requestString = NULL;
2213 INT responseLen;
2214 BOOL loop_next = FALSE;
2215 INTERNET_ASYNC_RESULT iar;
2217 TRACE("--> %p\n", lpwhr);
2219 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2221 /* Clear any error information */
2222 INTERNET_SetLastError(0);
2224 HTTP_FixVerb(lpwhr);
2226 /* if we are using optional stuff, we must add the fixed header of that option length */
2227 if (dwContentLength > 0)
2229 static const WCHAR szContentLength[] = {
2230 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0};
2231 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \n\r */ + 20 /* int */ ];
2232 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2233 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L,
2234 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2239 DWORD len;
2240 char *ascii_req;
2242 if (TRACE_ON(wininet))
2244 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2245 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2248 HTTP_FixURL(lpwhr);
2250 /* add the headers the caller supplied */
2251 if( lpszHeaders && dwHeaderLength )
2253 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2254 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2257 /* if there's a proxy username and password, add it to the headers */
2258 HTTP_AddProxyInfo(lpwhr);
2260 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, FALSE);
2262 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2264 /* Send the request and store the results */
2265 if (!HTTP_OpenConnection(lpwhr))
2266 goto lend;
2268 /* send the request as ASCII, tack on the optional data */
2269 if( !lpOptional )
2270 dwOptionalLength = 0;
2271 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2272 NULL, 0, NULL, NULL );
2273 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2274 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2275 ascii_req, len, NULL, NULL );
2276 if( lpOptional )
2277 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2278 len = (len + dwOptionalLength - 1);
2279 ascii_req[len] = 0;
2280 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2282 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2283 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2285 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2286 HeapFree( GetProcessHeap(), 0, ascii_req );
2288 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2289 INTERNET_STATUS_REQUEST_SENT,
2290 &len, sizeof(DWORD));
2292 if (bEndRequest)
2294 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2295 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2297 if (cnt < 0)
2298 goto lend;
2300 responseLen = HTTP_GetResponseHeaders(lpwhr);
2301 if (responseLen)
2302 bSuccess = TRUE;
2304 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2305 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2306 sizeof(DWORD));
2308 HTTP_ProcessHeaders(lpwhr);
2310 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2312 DWORD dwCode,dwCodeLength=sizeof(DWORD),dwIndex=0;
2313 WCHAR szNewLocation[2048];
2314 DWORD dwBufferSize=2048;
2315 if (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,&dwIndex) &&
2316 (dwCode==HTTP_STATUS_REDIRECT || dwCode==HTTP_STATUS_MOVED) &&
2317 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,&dwIndex))
2319 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2320 INTERNET_STATUS_REDIRECT, szNewLocation,
2321 dwBufferSize);
2322 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2323 if (bSuccess)
2325 HeapFree(GetProcessHeap(), 0, requestString);
2326 loop_next = TRUE;
2332 else
2333 bSuccess = TRUE;
2335 while (loop_next);
2337 lend:
2339 HeapFree(GetProcessHeap(), 0, requestString);
2341 /* TODO: send notification for P3P header */
2343 iar.dwResult = (DWORD)bSuccess;
2344 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2346 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2347 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2348 sizeof(INTERNET_ASYNC_RESULT));
2350 TRACE("<--\n");
2351 return bSuccess;
2355 /***********************************************************************
2356 * HTTP_Connect (internal)
2358 * Create http session handle
2360 * RETURNS
2361 * HINTERNET a session handle on success
2362 * NULL on failure
2365 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
2366 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2367 LPCWSTR lpszPassword, DWORD dwFlags, DWORD dwContext,
2368 DWORD dwInternalFlags)
2370 BOOL bSuccess = FALSE;
2371 LPWININETHTTPSESSIONW lpwhs = NULL;
2372 HINTERNET handle = NULL;
2374 TRACE("-->\n");
2376 assert( hIC->hdr.htype == WH_HINIT );
2378 hIC->hdr.dwContext = dwContext;
2380 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
2381 if (NULL == lpwhs)
2383 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2384 goto lerror;
2388 * According to my tests. The name is not resolved until a request is sent
2391 lpwhs->hdr.htype = WH_HHTTPSESSION;
2392 lpwhs->hdr.dwFlags = dwFlags;
2393 lpwhs->hdr.dwContext = dwContext;
2394 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
2395 lpwhs->hdr.dwRefCount = 1;
2396 lpwhs->hdr.destroy = HTTP_CloseHTTPSessionHandle;
2397 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
2399 WININET_AddRef( &hIC->hdr );
2400 lpwhs->lpAppInfo = hIC;
2402 handle = WININET_AllocHandle( &lpwhs->hdr );
2403 if (NULL == handle)
2405 ERR("Failed to alloc handle\n");
2406 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2407 goto lerror;
2410 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
2411 if(strchrW(hIC->lpszProxy, ' '))
2412 FIXME("Several proxies not implemented.\n");
2413 if(hIC->lpszProxyBypass)
2414 FIXME("Proxy bypass is ignored.\n");
2416 if (lpszServerName && lpszServerName[0])
2418 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
2419 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
2421 if (lpszUserName && lpszUserName[0])
2422 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
2423 lpwhs->nServerPort = nServerPort;
2424 lpwhs->nHostPort = nServerPort;
2426 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2427 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
2429 INTERNET_SendCallback(&hIC->hdr, dwContext,
2430 INTERNET_STATUS_HANDLE_CREATED, &handle,
2431 sizeof(handle));
2434 bSuccess = TRUE;
2436 lerror:
2437 if( lpwhs )
2438 WININET_Release( &lpwhs->hdr );
2441 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
2442 * windows
2445 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
2446 return handle;
2450 /***********************************************************************
2451 * HTTP_OpenConnection (internal)
2453 * Connect to a web server
2455 * RETURNS
2457 * TRUE on success
2458 * FALSE on failure
2460 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
2462 BOOL bSuccess = FALSE;
2463 LPWININETHTTPSESSIONW lpwhs;
2464 LPWININETAPPINFOW hIC = NULL;
2465 char szaddr[32];
2467 TRACE("-->\n");
2470 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2472 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2473 goto lend;
2476 lpwhs = lpwhr->lpHttpSession;
2478 hIC = lpwhs->lpAppInfo;
2479 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
2480 szaddr, sizeof(szaddr));
2481 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2482 INTERNET_STATUS_CONNECTING_TO_SERVER,
2483 szaddr,
2484 strlen(szaddr)+1);
2486 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
2487 SOCK_STREAM, 0))
2489 WARN("Socket creation failed\n");
2490 goto lend;
2493 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
2494 sizeof(lpwhs->socketAddress)))
2495 goto lend;
2497 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
2499 /* Note: we differ from Microsoft's WinINet here. they seem to have
2500 * a bug that causes no status callbacks to be sent when starting
2501 * a tunnel to a proxy server using the CONNECT verb. i believe our
2502 * behaviour to be more correct and to not cause any incompatibilities
2503 * because using a secure connection through a proxy server is a rare
2504 * case that would be hard for anyone to depend on */
2505 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
2506 goto lend;
2508 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
2510 WARN("Couldn't connect securely to host\n");
2511 goto lend;
2515 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2516 INTERNET_STATUS_CONNECTED_TO_SERVER,
2517 szaddr, strlen(szaddr)+1);
2519 bSuccess = TRUE;
2521 lend:
2522 TRACE("%d <--\n", bSuccess);
2523 return bSuccess;
2527 /***********************************************************************
2528 * HTTP_clear_response_headers (internal)
2530 * clear out any old response headers
2532 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
2534 DWORD i;
2536 for( i=0; i<lpwhr->nCustHeaders; i++)
2538 if( !lpwhr->pCustHeaders[i].lpszField )
2539 continue;
2540 if( !lpwhr->pCustHeaders[i].lpszValue )
2541 continue;
2542 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
2543 continue;
2544 HTTP_DeleteCustomHeader( lpwhr, i );
2545 i--;
2549 /***********************************************************************
2550 * HTTP_GetResponseHeaders (internal)
2552 * Read server response
2554 * RETURNS
2556 * TRUE on success
2557 * FALSE on error
2559 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
2561 INT cbreaks = 0;
2562 WCHAR buffer[MAX_REPLY_LEN];
2563 DWORD buflen = MAX_REPLY_LEN;
2564 BOOL bSuccess = FALSE;
2565 INT rc = 0;
2566 static const WCHAR szCrLf[] = {'\r','\n',0};
2567 char bufferA[MAX_REPLY_LEN];
2568 LPWSTR status_code, status_text;
2569 DWORD cchMaxRawHeaders = 1024;
2570 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2571 DWORD cchRawHeaders = 0;
2573 TRACE("-->\n");
2575 /* clear old response headers (eg. from a redirect response) */
2576 HTTP_clear_response_headers( lpwhr );
2578 if (!NETCON_connected(&lpwhr->netConnection))
2579 goto lend;
2582 * HACK peek at the buffer
2584 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
2587 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
2589 buflen = MAX_REPLY_LEN;
2590 memset(buffer, 0, MAX_REPLY_LEN);
2591 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
2592 goto lend;
2593 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
2595 /* regenerate raw headers */
2596 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
2598 cchMaxRawHeaders *= 2;
2599 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2601 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
2602 cchRawHeaders += (buflen-1);
2603 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
2604 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
2605 lpszRawHeaders[cchRawHeaders] = '\0';
2607 /* split the version from the status code */
2608 status_code = strchrW( buffer, ' ' );
2609 if( !status_code )
2610 goto lend;
2611 *status_code++=0;
2613 /* split the status code from the status text */
2614 status_text = strchrW( status_code, ' ' );
2615 if( !status_text )
2616 goto lend;
2617 *status_text++=0;
2619 TRACE("version [%s] status code [%s] status text [%s]\n",
2620 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
2622 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
2623 HTTP_ADDHDR_FLAG_REPLACE);
2625 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
2626 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
2628 lpwhr->lpszVersion= WININET_strdupW(buffer);
2629 lpwhr->lpszStatusText = WININET_strdupW(status_text);
2631 /* Parse each response line */
2634 buflen = MAX_REPLY_LEN;
2635 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
2637 LPWSTR * pFieldAndValue;
2639 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
2640 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
2642 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
2644 cchMaxRawHeaders *= 2;
2645 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2647 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
2648 cchRawHeaders += (buflen-1);
2649 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
2650 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
2651 lpszRawHeaders[cchRawHeaders] = '\0';
2653 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
2654 if (!pFieldAndValue)
2655 break;
2657 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
2658 HTTP_ADDREQ_FLAG_ADD );
2660 HTTP_FreeTokens(pFieldAndValue);
2662 else
2664 cbreaks++;
2665 if (cbreaks >= 2)
2666 break;
2668 }while(1);
2670 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
2671 lpwhr->lpszRawHeaders = lpszRawHeaders;
2672 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
2673 bSuccess = TRUE;
2675 lend:
2677 TRACE("<--\n");
2678 if (bSuccess)
2679 return rc;
2680 else
2681 return 0;
2685 static void strip_spaces(LPWSTR start)
2687 LPWSTR str = start;
2688 LPWSTR end;
2690 while (*str == ' ' && *str != '\0')
2691 str++;
2693 if (str != start)
2694 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
2696 end = start + strlenW(start) - 1;
2697 while (end >= start && *end == ' ')
2699 *end = '\0';
2700 end--;
2705 /***********************************************************************
2706 * HTTP_InterpretHttpHeader (internal)
2708 * Parse server response
2710 * RETURNS
2712 * Pointer to array of field, value, NULL on success.
2713 * NULL on error.
2715 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
2717 LPWSTR * pTokenPair;
2718 LPWSTR pszColon;
2719 INT len;
2721 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
2723 pszColon = strchrW(buffer, ':');
2724 /* must have two tokens */
2725 if (!pszColon)
2727 HTTP_FreeTokens(pTokenPair);
2728 if (buffer[0])
2729 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
2730 return NULL;
2733 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
2734 if (!pTokenPair[0])
2736 HTTP_FreeTokens(pTokenPair);
2737 return NULL;
2739 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
2740 pTokenPair[0][pszColon - buffer] = '\0';
2742 /* skip colon */
2743 pszColon++;
2744 len = strlenW(pszColon);
2745 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2746 if (!pTokenPair[1])
2748 HTTP_FreeTokens(pTokenPair);
2749 return NULL;
2751 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
2753 strip_spaces(pTokenPair[0]);
2754 strip_spaces(pTokenPair[1]);
2756 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
2757 return pTokenPair;
2760 /***********************************************************************
2761 * HTTP_ProcessHeader (internal)
2763 * Stuff header into header tables according to <dwModifier>
2767 #define COALESCEFLASG (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
2769 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
2771 LPHTTPHEADERW lphttpHdr = NULL;
2772 BOOL bSuccess = FALSE;
2773 INT index = -1;
2774 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2775 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
2777 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
2779 /* Don't let applications add Connection header to request */
2780 if (strcmpW(szConnection,field)==0 && (dwModifier & HTTP_ADDHDR_FLAG_REQ))
2782 return FALSE;
2785 /* REPLACE wins out over ADD */
2786 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
2787 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
2789 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
2790 index = -1;
2791 else
2792 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
2794 if (index >= 0)
2796 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
2798 return FALSE;
2800 lphttpHdr = &lpwhr->pCustHeaders[index];
2802 else if (value)
2804 HTTPHEADERW hdr;
2806 hdr.lpszField = (LPWSTR)field;
2807 hdr.lpszValue = (LPWSTR)value;
2808 hdr.wFlags = hdr.wCount = 0;
2810 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2811 hdr.wFlags |= HDR_ISREQUEST;
2813 return HTTP_InsertCustomHeader(lpwhr, &hdr);
2816 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2817 lphttpHdr->wFlags |= HDR_ISREQUEST;
2818 else
2819 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
2821 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
2823 HTTP_DeleteCustomHeader( lpwhr, index );
2825 if (value)
2827 HTTPHEADERW hdr;
2829 hdr.lpszField = (LPWSTR)field;
2830 hdr.lpszValue = (LPWSTR)value;
2831 hdr.wFlags = hdr.wCount = 0;
2833 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2834 hdr.wFlags |= HDR_ISREQUEST;
2836 return HTTP_InsertCustomHeader(lpwhr, &hdr);
2839 return TRUE;
2841 else if (dwModifier & COALESCEFLASG)
2843 LPWSTR lpsztmp;
2844 WCHAR ch = 0;
2845 INT len = 0;
2846 INT origlen = strlenW(lphttpHdr->lpszValue);
2847 INT valuelen = strlenW(value);
2849 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
2851 ch = ',';
2852 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
2854 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
2856 ch = ';';
2857 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
2860 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
2862 lpsztmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
2863 if (lpsztmp)
2865 lphttpHdr->lpszValue = lpsztmp;
2866 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
2867 if (ch > 0)
2869 lphttpHdr->lpszValue[origlen] = ch;
2870 origlen++;
2871 lphttpHdr->lpszValue[origlen] = ' ';
2872 origlen++;
2875 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
2876 lphttpHdr->lpszValue[len] = '\0';
2877 bSuccess = TRUE;
2879 else
2881 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
2882 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2885 TRACE("<-- %d\n",bSuccess);
2886 return bSuccess;
2890 /***********************************************************************
2891 * HTTP_CloseConnection (internal)
2893 * Close socket connection
2896 static VOID HTTP_CloseConnection(LPWININETHTTPREQW lpwhr)
2898 LPWININETHTTPSESSIONW lpwhs = NULL;
2899 LPWININETAPPINFOW hIC = NULL;
2901 TRACE("%p\n",lpwhr);
2903 lpwhs = lpwhr->lpHttpSession;
2904 hIC = lpwhs->lpAppInfo;
2906 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2907 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2909 if (NETCON_connected(&lpwhr->netConnection))
2911 NETCON_close(&lpwhr->netConnection);
2914 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2915 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2919 /***********************************************************************
2920 * HTTP_CloseHTTPRequestHandle (internal)
2922 * Deallocate request handle
2925 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr)
2927 DWORD i;
2928 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
2930 TRACE("\n");
2932 WININET_Release(&lpwhr->hdr);
2934 if (NETCON_connected(&lpwhr->netConnection))
2935 HTTP_CloseConnection(lpwhr);
2937 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2938 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
2939 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
2940 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
2941 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
2943 for (i = 0; i < lpwhr->nCustHeaders; i++)
2945 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
2946 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
2949 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
2950 HeapFree(GetProcessHeap(), 0, lpwhr);
2954 /***********************************************************************
2955 * HTTP_CloseHTTPSessionHandle (internal)
2957 * Deallocate session handle
2960 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr)
2962 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
2964 TRACE("%p\n", lpwhs);
2966 WININET_Release(&lpwhs->lpAppInfo->hdr);
2968 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2969 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2970 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2971 HeapFree(GetProcessHeap(), 0, lpwhs);
2975 /***********************************************************************
2976 * HTTP_GetCustomHeaderIndex (internal)
2978 * Return index of custom header from header array
2981 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
2982 int requested_index, BOOL request_only)
2984 DWORD index;
2986 TRACE("%s\n", debugstr_w(lpszField));
2988 for (index = 0; index < lpwhr->nCustHeaders; index++)
2990 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
2991 continue;
2993 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
2994 continue;
2996 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
2997 continue;
2999 if (requested_index == 0)
3000 break;
3001 requested_index --;
3004 if (index >= lpwhr->nCustHeaders)
3005 index = -1;
3007 TRACE("Return: %d\n", index);
3008 return index;
3012 /***********************************************************************
3013 * HTTP_InsertCustomHeader (internal)
3015 * Insert header into array
3018 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3020 INT count;
3021 LPHTTPHEADERW lph = NULL;
3022 BOOL r = FALSE;
3024 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3025 count = lpwhr->nCustHeaders + 1;
3026 if (count > 1)
3027 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3028 else
3029 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3031 if (NULL != lph)
3033 lpwhr->pCustHeaders = lph;
3034 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3035 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3036 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3037 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3038 lpwhr->nCustHeaders++;
3039 r = TRUE;
3041 else
3043 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3046 return r;
3050 /***********************************************************************
3051 * HTTP_DeleteCustomHeader (internal)
3053 * Delete header from array
3054 * If this function is called, the indexs may change.
3056 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3058 if( lpwhr->nCustHeaders <= 0 )
3059 return FALSE;
3060 if( index >= lpwhr->nCustHeaders )
3061 return FALSE;
3062 lpwhr->nCustHeaders--;
3064 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3065 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3066 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3068 return TRUE;
3071 /***********************************************************************
3072 * IsHostInProxyBypassList (@)
3074 * Undocumented
3077 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3079 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3080 return FALSE;