push 20d539bd3127e997ce79233e3988ba5740356ce5
[wine/hacks.git] / dlls / wininet / http.c
blob9b746f50212338af700f23141eb4da45ea991349
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
9 * Copyright 2006 Robert Shearman for CodeWeavers
11 * Ulrich Czekalla
12 * David Hammerton
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #include "config.h"
30 #include "wine/port.h"
32 #if defined(__MINGW32__) || defined (_MSC_VER)
33 #include <ws2tcpip.h>
34 #endif
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
42 #endif
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49 #include <time.h>
50 #include <assert.h>
52 #include "windef.h"
53 #include "winbase.h"
54 #include "wininet.h"
55 #include "winerror.h"
56 #define NO_SHLWAPI_STREAM
57 #define NO_SHLWAPI_REG
58 #define NO_SHLWAPI_STRFCNS
59 #define NO_SHLWAPI_GDI
60 #include "shlwapi.h"
61 #include "sspi.h"
62 #include "wincrypt.h"
64 #include "internet.h"
65 #include "wine/debug.h"
66 #include "wine/exception.h"
67 #include "wine/unicode.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
71 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
72 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
73 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
74 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
75 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
76 static const WCHAR szHost[] = { 'H','o','s','t',0 };
77 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
78 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
79 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
80 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
81 static const WCHAR szGET[] = { 'G','E','T', 0 };
82 static const WCHAR szCrLf[] = {'\r','\n', 0};
84 #define MAXHOSTNAME 100
85 #define MAX_FIELD_VALUE_LEN 256
86 #define MAX_FIELD_LEN 256
88 #define HTTP_REFERER g_szReferer
89 #define HTTP_ACCEPT g_szAccept
90 #define HTTP_USERAGENT g_szUserAgent
92 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
93 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
94 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
95 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
96 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
97 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
98 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
100 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
102 struct HttpAuthInfo
104 LPWSTR scheme;
105 CredHandle cred;
106 CtxtHandle ctx;
107 TimeStamp exp;
108 ULONG attr;
109 ULONG max_token;
110 void *auth_data;
111 unsigned int auth_data_len;
112 BOOL finished; /* finished authenticating */
115 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
116 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
117 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
118 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
119 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
120 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
121 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
122 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
123 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
124 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
125 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
126 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
127 static void HTTP_DrainContent(WININETHTTPREQW *req);
128 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr);
130 static LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
132 int HeaderIndex = 0;
133 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
134 if (HeaderIndex == -1)
135 return NULL;
136 else
137 return &req->pCustHeaders[HeaderIndex];
140 /***********************************************************************
141 * HTTP_Tokenize (internal)
143 * Tokenize a string, allocating memory for the tokens.
145 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
147 LPWSTR * token_array;
148 int tokens = 0;
149 int i;
150 LPCWSTR next_token;
152 if (string)
154 /* empty string has no tokens */
155 if (*string)
156 tokens++;
157 /* count tokens */
158 for (i = 0; string[i]; i++)
160 if (!strncmpW(string+i, token_string, strlenW(token_string)))
162 DWORD j;
163 tokens++;
164 /* we want to skip over separators, but not the null terminator */
165 for (j = 0; j < strlenW(token_string) - 1; j++)
166 if (!string[i+j])
167 break;
168 i += j;
173 /* add 1 for terminating NULL */
174 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
175 token_array[tokens] = NULL;
176 if (!tokens)
177 return token_array;
178 for (i = 0; i < tokens; i++)
180 int len;
181 next_token = strstrW(string, token_string);
182 if (!next_token) next_token = string+strlenW(string);
183 len = next_token - string;
184 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
185 memcpy(token_array[i], string, len*sizeof(WCHAR));
186 token_array[i][len] = '\0';
187 string = next_token+strlenW(token_string);
189 return token_array;
192 /***********************************************************************
193 * HTTP_FreeTokens (internal)
195 * Frees memory returned from HTTP_Tokenize.
197 static void HTTP_FreeTokens(LPWSTR * token_array)
199 int i;
200 for (i = 0; token_array[i]; i++)
201 HeapFree(GetProcessHeap(), 0, token_array[i]);
202 HeapFree(GetProcessHeap(), 0, token_array);
205 /* **********************************************************************
207 * Helper functions for the HttpSendRequest(Ex) functions
210 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
212 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
213 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
215 TRACE("%p\n", lpwhr);
217 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
218 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
219 req->dwContentLength, req->bEndRequest);
221 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
224 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
226 static const WCHAR szSlash[] = { '/',0 };
227 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
229 /* If we don't have a path we set it to root */
230 if (NULL == lpwhr->lpszPath)
231 lpwhr->lpszPath = WININET_strdupW(szSlash);
232 else /* remove \r and \n*/
234 int nLen = strlenW(lpwhr->lpszPath);
235 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
237 nLen--;
238 lpwhr->lpszPath[nLen]='\0';
240 /* Replace '\' with '/' */
241 while (nLen>0) {
242 nLen--;
243 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
247 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
248 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
249 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
251 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
252 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
253 *fixurl = '/';
254 strcpyW(fixurl + 1, lpwhr->lpszPath);
255 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
256 lpwhr->lpszPath = fixurl;
260 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
262 LPWSTR requestString;
263 DWORD len, n;
264 LPCWSTR *req;
265 UINT i;
266 LPWSTR p;
268 static const WCHAR szSpace[] = { ' ',0 };
269 static const WCHAR szColon[] = { ':',' ',0 };
270 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
272 /* allocate space for an array of all the string pointers to be added */
273 len = (lpwhr->nCustHeaders)*4 + 10;
274 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
276 /* add the verb, path and HTTP version string */
277 n = 0;
278 req[n++] = verb;
279 req[n++] = szSpace;
280 req[n++] = path;
281 req[n++] = szSpace;
282 req[n++] = version;
284 /* Append custom request headers */
285 for (i = 0; i < lpwhr->nCustHeaders; i++)
287 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
289 req[n++] = szCrLf;
290 req[n++] = lpwhr->pCustHeaders[i].lpszField;
291 req[n++] = szColon;
292 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
294 TRACE("Adding custom header %s (%s)\n",
295 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
296 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
300 if( n >= len )
301 ERR("oops. buffer overrun\n");
303 req[n] = NULL;
304 requestString = HTTP_build_req( req, 4 );
305 HeapFree( GetProcessHeap(), 0, req );
308 * Set (header) termination string for request
309 * Make sure there's exactly two new lines at the end of the request
311 p = &requestString[strlenW(requestString)-1];
312 while ( (*p == '\n') || (*p == '\r') )
313 p--;
314 strcpyW( p+1, sztwocrlf );
316 return requestString;
319 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
321 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
322 int HeaderIndex;
323 int numCookies = 0;
324 LPHTTPHEADERW setCookieHeader;
326 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
328 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
330 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
332 int len;
333 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
334 LPWSTR buf_url;
335 LPHTTPHEADERW Host;
337 Host = HTTP_GetHeader(lpwhr,szHost);
338 len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
339 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
340 sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
341 InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
343 HeapFree(GetProcessHeap(), 0, buf_url);
345 numCookies++;
349 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
351 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
352 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
353 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
356 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
357 struct HttpAuthInfo **ppAuthInfo,
358 LPWSTR domain_and_username, LPWSTR password )
360 SECURITY_STATUS sec_status;
361 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
362 BOOL first = FALSE;
364 TRACE("%s\n", debugstr_w(pszAuthValue));
366 if (!pAuthInfo)
368 TimeStamp exp;
370 first = TRUE;
371 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
372 if (!pAuthInfo)
373 return FALSE;
375 SecInvalidateHandle(&pAuthInfo->cred);
376 SecInvalidateHandle(&pAuthInfo->ctx);
377 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
378 pAuthInfo->attr = 0;
379 pAuthInfo->auth_data = NULL;
380 pAuthInfo->auth_data_len = 0;
381 pAuthInfo->finished = FALSE;
383 if (is_basic_auth_value(pszAuthValue))
385 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
386 pAuthInfo->scheme = WININET_strdupW(szBasic);
387 if (!pAuthInfo->scheme)
389 HeapFree(GetProcessHeap(), 0, pAuthInfo);
390 return FALSE;
393 else
395 PVOID pAuthData;
396 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
398 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
399 if (!pAuthInfo->scheme)
401 HeapFree(GetProcessHeap(), 0, pAuthInfo);
402 return FALSE;
405 if (domain_and_username)
407 WCHAR *user = strchrW(domain_and_username, '\\');
408 WCHAR *domain = domain_and_username;
410 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
412 pAuthData = &nt_auth_identity;
414 if (user) user++;
415 else
417 user = domain_and_username;
418 domain = NULL;
421 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
422 nt_auth_identity.User = user;
423 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
424 nt_auth_identity.Domain = domain;
425 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
426 nt_auth_identity.Password = password;
427 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
429 else
430 /* use default credentials */
431 pAuthData = NULL;
433 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
434 SECPKG_CRED_OUTBOUND, NULL,
435 pAuthData, NULL,
436 NULL, &pAuthInfo->cred,
437 &exp);
438 if (sec_status == SEC_E_OK)
440 PSecPkgInfoW sec_pkg_info;
441 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
442 if (sec_status == SEC_E_OK)
444 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
445 FreeContextBuffer(sec_pkg_info);
448 if (sec_status != SEC_E_OK)
450 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
451 debugstr_w(pAuthInfo->scheme), sec_status);
452 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
453 HeapFree(GetProcessHeap(), 0, pAuthInfo);
454 return FALSE;
457 *ppAuthInfo = pAuthInfo;
459 else if (pAuthInfo->finished)
460 return FALSE;
462 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
463 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
465 ERR("authentication scheme changed from %s to %s\n",
466 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
467 return FALSE;
470 if (is_basic_auth_value(pszAuthValue))
472 int userlen;
473 int passlen;
474 char *auth_data;
476 TRACE("basic authentication\n");
478 /* we don't cache credentials for basic authentication, so we can't
479 * retrieve them if the application didn't pass us any credentials */
480 if (!domain_and_username) return FALSE;
482 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
483 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
485 /* length includes a nul terminator, which will be re-used for the ':' */
486 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
487 if (!auth_data)
488 return FALSE;
490 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
491 auth_data[userlen] = ':';
492 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
494 pAuthInfo->auth_data = auth_data;
495 pAuthInfo->auth_data_len = userlen + 1 + passlen;
496 pAuthInfo->finished = TRUE;
498 return TRUE;
500 else
502 LPCWSTR pszAuthData;
503 SecBufferDesc out_desc, in_desc;
504 SecBuffer out, in;
505 unsigned char *buffer;
506 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
507 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
509 in.BufferType = SECBUFFER_TOKEN;
510 in.cbBuffer = 0;
511 in.pvBuffer = NULL;
513 in_desc.ulVersion = 0;
514 in_desc.cBuffers = 1;
515 in_desc.pBuffers = &in;
517 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
518 if (*pszAuthData == ' ')
520 pszAuthData++;
521 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
522 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
523 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
526 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
528 out.BufferType = SECBUFFER_TOKEN;
529 out.cbBuffer = pAuthInfo->max_token;
530 out.pvBuffer = buffer;
532 out_desc.ulVersion = 0;
533 out_desc.cBuffers = 1;
534 out_desc.pBuffers = &out;
536 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
537 first ? NULL : &pAuthInfo->ctx,
538 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
539 context_req, 0, SECURITY_NETWORK_DREP,
540 in.pvBuffer ? &in_desc : NULL,
541 0, &pAuthInfo->ctx, &out_desc,
542 &pAuthInfo->attr, &pAuthInfo->exp);
543 if (sec_status == SEC_E_OK)
545 pAuthInfo->finished = TRUE;
546 pAuthInfo->auth_data = out.pvBuffer;
547 pAuthInfo->auth_data_len = out.cbBuffer;
548 TRACE("sending last auth packet\n");
550 else if (sec_status == SEC_I_CONTINUE_NEEDED)
552 pAuthInfo->auth_data = out.pvBuffer;
553 pAuthInfo->auth_data_len = out.cbBuffer;
554 TRACE("sending next auth packet\n");
556 else
558 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
559 pAuthInfo->finished = TRUE;
560 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
561 return FALSE;
565 return TRUE;
568 /***********************************************************************
569 * HTTP_HttpAddRequestHeadersW (internal)
571 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
572 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
574 LPWSTR lpszStart;
575 LPWSTR lpszEnd;
576 LPWSTR buffer;
577 BOOL bSuccess = FALSE;
578 DWORD len;
580 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
582 if( dwHeaderLength == ~0U )
583 len = strlenW(lpszHeader);
584 else
585 len = dwHeaderLength;
586 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
587 lstrcpynW( buffer, lpszHeader, len + 1);
589 lpszStart = buffer;
593 LPWSTR * pFieldAndValue;
595 lpszEnd = lpszStart;
597 while (*lpszEnd != '\0')
599 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
600 break;
601 lpszEnd++;
604 if (*lpszStart == '\0')
605 break;
607 if (*lpszEnd == '\r')
609 *lpszEnd = '\0';
610 lpszEnd += 2; /* Jump over \r\n */
612 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
613 if (*lpszStart == '\0')
615 /* Skip 0-length headers */
616 lpszStart = lpszEnd;
617 bSuccess = TRUE;
618 continue;
620 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
621 if (pFieldAndValue)
623 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
624 if (bSuccess)
625 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
626 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
627 HTTP_FreeTokens(pFieldAndValue);
630 lpszStart = lpszEnd;
631 } while (bSuccess);
633 HeapFree(GetProcessHeap(), 0, buffer);
635 return bSuccess;
638 /***********************************************************************
639 * HttpAddRequestHeadersW (WININET.@)
641 * Adds one or more HTTP header to the request handler
643 * NOTE
644 * On Windows if dwHeaderLength includes the trailing '\0', then
645 * HttpAddRequestHeadersW() adds it too. However this results in an
646 * invalid Http header which is rejected by some servers so we probably
647 * don't need to match Windows on that point.
649 * RETURNS
650 * TRUE on success
651 * FALSE on failure
654 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
655 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
657 BOOL bSuccess = FALSE;
658 LPWININETHTTPREQW lpwhr;
660 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
662 if (!lpszHeader)
663 return TRUE;
665 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
666 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
668 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
669 goto lend;
671 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
672 lend:
673 if( lpwhr )
674 WININET_Release( &lpwhr->hdr );
676 return bSuccess;
679 /***********************************************************************
680 * HttpAddRequestHeadersA (WININET.@)
682 * Adds one or more HTTP header to the request handler
684 * RETURNS
685 * TRUE on success
686 * FALSE on failure
689 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
690 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
692 DWORD len;
693 LPWSTR hdr;
694 BOOL r;
696 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
698 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
699 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
700 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
701 if( dwHeaderLength != ~0U )
702 dwHeaderLength = len;
704 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
706 HeapFree( GetProcessHeap(), 0, hdr );
708 return r;
711 /***********************************************************************
712 * HttpEndRequestA (WININET.@)
714 * Ends an HTTP request that was started by HttpSendRequestEx
716 * RETURNS
717 * TRUE if successful
718 * FALSE on failure
721 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
722 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
724 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
726 if (lpBuffersOut)
728 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
729 return FALSE;
732 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
735 static BOOL HTTP_HttpEndRequestW(LPWININETHTTPREQW lpwhr, DWORD dwFlags, DWORD_PTR dwContext)
737 BOOL rc = FALSE;
738 INT responseLen;
739 DWORD dwBufferSize;
740 INTERNET_ASYNC_RESULT iar;
742 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
743 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
745 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
746 if (responseLen)
747 rc = TRUE;
749 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
750 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
752 /* process cookies here. Is this right? */
753 HTTP_ProcessCookies(lpwhr);
755 dwBufferSize = sizeof(lpwhr->dwContentLength);
756 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
757 &lpwhr->dwContentLength, &dwBufferSize, NULL))
758 lpwhr->dwContentLength = -1;
760 if (lpwhr->dwContentLength == 0)
761 HTTP_FinishedReading(lpwhr);
763 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
765 DWORD dwCode,dwCodeLength = sizeof(DWORD);
766 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE, &dwCode, &dwCodeLength, NULL) &&
767 (dwCode == 302 || dwCode == 301 || dwCode == 303))
769 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
770 dwBufferSize=sizeof(szNewLocation);
771 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL))
773 /* redirects are always GETs */
774 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
775 lpwhr->lpszVerb = WININET_strdupW(szGET);
776 HTTP_DrainContent(lpwhr);
777 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
778 INTERNET_STATUS_REDIRECT, szNewLocation, dwBufferSize);
779 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
780 if (rc)
781 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
786 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
787 iar.dwError = rc ? 0 : INTERNET_GetLastError();
789 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
790 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
791 sizeof(INTERNET_ASYNC_RESULT));
792 return rc;
795 static void AsyncHttpEndRequestProc(WORKREQUEST *work)
797 struct WORKREQ_HTTPENDREQUESTW const *req = &work->u.HttpEndRequestW;
798 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)work->hdr;
800 TRACE("%p\n", lpwhr);
802 HTTP_HttpEndRequestW(lpwhr, req->dwFlags, req->dwContext);
805 /***********************************************************************
806 * HttpEndRequestW (WININET.@)
808 * Ends an HTTP request that was started by HttpSendRequestEx
810 * RETURNS
811 * TRUE if successful
812 * FALSE on failure
815 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
816 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
818 BOOL rc = FALSE;
819 LPWININETHTTPREQW lpwhr;
821 TRACE("-->\n");
823 if (lpBuffersOut)
825 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
826 return FALSE;
829 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
831 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
833 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
834 if (lpwhr)
835 WININET_Release( &lpwhr->hdr );
836 return FALSE;
838 lpwhr->hdr.dwFlags |= dwFlags;
840 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
842 WORKREQUEST work;
843 struct WORKREQ_HTTPENDREQUESTW *request;
845 work.asyncproc = AsyncHttpEndRequestProc;
846 work.hdr = WININET_AddRef( &lpwhr->hdr );
848 request = &work.u.HttpEndRequestW;
849 request->dwFlags = dwFlags;
850 request->dwContext = dwContext;
852 INTERNET_AsyncCall(&work);
853 INTERNET_SetLastError(ERROR_IO_PENDING);
855 else
856 rc = HTTP_HttpEndRequestW(lpwhr, dwFlags, dwContext);
858 WININET_Release( &lpwhr->hdr );
859 TRACE("%i <--\n",rc);
860 return rc;
863 /***********************************************************************
864 * HttpOpenRequestW (WININET.@)
866 * Open a HTTP request handle
868 * RETURNS
869 * HINTERNET a HTTP request handle on success
870 * NULL on failure
873 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
874 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
875 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
876 DWORD dwFlags, DWORD_PTR dwContext)
878 LPWININETHTTPSESSIONW lpwhs;
879 HINTERNET handle = NULL;
881 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
882 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
883 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
884 dwFlags, dwContext);
885 if(lpszAcceptTypes!=NULL)
887 int i;
888 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
889 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
892 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
893 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
895 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
896 goto lend;
900 * My tests seem to show that the windows version does not
901 * become asynchronous until after this point. And anyhow
902 * if this call was asynchronous then how would you get the
903 * necessary HINTERNET pointer returned by this function.
906 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
907 lpszVersion, lpszReferrer, lpszAcceptTypes,
908 dwFlags, dwContext);
909 lend:
910 if( lpwhs )
911 WININET_Release( &lpwhs->hdr );
912 TRACE("returning %p\n", handle);
913 return handle;
917 /***********************************************************************
918 * HttpOpenRequestA (WININET.@)
920 * Open a HTTP request handle
922 * RETURNS
923 * HINTERNET a HTTP request handle on success
924 * NULL on failure
927 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
928 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
929 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
930 DWORD dwFlags, DWORD_PTR dwContext)
932 LPWSTR szVerb = NULL, szObjectName = NULL;
933 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
934 INT len, acceptTypesCount;
935 HINTERNET rc = FALSE;
936 LPCSTR *types;
938 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
939 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
940 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
941 dwFlags, dwContext);
943 if (lpszVerb)
945 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
946 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
947 if ( !szVerb )
948 goto end;
949 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
952 if (lpszObjectName)
954 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
955 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
956 if ( !szObjectName )
957 goto end;
958 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
961 if (lpszVersion)
963 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
964 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
965 if ( !szVersion )
966 goto end;
967 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
970 if (lpszReferrer)
972 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
973 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
974 if ( !szReferrer )
975 goto end;
976 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
979 if (lpszAcceptTypes)
981 acceptTypesCount = 0;
982 types = lpszAcceptTypes;
983 while (*types)
985 __TRY
987 /* find out how many there are */
988 if (*types && **types)
990 TRACE("accept type: %s\n", debugstr_a(*types));
991 acceptTypesCount++;
994 __EXCEPT_PAGE_FAULT
996 WARN("invalid accept type pointer\n");
998 __ENDTRY;
999 types++;
1001 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1002 if (!szAcceptTypes) goto end;
1004 acceptTypesCount = 0;
1005 types = lpszAcceptTypes;
1006 while (*types)
1008 __TRY
1010 if (*types && **types)
1012 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1013 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1015 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1016 acceptTypesCount++;
1019 __EXCEPT_PAGE_FAULT
1021 /* ignore invalid pointer */
1023 __ENDTRY;
1024 types++;
1026 szAcceptTypes[acceptTypesCount] = NULL;
1029 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1030 szVersion, szReferrer,
1031 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1033 end:
1034 if (szAcceptTypes)
1036 acceptTypesCount = 0;
1037 while (szAcceptTypes[acceptTypesCount])
1039 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1040 acceptTypesCount++;
1042 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1044 HeapFree(GetProcessHeap(), 0, szReferrer);
1045 HeapFree(GetProcessHeap(), 0, szVersion);
1046 HeapFree(GetProcessHeap(), 0, szObjectName);
1047 HeapFree(GetProcessHeap(), 0, szVerb);
1049 return rc;
1052 /***********************************************************************
1053 * HTTP_EncodeBase64
1055 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1057 UINT n = 0, x;
1058 static const CHAR HTTP_Base64Enc[] =
1059 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1061 while( len > 0 )
1063 /* first 6 bits, all from bin[0] */
1064 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1065 x = (bin[0] & 3) << 4;
1067 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1068 if( len == 1 )
1070 base64[n++] = HTTP_Base64Enc[x];
1071 base64[n++] = '=';
1072 base64[n++] = '=';
1073 break;
1075 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1076 x = ( bin[1] & 0x0f ) << 2;
1078 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1079 if( len == 2 )
1081 base64[n++] = HTTP_Base64Enc[x];
1082 base64[n++] = '=';
1083 break;
1085 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1087 /* last 6 bits, all from bin [2] */
1088 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1089 bin += 3;
1090 len -= 3;
1092 base64[n] = 0;
1093 return n;
1096 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1097 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1098 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1099 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1100 static const signed char HTTP_Base64Dec[256] =
1102 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1103 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1104 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1105 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1106 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1107 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1108 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1109 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1110 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1111 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1112 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1113 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1114 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1115 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1116 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1117 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1118 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1119 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1120 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1121 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1122 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1123 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1124 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1125 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1126 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1127 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1129 #undef CH
1131 /***********************************************************************
1132 * HTTP_DecodeBase64
1134 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1136 unsigned int n = 0;
1138 while(*base64)
1140 signed char in[4];
1142 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1143 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1144 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1145 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1147 WARN("invalid base64: %s\n", debugstr_w(base64));
1148 return 0;
1150 if (bin)
1151 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1152 n++;
1154 if ((base64[2] == '=') && (base64[3] == '='))
1155 break;
1156 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1157 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1159 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1160 return 0;
1162 if (bin)
1163 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1164 n++;
1166 if (base64[3] == '=')
1167 break;
1168 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1169 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1171 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1172 return 0;
1174 if (bin)
1175 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1176 n++;
1178 base64 += 4;
1181 return n;
1184 /***********************************************************************
1185 * HTTP_InsertAuthorization
1187 * Insert or delete the authorization field in the request header.
1189 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1191 if (pAuthInfo)
1193 static const WCHAR wszSpace[] = {' ',0};
1194 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1195 unsigned int len;
1196 WCHAR *authorization = NULL;
1198 if (pAuthInfo->auth_data_len)
1200 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1201 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1202 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1203 if (!authorization)
1204 return FALSE;
1206 strcpyW(authorization, pAuthInfo->scheme);
1207 strcatW(authorization, wszSpace);
1208 HTTP_EncodeBase64(pAuthInfo->auth_data,
1209 pAuthInfo->auth_data_len,
1210 authorization+strlenW(authorization));
1212 /* clear the data as it isn't valid now that it has been sent to the
1213 * server, unless it's Basic authentication which doesn't do
1214 * connection tracking */
1215 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1217 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1218 pAuthInfo->auth_data = NULL;
1219 pAuthInfo->auth_data_len = 0;
1223 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1225 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1227 HeapFree(GetProcessHeap(), 0, authorization);
1229 return TRUE;
1232 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1234 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1235 DWORD size;
1237 size = sizeof(new_location);
1238 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1240 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1241 strcpyW( url, new_location );
1243 else
1245 static const WCHAR slash[] = { '/',0 };
1246 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1247 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1248 WININETHTTPSESSIONW *session = req->lpHttpSession;
1250 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1251 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1253 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1255 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1256 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1257 else
1258 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1259 if (req->lpszPath[0] != '/') strcatW( url, slash );
1260 strcatW( url, req->lpszPath );
1262 TRACE("url=%s\n", debugstr_w(url));
1263 return url;
1266 /***********************************************************************
1267 * HTTP_DealWithProxy
1269 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1270 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1272 WCHAR buf[MAXHOSTNAME];
1273 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1274 static WCHAR szNul[] = { 0 };
1275 URL_COMPONENTSW UrlComponents;
1276 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1277 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1279 memset( &UrlComponents, 0, sizeof UrlComponents );
1280 UrlComponents.dwStructSize = sizeof UrlComponents;
1281 UrlComponents.lpszHostName = buf;
1282 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1284 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1285 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1286 sprintfW(proxy, szFormat, hIC->lpszProxy);
1287 else
1288 strcpyW(proxy, hIC->lpszProxy);
1289 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1290 return FALSE;
1291 if( UrlComponents.dwHostNameLength == 0 )
1292 return FALSE;
1294 if( !lpwhr->lpszPath )
1295 lpwhr->lpszPath = szNul;
1297 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1298 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1300 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1301 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1302 lpwhs->nServerPort = UrlComponents.nPort;
1304 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1305 return TRUE;
1308 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1310 char szaddr[32];
1311 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1313 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1314 INTERNET_STATUS_RESOLVING_NAME,
1315 lpwhs->lpszServerName,
1316 strlenW(lpwhs->lpszServerName)+1);
1318 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1319 &lpwhs->socketAddress))
1321 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1322 return FALSE;
1325 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1326 szaddr, sizeof(szaddr));
1327 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1328 INTERNET_STATUS_NAME_RESOLVED,
1329 szaddr, strlen(szaddr)+1);
1331 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1332 return TRUE;
1336 /***********************************************************************
1337 * HTTPREQ_Destroy (internal)
1339 * Deallocate request handle
1342 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1344 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1345 DWORD i;
1347 TRACE("\n");
1349 if(lpwhr->hCacheFile)
1350 CloseHandle(lpwhr->hCacheFile);
1352 if(lpwhr->lpszCacheFile) {
1353 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1354 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1357 WININET_Release(&lpwhr->lpHttpSession->hdr);
1359 if (lpwhr->pAuthInfo)
1361 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1362 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1363 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1364 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1366 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1367 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1368 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1369 lpwhr->pAuthInfo = NULL;
1372 if (lpwhr->pProxyAuthInfo)
1374 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1375 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1376 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1377 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1379 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1380 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1381 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1382 lpwhr->pProxyAuthInfo = NULL;
1385 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1386 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1387 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1388 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1389 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1391 for (i = 0; i < lpwhr->nCustHeaders; i++)
1393 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1394 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1397 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1398 HeapFree(GetProcessHeap(), 0, lpwhr);
1401 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1403 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1405 TRACE("%p\n",lpwhr);
1407 if (!NETCON_connected(&lpwhr->netConnection))
1408 return;
1410 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1411 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1413 NETCON_close(&lpwhr->netConnection);
1415 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1416 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1419 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1421 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1423 switch(option) {
1424 case INTERNET_OPTION_HANDLE_TYPE:
1425 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1427 if (*size < sizeof(ULONG))
1428 return ERROR_INSUFFICIENT_BUFFER;
1430 *size = sizeof(DWORD);
1431 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1432 return ERROR_SUCCESS;
1434 case INTERNET_OPTION_URL: {
1435 WCHAR url[INTERNET_MAX_URL_LENGTH];
1436 HTTPHEADERW *host;
1437 DWORD len;
1438 WCHAR *pch;
1440 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1441 static const WCHAR hostW[] = {'H','o','s','t',0};
1443 TRACE("INTERNET_OPTION_URL\n");
1445 host = HTTP_GetHeader(req, hostW);
1446 strcpyW(url, httpW);
1447 strcatW(url, host->lpszValue);
1448 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1449 *pch = 0;
1450 strcatW(url, req->lpszPath);
1452 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1454 if(unicode) {
1455 len = (strlenW(url)+1) * sizeof(WCHAR);
1456 if(*size < len)
1457 return ERROR_INSUFFICIENT_BUFFER;
1459 *size = len;
1460 strcpyW(buffer, url);
1461 return ERROR_SUCCESS;
1462 }else {
1463 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1464 if(len > *size)
1465 return ERROR_INSUFFICIENT_BUFFER;
1467 *size = len;
1468 return ERROR_SUCCESS;
1472 case INTERNET_OPTION_DATAFILE_NAME: {
1473 DWORD req_size;
1475 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1477 if(!req->lpszCacheFile) {
1478 *size = 0;
1479 return ERROR_INTERNET_ITEM_NOT_FOUND;
1482 if(unicode) {
1483 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1484 if(*size < req_size)
1485 return ERROR_INSUFFICIENT_BUFFER;
1487 *size = req_size;
1488 memcpy(buffer, req->lpszCacheFile, *size);
1489 return ERROR_SUCCESS;
1490 }else {
1491 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1492 if (req_size > *size)
1493 return ERROR_INSUFFICIENT_BUFFER;
1495 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1496 -1, buffer, *size, NULL, NULL);
1497 return ERROR_SUCCESS;
1501 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1502 PCCERT_CONTEXT context;
1504 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1505 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1506 return ERROR_INSUFFICIENT_BUFFER;
1509 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1510 if(context) {
1511 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1512 DWORD len;
1514 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1515 info->ftExpiry = context->pCertInfo->NotAfter;
1516 info->ftStart = context->pCertInfo->NotBefore;
1517 if(unicode) {
1518 len = CertNameToStrW(context->dwCertEncodingType,
1519 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1520 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1521 if(info->lpszSubjectInfo)
1522 CertNameToStrW(context->dwCertEncodingType,
1523 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1524 info->lpszSubjectInfo, len);
1525 len = CertNameToStrW(context->dwCertEncodingType,
1526 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1527 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1528 if (info->lpszIssuerInfo)
1529 CertNameToStrW(context->dwCertEncodingType,
1530 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1531 info->lpszIssuerInfo, len);
1532 }else {
1533 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1535 len = CertNameToStrA(context->dwCertEncodingType,
1536 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1537 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1538 if(infoA->lpszSubjectInfo)
1539 CertNameToStrA(context->dwCertEncodingType,
1540 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1541 infoA->lpszSubjectInfo, len);
1542 len = CertNameToStrA(context->dwCertEncodingType,
1543 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1544 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1545 if(infoA->lpszIssuerInfo)
1546 CertNameToStrA(context->dwCertEncodingType,
1547 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1548 infoA->lpszIssuerInfo, len);
1552 * Contrary to MSDN, these do not appear to be set.
1553 * lpszProtocolName
1554 * lpszSignatureAlgName
1555 * lpszEncryptionAlgName
1556 * dwKeySize
1558 CertFreeCertificateContext(context);
1559 return ERROR_SUCCESS;
1564 return INET_QueryOption(option, buffer, size, unicode);
1567 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1569 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1571 switch(option) {
1572 case INTERNET_OPTION_SEND_TIMEOUT:
1573 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1574 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1576 if (size != sizeof(DWORD))
1577 return ERROR_INVALID_PARAMETER;
1579 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1580 *(DWORD*)buffer);
1582 case INTERNET_OPTION_USERNAME:
1583 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1584 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1585 return ERROR_SUCCESS;
1587 case INTERNET_OPTION_PASSWORD:
1588 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1589 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1590 return ERROR_SUCCESS;
1593 return ERROR_INTERNET_INVALID_OPTION;
1596 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1598 INTERNET_ASYNC_RESULT iar;
1599 BYTE buffer[4096];
1600 int available;
1601 BOOL res;
1603 TRACE("%p\n", req);
1605 res = NETCON_recv(&req->netConnection, buffer,
1606 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1607 MSG_PEEK, &available);
1609 if(res) {
1610 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1611 iar.dwError = first_notif ? 0 : available;
1612 }else {
1613 iar.dwResult = 0;
1614 iar.dwError = INTERNET_GetLastError();
1617 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1618 sizeof(INTERNET_ASYNC_RESULT));
1621 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1623 int bytes_read;
1625 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1626 sync ? MSG_WAITALL : 0, &bytes_read)) {
1627 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1628 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1630 /* always return success, even if the network layer returns an error */
1631 *read = 0;
1632 HTTP_FinishedReading(req);
1633 return ERROR_SUCCESS;
1636 req->dwContentRead += bytes_read;
1637 *read = bytes_read;
1639 if(req->lpszCacheFile) {
1640 BOOL res;
1641 DWORD dwBytesWritten;
1643 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1644 if(!res)
1645 WARN("WriteFile failed: %u\n", GetLastError());
1648 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1649 HTTP_FinishedReading(req);
1651 return ERROR_SUCCESS;
1654 static DWORD get_chunk_size(const char *buffer)
1656 const char *p;
1657 DWORD size = 0;
1659 for (p = buffer; *p; p++)
1661 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1662 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1663 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1664 else if (*p == ';') break;
1666 return size;
1669 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1671 char reply[MAX_REPLY_LEN], *p = buffer;
1672 DWORD buflen, to_read, to_write = size;
1673 int bytes_read;
1675 *read = 0;
1676 for (;;)
1678 if (*read == size) break;
1680 if (req->dwContentLength == ~0u) /* new chunk */
1682 buflen = sizeof(reply);
1683 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1685 if (!(req->dwContentLength = get_chunk_size(reply)))
1687 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1688 HTTP_GetResponseHeaders(req, FALSE);
1689 break;
1692 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1694 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1696 if (bytes_read != to_read)
1697 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1699 /* always return success, even if the network layer returns an error */
1700 *read = 0;
1701 break;
1703 if (!bytes_read) break;
1705 req->dwContentRead += bytes_read;
1706 to_write -= bytes_read;
1707 *read += bytes_read;
1709 if (req->lpszCacheFile)
1711 DWORD dwBytesWritten;
1713 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1714 WARN("WriteFile failed: %u\n", GetLastError());
1716 p += bytes_read;
1718 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1720 req->dwContentRead = 0;
1721 req->dwContentLength = ~0u;
1723 buflen = sizeof(reply);
1724 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1726 ERR("Malformed chunk\n");
1727 *read = 0;
1728 break;
1732 if (!*read) HTTP_FinishedReading(req);
1733 return ERROR_SUCCESS;
1736 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1738 WCHAR encoding[20];
1739 DWORD buflen = sizeof(encoding);
1740 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1742 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1743 !strcmpiW(encoding, szChunked))
1745 return HTTP_ReadChunked(req, buffer, size, read, sync);
1747 else
1748 return HTTP_Read(req, buffer, size, read, sync);
1751 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1753 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1754 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1757 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
1759 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1760 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1761 INTERNET_ASYNC_RESULT iar;
1762 DWORD res;
1764 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1766 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1767 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1769 iar.dwResult = res == ERROR_SUCCESS;
1770 iar.dwError = res;
1772 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1773 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1774 sizeof(INTERNET_ASYNC_RESULT));
1777 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1778 DWORD flags, DWORD_PTR context)
1781 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1782 DWORD res;
1784 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1785 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1787 if (buffers->dwStructSize != sizeof(*buffers))
1788 return ERROR_INVALID_PARAMETER;
1790 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1792 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1793 DWORD available = 0;
1795 NETCON_query_data_available(&req->netConnection, &available);
1796 if (!available)
1798 WORKREQUEST workRequest;
1800 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
1801 workRequest.hdr = WININET_AddRef(&req->hdr);
1802 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1804 INTERNET_AsyncCall(&workRequest);
1806 return ERROR_IO_PENDING;
1810 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1811 !(flags & IRF_NO_WAIT));
1813 if (res == ERROR_SUCCESS) {
1814 DWORD size = buffers->dwBufferLength;
1815 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1816 &size, sizeof(size));
1819 return res;
1822 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
1824 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
1825 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1826 INTERNET_ASYNC_RESULT iar;
1827 DWORD res;
1829 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
1831 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1832 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1834 iar.dwResult = res == ERROR_SUCCESS;
1835 iar.dwError = res;
1837 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1838 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1839 sizeof(INTERNET_ASYNC_RESULT));
1842 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
1843 DWORD flags, DWORD_PTR context)
1846 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1847 DWORD res;
1849 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1850 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1852 if (buffers->dwStructSize != sizeof(*buffers))
1853 return ERROR_INVALID_PARAMETER;
1855 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1857 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1858 DWORD available = 0;
1860 NETCON_query_data_available(&req->netConnection, &available);
1861 if (!available)
1863 WORKREQUEST workRequest;
1865 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
1866 workRequest.hdr = WININET_AddRef(&req->hdr);
1867 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
1869 INTERNET_AsyncCall(&workRequest);
1871 return ERROR_IO_PENDING;
1875 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1876 !(flags & IRF_NO_WAIT));
1878 if (res == ERROR_SUCCESS) {
1879 DWORD size = buffers->dwBufferLength;
1880 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1881 &size, sizeof(size));
1884 return res;
1887 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1889 BOOL ret;
1890 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1892 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1894 *written = 0;
1895 if ((ret = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written)))
1896 lpwhr->dwBytesWritten += *written;
1898 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
1899 return ret;
1902 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1904 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1906 HTTP_ReceiveRequestData(req, FALSE);
1909 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1911 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1912 BYTE buffer[4048];
1913 BOOL async;
1915 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1917 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1918 return ERROR_SUCCESS;
1920 /* Even if we are in async mode, we need to determine whether
1921 * there is actually more data available. We do this by trying
1922 * to peek only a single byte in async mode. */
1923 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1925 if (NETCON_recv(&req->netConnection, buffer,
1926 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1927 MSG_PEEK, (int *)available) && async && *available)
1929 WORKREQUEST workRequest;
1931 *available = 0;
1932 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1933 workRequest.hdr = WININET_AddRef( &req->hdr );
1935 INTERNET_AsyncCall(&workRequest);
1937 return ERROR_IO_PENDING;
1940 return ERROR_SUCCESS;
1943 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1944 HTTPREQ_Destroy,
1945 HTTPREQ_CloseConnection,
1946 HTTPREQ_QueryOption,
1947 HTTPREQ_SetOption,
1948 HTTPREQ_ReadFile,
1949 HTTPREQ_ReadFileExA,
1950 HTTPREQ_ReadFileExW,
1951 HTTPREQ_WriteFile,
1952 HTTPREQ_QueryDataAvailable,
1953 NULL
1956 /***********************************************************************
1957 * HTTP_HttpOpenRequestW (internal)
1959 * Open a HTTP request handle
1961 * RETURNS
1962 * HINTERNET a HTTP request handle on success
1963 * NULL on failure
1966 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1967 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1968 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1969 DWORD dwFlags, DWORD_PTR dwContext)
1971 LPWININETAPPINFOW hIC = NULL;
1972 LPWININETHTTPREQW lpwhr;
1973 LPWSTR lpszHostName = NULL;
1974 HINTERNET handle = NULL;
1975 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1976 DWORD len;
1978 TRACE("-->\n");
1980 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1981 hIC = lpwhs->lpAppInfo;
1983 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1984 if (NULL == lpwhr)
1986 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1987 goto lend;
1989 lpwhr->hdr.htype = WH_HHTTPREQ;
1990 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1991 lpwhr->hdr.dwFlags = dwFlags;
1992 lpwhr->hdr.dwContext = dwContext;
1993 lpwhr->hdr.refs = 1;
1994 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1995 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1997 WININET_AddRef( &lpwhs->hdr );
1998 lpwhr->lpHttpSession = lpwhs;
1999 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
2001 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
2002 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
2003 if (NULL == lpszHostName)
2005 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2006 goto lend;
2009 handle = WININET_AllocHandle( &lpwhr->hdr );
2010 if (NULL == handle)
2012 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2013 goto lend;
2016 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
2018 InternetCloseHandle( handle );
2019 handle = NULL;
2020 goto lend;
2023 if (lpszObjectName && *lpszObjectName) {
2024 HRESULT rc;
2026 len = 0;
2027 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2028 if (rc != E_POINTER)
2029 len = strlenW(lpszObjectName)+1;
2030 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2031 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2032 URL_ESCAPE_SPACES_ONLY);
2033 if (rc != S_OK)
2035 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2036 strcpyW(lpwhr->lpszPath,lpszObjectName);
2040 if (lpszReferrer && *lpszReferrer)
2041 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2043 if (lpszAcceptTypes)
2045 int i;
2046 for (i = 0; lpszAcceptTypes[i]; i++)
2048 if (!*lpszAcceptTypes[i]) continue;
2049 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2050 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2051 HTTP_ADDHDR_FLAG_REQ |
2052 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2056 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2058 if (lpszVersion)
2059 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2060 else
2061 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2063 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2064 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2065 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2067 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2068 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2069 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2071 else
2072 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2073 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2075 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2076 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2077 INTERNET_DEFAULT_HTTPS_PORT :
2078 INTERNET_DEFAULT_HTTP_PORT);
2080 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2081 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2082 INTERNET_DEFAULT_HTTPS_PORT :
2083 INTERNET_DEFAULT_HTTP_PORT);
2085 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2086 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2088 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2089 INTERNET_STATUS_HANDLE_CREATED, &handle,
2090 sizeof(handle));
2092 lend:
2093 HeapFree(GetProcessHeap(), 0, lpszHostName);
2094 if( lpwhr )
2095 WININET_Release( &lpwhr->hdr );
2097 TRACE("<-- %p (%p)\n", handle, lpwhr);
2098 return handle;
2101 /* read any content returned by the server so that the connection can be
2102 * reused */
2103 static void HTTP_DrainContent(WININETHTTPREQW *req)
2105 DWORD bytes_read;
2107 if (!NETCON_connected(&req->netConnection)) return;
2109 if (req->dwContentLength == -1)
2110 NETCON_close(&req->netConnection);
2114 char buffer[2048];
2115 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2116 return;
2117 } while (bytes_read);
2120 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2121 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2122 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2123 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2124 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2125 static const WCHAR szAge[] = { 'A','g','e',0 };
2126 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2127 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2128 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2129 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2130 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2131 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2132 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2133 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2134 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2135 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2136 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2137 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 };
2138 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2139 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2140 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2141 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2142 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2143 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2144 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2145 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2146 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2147 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2148 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2149 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2150 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2151 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2152 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2153 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2154 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2155 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2156 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2157 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2158 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2159 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2160 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2161 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2162 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2163 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2164 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 };
2165 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2166 static const WCHAR szURI[] = { 'U','R','I',0 };
2167 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2168 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2169 static const WCHAR szVia[] = { 'V','i','a',0 };
2170 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2171 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2173 static const LPCWSTR header_lookup[] = {
2174 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2175 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2176 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2177 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2178 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2179 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2180 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2181 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2182 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2183 szDate, /* HTTP_QUERY_DATE = 9 */
2184 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2185 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2186 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2187 szURI, /* HTTP_QUERY_URI = 13 */
2188 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2189 NULL, /* HTTP_QUERY_COST = 15 */
2190 NULL, /* HTTP_QUERY_LINK = 16 */
2191 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2192 NULL, /* HTTP_QUERY_VERSION = 18 */
2193 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2194 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2195 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2196 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2197 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2198 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2199 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2200 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2201 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2202 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2203 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2204 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2205 NULL, /* HTTP_QUERY_FROM = 31 */
2206 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2207 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2208 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2209 szReferer, /* HTTP_QUERY_REFERER = 35 */
2210 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2211 szServer, /* HTTP_QUERY_SERVER = 37 */
2212 NULL, /* HTTP_TITLE = 38 */
2213 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2214 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2215 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2216 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2217 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2218 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2219 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2220 NULL, /* HTTP_QUERY_REFRESH = 46 */
2221 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2222 szAge, /* HTTP_QUERY_AGE = 48 */
2223 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2224 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2225 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2226 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2227 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2228 szETag, /* HTTP_QUERY_ETAG = 54 */
2229 szHost, /* HTTP_QUERY_HOST = 55 */
2230 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2231 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2232 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2233 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2234 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2235 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2236 szRange, /* HTTP_QUERY_RANGE = 62 */
2237 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2238 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2239 szVary, /* HTTP_QUERY_VARY = 65 */
2240 szVia, /* HTTP_QUERY_VIA = 66 */
2241 szWarning, /* HTTP_QUERY_WARNING = 67 */
2242 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2243 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2244 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2247 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2249 /***********************************************************************
2250 * HTTP_HttpQueryInfoW (internal)
2252 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2253 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2255 LPHTTPHEADERW lphttpHdr = NULL;
2256 BOOL bSuccess = FALSE;
2257 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2258 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2259 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2260 INT index = -1;
2262 /* Find requested header structure */
2263 switch (level)
2265 case HTTP_QUERY_CUSTOM:
2266 if (!lpBuffer) return FALSE;
2267 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2268 break;
2270 case HTTP_QUERY_RAW_HEADERS_CRLF:
2272 LPWSTR headers;
2273 DWORD len = 0;
2274 BOOL ret = FALSE;
2276 if (request_only)
2277 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2278 else
2279 headers = lpwhr->lpszRawHeaders;
2281 if (headers)
2282 len = strlenW(headers) * sizeof(WCHAR);
2284 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2286 len += sizeof(WCHAR);
2287 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2288 ret = FALSE;
2290 else if (lpBuffer)
2292 if (headers)
2293 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2294 else
2296 len = strlenW(szCrLf) * sizeof(WCHAR);
2297 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2299 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2300 ret = TRUE;
2302 *lpdwBufferLength = len;
2304 if (request_only)
2305 HeapFree(GetProcessHeap(), 0, headers);
2306 return ret;
2308 case HTTP_QUERY_RAW_HEADERS:
2310 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2311 DWORD i, size = 0;
2312 LPWSTR pszString = lpBuffer;
2314 for (i = 0; ppszRawHeaderLines[i]; i++)
2315 size += strlenW(ppszRawHeaderLines[i]) + 1;
2317 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2319 HTTP_FreeTokens(ppszRawHeaderLines);
2320 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2321 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2322 return FALSE;
2324 if (pszString)
2326 for (i = 0; ppszRawHeaderLines[i]; i++)
2328 DWORD len = strlenW(ppszRawHeaderLines[i]);
2329 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2330 pszString += len+1;
2332 *pszString = '\0';
2333 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2335 *lpdwBufferLength = size * sizeof(WCHAR);
2336 HTTP_FreeTokens(ppszRawHeaderLines);
2338 return TRUE;
2340 case HTTP_QUERY_STATUS_TEXT:
2341 if (lpwhr->lpszStatusText)
2343 DWORD len = strlenW(lpwhr->lpszStatusText);
2344 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2346 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2347 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2348 return FALSE;
2350 if (lpBuffer)
2352 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2353 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2355 *lpdwBufferLength = len * sizeof(WCHAR);
2356 return TRUE;
2358 break;
2359 case HTTP_QUERY_VERSION:
2360 if (lpwhr->lpszVersion)
2362 DWORD len = strlenW(lpwhr->lpszVersion);
2363 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2365 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2366 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2367 return FALSE;
2369 if (lpBuffer)
2371 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2372 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2374 *lpdwBufferLength = len * sizeof(WCHAR);
2375 return TRUE;
2377 break;
2378 default:
2379 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2381 if (level < LAST_TABLE_HEADER && header_lookup[level])
2382 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2383 requested_index,request_only);
2386 if (index >= 0)
2387 lphttpHdr = &lpwhr->pCustHeaders[index];
2389 /* Ensure header satisfies requested attributes */
2390 if (!lphttpHdr ||
2391 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2392 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2394 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2395 return bSuccess;
2398 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2400 /* coalesce value to requested type */
2401 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2403 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2404 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2405 bSuccess = TRUE;
2407 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2409 time_t tmpTime;
2410 struct tm tmpTM;
2411 SYSTEMTIME *STHook;
2413 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2415 tmpTM = *gmtime(&tmpTime);
2416 STHook = (SYSTEMTIME *)lpBuffer;
2417 STHook->wDay = tmpTM.tm_mday;
2418 STHook->wHour = tmpTM.tm_hour;
2419 STHook->wMilliseconds = 0;
2420 STHook->wMinute = tmpTM.tm_min;
2421 STHook->wDayOfWeek = tmpTM.tm_wday;
2422 STHook->wMonth = tmpTM.tm_mon + 1;
2423 STHook->wSecond = tmpTM.tm_sec;
2424 STHook->wYear = tmpTM.tm_year;
2425 bSuccess = TRUE;
2427 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2428 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2429 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2431 else if (lphttpHdr->lpszValue)
2433 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2435 if (len > *lpdwBufferLength)
2437 *lpdwBufferLength = len;
2438 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2439 return bSuccess;
2441 if (lpBuffer)
2443 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2444 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2446 *lpdwBufferLength = len - sizeof(WCHAR);
2447 bSuccess = TRUE;
2449 return bSuccess;
2452 /***********************************************************************
2453 * HttpQueryInfoW (WININET.@)
2455 * Queries for information about an HTTP request
2457 * RETURNS
2458 * TRUE on success
2459 * FALSE on failure
2462 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2463 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2465 BOOL bSuccess = FALSE;
2466 LPWININETHTTPREQW lpwhr;
2468 if (TRACE_ON(wininet)) {
2469 #define FE(x) { x, #x }
2470 static const wininet_flag_info query_flags[] = {
2471 FE(HTTP_QUERY_MIME_VERSION),
2472 FE(HTTP_QUERY_CONTENT_TYPE),
2473 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2474 FE(HTTP_QUERY_CONTENT_ID),
2475 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2476 FE(HTTP_QUERY_CONTENT_LENGTH),
2477 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2478 FE(HTTP_QUERY_ALLOW),
2479 FE(HTTP_QUERY_PUBLIC),
2480 FE(HTTP_QUERY_DATE),
2481 FE(HTTP_QUERY_EXPIRES),
2482 FE(HTTP_QUERY_LAST_MODIFIED),
2483 FE(HTTP_QUERY_MESSAGE_ID),
2484 FE(HTTP_QUERY_URI),
2485 FE(HTTP_QUERY_DERIVED_FROM),
2486 FE(HTTP_QUERY_COST),
2487 FE(HTTP_QUERY_LINK),
2488 FE(HTTP_QUERY_PRAGMA),
2489 FE(HTTP_QUERY_VERSION),
2490 FE(HTTP_QUERY_STATUS_CODE),
2491 FE(HTTP_QUERY_STATUS_TEXT),
2492 FE(HTTP_QUERY_RAW_HEADERS),
2493 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2494 FE(HTTP_QUERY_CONNECTION),
2495 FE(HTTP_QUERY_ACCEPT),
2496 FE(HTTP_QUERY_ACCEPT_CHARSET),
2497 FE(HTTP_QUERY_ACCEPT_ENCODING),
2498 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2499 FE(HTTP_QUERY_AUTHORIZATION),
2500 FE(HTTP_QUERY_CONTENT_ENCODING),
2501 FE(HTTP_QUERY_FORWARDED),
2502 FE(HTTP_QUERY_FROM),
2503 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2504 FE(HTTP_QUERY_LOCATION),
2505 FE(HTTP_QUERY_ORIG_URI),
2506 FE(HTTP_QUERY_REFERER),
2507 FE(HTTP_QUERY_RETRY_AFTER),
2508 FE(HTTP_QUERY_SERVER),
2509 FE(HTTP_QUERY_TITLE),
2510 FE(HTTP_QUERY_USER_AGENT),
2511 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2512 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2513 FE(HTTP_QUERY_ACCEPT_RANGES),
2514 FE(HTTP_QUERY_SET_COOKIE),
2515 FE(HTTP_QUERY_COOKIE),
2516 FE(HTTP_QUERY_REQUEST_METHOD),
2517 FE(HTTP_QUERY_REFRESH),
2518 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2519 FE(HTTP_QUERY_AGE),
2520 FE(HTTP_QUERY_CACHE_CONTROL),
2521 FE(HTTP_QUERY_CONTENT_BASE),
2522 FE(HTTP_QUERY_CONTENT_LOCATION),
2523 FE(HTTP_QUERY_CONTENT_MD5),
2524 FE(HTTP_QUERY_CONTENT_RANGE),
2525 FE(HTTP_QUERY_ETAG),
2526 FE(HTTP_QUERY_HOST),
2527 FE(HTTP_QUERY_IF_MATCH),
2528 FE(HTTP_QUERY_IF_NONE_MATCH),
2529 FE(HTTP_QUERY_IF_RANGE),
2530 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2531 FE(HTTP_QUERY_MAX_FORWARDS),
2532 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2533 FE(HTTP_QUERY_RANGE),
2534 FE(HTTP_QUERY_TRANSFER_ENCODING),
2535 FE(HTTP_QUERY_UPGRADE),
2536 FE(HTTP_QUERY_VARY),
2537 FE(HTTP_QUERY_VIA),
2538 FE(HTTP_QUERY_WARNING),
2539 FE(HTTP_QUERY_CUSTOM)
2541 static const wininet_flag_info modifier_flags[] = {
2542 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2543 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2544 FE(HTTP_QUERY_FLAG_NUMBER),
2545 FE(HTTP_QUERY_FLAG_COALESCE)
2547 #undef FE
2548 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2549 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2550 DWORD i;
2552 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2553 TRACE(" Attribute:");
2554 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2555 if (query_flags[i].val == info) {
2556 TRACE(" %s", query_flags[i].name);
2557 break;
2560 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2561 TRACE(" Unknown (%08x)", info);
2564 TRACE(" Modifier:");
2565 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2566 if (modifier_flags[i].val & info_mod) {
2567 TRACE(" %s", modifier_flags[i].name);
2568 info_mod &= ~ modifier_flags[i].val;
2572 if (info_mod) {
2573 TRACE(" Unknown (%08x)", info_mod);
2575 TRACE("\n");
2578 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2579 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2581 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2582 goto lend;
2585 if (lpBuffer == NULL)
2586 *lpdwBufferLength = 0;
2587 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2588 lpBuffer, lpdwBufferLength, lpdwIndex);
2590 lend:
2591 if( lpwhr )
2592 WININET_Release( &lpwhr->hdr );
2594 TRACE("%d <--\n", bSuccess);
2595 return bSuccess;
2598 /***********************************************************************
2599 * HttpQueryInfoA (WININET.@)
2601 * Queries for information about an HTTP request
2603 * RETURNS
2604 * TRUE on success
2605 * FALSE on failure
2608 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2609 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2611 BOOL result;
2612 DWORD len;
2613 WCHAR* bufferW;
2615 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2616 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2618 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2619 lpdwBufferLength, lpdwIndex );
2622 if (lpBuffer)
2624 DWORD alloclen;
2625 len = (*lpdwBufferLength)*sizeof(WCHAR);
2626 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2628 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2629 if (alloclen < len)
2630 alloclen = len;
2632 else
2633 alloclen = len;
2634 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2635 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2636 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2637 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2638 } else
2640 bufferW = NULL;
2641 len = 0;
2644 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2645 &len, lpdwIndex );
2646 if( result )
2648 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2649 lpBuffer, *lpdwBufferLength, NULL, NULL );
2650 *lpdwBufferLength = len - 1;
2652 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2654 else
2655 /* since the strings being returned from HttpQueryInfoW should be
2656 * only ASCII characters, it is reasonable to assume that all of
2657 * the Unicode characters can be reduced to a single byte */
2658 *lpdwBufferLength = len / sizeof(WCHAR);
2660 HeapFree(GetProcessHeap(), 0, bufferW );
2662 return result;
2665 /***********************************************************************
2666 * HttpSendRequestExA (WININET.@)
2668 * Sends the specified request to the HTTP server and allows chunked
2669 * transfers.
2671 * RETURNS
2672 * Success: TRUE
2673 * Failure: FALSE, call GetLastError() for more information.
2675 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2676 LPINTERNET_BUFFERSA lpBuffersIn,
2677 LPINTERNET_BUFFERSA lpBuffersOut,
2678 DWORD dwFlags, DWORD_PTR dwContext)
2680 INTERNET_BUFFERSW BuffersInW;
2681 BOOL rc = FALSE;
2682 DWORD headerlen;
2683 LPWSTR header = NULL;
2685 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2686 lpBuffersOut, dwFlags, dwContext);
2688 if (lpBuffersIn)
2690 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2691 if (lpBuffersIn->lpcszHeader)
2693 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2694 lpBuffersIn->dwHeadersLength,0,0);
2695 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2696 if (!(BuffersInW.lpcszHeader = header))
2698 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2699 return FALSE;
2701 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2702 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2703 header, headerlen);
2705 else
2706 BuffersInW.lpcszHeader = NULL;
2707 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2708 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2709 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2710 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2711 BuffersInW.Next = NULL;
2714 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2716 HeapFree(GetProcessHeap(),0,header);
2718 return rc;
2721 /***********************************************************************
2722 * HttpSendRequestExW (WININET.@)
2724 * Sends the specified request to the HTTP server and allows chunked
2725 * transfers
2727 * RETURNS
2728 * Success: TRUE
2729 * Failure: FALSE, call GetLastError() for more information.
2731 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2732 LPINTERNET_BUFFERSW lpBuffersIn,
2733 LPINTERNET_BUFFERSW lpBuffersOut,
2734 DWORD dwFlags, DWORD_PTR dwContext)
2736 BOOL ret = FALSE;
2737 LPWININETHTTPREQW lpwhr;
2738 LPWININETHTTPSESSIONW lpwhs;
2739 LPWININETAPPINFOW hIC;
2741 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2742 lpBuffersOut, dwFlags, dwContext);
2744 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2746 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2748 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2749 goto lend;
2752 lpwhs = lpwhr->lpHttpSession;
2753 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2754 hIC = lpwhs->lpAppInfo;
2755 assert(hIC->hdr.htype == WH_HINIT);
2757 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2759 WORKREQUEST workRequest;
2760 struct WORKREQ_HTTPSENDREQUESTW *req;
2762 workRequest.asyncproc = AsyncHttpSendRequestProc;
2763 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2764 req = &workRequest.u.HttpSendRequestW;
2765 if (lpBuffersIn)
2767 if (lpBuffersIn->lpcszHeader)
2768 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2769 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2770 else
2771 req->lpszHeader = NULL;
2772 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2773 req->lpOptional = lpBuffersIn->lpvBuffer;
2774 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2775 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2777 else
2779 req->lpszHeader = NULL;
2780 req->dwHeaderLength = 0;
2781 req->lpOptional = NULL;
2782 req->dwOptionalLength = 0;
2783 req->dwContentLength = 0;
2786 req->bEndRequest = FALSE;
2788 INTERNET_AsyncCall(&workRequest);
2790 * This is from windows.
2792 INTERNET_SetLastError(ERROR_IO_PENDING);
2794 else
2796 if (lpBuffersIn)
2797 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2798 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2799 lpBuffersIn->dwBufferTotal, FALSE);
2800 else
2801 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2804 lend:
2805 if ( lpwhr )
2806 WININET_Release( &lpwhr->hdr );
2808 TRACE("<---\n");
2809 return ret;
2812 /***********************************************************************
2813 * HttpSendRequestW (WININET.@)
2815 * Sends the specified request to the HTTP server
2817 * RETURNS
2818 * TRUE on success
2819 * FALSE on failure
2822 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2823 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2825 LPWININETHTTPREQW lpwhr;
2826 LPWININETHTTPSESSIONW lpwhs = NULL;
2827 LPWININETAPPINFOW hIC = NULL;
2828 BOOL r;
2830 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2831 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2833 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2834 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2836 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2837 r = FALSE;
2838 goto lend;
2841 lpwhs = lpwhr->lpHttpSession;
2842 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2844 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2845 r = FALSE;
2846 goto lend;
2849 hIC = lpwhs->lpAppInfo;
2850 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2852 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2853 r = FALSE;
2854 goto lend;
2857 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2859 WORKREQUEST workRequest;
2860 struct WORKREQ_HTTPSENDREQUESTW *req;
2862 workRequest.asyncproc = AsyncHttpSendRequestProc;
2863 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2864 req = &workRequest.u.HttpSendRequestW;
2865 if (lpszHeaders)
2867 DWORD size;
2869 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
2870 else size = dwHeaderLength * sizeof(WCHAR);
2872 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
2873 memcpy(req->lpszHeader, lpszHeaders, size);
2875 else
2876 req->lpszHeader = 0;
2877 req->dwHeaderLength = dwHeaderLength;
2878 req->lpOptional = lpOptional;
2879 req->dwOptionalLength = dwOptionalLength;
2880 req->dwContentLength = dwOptionalLength;
2881 req->bEndRequest = TRUE;
2883 INTERNET_AsyncCall(&workRequest);
2885 * This is from windows.
2887 INTERNET_SetLastError(ERROR_IO_PENDING);
2888 r = FALSE;
2890 else
2892 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2893 dwHeaderLength, lpOptional, dwOptionalLength,
2894 dwOptionalLength, TRUE);
2896 lend:
2897 if( lpwhr )
2898 WININET_Release( &lpwhr->hdr );
2899 return r;
2902 /***********************************************************************
2903 * HttpSendRequestA (WININET.@)
2905 * Sends the specified request to the HTTP server
2907 * RETURNS
2908 * TRUE on success
2909 * FALSE on failure
2912 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2913 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2915 BOOL result;
2916 LPWSTR szHeaders=NULL;
2917 DWORD nLen=dwHeaderLength;
2918 if(lpszHeaders!=NULL)
2920 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2921 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2922 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2924 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2925 HeapFree(GetProcessHeap(),0,szHeaders);
2926 return result;
2929 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2931 LPHTTPHEADERW host_header;
2933 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2935 host_header = HTTP_GetHeader(req, szHost);
2936 if(!host_header)
2937 return FALSE;
2939 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2940 return TRUE;
2943 /***********************************************************************
2944 * HTTP_HandleRedirect (internal)
2946 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2948 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2949 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2950 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2951 WCHAR path[INTERNET_MAX_URL_LENGTH];
2952 int index;
2954 if(lpszUrl[0]=='/')
2956 /* if it's an absolute path, keep the same session info */
2957 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2959 else
2961 URL_COMPONENTSW urlComponents;
2962 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2963 static WCHAR szHttp[] = {'h','t','t','p',0};
2964 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2965 DWORD url_length = 0;
2966 LPWSTR orig_url;
2967 LPWSTR combined_url;
2969 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2970 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2971 urlComponents.dwSchemeLength = 0;
2972 urlComponents.lpszHostName = lpwhs->lpszHostName;
2973 urlComponents.dwHostNameLength = 0;
2974 urlComponents.nPort = lpwhs->nHostPort;
2975 urlComponents.lpszUserName = lpwhs->lpszUserName;
2976 urlComponents.dwUserNameLength = 0;
2977 urlComponents.lpszPassword = NULL;
2978 urlComponents.dwPasswordLength = 0;
2979 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2980 urlComponents.dwUrlPathLength = 0;
2981 urlComponents.lpszExtraInfo = NULL;
2982 urlComponents.dwExtraInfoLength = 0;
2984 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2985 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2986 return FALSE;
2988 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2990 /* convert from bytes to characters */
2991 url_length = url_length / sizeof(WCHAR) - 1;
2992 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2994 HeapFree(GetProcessHeap(), 0, orig_url);
2995 return FALSE;
2998 url_length = 0;
2999 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
3000 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3002 HeapFree(GetProcessHeap(), 0, orig_url);
3003 return FALSE;
3005 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
3007 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
3009 HeapFree(GetProcessHeap(), 0, orig_url);
3010 HeapFree(GetProcessHeap(), 0, combined_url);
3011 return FALSE;
3013 HeapFree(GetProcessHeap(), 0, orig_url);
3015 userName[0] = 0;
3016 hostName[0] = 0;
3017 protocol[0] = 0;
3019 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3020 urlComponents.lpszScheme = protocol;
3021 urlComponents.dwSchemeLength = 32;
3022 urlComponents.lpszHostName = hostName;
3023 urlComponents.dwHostNameLength = MAXHOSTNAME;
3024 urlComponents.lpszUserName = userName;
3025 urlComponents.dwUserNameLength = 1024;
3026 urlComponents.lpszPassword = NULL;
3027 urlComponents.dwPasswordLength = 0;
3028 urlComponents.lpszUrlPath = path;
3029 urlComponents.dwUrlPathLength = 2048;
3030 urlComponents.lpszExtraInfo = NULL;
3031 urlComponents.dwExtraInfoLength = 0;
3032 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
3034 HeapFree(GetProcessHeap(), 0, combined_url);
3035 return FALSE;
3038 HeapFree(GetProcessHeap(), 0, combined_url);
3040 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3041 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3043 TRACE("redirect from secure page to non-secure page\n");
3044 /* FIXME: warn about from secure redirect to non-secure page */
3045 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3047 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3048 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3050 TRACE("redirect from non-secure page to secure page\n");
3051 /* FIXME: notify about redirect to secure page */
3052 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3055 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3057 if (lstrlenW(protocol)>4) /*https*/
3058 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3059 else /*http*/
3060 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3063 #if 0
3065 * This upsets redirects to binary files on sourceforge.net
3066 * and gives an html page instead of the target file
3067 * Examination of the HTTP request sent by native wininet.dll
3068 * reveals that it doesn't send a referrer in that case.
3069 * Maybe there's a flag that enables this, or maybe a referrer
3070 * shouldn't be added in case of a redirect.
3073 /* consider the current host as the referrer */
3074 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3075 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3076 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3077 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3078 #endif
3080 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3081 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3082 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3084 int len;
3085 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3086 len = lstrlenW(hostName);
3087 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3088 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3089 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3091 else
3092 lpwhs->lpszHostName = WININET_strdupW(hostName);
3094 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3096 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3097 lpwhs->lpszUserName = NULL;
3098 if (userName[0])
3099 lpwhs->lpszUserName = WININET_strdupW(userName);
3101 if (!using_proxy)
3103 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3105 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3106 lpwhs->lpszServerName = WININET_strdupW(hostName);
3107 lpwhs->nServerPort = urlComponents.nPort;
3109 NETCON_close(&lpwhr->netConnection);
3110 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3111 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3114 else
3115 TRACE("Redirect through proxy\n");
3118 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3119 lpwhr->lpszPath=NULL;
3120 if (*path)
3122 DWORD needed = 0;
3123 HRESULT rc;
3125 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3126 if (rc != E_POINTER)
3127 needed = strlenW(path)+1;
3128 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3129 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3130 URL_ESCAPE_SPACES_ONLY);
3131 if (rc != S_OK)
3133 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3134 strcpyW(lpwhr->lpszPath,path);
3138 /* Remove custom content-type/length headers on redirects. */
3139 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3140 if (0 <= index)
3141 HTTP_DeleteCustomHeader(lpwhr, index);
3142 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3143 if (0 <= index)
3144 HTTP_DeleteCustomHeader(lpwhr, index);
3146 return TRUE;
3149 /***********************************************************************
3150 * HTTP_build_req (internal)
3152 * concatenate all the strings in the request together
3154 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3156 LPCWSTR *t;
3157 LPWSTR str;
3159 for( t = list; *t ; t++ )
3160 len += strlenW( *t );
3161 len++;
3163 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3164 *str = 0;
3166 for( t = list; *t ; t++ )
3167 strcatW( str, *t );
3169 return str;
3172 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3174 LPWSTR lpszPath;
3175 LPWSTR requestString;
3176 INT len;
3177 INT cnt;
3178 INT responseLen;
3179 char *ascii_req;
3180 BOOL ret;
3181 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3182 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3183 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3185 TRACE("\n");
3187 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3188 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3189 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3190 HeapFree( GetProcessHeap(), 0, lpszPath );
3192 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3193 NULL, 0, NULL, NULL );
3194 len--; /* the nul terminator isn't needed */
3195 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3196 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3197 ascii_req, len, NULL, NULL );
3198 HeapFree( GetProcessHeap(), 0, requestString );
3200 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3202 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3203 HeapFree( GetProcessHeap(), 0, ascii_req );
3204 if (!ret || cnt < 0)
3205 return FALSE;
3207 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3208 if (!responseLen)
3209 return FALSE;
3211 return TRUE;
3214 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3216 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3217 LPWSTR lpszCookies, lpszUrl = NULL;
3218 DWORD nCookieSize, size;
3219 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3221 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3222 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3223 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3225 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3227 int cnt = 0;
3228 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3230 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3231 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3233 cnt += sprintfW(lpszCookies, szCookie);
3234 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3235 strcatW(lpszCookies, szCrLf);
3237 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_REPLACE);
3238 HeapFree(GetProcessHeap(), 0, lpszCookies);
3241 HeapFree(GetProcessHeap(), 0, lpszUrl);
3244 /***********************************************************************
3245 * HTTP_HttpSendRequestW (internal)
3247 * Sends the specified request to the HTTP server
3249 * RETURNS
3250 * TRUE on success
3251 * FALSE on failure
3254 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3255 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3256 DWORD dwContentLength, BOOL bEndRequest)
3258 INT cnt;
3259 BOOL bSuccess = FALSE;
3260 LPWSTR requestString = NULL;
3261 INT responseLen;
3262 BOOL loop_next;
3263 INTERNET_ASYNC_RESULT iar;
3264 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3265 static const WCHAR szContentLength[] =
3266 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3267 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3269 TRACE("--> %p\n", lpwhr);
3271 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3273 /* if the verb is NULL default to GET */
3274 if (!lpwhr->lpszVerb)
3275 lpwhr->lpszVerb = WININET_strdupW(szGET);
3277 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3279 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3280 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
3281 lpwhr->dwBytesToWrite = dwContentLength;
3283 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3285 WCHAR *agent_header;
3286 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3287 int len;
3289 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3290 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3291 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3293 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3294 HeapFree(GetProcessHeap(), 0, agent_header);
3296 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3298 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3299 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3301 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3303 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3304 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3305 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3310 DWORD len;
3311 char *ascii_req;
3313 loop_next = FALSE;
3315 /* like native, just in case the caller forgot to call InternetReadFile
3316 * for all the data */
3317 HTTP_DrainContent(lpwhr);
3318 lpwhr->dwContentRead = 0;
3320 if (TRACE_ON(wininet))
3322 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3323 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3326 HTTP_FixURL(lpwhr);
3327 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3329 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3331 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3332 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3334 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3335 HTTP_InsertCookies(lpwhr);
3337 /* add the headers the caller supplied */
3338 if( lpszHeaders && dwHeaderLength )
3340 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3341 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3344 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3346 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3347 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3348 HeapFree(GetProcessHeap(), 0, url);
3350 else
3351 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3354 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3356 /* Send the request and store the results */
3357 if (!HTTP_OpenConnection(lpwhr))
3358 goto lend;
3360 /* send the request as ASCII, tack on the optional data */
3361 if( !lpOptional )
3362 dwOptionalLength = 0;
3363 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3364 NULL, 0, NULL, NULL );
3365 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3366 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3367 ascii_req, len, NULL, NULL );
3368 if( lpOptional )
3369 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3370 len = (len + dwOptionalLength - 1);
3371 ascii_req[len] = 0;
3372 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3374 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3375 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3377 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3378 HeapFree( GetProcessHeap(), 0, ascii_req );
3380 lpwhr->dwBytesWritten = dwOptionalLength;
3382 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3383 INTERNET_STATUS_REQUEST_SENT,
3384 &len, sizeof(DWORD));
3386 if (bEndRequest)
3388 DWORD dwBufferSize;
3389 DWORD dwStatusCode;
3390 WCHAR encoding[20];
3391 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3393 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3394 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3396 if (cnt < 0)
3397 goto lend;
3399 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3400 if (responseLen)
3401 bSuccess = TRUE;
3403 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3404 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3405 sizeof(DWORD));
3407 HTTP_ProcessCookies(lpwhr);
3409 dwBufferSize = sizeof(lpwhr->dwContentLength);
3410 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3411 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3412 lpwhr->dwContentLength = -1;
3414 if (lpwhr->dwContentLength == 0)
3415 HTTP_FinishedReading(lpwhr);
3417 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3419 dwBufferSize = sizeof(encoding);
3420 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3421 !strcmpiW(encoding, szChunked))
3423 lpwhr->dwContentLength = -1;
3426 dwBufferSize = sizeof(dwStatusCode);
3427 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3428 &dwStatusCode,&dwBufferSize,NULL))
3429 dwStatusCode = 0;
3431 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3433 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3434 dwBufferSize=sizeof(szNewLocation);
3435 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3436 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3438 /* redirects are always GETs */
3439 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3440 lpwhr->lpszVerb = WININET_strdupW(szGET);
3442 HTTP_DrainContent(lpwhr);
3443 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3444 INTERNET_STATUS_REDIRECT, szNewLocation,
3445 dwBufferSize);
3446 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3447 if (bSuccess)
3449 HeapFree(GetProcessHeap(), 0, requestString);
3450 loop_next = TRUE;
3454 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3456 WCHAR szAuthValue[2048];
3457 dwBufferSize=2048;
3458 if (dwStatusCode == HTTP_STATUS_DENIED)
3460 DWORD dwIndex = 0;
3461 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3463 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3464 &lpwhr->pAuthInfo,
3465 lpwhr->lpHttpSession->lpszUserName,
3466 lpwhr->lpHttpSession->lpszPassword))
3468 loop_next = TRUE;
3469 break;
3473 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3475 DWORD dwIndex = 0;
3476 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3478 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3479 &lpwhr->pProxyAuthInfo,
3480 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3481 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3483 loop_next = TRUE;
3484 break;
3490 else
3491 bSuccess = TRUE;
3493 while (loop_next);
3495 /* FIXME: Better check, when we have to create the cache file */
3496 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3497 WCHAR url[INTERNET_MAX_URL_LENGTH];
3498 WCHAR cacheFileName[MAX_PATH+1];
3499 BOOL b;
3501 b = HTTP_GetRequestURL(lpwhr, url);
3502 if(!b) {
3503 WARN("Could not get URL\n");
3504 goto lend;
3507 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3508 if(b) {
3509 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3510 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3511 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3512 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3513 WARN("Could not create file: %u\n", GetLastError());
3514 lpwhr->hCacheFile = NULL;
3516 }else {
3517 WARN("Could not create cache entry: %08x\n", GetLastError());
3521 lend:
3523 HeapFree(GetProcessHeap(), 0, requestString);
3525 /* TODO: send notification for P3P header */
3527 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3529 if (bSuccess)
3531 if (lpwhr->dwBytesWritten == lpwhr->dwBytesToWrite) HTTP_ReceiveRequestData(lpwhr, TRUE);
3532 else
3534 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3535 iar.dwError = 0;
3537 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3538 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3539 sizeof(INTERNET_ASYNC_RESULT));
3542 else
3544 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3545 iar.dwError = INTERNET_GetLastError();
3547 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3548 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3549 sizeof(INTERNET_ASYNC_RESULT));
3553 TRACE("<--\n");
3554 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3555 return bSuccess;
3558 /***********************************************************************
3559 * HTTPSESSION_Destroy (internal)
3561 * Deallocate session handle
3564 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3566 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3568 TRACE("%p\n", lpwhs);
3570 WININET_Release(&lpwhs->lpAppInfo->hdr);
3572 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3573 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3574 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3575 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3576 HeapFree(GetProcessHeap(), 0, lpwhs);
3579 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3581 switch(option) {
3582 case INTERNET_OPTION_HANDLE_TYPE:
3583 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3585 if (*size < sizeof(ULONG))
3586 return ERROR_INSUFFICIENT_BUFFER;
3588 *size = sizeof(DWORD);
3589 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3590 return ERROR_SUCCESS;
3593 return INET_QueryOption(option, buffer, size, unicode);
3596 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3598 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3600 switch(option) {
3601 case INTERNET_OPTION_USERNAME:
3603 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3604 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3605 return ERROR_SUCCESS;
3607 case INTERNET_OPTION_PASSWORD:
3609 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3610 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3611 return ERROR_SUCCESS;
3613 default: break;
3616 return ERROR_INTERNET_INVALID_OPTION;
3619 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3620 HTTPSESSION_Destroy,
3621 NULL,
3622 HTTPSESSION_QueryOption,
3623 HTTPSESSION_SetOption,
3624 NULL,
3625 NULL,
3626 NULL,
3627 NULL,
3628 NULL
3632 /***********************************************************************
3633 * HTTP_Connect (internal)
3635 * Create http session handle
3637 * RETURNS
3638 * HINTERNET a session handle on success
3639 * NULL on failure
3642 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3643 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3644 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3645 DWORD dwInternalFlags)
3647 LPWININETHTTPSESSIONW lpwhs = NULL;
3648 HINTERNET handle = NULL;
3650 TRACE("-->\n");
3652 if (!lpszServerName || !lpszServerName[0])
3654 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3655 goto lerror;
3658 assert( hIC->hdr.htype == WH_HINIT );
3660 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3661 if (NULL == lpwhs)
3663 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3664 goto lerror;
3668 * According to my tests. The name is not resolved until a request is sent
3671 lpwhs->hdr.htype = WH_HHTTPSESSION;
3672 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3673 lpwhs->hdr.dwFlags = dwFlags;
3674 lpwhs->hdr.dwContext = dwContext;
3675 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3676 lpwhs->hdr.refs = 1;
3677 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3679 WININET_AddRef( &hIC->hdr );
3680 lpwhs->lpAppInfo = hIC;
3681 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3683 handle = WININET_AllocHandle( &lpwhs->hdr );
3684 if (NULL == handle)
3686 ERR("Failed to alloc handle\n");
3687 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3688 goto lerror;
3691 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3692 if(strchrW(hIC->lpszProxy, ' '))
3693 FIXME("Several proxies not implemented.\n");
3694 if(hIC->lpszProxyBypass)
3695 FIXME("Proxy bypass is ignored.\n");
3697 if (lpszServerName && lpszServerName[0])
3699 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3700 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3702 if (lpszUserName && lpszUserName[0])
3703 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3704 if (lpszPassword && lpszPassword[0])
3705 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3706 lpwhs->nServerPort = nServerPort;
3707 lpwhs->nHostPort = nServerPort;
3709 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3710 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3712 INTERNET_SendCallback(&hIC->hdr, dwContext,
3713 INTERNET_STATUS_HANDLE_CREATED, &handle,
3714 sizeof(handle));
3717 lerror:
3718 if( lpwhs )
3719 WININET_Release( &lpwhs->hdr );
3722 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3723 * windows
3726 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3727 return handle;
3731 /***********************************************************************
3732 * HTTP_OpenConnection (internal)
3734 * Connect to a web server
3736 * RETURNS
3738 * TRUE on success
3739 * FALSE on failure
3741 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3743 BOOL bSuccess = FALSE;
3744 LPWININETHTTPSESSIONW lpwhs;
3745 LPWININETAPPINFOW hIC = NULL;
3746 char szaddr[32];
3748 TRACE("-->\n");
3751 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3753 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3754 goto lend;
3757 if (NETCON_connected(&lpwhr->netConnection))
3759 bSuccess = TRUE;
3760 goto lend;
3762 if (!HTTP_ResolveName(lpwhr)) goto lend;
3764 lpwhs = lpwhr->lpHttpSession;
3766 hIC = lpwhs->lpAppInfo;
3767 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3768 szaddr, sizeof(szaddr));
3769 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3770 INTERNET_STATUS_CONNECTING_TO_SERVER,
3771 szaddr,
3772 strlen(szaddr)+1);
3774 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3775 SOCK_STREAM, 0))
3777 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3778 goto lend;
3781 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3782 sizeof(lpwhs->socketAddress)))
3783 goto lend;
3785 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3787 /* Note: we differ from Microsoft's WinINet here. they seem to have
3788 * a bug that causes no status callbacks to be sent when starting
3789 * a tunnel to a proxy server using the CONNECT verb. i believe our
3790 * behaviour to be more correct and to not cause any incompatibilities
3791 * because using a secure connection through a proxy server is a rare
3792 * case that would be hard for anyone to depend on */
3793 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3794 goto lend;
3796 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3798 WARN("Couldn't connect securely to host\n");
3799 goto lend;
3803 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3804 INTERNET_STATUS_CONNECTED_TO_SERVER,
3805 szaddr, strlen(szaddr)+1);
3807 bSuccess = TRUE;
3809 lend:
3810 TRACE("%d <--\n", bSuccess);
3811 return bSuccess;
3815 /***********************************************************************
3816 * HTTP_clear_response_headers (internal)
3818 * clear out any old response headers
3820 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3822 DWORD i;
3824 for( i=0; i<lpwhr->nCustHeaders; i++)
3826 if( !lpwhr->pCustHeaders[i].lpszField )
3827 continue;
3828 if( !lpwhr->pCustHeaders[i].lpszValue )
3829 continue;
3830 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3831 continue;
3832 HTTP_DeleteCustomHeader( lpwhr, i );
3833 i--;
3837 /***********************************************************************
3838 * HTTP_GetResponseHeaders (internal)
3840 * Read server response
3842 * RETURNS
3844 * TRUE on success
3845 * FALSE on error
3847 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3849 INT cbreaks = 0;
3850 WCHAR buffer[MAX_REPLY_LEN];
3851 DWORD buflen = MAX_REPLY_LEN;
3852 BOOL bSuccess = FALSE;
3853 INT rc = 0;
3854 static const WCHAR szHundred[] = {'1','0','0',0};
3855 char bufferA[MAX_REPLY_LEN];
3856 LPWSTR status_code, status_text;
3857 DWORD cchMaxRawHeaders = 1024;
3858 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3859 DWORD cchRawHeaders = 0;
3861 TRACE("-->\n");
3863 /* clear old response headers (eg. from a redirect response) */
3864 if (clear) HTTP_clear_response_headers( lpwhr );
3866 if (!NETCON_connected(&lpwhr->netConnection))
3867 goto lend;
3869 do {
3871 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3873 buflen = MAX_REPLY_LEN;
3874 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3875 goto lend;
3876 rc += buflen;
3877 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3879 /* split the version from the status code */
3880 status_code = strchrW( buffer, ' ' );
3881 if( !status_code )
3882 goto lend;
3883 *status_code++=0;
3885 /* split the status code from the status text */
3886 status_text = strchrW( status_code, ' ' );
3887 if( !status_text )
3888 goto lend;
3889 *status_text++=0;
3891 TRACE("version [%s] status code [%s] status text [%s]\n",
3892 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3894 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3896 /* Add status code */
3897 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3898 HTTP_ADDHDR_FLAG_REPLACE);
3900 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3901 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3903 lpwhr->lpszVersion= WININET_strdupW(buffer);
3904 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3906 /* Restore the spaces */
3907 *(status_code-1) = ' ';
3908 *(status_text-1) = ' ';
3910 /* regenerate raw headers */
3911 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3913 cchMaxRawHeaders *= 2;
3914 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3916 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3917 cchRawHeaders += (buflen-1);
3918 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3919 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3920 lpszRawHeaders[cchRawHeaders] = '\0';
3922 /* Parse each response line */
3925 buflen = MAX_REPLY_LEN;
3926 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3928 LPWSTR * pFieldAndValue;
3930 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3932 if (!bufferA[0]) break;
3933 if (!strchr(bufferA, ':'))
3935 WARN("invalid header\n");
3936 continue;
3938 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3940 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3942 cchMaxRawHeaders *= 2;
3943 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3945 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3946 cchRawHeaders += (buflen-1);
3947 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3948 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3949 lpszRawHeaders[cchRawHeaders] = '\0';
3951 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3952 if (!pFieldAndValue)
3953 break;
3955 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3956 HTTP_ADDREQ_FLAG_ADD );
3958 HTTP_FreeTokens(pFieldAndValue);
3960 else
3962 cbreaks++;
3963 if (cbreaks >= 2)
3964 break;
3966 }while(1);
3968 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3969 lpwhr->lpszRawHeaders = lpszRawHeaders;
3970 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3971 bSuccess = TRUE;
3973 lend:
3975 TRACE("<--\n");
3976 if (bSuccess)
3977 return rc;
3978 else
3980 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3981 return 0;
3986 static void strip_spaces(LPWSTR start)
3988 LPWSTR str = start;
3989 LPWSTR end;
3991 while (*str == ' ' && *str != '\0')
3992 str++;
3994 if (str != start)
3995 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3997 end = start + strlenW(start) - 1;
3998 while (end >= start && *end == ' ')
4000 *end = '\0';
4001 end--;
4006 /***********************************************************************
4007 * HTTP_InterpretHttpHeader (internal)
4009 * Parse server response
4011 * RETURNS
4013 * Pointer to array of field, value, NULL on success.
4014 * NULL on error.
4016 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
4018 LPWSTR * pTokenPair;
4019 LPWSTR pszColon;
4020 INT len;
4022 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4024 pszColon = strchrW(buffer, ':');
4025 /* must have two tokens */
4026 if (!pszColon)
4028 HTTP_FreeTokens(pTokenPair);
4029 if (buffer[0])
4030 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4031 return NULL;
4034 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4035 if (!pTokenPair[0])
4037 HTTP_FreeTokens(pTokenPair);
4038 return NULL;
4040 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4041 pTokenPair[0][pszColon - buffer] = '\0';
4043 /* skip colon */
4044 pszColon++;
4045 len = strlenW(pszColon);
4046 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4047 if (!pTokenPair[1])
4049 HTTP_FreeTokens(pTokenPair);
4050 return NULL;
4052 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4054 strip_spaces(pTokenPair[0]);
4055 strip_spaces(pTokenPair[1]);
4057 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4058 return pTokenPair;
4061 /***********************************************************************
4062 * HTTP_ProcessHeader (internal)
4064 * Stuff header into header tables according to <dwModifier>
4068 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4070 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4072 LPHTTPHEADERW lphttpHdr = NULL;
4073 BOOL bSuccess = FALSE;
4074 INT index = -1;
4075 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4077 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4079 /* REPLACE wins out over ADD */
4080 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4081 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4083 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4084 index = -1;
4085 else
4086 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4088 if (index >= 0)
4090 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4092 return FALSE;
4094 lphttpHdr = &lpwhr->pCustHeaders[index];
4096 else if (value)
4098 HTTPHEADERW hdr;
4100 hdr.lpszField = (LPWSTR)field;
4101 hdr.lpszValue = (LPWSTR)value;
4102 hdr.wFlags = hdr.wCount = 0;
4104 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4105 hdr.wFlags |= HDR_ISREQUEST;
4107 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4109 /* no value to delete */
4110 else return TRUE;
4112 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4113 lphttpHdr->wFlags |= HDR_ISREQUEST;
4114 else
4115 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4117 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4119 HTTP_DeleteCustomHeader( lpwhr, index );
4121 if (value)
4123 HTTPHEADERW hdr;
4125 hdr.lpszField = (LPWSTR)field;
4126 hdr.lpszValue = (LPWSTR)value;
4127 hdr.wFlags = hdr.wCount = 0;
4129 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4130 hdr.wFlags |= HDR_ISREQUEST;
4132 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4135 return TRUE;
4137 else if (dwModifier & COALESCEFLAGS)
4139 LPWSTR lpsztmp;
4140 WCHAR ch = 0;
4141 INT len = 0;
4142 INT origlen = strlenW(lphttpHdr->lpszValue);
4143 INT valuelen = strlenW(value);
4145 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4147 ch = ',';
4148 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4150 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4152 ch = ';';
4153 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4156 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4158 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4159 if (lpsztmp)
4161 lphttpHdr->lpszValue = lpsztmp;
4162 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4163 if (ch > 0)
4165 lphttpHdr->lpszValue[origlen] = ch;
4166 origlen++;
4167 lphttpHdr->lpszValue[origlen] = ' ';
4168 origlen++;
4171 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4172 lphttpHdr->lpszValue[len] = '\0';
4173 bSuccess = TRUE;
4175 else
4177 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4178 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4181 TRACE("<-- %d\n",bSuccess);
4182 return bSuccess;
4186 /***********************************************************************
4187 * HTTP_FinishedReading (internal)
4189 * Called when all content from server has been read by client.
4192 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4194 WCHAR szVersion[10];
4195 WCHAR szConnectionResponse[20];
4196 DWORD dwBufferSize = sizeof(szVersion);
4197 BOOL keepalive = FALSE;
4199 TRACE("\n");
4201 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4202 * the connection is keep-alive by default */
4203 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4204 &dwBufferSize, NULL) &&
4205 !strcmpiW(szVersion, g_szHttp1_1))
4207 keepalive = TRUE;
4210 dwBufferSize = sizeof(szConnectionResponse);
4211 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4212 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4214 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4217 if (!keepalive)
4219 HTTPREQ_CloseConnection(&lpwhr->hdr);
4222 /* FIXME: store data in the URL cache here */
4224 return TRUE;
4228 /***********************************************************************
4229 * HTTP_GetCustomHeaderIndex (internal)
4231 * Return index of custom header from header array
4234 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4235 int requested_index, BOOL request_only)
4237 DWORD index;
4239 TRACE("%s\n", debugstr_w(lpszField));
4241 for (index = 0; index < lpwhr->nCustHeaders; index++)
4243 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4244 continue;
4246 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4247 continue;
4249 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4250 continue;
4252 if (requested_index == 0)
4253 break;
4254 requested_index --;
4257 if (index >= lpwhr->nCustHeaders)
4258 index = -1;
4260 TRACE("Return: %d\n", index);
4261 return index;
4265 /***********************************************************************
4266 * HTTP_InsertCustomHeader (internal)
4268 * Insert header into array
4271 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4273 INT count;
4274 LPHTTPHEADERW lph = NULL;
4275 BOOL r = FALSE;
4277 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4278 count = lpwhr->nCustHeaders + 1;
4279 if (count > 1)
4280 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4281 else
4282 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4284 if (NULL != lph)
4286 lpwhr->pCustHeaders = lph;
4287 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4288 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4289 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4290 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4291 lpwhr->nCustHeaders++;
4292 r = TRUE;
4294 else
4296 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4299 return r;
4303 /***********************************************************************
4304 * HTTP_DeleteCustomHeader (internal)
4306 * Delete header from array
4307 * If this function is called, the indexs may change.
4309 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4311 if( lpwhr->nCustHeaders <= 0 )
4312 return FALSE;
4313 if( index >= lpwhr->nCustHeaders )
4314 return FALSE;
4315 lpwhr->nCustHeaders--;
4317 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4318 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4320 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4321 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4322 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4324 return TRUE;
4328 /***********************************************************************
4329 * HTTP_VerifyValidHeader (internal)
4331 * Verify the given header is not invalid for the given http request
4334 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4336 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4337 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4338 return FALSE;
4340 return TRUE;
4343 /***********************************************************************
4344 * IsHostInProxyBypassList (@)
4346 * Undocumented
4349 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4351 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4352 return FALSE;