push 8742e928a3d078c1d2cecb5ceee0ffde3118cbb7
[wine/hacks.git] / dlls / wininet / http.c
blob8729df3835cce97da336d7cf9dca2f6a29c48928
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 #include <sys/types.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
38 #endif
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #include <time.h>
46 #include <assert.h>
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wininet.h"
51 #include "winerror.h"
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
56 #include "shlwapi.h"
57 #include "sspi.h"
58 #include "wincrypt.h"
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/unicode.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
66 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
67 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
68 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
69 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
70 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
71 static const WCHAR szHost[] = { 'H','o','s','t',0 };
72 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
74 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
75 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
76 static const WCHAR szGET[] = { 'G','E','T', 0 };
77 static const WCHAR szCrLf[] = {'\r','\n', 0};
79 #define MAXHOSTNAME 100
80 #define MAX_FIELD_VALUE_LEN 256
81 #define MAX_FIELD_LEN 256
83 #define HTTP_REFERER g_szReferer
84 #define HTTP_ACCEPT g_szAccept
85 #define HTTP_USERAGENT g_szUserAgent
87 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
88 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
89 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
90 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
91 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
92 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
93 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
95 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
97 struct HttpAuthInfo
99 LPWSTR scheme;
100 CredHandle cred;
101 CtxtHandle ctx;
102 TimeStamp exp;
103 ULONG attr;
104 ULONG max_token;
105 void *auth_data;
106 unsigned int auth_data_len;
107 BOOL finished; /* finished authenticating */
110 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
111 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
112 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
113 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
114 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
115 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
116 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
117 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
118 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
119 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
120 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
121 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
122 static void HTTP_DrainContent(WININETHTTPREQW *req);
124 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
126 int HeaderIndex = 0;
127 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
128 if (HeaderIndex == -1)
129 return NULL;
130 else
131 return &req->pCustHeaders[HeaderIndex];
134 /***********************************************************************
135 * HTTP_Tokenize (internal)
137 * Tokenize a string, allocating memory for the tokens.
139 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
141 LPWSTR * token_array;
142 int tokens = 0;
143 int i;
144 LPCWSTR next_token;
146 if (string)
148 /* empty string has no tokens */
149 if (*string)
150 tokens++;
151 /* count tokens */
152 for (i = 0; string[i]; i++)
154 if (!strncmpW(string+i, token_string, strlenW(token_string)))
156 DWORD j;
157 tokens++;
158 /* we want to skip over separators, but not the null terminator */
159 for (j = 0; j < strlenW(token_string) - 1; j++)
160 if (!string[i+j])
161 break;
162 i += j;
167 /* add 1 for terminating NULL */
168 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
169 token_array[tokens] = NULL;
170 if (!tokens)
171 return token_array;
172 for (i = 0; i < tokens; i++)
174 int len;
175 next_token = strstrW(string, token_string);
176 if (!next_token) next_token = string+strlenW(string);
177 len = next_token - string;
178 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
179 memcpy(token_array[i], string, len*sizeof(WCHAR));
180 token_array[i][len] = '\0';
181 string = next_token+strlenW(token_string);
183 return token_array;
186 /***********************************************************************
187 * HTTP_FreeTokens (internal)
189 * Frees memory returned from HTTP_Tokenize.
191 static void HTTP_FreeTokens(LPWSTR * token_array)
193 int i;
194 for (i = 0; token_array[i]; i++)
195 HeapFree(GetProcessHeap(), 0, token_array[i]);
196 HeapFree(GetProcessHeap(), 0, token_array);
199 /* **********************************************************************
201 * Helper functions for the HttpSendRequest(Ex) functions
204 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
206 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
207 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
209 TRACE("%p\n", lpwhr);
211 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
212 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
213 req->dwContentLength, req->bEndRequest);
215 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
218 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
220 static const WCHAR szSlash[] = { '/',0 };
221 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
223 /* If we don't have a path we set it to root */
224 if (NULL == lpwhr->lpszPath)
225 lpwhr->lpszPath = WININET_strdupW(szSlash);
226 else /* remove \r and \n*/
228 int nLen = strlenW(lpwhr->lpszPath);
229 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
231 nLen--;
232 lpwhr->lpszPath[nLen]='\0';
234 /* Replace '\' with '/' */
235 while (nLen>0) {
236 nLen--;
237 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
241 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
242 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
243 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
245 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
246 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
247 *fixurl = '/';
248 strcpyW(fixurl + 1, lpwhr->lpszPath);
249 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
250 lpwhr->lpszPath = fixurl;
254 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
256 LPWSTR requestString;
257 DWORD len, n;
258 LPCWSTR *req;
259 UINT i;
260 LPWSTR p;
262 static const WCHAR szSpace[] = { ' ',0 };
263 static const WCHAR szColon[] = { ':',' ',0 };
264 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
266 /* allocate space for an array of all the string pointers to be added */
267 len = (lpwhr->nCustHeaders)*4 + 10;
268 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
270 /* add the verb, path and HTTP version string */
271 n = 0;
272 req[n++] = verb;
273 req[n++] = szSpace;
274 req[n++] = path;
275 req[n++] = szSpace;
276 req[n++] = version;
278 /* Append custom request headers */
279 for (i = 0; i < lpwhr->nCustHeaders; i++)
281 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
283 req[n++] = szCrLf;
284 req[n++] = lpwhr->pCustHeaders[i].lpszField;
285 req[n++] = szColon;
286 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
288 TRACE("Adding custom header %s (%s)\n",
289 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
290 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
294 if( n >= len )
295 ERR("oops. buffer overrun\n");
297 req[n] = NULL;
298 requestString = HTTP_build_req( req, 4 );
299 HeapFree( GetProcessHeap(), 0, req );
302 * Set (header) termination string for request
303 * Make sure there's exactly two new lines at the end of the request
305 p = &requestString[strlenW(requestString)-1];
306 while ( (*p == '\n') || (*p == '\r') )
307 p--;
308 strcpyW( p+1, sztwocrlf );
310 return requestString;
313 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
315 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
316 int HeaderIndex;
317 int numCookies = 0;
318 LPHTTPHEADERW setCookieHeader;
320 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
322 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
324 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
326 int nPosStart = 0, nPosEnd = 0, len;
327 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
329 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
331 LPWSTR buf_cookie, cookie_name, cookie_data;
332 LPWSTR buf_url;
333 LPWSTR domain = NULL;
334 LPHTTPHEADERW Host;
336 int nEqualPos = 0;
337 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
338 setCookieHeader->lpszValue[nPosEnd] != '\0')
340 nPosEnd++;
342 if (setCookieHeader->lpszValue[nPosEnd] == ';')
344 /* fixme: not case sensitive, strcasestr is gnu only */
345 int nDomainPosEnd = 0;
346 int nDomainPosStart = 0, nDomainLength = 0;
347 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
348 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
349 if (lpszDomain)
350 { /* they have specified their own domain, lets use it */
351 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
352 lpszDomain[nDomainPosEnd] != '\0')
354 nDomainPosEnd++;
356 nDomainPosStart = strlenW(szDomain);
357 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
358 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
359 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
362 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
363 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
364 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
365 TRACE("%s\n", debugstr_w(buf_cookie));
366 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
368 nEqualPos++;
370 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
372 HeapFree(GetProcessHeap(), 0, buf_cookie);
373 break;
376 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
377 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
378 cookie_data = &buf_cookie[nEqualPos + 1];
380 Host = HTTP_GetHeader(lpwhr,szHost);
381 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
382 strlenW(lpwhr->lpszPath) + 9;
383 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
384 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
385 InternetSetCookieW(buf_url, cookie_name, cookie_data);
387 HeapFree(GetProcessHeap(), 0, buf_url);
388 HeapFree(GetProcessHeap(), 0, buf_cookie);
389 HeapFree(GetProcessHeap(), 0, cookie_name);
390 HeapFree(GetProcessHeap(), 0, domain);
391 nPosStart = nPosEnd;
394 numCookies++;
398 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
400 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
401 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
402 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
405 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
406 struct HttpAuthInfo **ppAuthInfo,
407 LPWSTR domain_and_username, LPWSTR password )
409 SECURITY_STATUS sec_status;
410 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
411 BOOL first = FALSE;
413 TRACE("%s\n", debugstr_w(pszAuthValue));
415 if (!pAuthInfo)
417 TimeStamp exp;
419 first = TRUE;
420 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
421 if (!pAuthInfo)
422 return FALSE;
424 SecInvalidateHandle(&pAuthInfo->cred);
425 SecInvalidateHandle(&pAuthInfo->ctx);
426 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
427 pAuthInfo->attr = 0;
428 pAuthInfo->auth_data = NULL;
429 pAuthInfo->auth_data_len = 0;
430 pAuthInfo->finished = FALSE;
432 if (is_basic_auth_value(pszAuthValue))
434 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
435 pAuthInfo->scheme = WININET_strdupW(szBasic);
436 if (!pAuthInfo->scheme)
438 HeapFree(GetProcessHeap(), 0, pAuthInfo);
439 return FALSE;
442 else
444 PVOID pAuthData;
445 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
447 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
448 if (!pAuthInfo->scheme)
450 HeapFree(GetProcessHeap(), 0, pAuthInfo);
451 return FALSE;
454 if (domain_and_username)
456 WCHAR *user = strchrW(domain_and_username, '\\');
457 WCHAR *domain = domain_and_username;
459 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
461 pAuthData = &nt_auth_identity;
463 if (user) user++;
464 else
466 user = domain_and_username;
467 domain = NULL;
470 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
471 nt_auth_identity.User = user;
472 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
473 nt_auth_identity.Domain = domain;
474 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
475 nt_auth_identity.Password = password;
476 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
478 else
479 /* use default credentials */
480 pAuthData = NULL;
482 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
483 SECPKG_CRED_OUTBOUND, NULL,
484 pAuthData, NULL,
485 NULL, &pAuthInfo->cred,
486 &exp);
487 if (sec_status == SEC_E_OK)
489 PSecPkgInfoW sec_pkg_info;
490 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
491 if (sec_status == SEC_E_OK)
493 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
494 FreeContextBuffer(sec_pkg_info);
497 if (sec_status != SEC_E_OK)
499 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
500 debugstr_w(pAuthInfo->scheme), sec_status);
501 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
502 HeapFree(GetProcessHeap(), 0, pAuthInfo);
503 return FALSE;
506 *ppAuthInfo = pAuthInfo;
508 else if (pAuthInfo->finished)
509 return FALSE;
511 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
512 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
514 ERR("authentication scheme changed from %s to %s\n",
515 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
516 return FALSE;
519 if (is_basic_auth_value(pszAuthValue))
521 int userlen;
522 int passlen;
523 char *auth_data;
525 TRACE("basic authentication\n");
527 /* we don't cache credentials for basic authentication, so we can't
528 * retrieve them if the application didn't pass us any credentials */
529 if (!domain_and_username) return FALSE;
531 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
532 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
534 /* length includes a nul terminator, which will be re-used for the ':' */
535 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
536 if (!auth_data)
537 return FALSE;
539 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
540 auth_data[userlen] = ':';
541 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
543 pAuthInfo->auth_data = auth_data;
544 pAuthInfo->auth_data_len = userlen + 1 + passlen;
545 pAuthInfo->finished = TRUE;
547 return TRUE;
549 else
551 LPCWSTR pszAuthData;
552 SecBufferDesc out_desc, in_desc;
553 SecBuffer out, in;
554 unsigned char *buffer;
555 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
556 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
558 in.BufferType = SECBUFFER_TOKEN;
559 in.cbBuffer = 0;
560 in.pvBuffer = NULL;
562 in_desc.ulVersion = 0;
563 in_desc.cBuffers = 1;
564 in_desc.pBuffers = &in;
566 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
567 if (*pszAuthData == ' ')
569 pszAuthData++;
570 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
571 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
572 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
575 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
577 out.BufferType = SECBUFFER_TOKEN;
578 out.cbBuffer = pAuthInfo->max_token;
579 out.pvBuffer = buffer;
581 out_desc.ulVersion = 0;
582 out_desc.cBuffers = 1;
583 out_desc.pBuffers = &out;
585 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
586 first ? NULL : &pAuthInfo->ctx,
587 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
588 context_req, 0, SECURITY_NETWORK_DREP,
589 in.pvBuffer ? &in_desc : NULL,
590 0, &pAuthInfo->ctx, &out_desc,
591 &pAuthInfo->attr, &pAuthInfo->exp);
592 if (sec_status == SEC_E_OK)
594 pAuthInfo->finished = TRUE;
595 pAuthInfo->auth_data = out.pvBuffer;
596 pAuthInfo->auth_data_len = out.cbBuffer;
597 TRACE("sending last auth packet\n");
599 else if (sec_status == SEC_I_CONTINUE_NEEDED)
601 pAuthInfo->auth_data = out.pvBuffer;
602 pAuthInfo->auth_data_len = out.cbBuffer;
603 TRACE("sending next auth packet\n");
605 else
607 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
608 pAuthInfo->finished = TRUE;
609 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
610 return FALSE;
614 return TRUE;
617 /***********************************************************************
618 * HTTP_HttpAddRequestHeadersW (internal)
620 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
621 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
623 LPWSTR lpszStart;
624 LPWSTR lpszEnd;
625 LPWSTR buffer;
626 BOOL bSuccess = FALSE;
627 DWORD len;
629 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
631 if( dwHeaderLength == ~0U )
632 len = strlenW(lpszHeader);
633 else
634 len = dwHeaderLength;
635 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
636 lstrcpynW( buffer, lpszHeader, len + 1);
638 lpszStart = buffer;
642 LPWSTR * pFieldAndValue;
644 lpszEnd = lpszStart;
646 while (*lpszEnd != '\0')
648 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
649 break;
650 lpszEnd++;
653 if (*lpszStart == '\0')
654 break;
656 if (*lpszEnd == '\r')
658 *lpszEnd = '\0';
659 lpszEnd += 2; /* Jump over \r\n */
661 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
662 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
663 if (pFieldAndValue)
665 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
666 if (bSuccess)
667 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
668 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
669 HTTP_FreeTokens(pFieldAndValue);
672 lpszStart = lpszEnd;
673 } while (bSuccess);
675 HeapFree(GetProcessHeap(), 0, buffer);
677 return bSuccess;
680 /***********************************************************************
681 * HttpAddRequestHeadersW (WININET.@)
683 * Adds one or more HTTP header to the request handler
685 * NOTE
686 * On Windows if dwHeaderLength includes the trailing '\0', then
687 * HttpAddRequestHeadersW() adds it too. However this results in an
688 * invalid Http header which is rejected by some servers so we probably
689 * don't need to match Windows on that point.
691 * RETURNS
692 * TRUE on success
693 * FALSE on failure
696 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
697 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
699 BOOL bSuccess = FALSE;
700 LPWININETHTTPREQW lpwhr;
702 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
704 if (!lpszHeader)
705 return TRUE;
707 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
708 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
710 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
711 goto lend;
713 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
714 lend:
715 if( lpwhr )
716 WININET_Release( &lpwhr->hdr );
718 return bSuccess;
721 /***********************************************************************
722 * HttpAddRequestHeadersA (WININET.@)
724 * Adds one or more HTTP header to the request handler
726 * RETURNS
727 * TRUE on success
728 * FALSE on failure
731 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
732 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
734 DWORD len;
735 LPWSTR hdr;
736 BOOL r;
738 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
740 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
741 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
742 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
743 if( dwHeaderLength != ~0U )
744 dwHeaderLength = len;
746 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
748 HeapFree( GetProcessHeap(), 0, hdr );
750 return r;
753 /***********************************************************************
754 * HttpEndRequestA (WININET.@)
756 * Ends an HTTP request that was started by HttpSendRequestEx
758 * RETURNS
759 * TRUE if successful
760 * FALSE on failure
763 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
764 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
766 LPINTERNET_BUFFERSA ptr;
767 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
768 BOOL rc = FALSE;
770 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
771 dwContext);
773 ptr = lpBuffersOut;
774 if (ptr)
775 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
776 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
777 else
778 lpBuffersOutW = NULL;
780 ptrW = lpBuffersOutW;
781 while (ptr)
783 if (ptr->lpvBuffer && ptr->dwBufferLength)
784 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
785 ptrW->dwBufferLength = ptr->dwBufferLength;
786 ptrW->dwBufferTotal= ptr->dwBufferTotal;
788 if (ptr->Next)
789 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
790 sizeof(INTERNET_BUFFERSW));
792 ptr = ptr->Next;
793 ptrW = ptrW->Next;
796 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
798 if (lpBuffersOutW)
800 ptrW = lpBuffersOutW;
801 while (ptrW)
803 LPINTERNET_BUFFERSW ptrW2;
805 FIXME("Do we need to translate info out of these buffer?\n");
807 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
808 ptrW2 = ptrW->Next;
809 HeapFree(GetProcessHeap(),0,ptrW);
810 ptrW = ptrW2;
814 return rc;
817 /***********************************************************************
818 * HttpEndRequestW (WININET.@)
820 * Ends an HTTP request that was started by HttpSendRequestEx
822 * RETURNS
823 * TRUE if successful
824 * FALSE on failure
827 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
828 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
830 BOOL rc = FALSE;
831 LPWININETHTTPREQW lpwhr;
832 INT responseLen;
833 DWORD dwBufferSize;
835 TRACE("-->\n");
836 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
838 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
840 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
841 if (lpwhr)
842 WININET_Release( &lpwhr->hdr );
843 return FALSE;
846 lpwhr->hdr.dwFlags |= dwFlags;
847 lpwhr->hdr.dwContext = dwContext;
849 /* We appear to do nothing with lpBuffersOut.. is that correct? */
851 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
852 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
854 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
855 if (responseLen)
856 rc = TRUE;
858 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
859 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
861 /* process cookies here. Is this right? */
862 HTTP_ProcessCookies(lpwhr);
864 dwBufferSize = sizeof(lpwhr->dwContentLength);
865 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
866 &lpwhr->dwContentLength,&dwBufferSize,NULL))
867 lpwhr->dwContentLength = -1;
869 if (lpwhr->dwContentLength == 0)
870 HTTP_FinishedReading(lpwhr);
872 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
874 DWORD dwCode,dwCodeLength=sizeof(DWORD);
875 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
876 (dwCode==302 || dwCode==301))
878 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
879 dwBufferSize=sizeof(szNewLocation);
880 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
882 /* redirects are always GETs */
883 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
884 lpwhr->lpszVerb = WININET_strdupW(szGET);
885 HTTP_DrainContent(lpwhr);
886 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
887 INTERNET_STATUS_REDIRECT, szNewLocation,
888 dwBufferSize);
889 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
890 if (rc)
891 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
896 WININET_Release( &lpwhr->hdr );
897 TRACE("%i <--\n",rc);
898 return rc;
901 /***********************************************************************
902 * HttpOpenRequestW (WININET.@)
904 * Open a HTTP request handle
906 * RETURNS
907 * HINTERNET a HTTP request handle on success
908 * NULL on failure
911 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
912 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
913 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
914 DWORD dwFlags, DWORD_PTR dwContext)
916 LPWININETHTTPSESSIONW lpwhs;
917 HINTERNET handle = NULL;
919 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
920 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
921 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
922 dwFlags, dwContext);
923 if(lpszAcceptTypes!=NULL)
925 int i;
926 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
927 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
930 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
931 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
933 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
934 goto lend;
938 * My tests seem to show that the windows version does not
939 * become asynchronous until after this point. And anyhow
940 * if this call was asynchronous then how would you get the
941 * necessary HINTERNET pointer returned by this function.
944 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
945 lpszVersion, lpszReferrer, lpszAcceptTypes,
946 dwFlags, dwContext);
947 lend:
948 if( lpwhs )
949 WININET_Release( &lpwhs->hdr );
950 TRACE("returning %p\n", handle);
951 return handle;
955 /***********************************************************************
956 * HttpOpenRequestA (WININET.@)
958 * Open a HTTP request handle
960 * RETURNS
961 * HINTERNET a HTTP request handle on success
962 * NULL on failure
965 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
966 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
967 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
968 DWORD dwFlags, DWORD_PTR dwContext)
970 LPWSTR szVerb = NULL, szObjectName = NULL;
971 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
972 INT len, acceptTypesCount;
973 HINTERNET rc = FALSE;
974 LPCSTR *types;
976 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
977 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
978 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
979 dwFlags, dwContext);
981 if (lpszVerb)
983 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
984 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
985 if ( !szVerb )
986 goto end;
987 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
990 if (lpszObjectName)
992 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
993 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
994 if ( !szObjectName )
995 goto end;
996 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
999 if (lpszVersion)
1001 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
1002 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1003 if ( !szVersion )
1004 goto end;
1005 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1008 if (lpszReferrer)
1010 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1011 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1012 if ( !szReferrer )
1013 goto end;
1014 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1017 if (lpszAcceptTypes)
1019 acceptTypesCount = 0;
1020 types = lpszAcceptTypes;
1021 while (*types)
1023 /* find out how many there are */
1024 if (((ULONG_PTR)*types >> 16) && **types)
1026 TRACE("accept type: %s\n", debugstr_a(*types));
1027 acceptTypesCount++;
1029 types++;
1031 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1032 if (!szAcceptTypes) goto end;
1034 acceptTypesCount = 0;
1035 types = lpszAcceptTypes;
1036 while (*types)
1038 if (((ULONG_PTR)*types >> 16) && **types)
1040 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1041 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1042 if (!szAcceptTypes[acceptTypesCount]) goto end;
1044 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1045 acceptTypesCount++;
1047 types++;
1049 szAcceptTypes[acceptTypesCount] = NULL;
1051 else szAcceptTypes = 0;
1053 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1054 szVersion, szReferrer,
1055 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1057 end:
1058 if (szAcceptTypes)
1060 acceptTypesCount = 0;
1061 while (szAcceptTypes[acceptTypesCount])
1063 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1064 acceptTypesCount++;
1066 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1068 HeapFree(GetProcessHeap(), 0, szReferrer);
1069 HeapFree(GetProcessHeap(), 0, szVersion);
1070 HeapFree(GetProcessHeap(), 0, szObjectName);
1071 HeapFree(GetProcessHeap(), 0, szVerb);
1073 return rc;
1076 /***********************************************************************
1077 * HTTP_EncodeBase64
1079 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1081 UINT n = 0, x;
1082 static const CHAR HTTP_Base64Enc[] =
1083 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1085 while( len > 0 )
1087 /* first 6 bits, all from bin[0] */
1088 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1089 x = (bin[0] & 3) << 4;
1091 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1092 if( len == 1 )
1094 base64[n++] = HTTP_Base64Enc[x];
1095 base64[n++] = '=';
1096 base64[n++] = '=';
1097 break;
1099 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1100 x = ( bin[1] & 0x0f ) << 2;
1102 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1103 if( len == 2 )
1105 base64[n++] = HTTP_Base64Enc[x];
1106 base64[n++] = '=';
1107 break;
1109 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1111 /* last 6 bits, all from bin [2] */
1112 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1113 bin += 3;
1114 len -= 3;
1116 base64[n] = 0;
1117 return n;
1120 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1121 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1122 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1123 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1124 static const signed char HTTP_Base64Dec[256] =
1126 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1127 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1128 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1129 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1130 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1131 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1132 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1133 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1134 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1135 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1136 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1137 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1138 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1139 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1140 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1141 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1142 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1143 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1144 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1145 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1146 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1147 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1148 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1149 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1150 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1151 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1153 #undef CH
1155 /***********************************************************************
1156 * HTTP_DecodeBase64
1158 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1160 unsigned int n = 0;
1162 while(*base64)
1164 signed char in[4];
1166 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1167 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1168 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1169 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1171 WARN("invalid base64: %s\n", debugstr_w(base64));
1172 return 0;
1174 if (bin)
1175 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1176 n++;
1178 if ((base64[2] == '=') && (base64[3] == '='))
1179 break;
1180 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1181 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1183 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1184 return 0;
1186 if (bin)
1187 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1188 n++;
1190 if (base64[3] == '=')
1191 break;
1192 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1193 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1195 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1196 return 0;
1198 if (bin)
1199 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1200 n++;
1202 base64 += 4;
1205 return n;
1208 /***********************************************************************
1209 * HTTP_InsertAuthorization
1211 * Insert or delete the authorization field in the request header.
1213 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1215 if (pAuthInfo)
1217 static const WCHAR wszSpace[] = {' ',0};
1218 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1219 unsigned int len;
1220 WCHAR *authorization = NULL;
1222 if (pAuthInfo->auth_data_len)
1224 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1225 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1226 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1227 if (!authorization)
1228 return FALSE;
1230 strcpyW(authorization, pAuthInfo->scheme);
1231 strcatW(authorization, wszSpace);
1232 HTTP_EncodeBase64(pAuthInfo->auth_data,
1233 pAuthInfo->auth_data_len,
1234 authorization+strlenW(authorization));
1236 /* clear the data as it isn't valid now that it has been sent to the
1237 * server, unless it's Basic authentication which doesn't do
1238 * connection tracking */
1239 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1241 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1242 pAuthInfo->auth_data = NULL;
1243 pAuthInfo->auth_data_len = 0;
1247 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1249 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1251 HeapFree(GetProcessHeap(), 0, authorization);
1253 return TRUE;
1256 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1258 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1259 DWORD size;
1261 size = sizeof(new_location);
1262 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1264 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1265 strcpyW( url, new_location );
1267 else
1269 static const WCHAR slash[] = { '/',0 };
1270 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1271 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1272 WININETHTTPSESSIONW *session = req->lpHttpSession;
1274 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1275 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1277 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1279 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1280 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1281 else
1282 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1283 if (req->lpszPath[0] != '/') strcatW( url, slash );
1284 strcatW( url, req->lpszPath );
1286 TRACE("url=%s\n", debugstr_w(url));
1287 return url;
1290 /***********************************************************************
1291 * HTTP_DealWithProxy
1293 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1294 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1296 WCHAR buf[MAXHOSTNAME];
1297 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1298 static WCHAR szNul[] = { 0 };
1299 URL_COMPONENTSW UrlComponents;
1300 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1301 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1303 memset( &UrlComponents, 0, sizeof UrlComponents );
1304 UrlComponents.dwStructSize = sizeof UrlComponents;
1305 UrlComponents.lpszHostName = buf;
1306 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1308 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1309 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1310 sprintfW(proxy, szFormat, hIC->lpszProxy);
1311 else
1312 strcpyW(proxy, hIC->lpszProxy);
1313 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1314 return FALSE;
1315 if( UrlComponents.dwHostNameLength == 0 )
1316 return FALSE;
1318 if( !lpwhr->lpszPath )
1319 lpwhr->lpszPath = szNul;
1321 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1322 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1324 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1325 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1326 lpwhs->nServerPort = UrlComponents.nPort;
1328 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1329 return TRUE;
1332 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1334 char szaddr[32];
1335 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1337 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1338 INTERNET_STATUS_RESOLVING_NAME,
1339 lpwhs->lpszServerName,
1340 strlenW(lpwhs->lpszServerName)+1);
1342 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1343 &lpwhs->socketAddress))
1345 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1346 return FALSE;
1349 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1350 szaddr, sizeof(szaddr));
1351 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1352 INTERNET_STATUS_NAME_RESOLVED,
1353 szaddr, strlen(szaddr)+1);
1355 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1356 return TRUE;
1360 /***********************************************************************
1361 * HTTPREQ_Destroy (internal)
1363 * Deallocate request handle
1366 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1368 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1369 DWORD i;
1371 TRACE("\n");
1373 if(lpwhr->hCacheFile)
1374 CloseHandle(lpwhr->hCacheFile);
1376 if(lpwhr->lpszCacheFile) {
1377 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1381 WININET_Release(&lpwhr->lpHttpSession->hdr);
1383 if (lpwhr->pAuthInfo)
1385 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1386 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1387 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1388 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1390 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1391 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1392 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1393 lpwhr->pAuthInfo = NULL;
1396 if (lpwhr->pProxyAuthInfo)
1398 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1399 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1400 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1401 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1403 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1404 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1405 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1406 lpwhr->pProxyAuthInfo = NULL;
1409 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1410 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1411 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1412 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1413 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1415 for (i = 0; i < lpwhr->nCustHeaders; i++)
1417 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1418 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1421 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1422 HeapFree(GetProcessHeap(), 0, lpwhr);
1425 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1427 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1429 TRACE("%p\n",lpwhr);
1431 if (!NETCON_connected(&lpwhr->netConnection))
1432 return;
1434 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1435 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1437 NETCON_close(&lpwhr->netConnection);
1439 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1440 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1443 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1445 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1447 switch(option) {
1448 case INTERNET_OPTION_HANDLE_TYPE:
1449 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1451 if (*size < sizeof(ULONG))
1452 return ERROR_INSUFFICIENT_BUFFER;
1454 *size = sizeof(DWORD);
1455 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1456 return ERROR_SUCCESS;
1458 case INTERNET_OPTION_URL: {
1459 WCHAR url[INTERNET_MAX_URL_LENGTH];
1460 HTTPHEADERW *host;
1461 DWORD len;
1462 WCHAR *pch;
1464 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1465 static const WCHAR hostW[] = {'H','o','s','t',0};
1467 TRACE("INTERNET_OPTION_URL\n");
1469 host = HTTP_GetHeader(req, hostW);
1470 strcpyW(url, httpW);
1471 strcatW(url, host->lpszValue);
1472 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1473 *pch = 0;
1474 strcatW(url, req->lpszPath);
1476 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1478 if(unicode) {
1479 len = (strlenW(url)+1) * sizeof(WCHAR);
1480 if(*size < len)
1481 return ERROR_INSUFFICIENT_BUFFER;
1483 *size = len;
1484 strcpyW(buffer, url);
1485 return ERROR_SUCCESS;
1486 }else {
1487 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1488 if(len > *size)
1489 return ERROR_INSUFFICIENT_BUFFER;
1491 *size = len;
1492 return ERROR_SUCCESS;
1496 case INTERNET_OPTION_DATAFILE_NAME: {
1497 DWORD req_size;
1499 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1501 if(!req->lpszCacheFile) {
1502 *size = 0;
1503 return ERROR_INTERNET_ITEM_NOT_FOUND;
1506 if(unicode) {
1507 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1508 if(*size < req_size)
1509 return ERROR_INSUFFICIENT_BUFFER;
1511 *size = req_size;
1512 memcpy(buffer, req->lpszCacheFile, *size);
1513 return ERROR_SUCCESS;
1514 }else {
1515 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1516 if (req_size > *size)
1517 return ERROR_INSUFFICIENT_BUFFER;
1519 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1520 -1, buffer, *size, NULL, NULL);
1521 return ERROR_SUCCESS;
1525 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1526 PCCERT_CONTEXT context;
1528 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1529 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1530 return ERROR_INSUFFICIENT_BUFFER;
1533 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1534 if(context) {
1535 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1536 DWORD len;
1538 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1539 info->ftExpiry = context->pCertInfo->NotAfter;
1540 info->ftStart = context->pCertInfo->NotBefore;
1541 if(unicode) {
1542 len = CertNameToStrW(context->dwCertEncodingType,
1543 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1544 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1545 if(info->lpszSubjectInfo)
1546 CertNameToStrW(context->dwCertEncodingType,
1547 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1548 info->lpszSubjectInfo, len);
1549 len = CertNameToStrW(context->dwCertEncodingType,
1550 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1551 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1552 if (info->lpszIssuerInfo)
1553 CertNameToStrW(context->dwCertEncodingType,
1554 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1555 info->lpszIssuerInfo, len);
1556 }else {
1557 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1559 len = CertNameToStrA(context->dwCertEncodingType,
1560 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1561 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1562 if(infoA->lpszSubjectInfo)
1563 CertNameToStrA(context->dwCertEncodingType,
1564 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1565 infoA->lpszSubjectInfo, len);
1566 len = CertNameToStrA(context->dwCertEncodingType,
1567 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1568 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1569 if(infoA->lpszIssuerInfo)
1570 CertNameToStrA(context->dwCertEncodingType,
1571 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1572 infoA->lpszIssuerInfo, len);
1576 * Contrary to MSDN, these do not appear to be set.
1577 * lpszProtocolName
1578 * lpszSignatureAlgName
1579 * lpszEncryptionAlgName
1580 * dwKeySize
1582 CertFreeCertificateContext(context);
1583 return ERROR_SUCCESS;
1588 return INET_QueryOption(option, buffer, size, unicode);
1591 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1593 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1595 switch(option) {
1596 case INTERNET_OPTION_SEND_TIMEOUT:
1597 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1598 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1600 if (size != sizeof(DWORD))
1601 return ERROR_INVALID_PARAMETER;
1603 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1604 *(DWORD*)buffer);
1607 return ERROR_INTERNET_INVALID_OPTION;
1610 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1612 int bytes_read;
1614 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1615 sync ? MSG_WAITALL : 0, &bytes_read)) {
1616 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1617 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1619 /* always return success, even if the network layer returns an error */
1620 *read = 0;
1621 HTTP_FinishedReading(req);
1622 return ERROR_SUCCESS;
1625 req->dwContentRead += bytes_read;
1626 *read = bytes_read;
1628 if(req->lpszCacheFile) {
1629 BOOL res;
1630 DWORD dwBytesWritten;
1632 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1633 if(!res)
1634 WARN("WriteFile failed: %u\n", GetLastError());
1637 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1638 HTTP_FinishedReading(req);
1640 return ERROR_SUCCESS;
1643 static DWORD get_chunk_size(const char *buffer)
1645 const char *p;
1646 DWORD size = 0;
1648 for (p = buffer; *p; p++)
1650 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1651 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1652 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1653 else if (*p == ';') break;
1655 return size;
1658 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1660 char reply[MAX_REPLY_LEN], *p = buffer;
1661 DWORD buflen, to_read, to_write = size;
1662 int bytes_read;
1664 *read = 0;
1665 for (;;)
1667 if (*read == size) break;
1669 if (req->dwContentLength == ~0UL) /* new chunk */
1671 buflen = sizeof(reply);
1672 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1674 if (!(req->dwContentLength = get_chunk_size(reply)))
1676 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1677 HTTP_GetResponseHeaders(req, FALSE);
1678 break;
1681 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1683 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1685 if (bytes_read != to_read)
1686 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1688 /* always return success, even if the network layer returns an error */
1689 *read = 0;
1690 break;
1692 if (!bytes_read) break;
1694 req->dwContentRead += bytes_read;
1695 to_write -= bytes_read;
1696 *read += bytes_read;
1698 if (req->lpszCacheFile)
1700 DWORD dwBytesWritten;
1702 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1703 WARN("WriteFile failed: %u\n", GetLastError());
1705 p += bytes_read;
1707 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1709 req->dwContentRead = 0;
1710 req->dwContentLength = ~0UL;
1712 buflen = sizeof(reply);
1713 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1715 ERR("Malformed chunk\n");
1716 *read = 0;
1717 break;
1721 if (!*read) HTTP_FinishedReading(req);
1722 return ERROR_SUCCESS;
1725 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1727 WCHAR encoding[20];
1728 DWORD buflen = sizeof(encoding);
1729 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1731 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1732 !strcmpiW(encoding, szChunked))
1734 return HTTP_ReadChunked(req, buffer, size, read, sync);
1736 else
1737 return HTTP_Read(req, buffer, size, read, sync);
1740 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1742 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1743 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1746 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1748 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1749 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1750 INTERNET_ASYNC_RESULT iar;
1751 DWORD res;
1753 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1755 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1756 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1758 iar.dwResult = res == ERROR_SUCCESS;
1759 iar.dwError = res;
1761 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1762 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1763 sizeof(INTERNET_ASYNC_RESULT));
1766 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1767 DWORD flags, DWORD_PTR context)
1770 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1771 DWORD res;
1773 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1774 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1776 if (buffers->dwStructSize != sizeof(*buffers))
1777 return ERROR_INVALID_PARAMETER;
1779 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1781 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1782 DWORD available = 0;
1784 NETCON_query_data_available(&req->netConnection, &available);
1785 if (!available)
1787 WORKREQUEST workRequest;
1789 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1790 workRequest.hdr = WININET_AddRef(&req->hdr);
1791 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1793 INTERNET_AsyncCall(&workRequest);
1795 return ERROR_IO_PENDING;
1799 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1800 !(flags & IRF_NO_WAIT));
1802 if (res == ERROR_SUCCESS) {
1803 DWORD size = buffers->dwBufferLength;
1804 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1805 &size, sizeof(size));
1808 return res;
1811 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1813 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1815 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1818 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1820 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1821 INTERNET_ASYNC_RESULT iar;
1822 char buffer[4048];
1824 TRACE("%p\n", workRequest->hdr);
1826 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1827 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1828 MSG_PEEK, (int *)&iar.dwError);
1830 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1831 sizeof(INTERNET_ASYNC_RESULT));
1834 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1836 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1837 BYTE buffer[4048];
1838 BOOL async;
1840 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1842 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1843 return ERROR_SUCCESS;
1845 /* Even if we are in async mode, we need to determine whether
1846 * there is actually more data available. We do this by trying
1847 * to peek only a single byte in async mode. */
1848 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1850 if (NETCON_recv(&req->netConnection, buffer,
1851 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1852 MSG_PEEK, (int *)available) && async && *available)
1854 WORKREQUEST workRequest;
1856 *available = 0;
1857 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1858 workRequest.hdr = WININET_AddRef( &req->hdr );
1860 INTERNET_AsyncCall(&workRequest);
1862 return ERROR_IO_PENDING;
1865 return ERROR_SUCCESS;
1868 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1869 HTTPREQ_Destroy,
1870 HTTPREQ_CloseConnection,
1871 HTTPREQ_QueryOption,
1872 HTTPREQ_SetOption,
1873 HTTPREQ_ReadFile,
1874 HTTPREQ_ReadFileExA,
1875 HTTPREQ_WriteFile,
1876 HTTPREQ_QueryDataAvailable,
1877 NULL
1880 /***********************************************************************
1881 * HTTP_HttpOpenRequestW (internal)
1883 * Open a HTTP request handle
1885 * RETURNS
1886 * HINTERNET a HTTP request handle on success
1887 * NULL on failure
1890 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1891 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1892 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1893 DWORD dwFlags, DWORD_PTR dwContext)
1895 LPWININETAPPINFOW hIC = NULL;
1896 LPWININETHTTPREQW lpwhr;
1897 LPWSTR lpszHostName = NULL;
1898 HINTERNET handle = NULL;
1899 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1900 DWORD len;
1902 TRACE("-->\n");
1904 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1905 hIC = lpwhs->lpAppInfo;
1907 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1908 if (NULL == lpwhr)
1910 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1911 goto lend;
1913 lpwhr->hdr.htype = WH_HHTTPREQ;
1914 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1915 lpwhr->hdr.dwFlags = dwFlags;
1916 lpwhr->hdr.dwContext = dwContext;
1917 lpwhr->hdr.refs = 1;
1918 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1919 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1921 WININET_AddRef( &lpwhs->hdr );
1922 lpwhr->lpHttpSession = lpwhs;
1923 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1925 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1926 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1927 if (NULL == lpszHostName)
1929 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1930 goto lend;
1933 handle = WININET_AllocHandle( &lpwhr->hdr );
1934 if (NULL == handle)
1936 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1937 goto lend;
1940 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1942 InternetCloseHandle( handle );
1943 handle = NULL;
1944 goto lend;
1947 if (lpszObjectName && *lpszObjectName) {
1948 HRESULT rc;
1950 len = 0;
1951 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1952 if (rc != E_POINTER)
1953 len = strlenW(lpszObjectName)+1;
1954 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1955 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1956 URL_ESCAPE_SPACES_ONLY);
1957 if (rc != S_OK)
1959 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1960 strcpyW(lpwhr->lpszPath,lpszObjectName);
1964 if (lpszReferrer && *lpszReferrer)
1965 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1967 if (lpszAcceptTypes)
1969 int i;
1970 for (i = 0; lpszAcceptTypes[i]; i++)
1972 if (!*lpszAcceptTypes[i]) continue;
1973 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1974 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1975 HTTP_ADDHDR_FLAG_REQ |
1976 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1980 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1982 if (lpszVersion)
1983 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1984 else
1985 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1987 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
1988 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
1989 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
1991 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
1992 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
1993 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1995 else
1996 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
1997 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1999 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2000 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2001 INTERNET_DEFAULT_HTTPS_PORT :
2002 INTERNET_DEFAULT_HTTP_PORT);
2004 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2005 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2006 INTERNET_DEFAULT_HTTPS_PORT :
2007 INTERNET_DEFAULT_HTTP_PORT);
2009 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2010 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2012 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2013 INTERNET_STATUS_HANDLE_CREATED, &handle,
2014 sizeof(handle));
2016 lend:
2017 HeapFree(GetProcessHeap(), 0, lpszHostName);
2018 if( lpwhr )
2019 WININET_Release( &lpwhr->hdr );
2021 TRACE("<-- %p (%p)\n", handle, lpwhr);
2022 return handle;
2025 /* read any content returned by the server so that the connection can be
2026 * reused */
2027 static void HTTP_DrainContent(WININETHTTPREQW *req)
2029 DWORD bytes_read;
2031 if (!NETCON_connected(&req->netConnection)) return;
2033 if (req->dwContentLength == -1)
2034 NETCON_close(&req->netConnection);
2038 char buffer[2048];
2039 if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2040 return;
2041 } while (bytes_read);
2044 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2045 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2046 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2047 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2048 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2049 static const WCHAR szAge[] = { 'A','g','e',0 };
2050 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2051 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2052 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2053 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2054 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2055 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2056 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2057 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2058 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2059 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2060 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2061 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 };
2062 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2063 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2064 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2065 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2066 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2067 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2068 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2069 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2070 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2071 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2072 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2073 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2074 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2075 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2076 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2077 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2078 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2079 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2080 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2081 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2082 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2083 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2084 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2085 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2086 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2087 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2088 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 };
2089 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2090 static const WCHAR szURI[] = { 'U','R','I',0 };
2091 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2092 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2093 static const WCHAR szVia[] = { 'V','i','a',0 };
2094 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2095 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2097 static const LPCWSTR header_lookup[] = {
2098 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2099 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2100 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2101 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2102 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2103 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2104 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2105 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2106 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2107 szDate, /* HTTP_QUERY_DATE = 9 */
2108 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2109 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2110 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2111 szURI, /* HTTP_QUERY_URI = 13 */
2112 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2113 NULL, /* HTTP_QUERY_COST = 15 */
2114 NULL, /* HTTP_QUERY_LINK = 16 */
2115 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2116 NULL, /* HTTP_QUERY_VERSION = 18 */
2117 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2118 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2119 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2120 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2121 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2122 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2123 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2124 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2125 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2126 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2127 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2128 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2129 NULL, /* HTTP_QUERY_FROM = 31 */
2130 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2131 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2132 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2133 szReferer, /* HTTP_QUERY_REFERER = 35 */
2134 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2135 szServer, /* HTTP_QUERY_SERVER = 37 */
2136 NULL, /* HTTP_TITLE = 38 */
2137 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2138 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2139 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2140 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2141 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2142 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2143 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2144 NULL, /* HTTP_QUERY_REFRESH = 46 */
2145 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2146 szAge, /* HTTP_QUERY_AGE = 48 */
2147 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2148 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2149 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2150 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2151 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2152 szETag, /* HTTP_QUERY_ETAG = 54 */
2153 szHost, /* HTTP_QUERY_HOST = 55 */
2154 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2155 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2156 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2157 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2158 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2159 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2160 szRange, /* HTTP_QUERY_RANGE = 62 */
2161 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2162 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2163 szVary, /* HTTP_QUERY_VARY = 65 */
2164 szVia, /* HTTP_QUERY_VIA = 66 */
2165 szWarning, /* HTTP_QUERY_WARNING = 67 */
2166 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2167 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2168 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2171 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2173 /***********************************************************************
2174 * HTTP_HttpQueryInfoW (internal)
2176 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2177 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2179 LPHTTPHEADERW lphttpHdr = NULL;
2180 BOOL bSuccess = FALSE;
2181 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2182 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2183 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2184 INT index = -1;
2186 /* Find requested header structure */
2187 switch (level)
2189 case HTTP_QUERY_CUSTOM:
2190 if (!lpBuffer) return FALSE;
2191 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2192 break;
2194 case HTTP_QUERY_RAW_HEADERS_CRLF:
2196 LPWSTR headers;
2197 DWORD len = 0;
2198 BOOL ret = FALSE;
2200 if (request_only)
2201 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2202 else
2203 headers = lpwhr->lpszRawHeaders;
2205 if (headers)
2206 len = strlenW(headers) * sizeof(WCHAR);
2208 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2210 len += sizeof(WCHAR);
2211 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2212 ret = FALSE;
2214 else if (lpBuffer)
2216 if (headers)
2217 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2218 else
2220 len = strlenW(szCrLf) * sizeof(WCHAR);
2221 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2223 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2224 ret = TRUE;
2226 *lpdwBufferLength = len;
2228 if (request_only)
2229 HeapFree(GetProcessHeap(), 0, headers);
2230 return ret;
2232 case HTTP_QUERY_RAW_HEADERS:
2234 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2235 DWORD i, size = 0;
2236 LPWSTR pszString = lpBuffer;
2238 for (i = 0; ppszRawHeaderLines[i]; i++)
2239 size += strlenW(ppszRawHeaderLines[i]) + 1;
2241 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2243 HTTP_FreeTokens(ppszRawHeaderLines);
2244 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2245 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2246 return FALSE;
2248 if (pszString)
2250 for (i = 0; ppszRawHeaderLines[i]; i++)
2252 DWORD len = strlenW(ppszRawHeaderLines[i]);
2253 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2254 pszString += len+1;
2256 *pszString = '\0';
2257 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2259 *lpdwBufferLength = size * sizeof(WCHAR);
2260 HTTP_FreeTokens(ppszRawHeaderLines);
2262 return TRUE;
2264 case HTTP_QUERY_STATUS_TEXT:
2265 if (lpwhr->lpszStatusText)
2267 DWORD len = strlenW(lpwhr->lpszStatusText);
2268 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2270 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2271 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2272 return FALSE;
2274 if (lpBuffer)
2276 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2277 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2279 *lpdwBufferLength = len * sizeof(WCHAR);
2280 return TRUE;
2282 break;
2283 case HTTP_QUERY_VERSION:
2284 if (lpwhr->lpszVersion)
2286 DWORD len = strlenW(lpwhr->lpszVersion);
2287 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2289 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2290 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2291 return FALSE;
2293 if (lpBuffer)
2295 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2296 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2298 *lpdwBufferLength = len * sizeof(WCHAR);
2299 return TRUE;
2301 break;
2302 default:
2303 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2305 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2306 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2307 requested_index,request_only);
2310 if (index >= 0)
2311 lphttpHdr = &lpwhr->pCustHeaders[index];
2313 /* Ensure header satisfies requested attributes */
2314 if (!lphttpHdr ||
2315 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2316 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2318 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2319 return bSuccess;
2322 if (lpdwIndex)
2323 (*lpdwIndex)++;
2325 /* coalesce value to requested type */
2326 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2328 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2329 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2330 bSuccess = TRUE;
2332 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2334 time_t tmpTime;
2335 struct tm tmpTM;
2336 SYSTEMTIME *STHook;
2338 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2340 tmpTM = *gmtime(&tmpTime);
2341 STHook = (SYSTEMTIME *)lpBuffer;
2342 if (!STHook) return bSuccess;
2344 STHook->wDay = tmpTM.tm_mday;
2345 STHook->wHour = tmpTM.tm_hour;
2346 STHook->wMilliseconds = 0;
2347 STHook->wMinute = tmpTM.tm_min;
2348 STHook->wDayOfWeek = tmpTM.tm_wday;
2349 STHook->wMonth = tmpTM.tm_mon + 1;
2350 STHook->wSecond = tmpTM.tm_sec;
2351 STHook->wYear = tmpTM.tm_year;
2352 bSuccess = TRUE;
2354 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2355 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2356 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2358 else if (lphttpHdr->lpszValue)
2360 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2362 if (len > *lpdwBufferLength)
2364 *lpdwBufferLength = len;
2365 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2366 return bSuccess;
2368 if (lpBuffer)
2370 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2371 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2373 *lpdwBufferLength = len - sizeof(WCHAR);
2374 bSuccess = TRUE;
2376 return bSuccess;
2379 /***********************************************************************
2380 * HttpQueryInfoW (WININET.@)
2382 * Queries for information about an HTTP request
2384 * RETURNS
2385 * TRUE on success
2386 * FALSE on failure
2389 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2390 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2392 BOOL bSuccess = FALSE;
2393 LPWININETHTTPREQW lpwhr;
2395 if (TRACE_ON(wininet)) {
2396 #define FE(x) { x, #x }
2397 static const wininet_flag_info query_flags[] = {
2398 FE(HTTP_QUERY_MIME_VERSION),
2399 FE(HTTP_QUERY_CONTENT_TYPE),
2400 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2401 FE(HTTP_QUERY_CONTENT_ID),
2402 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2403 FE(HTTP_QUERY_CONTENT_LENGTH),
2404 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2405 FE(HTTP_QUERY_ALLOW),
2406 FE(HTTP_QUERY_PUBLIC),
2407 FE(HTTP_QUERY_DATE),
2408 FE(HTTP_QUERY_EXPIRES),
2409 FE(HTTP_QUERY_LAST_MODIFIED),
2410 FE(HTTP_QUERY_MESSAGE_ID),
2411 FE(HTTP_QUERY_URI),
2412 FE(HTTP_QUERY_DERIVED_FROM),
2413 FE(HTTP_QUERY_COST),
2414 FE(HTTP_QUERY_LINK),
2415 FE(HTTP_QUERY_PRAGMA),
2416 FE(HTTP_QUERY_VERSION),
2417 FE(HTTP_QUERY_STATUS_CODE),
2418 FE(HTTP_QUERY_STATUS_TEXT),
2419 FE(HTTP_QUERY_RAW_HEADERS),
2420 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2421 FE(HTTP_QUERY_CONNECTION),
2422 FE(HTTP_QUERY_ACCEPT),
2423 FE(HTTP_QUERY_ACCEPT_CHARSET),
2424 FE(HTTP_QUERY_ACCEPT_ENCODING),
2425 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2426 FE(HTTP_QUERY_AUTHORIZATION),
2427 FE(HTTP_QUERY_CONTENT_ENCODING),
2428 FE(HTTP_QUERY_FORWARDED),
2429 FE(HTTP_QUERY_FROM),
2430 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2431 FE(HTTP_QUERY_LOCATION),
2432 FE(HTTP_QUERY_ORIG_URI),
2433 FE(HTTP_QUERY_REFERER),
2434 FE(HTTP_QUERY_RETRY_AFTER),
2435 FE(HTTP_QUERY_SERVER),
2436 FE(HTTP_QUERY_TITLE),
2437 FE(HTTP_QUERY_USER_AGENT),
2438 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2439 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2440 FE(HTTP_QUERY_ACCEPT_RANGES),
2441 FE(HTTP_QUERY_SET_COOKIE),
2442 FE(HTTP_QUERY_COOKIE),
2443 FE(HTTP_QUERY_REQUEST_METHOD),
2444 FE(HTTP_QUERY_REFRESH),
2445 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2446 FE(HTTP_QUERY_AGE),
2447 FE(HTTP_QUERY_CACHE_CONTROL),
2448 FE(HTTP_QUERY_CONTENT_BASE),
2449 FE(HTTP_QUERY_CONTENT_LOCATION),
2450 FE(HTTP_QUERY_CONTENT_MD5),
2451 FE(HTTP_QUERY_CONTENT_RANGE),
2452 FE(HTTP_QUERY_ETAG),
2453 FE(HTTP_QUERY_HOST),
2454 FE(HTTP_QUERY_IF_MATCH),
2455 FE(HTTP_QUERY_IF_NONE_MATCH),
2456 FE(HTTP_QUERY_IF_RANGE),
2457 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2458 FE(HTTP_QUERY_MAX_FORWARDS),
2459 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2460 FE(HTTP_QUERY_RANGE),
2461 FE(HTTP_QUERY_TRANSFER_ENCODING),
2462 FE(HTTP_QUERY_UPGRADE),
2463 FE(HTTP_QUERY_VARY),
2464 FE(HTTP_QUERY_VIA),
2465 FE(HTTP_QUERY_WARNING),
2466 FE(HTTP_QUERY_CUSTOM)
2468 static const wininet_flag_info modifier_flags[] = {
2469 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2470 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2471 FE(HTTP_QUERY_FLAG_NUMBER),
2472 FE(HTTP_QUERY_FLAG_COALESCE)
2474 #undef FE
2475 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2476 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2477 DWORD i;
2479 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2480 TRACE(" Attribute:");
2481 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2482 if (query_flags[i].val == info) {
2483 TRACE(" %s", query_flags[i].name);
2484 break;
2487 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2488 TRACE(" Unknown (%08x)", info);
2491 TRACE(" Modifier:");
2492 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2493 if (modifier_flags[i].val & info_mod) {
2494 TRACE(" %s", modifier_flags[i].name);
2495 info_mod &= ~ modifier_flags[i].val;
2499 if (info_mod) {
2500 TRACE(" Unknown (%08x)", info_mod);
2502 TRACE("\n");
2505 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2506 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2508 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2509 goto lend;
2512 if (lpBuffer == NULL)
2513 *lpdwBufferLength = 0;
2514 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2515 lpBuffer, lpdwBufferLength, lpdwIndex);
2517 lend:
2518 if( lpwhr )
2519 WININET_Release( &lpwhr->hdr );
2521 TRACE("%d <--\n", bSuccess);
2522 return bSuccess;
2525 /***********************************************************************
2526 * HttpQueryInfoA (WININET.@)
2528 * Queries for information about an HTTP request
2530 * RETURNS
2531 * TRUE on success
2532 * FALSE on failure
2535 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2536 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2538 BOOL result;
2539 DWORD len;
2540 WCHAR* bufferW;
2542 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2543 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2545 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2546 lpdwBufferLength, lpdwIndex );
2549 if (lpBuffer)
2551 DWORD alloclen;
2552 len = (*lpdwBufferLength)*sizeof(WCHAR);
2553 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2555 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2556 if (alloclen < len)
2557 alloclen = len;
2559 else
2560 alloclen = len;
2561 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2562 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2563 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2564 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2565 } else
2567 bufferW = NULL;
2568 len = 0;
2571 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2572 &len, lpdwIndex );
2573 if( result )
2575 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2576 lpBuffer, *lpdwBufferLength, NULL, NULL );
2577 *lpdwBufferLength = len - 1;
2579 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2581 else
2582 /* since the strings being returned from HttpQueryInfoW should be
2583 * only ASCII characters, it is reasonable to assume that all of
2584 * the Unicode characters can be reduced to a single byte */
2585 *lpdwBufferLength = len / sizeof(WCHAR);
2587 HeapFree(GetProcessHeap(), 0, bufferW );
2589 return result;
2592 /***********************************************************************
2593 * HttpSendRequestExA (WININET.@)
2595 * Sends the specified request to the HTTP server and allows chunked
2596 * transfers.
2598 * RETURNS
2599 * Success: TRUE
2600 * Failure: FALSE, call GetLastError() for more information.
2602 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2603 LPINTERNET_BUFFERSA lpBuffersIn,
2604 LPINTERNET_BUFFERSA lpBuffersOut,
2605 DWORD dwFlags, DWORD_PTR dwContext)
2607 INTERNET_BUFFERSW BuffersInW;
2608 BOOL rc = FALSE;
2609 DWORD headerlen;
2610 LPWSTR header = NULL;
2612 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2613 lpBuffersOut, dwFlags, dwContext);
2615 if (lpBuffersIn)
2617 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2618 if (lpBuffersIn->lpcszHeader)
2620 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2621 lpBuffersIn->dwHeadersLength,0,0);
2622 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2623 if (!(BuffersInW.lpcszHeader = header))
2625 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2626 return FALSE;
2628 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2629 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2630 header, headerlen);
2632 else
2633 BuffersInW.lpcszHeader = NULL;
2634 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2635 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2636 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2637 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2638 BuffersInW.Next = NULL;
2641 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2643 HeapFree(GetProcessHeap(),0,header);
2645 return rc;
2648 /***********************************************************************
2649 * HttpSendRequestExW (WININET.@)
2651 * Sends the specified request to the HTTP server and allows chunked
2652 * transfers
2654 * RETURNS
2655 * Success: TRUE
2656 * Failure: FALSE, call GetLastError() for more information.
2658 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2659 LPINTERNET_BUFFERSW lpBuffersIn,
2660 LPINTERNET_BUFFERSW lpBuffersOut,
2661 DWORD dwFlags, DWORD_PTR dwContext)
2663 BOOL ret = FALSE;
2664 LPWININETHTTPREQW lpwhr;
2665 LPWININETHTTPSESSIONW lpwhs;
2666 LPWININETAPPINFOW hIC;
2668 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2669 lpBuffersOut, dwFlags, dwContext);
2671 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2673 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2675 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2676 goto lend;
2679 lpwhs = lpwhr->lpHttpSession;
2680 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2681 hIC = lpwhs->lpAppInfo;
2682 assert(hIC->hdr.htype == WH_HINIT);
2684 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2686 WORKREQUEST workRequest;
2687 struct WORKREQ_HTTPSENDREQUESTW *req;
2689 workRequest.asyncproc = AsyncHttpSendRequestProc;
2690 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2691 req = &workRequest.u.HttpSendRequestW;
2692 if (lpBuffersIn)
2694 if (lpBuffersIn->lpcszHeader)
2695 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2696 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2697 else
2698 req->lpszHeader = NULL;
2699 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2700 req->lpOptional = lpBuffersIn->lpvBuffer;
2701 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2702 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2704 else
2706 req->lpszHeader = NULL;
2707 req->dwHeaderLength = 0;
2708 req->lpOptional = NULL;
2709 req->dwOptionalLength = 0;
2710 req->dwContentLength = 0;
2713 req->bEndRequest = FALSE;
2715 INTERNET_AsyncCall(&workRequest);
2717 * This is from windows.
2719 INTERNET_SetLastError(ERROR_IO_PENDING);
2721 else
2723 if (lpBuffersIn)
2724 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2725 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2726 lpBuffersIn->dwBufferTotal, FALSE);
2727 else
2728 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2731 lend:
2732 if ( lpwhr )
2733 WININET_Release( &lpwhr->hdr );
2735 TRACE("<---\n");
2736 return ret;
2739 /***********************************************************************
2740 * HttpSendRequestW (WININET.@)
2742 * Sends the specified request to the HTTP server
2744 * RETURNS
2745 * TRUE on success
2746 * FALSE on failure
2749 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2750 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2752 LPWININETHTTPREQW lpwhr;
2753 LPWININETHTTPSESSIONW lpwhs = NULL;
2754 LPWININETAPPINFOW hIC = NULL;
2755 BOOL r;
2757 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2758 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2760 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2761 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2763 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2764 r = FALSE;
2765 goto lend;
2768 lpwhs = lpwhr->lpHttpSession;
2769 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2771 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2772 r = FALSE;
2773 goto lend;
2776 hIC = lpwhs->lpAppInfo;
2777 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2779 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2780 r = FALSE;
2781 goto lend;
2784 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2786 WORKREQUEST workRequest;
2787 struct WORKREQ_HTTPSENDREQUESTW *req;
2789 workRequest.asyncproc = AsyncHttpSendRequestProc;
2790 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2791 req = &workRequest.u.HttpSendRequestW;
2792 if (lpszHeaders)
2794 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2795 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2797 else
2798 req->lpszHeader = 0;
2799 req->dwHeaderLength = dwHeaderLength;
2800 req->lpOptional = lpOptional;
2801 req->dwOptionalLength = dwOptionalLength;
2802 req->dwContentLength = dwOptionalLength;
2803 req->bEndRequest = TRUE;
2805 INTERNET_AsyncCall(&workRequest);
2807 * This is from windows.
2809 INTERNET_SetLastError(ERROR_IO_PENDING);
2810 r = FALSE;
2812 else
2814 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2815 dwHeaderLength, lpOptional, dwOptionalLength,
2816 dwOptionalLength, TRUE);
2818 lend:
2819 if( lpwhr )
2820 WININET_Release( &lpwhr->hdr );
2821 return r;
2824 /***********************************************************************
2825 * HttpSendRequestA (WININET.@)
2827 * Sends the specified request to the HTTP server
2829 * RETURNS
2830 * TRUE on success
2831 * FALSE on failure
2834 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2835 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2837 BOOL result;
2838 LPWSTR szHeaders=NULL;
2839 DWORD nLen=dwHeaderLength;
2840 if(lpszHeaders!=NULL)
2842 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2843 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2844 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2846 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2847 HeapFree(GetProcessHeap(),0,szHeaders);
2848 return result;
2851 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2853 LPHTTPHEADERW host_header;
2855 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2857 host_header = HTTP_GetHeader(req, szHost);
2858 if(!host_header)
2859 return FALSE;
2861 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2862 return TRUE;
2865 /***********************************************************************
2866 * HTTP_HandleRedirect (internal)
2868 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2870 static const WCHAR szContentType[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
2871 static const WCHAR szContentLength[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
2872 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2873 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2874 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2875 WCHAR path[INTERNET_MAX_URL_LENGTH];
2876 int index;
2878 if(lpszUrl[0]=='/')
2880 /* if it's an absolute path, keep the same session info */
2881 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2883 else
2885 URL_COMPONENTSW urlComponents;
2886 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2887 static WCHAR szHttp[] = {'h','t','t','p',0};
2888 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2889 DWORD url_length = 0;
2890 LPWSTR orig_url;
2891 LPWSTR combined_url;
2893 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2894 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2895 urlComponents.dwSchemeLength = 0;
2896 urlComponents.lpszHostName = lpwhs->lpszHostName;
2897 urlComponents.dwHostNameLength = 0;
2898 urlComponents.nPort = lpwhs->nHostPort;
2899 urlComponents.lpszUserName = lpwhs->lpszUserName;
2900 urlComponents.dwUserNameLength = 0;
2901 urlComponents.lpszPassword = NULL;
2902 urlComponents.dwPasswordLength = 0;
2903 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2904 urlComponents.dwUrlPathLength = 0;
2905 urlComponents.lpszExtraInfo = NULL;
2906 urlComponents.dwExtraInfoLength = 0;
2908 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2909 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2910 return FALSE;
2912 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2914 /* convert from bytes to characters */
2915 url_length = url_length / sizeof(WCHAR) - 1;
2916 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2918 HeapFree(GetProcessHeap(), 0, orig_url);
2919 return FALSE;
2922 url_length = 0;
2923 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2924 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2926 HeapFree(GetProcessHeap(), 0, orig_url);
2927 return FALSE;
2929 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2931 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2933 HeapFree(GetProcessHeap(), 0, orig_url);
2934 HeapFree(GetProcessHeap(), 0, combined_url);
2935 return FALSE;
2937 HeapFree(GetProcessHeap(), 0, orig_url);
2939 userName[0] = 0;
2940 hostName[0] = 0;
2941 protocol[0] = 0;
2943 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2944 urlComponents.lpszScheme = protocol;
2945 urlComponents.dwSchemeLength = 32;
2946 urlComponents.lpszHostName = hostName;
2947 urlComponents.dwHostNameLength = MAXHOSTNAME;
2948 urlComponents.lpszUserName = userName;
2949 urlComponents.dwUserNameLength = 1024;
2950 urlComponents.lpszPassword = NULL;
2951 urlComponents.dwPasswordLength = 0;
2952 urlComponents.lpszUrlPath = path;
2953 urlComponents.dwUrlPathLength = 2048;
2954 urlComponents.lpszExtraInfo = NULL;
2955 urlComponents.dwExtraInfoLength = 0;
2956 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2958 HeapFree(GetProcessHeap(), 0, combined_url);
2959 return FALSE;
2962 HeapFree(GetProcessHeap(), 0, combined_url);
2964 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2965 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2967 TRACE("redirect from secure page to non-secure page\n");
2968 /* FIXME: warn about from secure redirect to non-secure page */
2969 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2971 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2972 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2974 TRACE("redirect from non-secure page to secure page\n");
2975 /* FIXME: notify about redirect to secure page */
2976 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2979 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2981 if (lstrlenW(protocol)>4) /*https*/
2982 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2983 else /*http*/
2984 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2987 #if 0
2989 * This upsets redirects to binary files on sourceforge.net
2990 * and gives an html page instead of the target file
2991 * Examination of the HTTP request sent by native wininet.dll
2992 * reveals that it doesn't send a referrer in that case.
2993 * Maybe there's a flag that enables this, or maybe a referrer
2994 * shouldn't be added in case of a redirect.
2997 /* consider the current host as the referrer */
2998 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2999 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3000 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3001 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3002 #endif
3004 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3005 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3006 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3008 int len;
3009 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3010 len = lstrlenW(hostName);
3011 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3012 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3013 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3015 else
3016 lpwhs->lpszHostName = WININET_strdupW(hostName);
3018 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3020 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3021 lpwhs->lpszUserName = NULL;
3022 if (userName[0])
3023 lpwhs->lpszUserName = WININET_strdupW(userName);
3025 if (!using_proxy)
3027 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3029 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3030 lpwhs->lpszServerName = WININET_strdupW(hostName);
3031 lpwhs->nServerPort = urlComponents.nPort;
3033 NETCON_close(&lpwhr->netConnection);
3034 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3035 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3038 else
3039 TRACE("Redirect through proxy\n");
3042 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3043 lpwhr->lpszPath=NULL;
3044 if (*path)
3046 DWORD needed = 0;
3047 HRESULT rc;
3049 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3050 if (rc != E_POINTER)
3051 needed = strlenW(path)+1;
3052 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3053 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3054 URL_ESCAPE_SPACES_ONLY);
3055 if (rc != S_OK)
3057 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3058 strcpyW(lpwhr->lpszPath,path);
3062 /* Remove custom content-type/length headers on redirects. */
3063 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentType, 0, TRUE);
3064 if (0 <= index)
3065 HTTP_DeleteCustomHeader(lpwhr, index);
3066 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentLength, 0, TRUE);
3067 if (0 <= index)
3068 HTTP_DeleteCustomHeader(lpwhr, index);
3070 return TRUE;
3073 /***********************************************************************
3074 * HTTP_build_req (internal)
3076 * concatenate all the strings in the request together
3078 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3080 LPCWSTR *t;
3081 LPWSTR str;
3083 for( t = list; *t ; t++ )
3084 len += strlenW( *t );
3085 len++;
3087 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3088 *str = 0;
3090 for( t = list; *t ; t++ )
3091 strcatW( str, *t );
3093 return str;
3096 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3098 LPWSTR lpszPath;
3099 LPWSTR requestString;
3100 INT len;
3101 INT cnt;
3102 INT responseLen;
3103 char *ascii_req;
3104 BOOL ret;
3105 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3106 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3107 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3109 TRACE("\n");
3111 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3112 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3113 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3114 HeapFree( GetProcessHeap(), 0, lpszPath );
3116 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3117 NULL, 0, NULL, NULL );
3118 len--; /* the nul terminator isn't needed */
3119 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3120 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3121 ascii_req, len, NULL, NULL );
3122 HeapFree( GetProcessHeap(), 0, requestString );
3124 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3126 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3127 HeapFree( GetProcessHeap(), 0, ascii_req );
3128 if (!ret || cnt < 0)
3129 return FALSE;
3131 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3132 if (!responseLen)
3133 return FALSE;
3135 return TRUE;
3138 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3140 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
3141 LPWSTR lpszCookies, lpszUrl = NULL;
3142 DWORD nCookieSize, size;
3143 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3145 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm)) * sizeof(WCHAR);
3146 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3147 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
3149 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3151 int cnt = 0;
3152 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3154 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3155 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3157 cnt += sprintfW(lpszCookies, szCookie);
3158 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3159 strcatW(lpszCookies, szCrLf);
3161 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3162 HeapFree(GetProcessHeap(), 0, lpszCookies);
3165 HeapFree(GetProcessHeap(), 0, lpszUrl);
3168 /***********************************************************************
3169 * HTTP_HttpSendRequestW (internal)
3171 * Sends the specified request to the HTTP server
3173 * RETURNS
3174 * TRUE on success
3175 * FALSE on failure
3178 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3179 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3180 DWORD dwContentLength, BOOL bEndRequest)
3182 INT cnt;
3183 BOOL bSuccess = FALSE;
3184 LPWSTR requestString = NULL;
3185 INT responseLen;
3186 BOOL loop_next;
3187 INTERNET_ASYNC_RESULT iar;
3188 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3189 static const WCHAR szContentLength[] =
3190 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3191 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3193 TRACE("--> %p\n", lpwhr);
3195 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3197 /* if the verb is NULL default to GET */
3198 if (!lpwhr->lpszVerb)
3199 lpwhr->lpszVerb = WININET_strdupW(szGET);
3201 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3203 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3204 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3206 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3208 WCHAR *agent_header;
3209 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3210 int len;
3212 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3213 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3214 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3216 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3217 HeapFree(GetProcessHeap(), 0, agent_header);
3219 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3221 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3222 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3224 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3226 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3227 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3228 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3233 DWORD len;
3234 char *ascii_req;
3236 loop_next = FALSE;
3238 /* like native, just in case the caller forgot to call InternetReadFile
3239 * for all the data */
3240 HTTP_DrainContent(lpwhr);
3241 lpwhr->dwContentRead = 0;
3243 if (TRACE_ON(wininet))
3245 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3246 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3249 HTTP_FixURL(lpwhr);
3250 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3252 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3254 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3255 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3257 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3258 HTTP_InsertCookies(lpwhr);
3260 /* add the headers the caller supplied */
3261 if( lpszHeaders && dwHeaderLength )
3263 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3264 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3267 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3269 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3270 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3271 HeapFree(GetProcessHeap(), 0, url);
3273 else
3274 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3277 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3279 /* Send the request and store the results */
3280 if (!HTTP_OpenConnection(lpwhr))
3281 goto lend;
3283 /* send the request as ASCII, tack on the optional data */
3284 if( !lpOptional )
3285 dwOptionalLength = 0;
3286 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3287 NULL, 0, NULL, NULL );
3288 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3289 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3290 ascii_req, len, NULL, NULL );
3291 if( lpOptional )
3292 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3293 len = (len + dwOptionalLength - 1);
3294 ascii_req[len] = 0;
3295 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3297 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3298 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3300 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3301 HeapFree( GetProcessHeap(), 0, ascii_req );
3303 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3304 INTERNET_STATUS_REQUEST_SENT,
3305 &len, sizeof(DWORD));
3307 if (bEndRequest)
3309 DWORD dwBufferSize;
3310 DWORD dwStatusCode;
3311 WCHAR encoding[20];
3312 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3314 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3315 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3317 if (cnt < 0)
3318 goto lend;
3320 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3321 if (responseLen)
3322 bSuccess = TRUE;
3324 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3325 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3326 sizeof(DWORD));
3328 HTTP_ProcessCookies(lpwhr);
3330 dwBufferSize = sizeof(lpwhr->dwContentLength);
3331 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3332 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3333 lpwhr->dwContentLength = -1;
3335 if (lpwhr->dwContentLength == 0)
3336 HTTP_FinishedReading(lpwhr);
3338 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3340 dwBufferSize = sizeof(encoding);
3341 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3342 !strcmpiW(encoding, szChunked))
3344 lpwhr->dwContentLength = -1;
3347 dwBufferSize = sizeof(dwStatusCode);
3348 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3349 &dwStatusCode,&dwBufferSize,NULL))
3350 dwStatusCode = 0;
3352 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3354 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3355 dwBufferSize=sizeof(szNewLocation);
3356 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3357 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3359 HTTP_DrainContent(lpwhr);
3360 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3361 INTERNET_STATUS_REDIRECT, szNewLocation,
3362 dwBufferSize);
3363 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3364 if (bSuccess)
3366 HeapFree(GetProcessHeap(), 0, requestString);
3367 loop_next = TRUE;
3371 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3373 WCHAR szAuthValue[2048];
3374 dwBufferSize=2048;
3375 if (dwStatusCode == HTTP_STATUS_DENIED)
3377 DWORD dwIndex = 0;
3378 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3380 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3381 &lpwhr->pAuthInfo,
3382 lpwhr->lpHttpSession->lpszUserName,
3383 lpwhr->lpHttpSession->lpszPassword))
3385 loop_next = TRUE;
3386 break;
3390 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3392 DWORD dwIndex = 0;
3393 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3395 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3396 &lpwhr->pProxyAuthInfo,
3397 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3398 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3400 loop_next = TRUE;
3401 break;
3407 else
3408 bSuccess = TRUE;
3410 while (loop_next);
3412 /* FIXME: Better check, when we have to create the cache file */
3413 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3414 WCHAR url[INTERNET_MAX_URL_LENGTH];
3415 WCHAR cacheFileName[MAX_PATH+1];
3416 BOOL b;
3418 b = HTTP_GetRequestURL(lpwhr, url);
3419 if(!b) {
3420 WARN("Could not get URL\n");
3421 goto lend;
3424 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3425 if(b) {
3426 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3427 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3428 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3429 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3430 WARN("Could not create file: %u\n", GetLastError());
3431 lpwhr->hCacheFile = NULL;
3433 }else {
3434 WARN("Could not create cache entry: %08x\n", GetLastError());
3438 lend:
3440 HeapFree(GetProcessHeap(), 0, requestString);
3442 /* TODO: send notification for P3P header */
3444 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3445 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3447 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3448 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3449 sizeof(INTERNET_ASYNC_RESULT));
3451 TRACE("<--\n");
3452 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3453 return bSuccess;
3456 /***********************************************************************
3457 * HTTPSESSION_Destroy (internal)
3459 * Deallocate session handle
3462 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3464 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3466 TRACE("%p\n", lpwhs);
3468 WININET_Release(&lpwhs->lpAppInfo->hdr);
3470 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3471 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3472 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3473 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3474 HeapFree(GetProcessHeap(), 0, lpwhs);
3477 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3479 switch(option) {
3480 case INTERNET_OPTION_HANDLE_TYPE:
3481 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3483 if (*size < sizeof(ULONG))
3484 return ERROR_INSUFFICIENT_BUFFER;
3486 *size = sizeof(DWORD);
3487 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3488 return ERROR_SUCCESS;
3491 return INET_QueryOption(option, buffer, size, unicode);
3494 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3496 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3498 switch(option) {
3499 case INTERNET_OPTION_USERNAME:
3501 if (!(ses->lpszUserName = WININET_strdupW(buffer))) break;
3502 return ERROR_SUCCESS;
3504 case INTERNET_OPTION_PASSWORD:
3506 if (!(ses->lpszPassword = WININET_strdupW(buffer))) break;
3507 return ERROR_SUCCESS;
3509 default: break;
3512 return ERROR_INTERNET_INVALID_OPTION;
3515 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3516 HTTPSESSION_Destroy,
3517 NULL,
3518 HTTPSESSION_QueryOption,
3519 HTTPSESSION_SetOption,
3520 NULL,
3521 NULL,
3522 NULL,
3523 NULL,
3524 NULL
3528 /***********************************************************************
3529 * HTTP_Connect (internal)
3531 * Create http session handle
3533 * RETURNS
3534 * HINTERNET a session handle on success
3535 * NULL on failure
3538 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3539 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3540 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3541 DWORD dwInternalFlags)
3543 LPWININETHTTPSESSIONW lpwhs = NULL;
3544 HINTERNET handle = NULL;
3546 TRACE("-->\n");
3548 if (!lpszServerName || !lpszServerName[0])
3550 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3551 goto lerror;
3554 assert( hIC->hdr.htype == WH_HINIT );
3556 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3557 if (NULL == lpwhs)
3559 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3560 goto lerror;
3564 * According to my tests. The name is not resolved until a request is sent
3567 lpwhs->hdr.htype = WH_HHTTPSESSION;
3568 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3569 lpwhs->hdr.dwFlags = dwFlags;
3570 lpwhs->hdr.dwContext = dwContext;
3571 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3572 lpwhs->hdr.refs = 1;
3573 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3575 WININET_AddRef( &hIC->hdr );
3576 lpwhs->lpAppInfo = hIC;
3577 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3579 handle = WININET_AllocHandle( &lpwhs->hdr );
3580 if (NULL == handle)
3582 ERR("Failed to alloc handle\n");
3583 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3584 goto lerror;
3587 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3588 if(strchrW(hIC->lpszProxy, ' '))
3589 FIXME("Several proxies not implemented.\n");
3590 if(hIC->lpszProxyBypass)
3591 FIXME("Proxy bypass is ignored.\n");
3593 if (lpszServerName && lpszServerName[0])
3595 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3596 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3598 if (lpszUserName && lpszUserName[0])
3599 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3600 if (lpszPassword && lpszPassword[0])
3601 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3602 lpwhs->nServerPort = nServerPort;
3603 lpwhs->nHostPort = nServerPort;
3605 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3606 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3608 INTERNET_SendCallback(&hIC->hdr, dwContext,
3609 INTERNET_STATUS_HANDLE_CREATED, &handle,
3610 sizeof(handle));
3613 lerror:
3614 if( lpwhs )
3615 WININET_Release( &lpwhs->hdr );
3618 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3619 * windows
3622 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3623 return handle;
3627 /***********************************************************************
3628 * HTTP_OpenConnection (internal)
3630 * Connect to a web server
3632 * RETURNS
3634 * TRUE on success
3635 * FALSE on failure
3637 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3639 BOOL bSuccess = FALSE;
3640 LPWININETHTTPSESSIONW lpwhs;
3641 LPWININETAPPINFOW hIC = NULL;
3642 char szaddr[32];
3644 TRACE("-->\n");
3647 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3649 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3650 goto lend;
3653 if (NETCON_connected(&lpwhr->netConnection))
3655 bSuccess = TRUE;
3656 goto lend;
3658 if (!HTTP_ResolveName(lpwhr)) goto lend;
3660 lpwhs = lpwhr->lpHttpSession;
3662 hIC = lpwhs->lpAppInfo;
3663 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3664 szaddr, sizeof(szaddr));
3665 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3666 INTERNET_STATUS_CONNECTING_TO_SERVER,
3667 szaddr,
3668 strlen(szaddr)+1);
3670 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3671 SOCK_STREAM, 0))
3673 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3674 goto lend;
3677 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3678 sizeof(lpwhs->socketAddress)))
3679 goto lend;
3681 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3683 /* Note: we differ from Microsoft's WinINet here. they seem to have
3684 * a bug that causes no status callbacks to be sent when starting
3685 * a tunnel to a proxy server using the CONNECT verb. i believe our
3686 * behaviour to be more correct and to not cause any incompatibilities
3687 * because using a secure connection through a proxy server is a rare
3688 * case that would be hard for anyone to depend on */
3689 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3690 goto lend;
3692 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3694 WARN("Couldn't connect securely to host\n");
3695 goto lend;
3699 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3700 INTERNET_STATUS_CONNECTED_TO_SERVER,
3701 szaddr, strlen(szaddr)+1);
3703 bSuccess = TRUE;
3705 lend:
3706 TRACE("%d <--\n", bSuccess);
3707 return bSuccess;
3711 /***********************************************************************
3712 * HTTP_clear_response_headers (internal)
3714 * clear out any old response headers
3716 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3718 DWORD i;
3720 for( i=0; i<lpwhr->nCustHeaders; i++)
3722 if( !lpwhr->pCustHeaders[i].lpszField )
3723 continue;
3724 if( !lpwhr->pCustHeaders[i].lpszValue )
3725 continue;
3726 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3727 continue;
3728 HTTP_DeleteCustomHeader( lpwhr, i );
3729 i--;
3733 /***********************************************************************
3734 * HTTP_GetResponseHeaders (internal)
3736 * Read server response
3738 * RETURNS
3740 * TRUE on success
3741 * FALSE on error
3743 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3745 INT cbreaks = 0;
3746 WCHAR buffer[MAX_REPLY_LEN];
3747 DWORD buflen = MAX_REPLY_LEN;
3748 BOOL bSuccess = FALSE;
3749 INT rc = 0;
3750 static const WCHAR szHundred[] = {'1','0','0',0};
3751 char bufferA[MAX_REPLY_LEN];
3752 LPWSTR status_code, status_text;
3753 DWORD cchMaxRawHeaders = 1024;
3754 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3755 DWORD cchRawHeaders = 0;
3757 TRACE("-->\n");
3759 /* clear old response headers (eg. from a redirect response) */
3760 if (clear) HTTP_clear_response_headers( lpwhr );
3762 if (!NETCON_connected(&lpwhr->netConnection))
3763 goto lend;
3765 do {
3767 * HACK peek at the buffer
3769 buflen = MAX_REPLY_LEN;
3770 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3773 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3775 memset(buffer, 0, MAX_REPLY_LEN);
3776 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3777 goto lend;
3778 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3780 /* split the version from the status code */
3781 status_code = strchrW( buffer, ' ' );
3782 if( !status_code )
3783 goto lend;
3784 *status_code++=0;
3786 /* split the status code from the status text */
3787 status_text = strchrW( status_code, ' ' );
3788 if( !status_text )
3789 goto lend;
3790 *status_text++=0;
3792 TRACE("version [%s] status code [%s] status text [%s]\n",
3793 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3795 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3797 /* Add status code */
3798 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3799 HTTP_ADDHDR_FLAG_REPLACE);
3801 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3802 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3804 lpwhr->lpszVersion= WININET_strdupW(buffer);
3805 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3807 /* Restore the spaces */
3808 *(status_code-1) = ' ';
3809 *(status_text-1) = ' ';
3811 /* regenerate raw headers */
3812 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3814 cchMaxRawHeaders *= 2;
3815 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3817 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3818 cchRawHeaders += (buflen-1);
3819 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3820 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3821 lpszRawHeaders[cchRawHeaders] = '\0';
3823 /* Parse each response line */
3826 buflen = MAX_REPLY_LEN;
3827 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3829 LPWSTR * pFieldAndValue;
3831 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3832 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3834 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3836 cchMaxRawHeaders *= 2;
3837 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3839 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3840 cchRawHeaders += (buflen-1);
3841 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3842 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3843 lpszRawHeaders[cchRawHeaders] = '\0';
3845 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3846 if (!pFieldAndValue)
3847 break;
3849 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3850 HTTP_ADDREQ_FLAG_ADD );
3852 HTTP_FreeTokens(pFieldAndValue);
3854 else
3856 cbreaks++;
3857 if (cbreaks >= 2)
3858 break;
3860 }while(1);
3862 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3863 lpwhr->lpszRawHeaders = lpszRawHeaders;
3864 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3865 bSuccess = TRUE;
3867 lend:
3869 TRACE("<--\n");
3870 if (bSuccess)
3871 return rc;
3872 else
3874 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3875 return 0;
3880 static void strip_spaces(LPWSTR start)
3882 LPWSTR str = start;
3883 LPWSTR end;
3885 while (*str == ' ' && *str != '\0')
3886 str++;
3888 if (str != start)
3889 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3891 end = start + strlenW(start) - 1;
3892 while (end >= start && *end == ' ')
3894 *end = '\0';
3895 end--;
3900 /***********************************************************************
3901 * HTTP_InterpretHttpHeader (internal)
3903 * Parse server response
3905 * RETURNS
3907 * Pointer to array of field, value, NULL on success.
3908 * NULL on error.
3910 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3912 LPWSTR * pTokenPair;
3913 LPWSTR pszColon;
3914 INT len;
3916 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3918 pszColon = strchrW(buffer, ':');
3919 /* must have two tokens */
3920 if (!pszColon)
3922 HTTP_FreeTokens(pTokenPair);
3923 if (buffer[0])
3924 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3925 return NULL;
3928 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3929 if (!pTokenPair[0])
3931 HTTP_FreeTokens(pTokenPair);
3932 return NULL;
3934 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3935 pTokenPair[0][pszColon - buffer] = '\0';
3937 /* skip colon */
3938 pszColon++;
3939 len = strlenW(pszColon);
3940 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3941 if (!pTokenPair[1])
3943 HTTP_FreeTokens(pTokenPair);
3944 return NULL;
3946 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3948 strip_spaces(pTokenPair[0]);
3949 strip_spaces(pTokenPair[1]);
3951 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3952 return pTokenPair;
3955 /***********************************************************************
3956 * HTTP_ProcessHeader (internal)
3958 * Stuff header into header tables according to <dwModifier>
3962 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3964 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3966 LPHTTPHEADERW lphttpHdr = NULL;
3967 BOOL bSuccess = FALSE;
3968 INT index = -1;
3969 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3971 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3973 /* REPLACE wins out over ADD */
3974 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3975 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3977 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3978 index = -1;
3979 else
3980 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3982 if (index >= 0)
3984 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3986 return FALSE;
3988 lphttpHdr = &lpwhr->pCustHeaders[index];
3990 else if (value)
3992 HTTPHEADERW hdr;
3994 hdr.lpszField = (LPWSTR)field;
3995 hdr.lpszValue = (LPWSTR)value;
3996 hdr.wFlags = hdr.wCount = 0;
3998 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3999 hdr.wFlags |= HDR_ISREQUEST;
4001 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4003 /* no value to delete */
4004 else return TRUE;
4006 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4007 lphttpHdr->wFlags |= HDR_ISREQUEST;
4008 else
4009 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4011 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4013 HTTP_DeleteCustomHeader( lpwhr, index );
4015 if (value)
4017 HTTPHEADERW hdr;
4019 hdr.lpszField = (LPWSTR)field;
4020 hdr.lpszValue = (LPWSTR)value;
4021 hdr.wFlags = hdr.wCount = 0;
4023 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4024 hdr.wFlags |= HDR_ISREQUEST;
4026 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4029 return TRUE;
4031 else if (dwModifier & COALESCEFLAGS)
4033 LPWSTR lpsztmp;
4034 WCHAR ch = 0;
4035 INT len = 0;
4036 INT origlen = strlenW(lphttpHdr->lpszValue);
4037 INT valuelen = strlenW(value);
4039 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4041 ch = ',';
4042 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4044 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4046 ch = ';';
4047 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4050 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4052 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4053 if (lpsztmp)
4055 lphttpHdr->lpszValue = lpsztmp;
4056 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4057 if (ch > 0)
4059 lphttpHdr->lpszValue[origlen] = ch;
4060 origlen++;
4061 lphttpHdr->lpszValue[origlen] = ' ';
4062 origlen++;
4065 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4066 lphttpHdr->lpszValue[len] = '\0';
4067 bSuccess = TRUE;
4069 else
4071 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4072 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4075 TRACE("<-- %d\n",bSuccess);
4076 return bSuccess;
4080 /***********************************************************************
4081 * HTTP_FinishedReading (internal)
4083 * Called when all content from server has been read by client.
4086 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4088 WCHAR szVersion[10];
4089 WCHAR szConnectionResponse[20];
4090 DWORD dwBufferSize = sizeof(szVersion);
4091 BOOL keepalive = FALSE;
4093 TRACE("\n");
4095 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4096 * the connection is keep-alive by default */
4097 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4098 &dwBufferSize, NULL) &&
4099 !strcmpiW(szVersion, g_szHttp1_1))
4101 keepalive = TRUE;
4104 dwBufferSize = sizeof(szConnectionResponse);
4105 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4106 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4108 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4111 if (!keepalive)
4113 HTTPREQ_CloseConnection(&lpwhr->hdr);
4116 /* FIXME: store data in the URL cache here */
4118 return TRUE;
4122 /***********************************************************************
4123 * HTTP_GetCustomHeaderIndex (internal)
4125 * Return index of custom header from header array
4128 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4129 int requested_index, BOOL request_only)
4131 DWORD index;
4133 TRACE("%s\n", debugstr_w(lpszField));
4135 for (index = 0; index < lpwhr->nCustHeaders; index++)
4137 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4138 continue;
4140 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4141 continue;
4143 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4144 continue;
4146 if (requested_index == 0)
4147 break;
4148 requested_index --;
4151 if (index >= lpwhr->nCustHeaders)
4152 index = -1;
4154 TRACE("Return: %d\n", index);
4155 return index;
4159 /***********************************************************************
4160 * HTTP_InsertCustomHeader (internal)
4162 * Insert header into array
4165 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4167 INT count;
4168 LPHTTPHEADERW lph = NULL;
4169 BOOL r = FALSE;
4171 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4172 count = lpwhr->nCustHeaders + 1;
4173 if (count > 1)
4174 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4175 else
4176 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4178 if (NULL != lph)
4180 lpwhr->pCustHeaders = lph;
4181 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4182 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4183 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4184 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4185 lpwhr->nCustHeaders++;
4186 r = TRUE;
4188 else
4190 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4193 return r;
4197 /***********************************************************************
4198 * HTTP_DeleteCustomHeader (internal)
4200 * Delete header from array
4201 * If this function is called, the indexs may change.
4203 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4205 if( lpwhr->nCustHeaders <= 0 )
4206 return FALSE;
4207 if( index >= lpwhr->nCustHeaders )
4208 return FALSE;
4209 lpwhr->nCustHeaders--;
4211 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4212 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4214 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4215 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4216 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4218 return TRUE;
4222 /***********************************************************************
4223 * HTTP_VerifyValidHeader (internal)
4225 * Verify the given header is not invalid for the given http request
4228 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4230 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4231 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4232 return FALSE;
4234 return TRUE;
4237 /***********************************************************************
4238 * IsHostInProxyBypassList (@)
4240 * Undocumented
4243 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4245 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4246 return FALSE;