push a9ee6bdc492dbf6a3d2de76ff889abeabd04e8d0
[wine/hacks.git] / dlls / wininet / http.c
blob8d03b61cfe438618a8f4c7b9d2d1e79fab2f202f
1 /*
2 * Wininet - Http Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
11 * Ulrich Czekalla
12 * David Hammerton
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #include "config.h"
30 #include "wine/port.h"
32 #if defined(__MINGW32__) || defined (_MSC_VER)
33 #include <ws2tcpip.h>
34 #endif
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
42 #endif
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49 #include <time.h>
50 #include <assert.h>
52 #include "windef.h"
53 #include "winbase.h"
54 #include "wininet.h"
55 #include "winerror.h"
56 #define NO_SHLWAPI_STREAM
57 #define NO_SHLWAPI_REG
58 #define NO_SHLWAPI_STRFCNS
59 #define NO_SHLWAPI_GDI
60 #include "shlwapi.h"
61 #include "sspi.h"
62 #include "wincrypt.h"
64 #include "internet.h"
65 #include "wine/debug.h"
66 #include "wine/exception.h"
67 #include "wine/unicode.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
71 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
72 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
73 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
74 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
75 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
76 static const WCHAR szHost[] = { 'H','o','s','t',0 };
77 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
78 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
79 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
80 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
81 static const WCHAR szGET[] = { 'G','E','T', 0 };
82 static const WCHAR szCrLf[] = {'\r','\n', 0};
84 #define MAXHOSTNAME 100
85 #define MAX_FIELD_VALUE_LEN 256
86 #define MAX_FIELD_LEN 256
88 #define HTTP_REFERER g_szReferer
89 #define HTTP_ACCEPT g_szAccept
90 #define HTTP_USERAGENT g_szUserAgent
92 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
93 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
94 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
95 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
96 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
97 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
98 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
100 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
102 struct HttpAuthInfo
104 LPWSTR scheme;
105 CredHandle cred;
106 CtxtHandle ctx;
107 TimeStamp exp;
108 ULONG attr;
109 ULONG max_token;
110 void *auth_data;
111 unsigned int auth_data_len;
112 BOOL finished; /* finished authenticating */
115 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
116 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
117 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
118 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
119 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
120 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
121 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
122 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
123 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
124 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
125 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
126 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
127 static void HTTP_DrainContent(WININETHTTPREQW *req);
128 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr);
130 static LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
132 int HeaderIndex = 0;
133 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
134 if (HeaderIndex == -1)
135 return NULL;
136 else
137 return &req->pCustHeaders[HeaderIndex];
140 /***********************************************************************
141 * HTTP_Tokenize (internal)
143 * Tokenize a string, allocating memory for the tokens.
145 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
147 LPWSTR * token_array;
148 int tokens = 0;
149 int i;
150 LPCWSTR next_token;
152 if (string)
154 /* empty string has no tokens */
155 if (*string)
156 tokens++;
157 /* count tokens */
158 for (i = 0; string[i]; i++)
160 if (!strncmpW(string+i, token_string, strlenW(token_string)))
162 DWORD j;
163 tokens++;
164 /* we want to skip over separators, but not the null terminator */
165 for (j = 0; j < strlenW(token_string) - 1; j++)
166 if (!string[i+j])
167 break;
168 i += j;
173 /* add 1 for terminating NULL */
174 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
175 token_array[tokens] = NULL;
176 if (!tokens)
177 return token_array;
178 for (i = 0; i < tokens; i++)
180 int len;
181 next_token = strstrW(string, token_string);
182 if (!next_token) next_token = string+strlenW(string);
183 len = next_token - string;
184 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
185 memcpy(token_array[i], string, len*sizeof(WCHAR));
186 token_array[i][len] = '\0';
187 string = next_token+strlenW(token_string);
189 return token_array;
192 /***********************************************************************
193 * HTTP_FreeTokens (internal)
195 * Frees memory returned from HTTP_Tokenize.
197 static void HTTP_FreeTokens(LPWSTR * token_array)
199 int i;
200 for (i = 0; token_array[i]; i++)
201 HeapFree(GetProcessHeap(), 0, token_array[i]);
202 HeapFree(GetProcessHeap(), 0, token_array);
205 /* **********************************************************************
207 * Helper functions for the HttpSendRequest(Ex) functions
210 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
212 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
213 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
215 TRACE("%p\n", lpwhr);
217 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
218 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
219 req->dwContentLength, req->bEndRequest);
221 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
224 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
226 static const WCHAR szSlash[] = { '/',0 };
227 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
229 /* If we don't have a path we set it to root */
230 if (NULL == lpwhr->lpszPath)
231 lpwhr->lpszPath = WININET_strdupW(szSlash);
232 else /* remove \r and \n*/
234 int nLen = strlenW(lpwhr->lpszPath);
235 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
237 nLen--;
238 lpwhr->lpszPath[nLen]='\0';
240 /* Replace '\' with '/' */
241 while (nLen>0) {
242 nLen--;
243 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
247 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
248 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
249 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
251 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
252 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
253 *fixurl = '/';
254 strcpyW(fixurl + 1, lpwhr->lpszPath);
255 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
256 lpwhr->lpszPath = fixurl;
260 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
262 LPWSTR requestString;
263 DWORD len, n;
264 LPCWSTR *req;
265 UINT i;
266 LPWSTR p;
268 static const WCHAR szSpace[] = { ' ',0 };
269 static const WCHAR szColon[] = { ':',' ',0 };
270 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
272 /* allocate space for an array of all the string pointers to be added */
273 len = (lpwhr->nCustHeaders)*4 + 10;
274 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
276 /* add the verb, path and HTTP version string */
277 n = 0;
278 req[n++] = verb;
279 req[n++] = szSpace;
280 req[n++] = path;
281 req[n++] = szSpace;
282 req[n++] = version;
284 /* Append custom request headers */
285 for (i = 0; i < lpwhr->nCustHeaders; i++)
287 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
289 req[n++] = szCrLf;
290 req[n++] = lpwhr->pCustHeaders[i].lpszField;
291 req[n++] = szColon;
292 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
294 TRACE("Adding custom header %s (%s)\n",
295 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
296 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
300 if( n >= len )
301 ERR("oops. buffer overrun\n");
303 req[n] = NULL;
304 requestString = HTTP_build_req( req, 4 );
305 HeapFree( GetProcessHeap(), 0, req );
308 * Set (header) termination string for request
309 * Make sure there's exactly two new lines at the end of the request
311 p = &requestString[strlenW(requestString)-1];
312 while ( (*p == '\n') || (*p == '\r') )
313 p--;
314 strcpyW( p+1, sztwocrlf );
316 return requestString;
319 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
321 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
322 int HeaderIndex;
323 int numCookies = 0;
324 LPHTTPHEADERW setCookieHeader;
326 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
328 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
330 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
332 int len;
333 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
334 LPWSTR buf_url;
335 LPHTTPHEADERW Host;
337 Host = HTTP_GetHeader(lpwhr,szHost);
338 len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
339 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
340 sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
341 InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
343 HeapFree(GetProcessHeap(), 0, buf_url);
345 numCookies++;
349 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
351 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
352 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
353 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
356 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
357 struct HttpAuthInfo **ppAuthInfo,
358 LPWSTR domain_and_username, LPWSTR password )
360 SECURITY_STATUS sec_status;
361 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
362 BOOL first = FALSE;
364 TRACE("%s\n", debugstr_w(pszAuthValue));
366 if (!pAuthInfo)
368 TimeStamp exp;
370 first = TRUE;
371 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
372 if (!pAuthInfo)
373 return FALSE;
375 SecInvalidateHandle(&pAuthInfo->cred);
376 SecInvalidateHandle(&pAuthInfo->ctx);
377 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
378 pAuthInfo->attr = 0;
379 pAuthInfo->auth_data = NULL;
380 pAuthInfo->auth_data_len = 0;
381 pAuthInfo->finished = FALSE;
383 if (is_basic_auth_value(pszAuthValue))
385 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
386 pAuthInfo->scheme = WININET_strdupW(szBasic);
387 if (!pAuthInfo->scheme)
389 HeapFree(GetProcessHeap(), 0, pAuthInfo);
390 return FALSE;
393 else
395 PVOID pAuthData;
396 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
398 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
399 if (!pAuthInfo->scheme)
401 HeapFree(GetProcessHeap(), 0, pAuthInfo);
402 return FALSE;
405 if (domain_and_username)
407 WCHAR *user = strchrW(domain_and_username, '\\');
408 WCHAR *domain = domain_and_username;
410 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
412 pAuthData = &nt_auth_identity;
414 if (user) user++;
415 else
417 user = domain_and_username;
418 domain = NULL;
421 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
422 nt_auth_identity.User = user;
423 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
424 nt_auth_identity.Domain = domain;
425 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
426 nt_auth_identity.Password = password;
427 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
429 else
430 /* use default credentials */
431 pAuthData = NULL;
433 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
434 SECPKG_CRED_OUTBOUND, NULL,
435 pAuthData, NULL,
436 NULL, &pAuthInfo->cred,
437 &exp);
438 if (sec_status == SEC_E_OK)
440 PSecPkgInfoW sec_pkg_info;
441 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
442 if (sec_status == SEC_E_OK)
444 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
445 FreeContextBuffer(sec_pkg_info);
448 if (sec_status != SEC_E_OK)
450 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
451 debugstr_w(pAuthInfo->scheme), sec_status);
452 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
453 HeapFree(GetProcessHeap(), 0, pAuthInfo);
454 return FALSE;
457 *ppAuthInfo = pAuthInfo;
459 else if (pAuthInfo->finished)
460 return FALSE;
462 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
463 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
465 ERR("authentication scheme changed from %s to %s\n",
466 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
467 return FALSE;
470 if (is_basic_auth_value(pszAuthValue))
472 int userlen;
473 int passlen;
474 char *auth_data;
476 TRACE("basic authentication\n");
478 /* we don't cache credentials for basic authentication, so we can't
479 * retrieve them if the application didn't pass us any credentials */
480 if (!domain_and_username) return FALSE;
482 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
483 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
485 /* length includes a nul terminator, which will be re-used for the ':' */
486 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
487 if (!auth_data)
488 return FALSE;
490 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
491 auth_data[userlen] = ':';
492 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
494 pAuthInfo->auth_data = auth_data;
495 pAuthInfo->auth_data_len = userlen + 1 + passlen;
496 pAuthInfo->finished = TRUE;
498 return TRUE;
500 else
502 LPCWSTR pszAuthData;
503 SecBufferDesc out_desc, in_desc;
504 SecBuffer out, in;
505 unsigned char *buffer;
506 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
507 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
509 in.BufferType = SECBUFFER_TOKEN;
510 in.cbBuffer = 0;
511 in.pvBuffer = NULL;
513 in_desc.ulVersion = 0;
514 in_desc.cBuffers = 1;
515 in_desc.pBuffers = &in;
517 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
518 if (*pszAuthData == ' ')
520 pszAuthData++;
521 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
522 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
523 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
526 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
528 out.BufferType = SECBUFFER_TOKEN;
529 out.cbBuffer = pAuthInfo->max_token;
530 out.pvBuffer = buffer;
532 out_desc.ulVersion = 0;
533 out_desc.cBuffers = 1;
534 out_desc.pBuffers = &out;
536 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
537 first ? NULL : &pAuthInfo->ctx,
538 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
539 context_req, 0, SECURITY_NETWORK_DREP,
540 in.pvBuffer ? &in_desc : NULL,
541 0, &pAuthInfo->ctx, &out_desc,
542 &pAuthInfo->attr, &pAuthInfo->exp);
543 if (sec_status == SEC_E_OK)
545 pAuthInfo->finished = TRUE;
546 pAuthInfo->auth_data = out.pvBuffer;
547 pAuthInfo->auth_data_len = out.cbBuffer;
548 TRACE("sending last auth packet\n");
550 else if (sec_status == SEC_I_CONTINUE_NEEDED)
552 pAuthInfo->auth_data = out.pvBuffer;
553 pAuthInfo->auth_data_len = out.cbBuffer;
554 TRACE("sending next auth packet\n");
556 else
558 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
559 pAuthInfo->finished = TRUE;
560 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
561 return FALSE;
565 return TRUE;
568 /***********************************************************************
569 * HTTP_HttpAddRequestHeadersW (internal)
571 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
572 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
574 LPWSTR lpszStart;
575 LPWSTR lpszEnd;
576 LPWSTR buffer;
577 BOOL bSuccess = FALSE;
578 DWORD len;
580 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
582 if( dwHeaderLength == ~0U )
583 len = strlenW(lpszHeader);
584 else
585 len = dwHeaderLength;
586 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
587 lstrcpynW( buffer, lpszHeader, len + 1);
589 lpszStart = buffer;
593 LPWSTR * pFieldAndValue;
595 lpszEnd = lpszStart;
597 while (*lpszEnd != '\0')
599 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
600 break;
601 lpszEnd++;
604 if (*lpszStart == '\0')
605 break;
607 if (*lpszEnd == '\r')
609 *lpszEnd = '\0';
610 lpszEnd += 2; /* Jump over \r\n */
612 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
613 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
614 if (pFieldAndValue)
616 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
617 if (bSuccess)
618 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
619 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
620 HTTP_FreeTokens(pFieldAndValue);
623 lpszStart = lpszEnd;
624 } while (bSuccess);
626 HeapFree(GetProcessHeap(), 0, buffer);
628 return bSuccess;
631 /***********************************************************************
632 * HttpAddRequestHeadersW (WININET.@)
634 * Adds one or more HTTP header to the request handler
636 * NOTE
637 * On Windows if dwHeaderLength includes the trailing '\0', then
638 * HttpAddRequestHeadersW() adds it too. However this results in an
639 * invalid Http header which is rejected by some servers so we probably
640 * don't need to match Windows on that point.
642 * RETURNS
643 * TRUE on success
644 * FALSE on failure
647 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
648 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
650 BOOL bSuccess = FALSE;
651 LPWININETHTTPREQW lpwhr;
653 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
655 if (!lpszHeader)
656 return TRUE;
658 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
659 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
661 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
662 goto lend;
664 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
665 lend:
666 if( lpwhr )
667 WININET_Release( &lpwhr->hdr );
669 return bSuccess;
672 /***********************************************************************
673 * HttpAddRequestHeadersA (WININET.@)
675 * Adds one or more HTTP header to the request handler
677 * RETURNS
678 * TRUE on success
679 * FALSE on failure
682 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
683 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
685 DWORD len;
686 LPWSTR hdr;
687 BOOL r;
689 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
691 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
692 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
693 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
694 if( dwHeaderLength != ~0U )
695 dwHeaderLength = len;
697 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
699 HeapFree( GetProcessHeap(), 0, hdr );
701 return r;
704 /***********************************************************************
705 * HttpEndRequestA (WININET.@)
707 * Ends an HTTP request that was started by HttpSendRequestEx
709 * RETURNS
710 * TRUE if successful
711 * FALSE on failure
714 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
715 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
717 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
719 if (lpBuffersOut)
721 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
722 return FALSE;
725 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
728 static BOOL HTTP_HttpEndRequestW(LPWININETHTTPREQW lpwhr, DWORD dwFlags, DWORD_PTR dwContext)
730 BOOL rc = FALSE;
731 INT responseLen;
732 DWORD dwBufferSize;
733 INTERNET_ASYNC_RESULT iar;
735 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
736 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
738 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
739 if (responseLen)
740 rc = TRUE;
742 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
743 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
745 /* process cookies here. Is this right? */
746 HTTP_ProcessCookies(lpwhr);
748 dwBufferSize = sizeof(lpwhr->dwContentLength);
749 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
750 &lpwhr->dwContentLength, &dwBufferSize, NULL))
751 lpwhr->dwContentLength = -1;
753 if (lpwhr->dwContentLength == 0)
754 HTTP_FinishedReading(lpwhr);
756 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
758 DWORD dwCode,dwCodeLength = sizeof(DWORD);
759 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE, &dwCode, &dwCodeLength, NULL) &&
760 (dwCode == 302 || dwCode == 301 || dwCode == 303))
762 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
763 dwBufferSize=sizeof(szNewLocation);
764 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL))
766 /* redirects are always GETs */
767 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
768 lpwhr->lpszVerb = WININET_strdupW(szGET);
769 HTTP_DrainContent(lpwhr);
770 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
771 INTERNET_STATUS_REDIRECT, szNewLocation, dwBufferSize);
772 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
773 if (rc)
774 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
779 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
780 iar.dwError = rc ? 0 : INTERNET_GetLastError();
782 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
783 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
784 sizeof(INTERNET_ASYNC_RESULT));
785 return rc;
788 static void AsyncHttpEndRequestProc(WORKREQUEST *work)
790 struct WORKREQ_HTTPENDREQUESTW const *req = &work->u.HttpEndRequestW;
791 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)work->hdr;
793 TRACE("%p\n", lpwhr);
795 HTTP_HttpEndRequestW(lpwhr, req->dwFlags, req->dwContext);
798 /***********************************************************************
799 * HttpEndRequestW (WININET.@)
801 * Ends an HTTP request that was started by HttpSendRequestEx
803 * RETURNS
804 * TRUE if successful
805 * FALSE on failure
808 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
809 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
811 BOOL rc = FALSE;
812 LPWININETHTTPREQW lpwhr;
814 TRACE("-->\n");
816 if (lpBuffersOut)
818 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
819 return FALSE;
822 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
824 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
826 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
827 if (lpwhr)
828 WININET_Release( &lpwhr->hdr );
829 return FALSE;
831 lpwhr->hdr.dwFlags |= dwFlags;
833 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
835 WORKREQUEST work;
836 struct WORKREQ_HTTPENDREQUESTW *request;
838 work.asyncproc = AsyncHttpEndRequestProc;
839 work.hdr = WININET_AddRef( &lpwhr->hdr );
841 request = &work.u.HttpEndRequestW;
842 request->dwFlags = dwFlags;
843 request->dwContext = dwContext;
845 INTERNET_AsyncCall(&work);
846 INTERNET_SetLastError(ERROR_IO_PENDING);
848 else
849 rc = HTTP_HttpEndRequestW(lpwhr, dwFlags, dwContext);
851 WININET_Release( &lpwhr->hdr );
852 TRACE("%i <--\n",rc);
853 return rc;
856 /***********************************************************************
857 * HttpOpenRequestW (WININET.@)
859 * Open a HTTP request handle
861 * RETURNS
862 * HINTERNET a HTTP request handle on success
863 * NULL on failure
866 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
867 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
868 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
869 DWORD dwFlags, DWORD_PTR dwContext)
871 LPWININETHTTPSESSIONW lpwhs;
872 HINTERNET handle = NULL;
874 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
875 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
876 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
877 dwFlags, dwContext);
878 if(lpszAcceptTypes!=NULL)
880 int i;
881 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
882 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
885 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
886 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
888 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
889 goto lend;
893 * My tests seem to show that the windows version does not
894 * become asynchronous until after this point. And anyhow
895 * if this call was asynchronous then how would you get the
896 * necessary HINTERNET pointer returned by this function.
899 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
900 lpszVersion, lpszReferrer, lpszAcceptTypes,
901 dwFlags, dwContext);
902 lend:
903 if( lpwhs )
904 WININET_Release( &lpwhs->hdr );
905 TRACE("returning %p\n", handle);
906 return handle;
910 /***********************************************************************
911 * HttpOpenRequestA (WININET.@)
913 * Open a HTTP request handle
915 * RETURNS
916 * HINTERNET a HTTP request handle on success
917 * NULL on failure
920 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
921 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
922 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
923 DWORD dwFlags, DWORD_PTR dwContext)
925 LPWSTR szVerb = NULL, szObjectName = NULL;
926 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
927 INT len, acceptTypesCount;
928 HINTERNET rc = FALSE;
929 LPCSTR *types;
931 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
932 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
933 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
934 dwFlags, dwContext);
936 if (lpszVerb)
938 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
939 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
940 if ( !szVerb )
941 goto end;
942 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
945 if (lpszObjectName)
947 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
948 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
949 if ( !szObjectName )
950 goto end;
951 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
954 if (lpszVersion)
956 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
957 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
958 if ( !szVersion )
959 goto end;
960 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
963 if (lpszReferrer)
965 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
966 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
967 if ( !szReferrer )
968 goto end;
969 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
972 if (lpszAcceptTypes)
974 acceptTypesCount = 0;
975 types = lpszAcceptTypes;
976 while (*types)
978 __TRY
980 /* find out how many there are */
981 if (*types && **types)
983 TRACE("accept type: %s\n", debugstr_a(*types));
984 acceptTypesCount++;
987 __EXCEPT_PAGE_FAULT
989 WARN("invalid accept type pointer\n");
991 __ENDTRY;
992 types++;
994 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
995 if (!szAcceptTypes) goto end;
997 acceptTypesCount = 0;
998 types = lpszAcceptTypes;
999 while (*types)
1001 __TRY
1003 if (*types && **types)
1005 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1006 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1008 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1009 acceptTypesCount++;
1012 __EXCEPT_PAGE_FAULT
1014 /* ignore invalid pointer */
1016 __ENDTRY;
1017 types++;
1019 szAcceptTypes[acceptTypesCount] = NULL;
1022 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1023 szVersion, szReferrer,
1024 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1026 end:
1027 if (szAcceptTypes)
1029 acceptTypesCount = 0;
1030 while (szAcceptTypes[acceptTypesCount])
1032 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1033 acceptTypesCount++;
1035 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1037 HeapFree(GetProcessHeap(), 0, szReferrer);
1038 HeapFree(GetProcessHeap(), 0, szVersion);
1039 HeapFree(GetProcessHeap(), 0, szObjectName);
1040 HeapFree(GetProcessHeap(), 0, szVerb);
1042 return rc;
1045 /***********************************************************************
1046 * HTTP_EncodeBase64
1048 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1050 UINT n = 0, x;
1051 static const CHAR HTTP_Base64Enc[] =
1052 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1054 while( len > 0 )
1056 /* first 6 bits, all from bin[0] */
1057 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1058 x = (bin[0] & 3) << 4;
1060 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1061 if( len == 1 )
1063 base64[n++] = HTTP_Base64Enc[x];
1064 base64[n++] = '=';
1065 base64[n++] = '=';
1066 break;
1068 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1069 x = ( bin[1] & 0x0f ) << 2;
1071 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1072 if( len == 2 )
1074 base64[n++] = HTTP_Base64Enc[x];
1075 base64[n++] = '=';
1076 break;
1078 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1080 /* last 6 bits, all from bin [2] */
1081 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1082 bin += 3;
1083 len -= 3;
1085 base64[n] = 0;
1086 return n;
1089 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1090 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1091 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1092 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1093 static const signed char HTTP_Base64Dec[256] =
1095 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1096 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1097 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1098 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1099 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1100 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1101 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1102 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1103 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1104 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1105 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1106 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1107 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1108 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1109 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1110 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1111 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1112 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1113 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1114 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1115 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1116 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1117 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1118 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1119 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1120 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1122 #undef CH
1124 /***********************************************************************
1125 * HTTP_DecodeBase64
1127 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1129 unsigned int n = 0;
1131 while(*base64)
1133 signed char in[4];
1135 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1136 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1137 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1138 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1140 WARN("invalid base64: %s\n", debugstr_w(base64));
1141 return 0;
1143 if (bin)
1144 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1145 n++;
1147 if ((base64[2] == '=') && (base64[3] == '='))
1148 break;
1149 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1150 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1152 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1153 return 0;
1155 if (bin)
1156 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1157 n++;
1159 if (base64[3] == '=')
1160 break;
1161 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1162 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1164 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1165 return 0;
1167 if (bin)
1168 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1169 n++;
1171 base64 += 4;
1174 return n;
1177 /***********************************************************************
1178 * HTTP_InsertAuthorization
1180 * Insert or delete the authorization field in the request header.
1182 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1184 if (pAuthInfo)
1186 static const WCHAR wszSpace[] = {' ',0};
1187 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1188 unsigned int len;
1189 WCHAR *authorization = NULL;
1191 if (pAuthInfo->auth_data_len)
1193 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1194 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1195 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1196 if (!authorization)
1197 return FALSE;
1199 strcpyW(authorization, pAuthInfo->scheme);
1200 strcatW(authorization, wszSpace);
1201 HTTP_EncodeBase64(pAuthInfo->auth_data,
1202 pAuthInfo->auth_data_len,
1203 authorization+strlenW(authorization));
1205 /* clear the data as it isn't valid now that it has been sent to the
1206 * server, unless it's Basic authentication which doesn't do
1207 * connection tracking */
1208 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1210 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1211 pAuthInfo->auth_data = NULL;
1212 pAuthInfo->auth_data_len = 0;
1216 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1218 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1220 HeapFree(GetProcessHeap(), 0, authorization);
1222 return TRUE;
1225 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1227 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1228 DWORD size;
1230 size = sizeof(new_location);
1231 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1233 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1234 strcpyW( url, new_location );
1236 else
1238 static const WCHAR slash[] = { '/',0 };
1239 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1240 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1241 WININETHTTPSESSIONW *session = req->lpHttpSession;
1243 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1244 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1246 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1248 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1249 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1250 else
1251 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1252 if (req->lpszPath[0] != '/') strcatW( url, slash );
1253 strcatW( url, req->lpszPath );
1255 TRACE("url=%s\n", debugstr_w(url));
1256 return url;
1259 /***********************************************************************
1260 * HTTP_DealWithProxy
1262 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1263 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1265 WCHAR buf[MAXHOSTNAME];
1266 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1267 static WCHAR szNul[] = { 0 };
1268 URL_COMPONENTSW UrlComponents;
1269 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1270 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1272 memset( &UrlComponents, 0, sizeof UrlComponents );
1273 UrlComponents.dwStructSize = sizeof UrlComponents;
1274 UrlComponents.lpszHostName = buf;
1275 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1277 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1278 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1279 sprintfW(proxy, szFormat, hIC->lpszProxy);
1280 else
1281 strcpyW(proxy, hIC->lpszProxy);
1282 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1283 return FALSE;
1284 if( UrlComponents.dwHostNameLength == 0 )
1285 return FALSE;
1287 if( !lpwhr->lpszPath )
1288 lpwhr->lpszPath = szNul;
1290 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1291 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1293 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1294 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1295 lpwhs->nServerPort = UrlComponents.nPort;
1297 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1298 return TRUE;
1301 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1303 char szaddr[32];
1304 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1306 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1307 INTERNET_STATUS_RESOLVING_NAME,
1308 lpwhs->lpszServerName,
1309 strlenW(lpwhs->lpszServerName)+1);
1311 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1312 &lpwhs->socketAddress))
1314 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1315 return FALSE;
1318 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1319 szaddr, sizeof(szaddr));
1320 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1321 INTERNET_STATUS_NAME_RESOLVED,
1322 szaddr, strlen(szaddr)+1);
1324 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1325 return TRUE;
1329 /***********************************************************************
1330 * HTTPREQ_Destroy (internal)
1332 * Deallocate request handle
1335 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1337 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1338 DWORD i;
1340 TRACE("\n");
1342 if(lpwhr->hCacheFile)
1343 CloseHandle(lpwhr->hCacheFile);
1345 if(lpwhr->lpszCacheFile) {
1346 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1347 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1350 WININET_Release(&lpwhr->lpHttpSession->hdr);
1352 if (lpwhr->pAuthInfo)
1354 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1355 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1356 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1357 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1359 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1360 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1361 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1362 lpwhr->pAuthInfo = NULL;
1365 if (lpwhr->pProxyAuthInfo)
1367 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1368 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1369 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1370 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1372 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1373 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1374 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1375 lpwhr->pProxyAuthInfo = NULL;
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1379 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1380 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1381 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1382 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1384 for (i = 0; i < lpwhr->nCustHeaders; i++)
1386 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1387 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1390 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1391 HeapFree(GetProcessHeap(), 0, lpwhr);
1394 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1396 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1398 TRACE("%p\n",lpwhr);
1400 if (!NETCON_connected(&lpwhr->netConnection))
1401 return;
1403 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1404 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1406 NETCON_close(&lpwhr->netConnection);
1408 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1409 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1412 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1414 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1416 switch(option) {
1417 case INTERNET_OPTION_HANDLE_TYPE:
1418 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1420 if (*size < sizeof(ULONG))
1421 return ERROR_INSUFFICIENT_BUFFER;
1423 *size = sizeof(DWORD);
1424 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1425 return ERROR_SUCCESS;
1427 case INTERNET_OPTION_URL: {
1428 WCHAR url[INTERNET_MAX_URL_LENGTH];
1429 HTTPHEADERW *host;
1430 DWORD len;
1431 WCHAR *pch;
1433 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1434 static const WCHAR hostW[] = {'H','o','s','t',0};
1436 TRACE("INTERNET_OPTION_URL\n");
1438 host = HTTP_GetHeader(req, hostW);
1439 strcpyW(url, httpW);
1440 strcatW(url, host->lpszValue);
1441 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1442 *pch = 0;
1443 strcatW(url, req->lpszPath);
1445 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1447 if(unicode) {
1448 len = (strlenW(url)+1) * sizeof(WCHAR);
1449 if(*size < len)
1450 return ERROR_INSUFFICIENT_BUFFER;
1452 *size = len;
1453 strcpyW(buffer, url);
1454 return ERROR_SUCCESS;
1455 }else {
1456 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1457 if(len > *size)
1458 return ERROR_INSUFFICIENT_BUFFER;
1460 *size = len;
1461 return ERROR_SUCCESS;
1465 case INTERNET_OPTION_DATAFILE_NAME: {
1466 DWORD req_size;
1468 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1470 if(!req->lpszCacheFile) {
1471 *size = 0;
1472 return ERROR_INTERNET_ITEM_NOT_FOUND;
1475 if(unicode) {
1476 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1477 if(*size < req_size)
1478 return ERROR_INSUFFICIENT_BUFFER;
1480 *size = req_size;
1481 memcpy(buffer, req->lpszCacheFile, *size);
1482 return ERROR_SUCCESS;
1483 }else {
1484 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1485 if (req_size > *size)
1486 return ERROR_INSUFFICIENT_BUFFER;
1488 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1489 -1, buffer, *size, NULL, NULL);
1490 return ERROR_SUCCESS;
1494 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1495 PCCERT_CONTEXT context;
1497 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1498 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1499 return ERROR_INSUFFICIENT_BUFFER;
1502 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1503 if(context) {
1504 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1505 DWORD len;
1507 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1508 info->ftExpiry = context->pCertInfo->NotAfter;
1509 info->ftStart = context->pCertInfo->NotBefore;
1510 if(unicode) {
1511 len = CertNameToStrW(context->dwCertEncodingType,
1512 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1513 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1514 if(info->lpszSubjectInfo)
1515 CertNameToStrW(context->dwCertEncodingType,
1516 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1517 info->lpszSubjectInfo, len);
1518 len = CertNameToStrW(context->dwCertEncodingType,
1519 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1520 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1521 if (info->lpszIssuerInfo)
1522 CertNameToStrW(context->dwCertEncodingType,
1523 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1524 info->lpszIssuerInfo, len);
1525 }else {
1526 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1528 len = CertNameToStrA(context->dwCertEncodingType,
1529 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1530 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1531 if(infoA->lpszSubjectInfo)
1532 CertNameToStrA(context->dwCertEncodingType,
1533 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1534 infoA->lpszSubjectInfo, len);
1535 len = CertNameToStrA(context->dwCertEncodingType,
1536 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1537 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1538 if(infoA->lpszIssuerInfo)
1539 CertNameToStrA(context->dwCertEncodingType,
1540 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1541 infoA->lpszIssuerInfo, len);
1545 * Contrary to MSDN, these do not appear to be set.
1546 * lpszProtocolName
1547 * lpszSignatureAlgName
1548 * lpszEncryptionAlgName
1549 * dwKeySize
1551 CertFreeCertificateContext(context);
1552 return ERROR_SUCCESS;
1557 return INET_QueryOption(option, buffer, size, unicode);
1560 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1562 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1564 switch(option) {
1565 case INTERNET_OPTION_SEND_TIMEOUT:
1566 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1567 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1569 if (size != sizeof(DWORD))
1570 return ERROR_INVALID_PARAMETER;
1572 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1573 *(DWORD*)buffer);
1575 case INTERNET_OPTION_USERNAME:
1576 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1577 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1578 return ERROR_SUCCESS;
1580 case INTERNET_OPTION_PASSWORD:
1581 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1582 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1583 return ERROR_SUCCESS;
1586 return ERROR_INTERNET_INVALID_OPTION;
1589 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1591 INTERNET_ASYNC_RESULT iar;
1592 BYTE buffer[4096];
1593 int available;
1594 BOOL res;
1596 TRACE("%p\n", req);
1598 res = NETCON_recv(&req->netConnection, buffer,
1599 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1600 MSG_PEEK, &available);
1602 if(res) {
1603 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1604 iar.dwError = first_notif ? 0 : available;
1605 }else {
1606 iar.dwResult = 0;
1607 iar.dwError = INTERNET_GetLastError();
1610 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1611 sizeof(INTERNET_ASYNC_RESULT));
1614 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1616 int bytes_read;
1618 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1619 sync ? MSG_WAITALL : 0, &bytes_read)) {
1620 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1621 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1623 /* always return success, even if the network layer returns an error */
1624 *read = 0;
1625 HTTP_FinishedReading(req);
1626 return ERROR_SUCCESS;
1629 req->dwContentRead += bytes_read;
1630 *read = bytes_read;
1632 if(req->lpszCacheFile) {
1633 BOOL res;
1634 DWORD dwBytesWritten;
1636 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1637 if(!res)
1638 WARN("WriteFile failed: %u\n", GetLastError());
1641 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1642 HTTP_FinishedReading(req);
1644 return ERROR_SUCCESS;
1647 static DWORD get_chunk_size(const char *buffer)
1649 const char *p;
1650 DWORD size = 0;
1652 for (p = buffer; *p; p++)
1654 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1655 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1656 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1657 else if (*p == ';') break;
1659 return size;
1662 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1664 char reply[MAX_REPLY_LEN], *p = buffer;
1665 DWORD buflen, to_read, to_write = size;
1666 int bytes_read;
1668 *read = 0;
1669 for (;;)
1671 if (*read == size) break;
1673 if (req->dwContentLength == ~0u) /* new chunk */
1675 buflen = sizeof(reply);
1676 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1678 if (!(req->dwContentLength = get_chunk_size(reply)))
1680 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1681 HTTP_GetResponseHeaders(req, FALSE);
1682 break;
1685 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1687 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1689 if (bytes_read != to_read)
1690 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1692 /* always return success, even if the network layer returns an error */
1693 *read = 0;
1694 break;
1696 if (!bytes_read) break;
1698 req->dwContentRead += bytes_read;
1699 to_write -= bytes_read;
1700 *read += bytes_read;
1702 if (req->lpszCacheFile)
1704 DWORD dwBytesWritten;
1706 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1707 WARN("WriteFile failed: %u\n", GetLastError());
1709 p += bytes_read;
1711 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1713 req->dwContentRead = 0;
1714 req->dwContentLength = ~0u;
1716 buflen = sizeof(reply);
1717 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1719 ERR("Malformed chunk\n");
1720 *read = 0;
1721 break;
1725 if (!*read) HTTP_FinishedReading(req);
1726 return ERROR_SUCCESS;
1729 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1731 WCHAR encoding[20];
1732 DWORD buflen = sizeof(encoding);
1733 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1735 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1736 !strcmpiW(encoding, szChunked))
1738 return HTTP_ReadChunked(req, buffer, size, read, sync);
1740 else
1741 return HTTP_Read(req, buffer, size, read, sync);
1744 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1746 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1747 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1750 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
1752 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1753 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1754 INTERNET_ASYNC_RESULT iar;
1755 DWORD res;
1757 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1759 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1760 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1762 iar.dwResult = res == ERROR_SUCCESS;
1763 iar.dwError = res;
1765 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1766 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1767 sizeof(INTERNET_ASYNC_RESULT));
1770 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1771 DWORD flags, DWORD_PTR context)
1774 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1775 DWORD res;
1777 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1778 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1780 if (buffers->dwStructSize != sizeof(*buffers))
1781 return ERROR_INVALID_PARAMETER;
1783 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1785 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1786 DWORD available = 0;
1788 NETCON_query_data_available(&req->netConnection, &available);
1789 if (!available)
1791 WORKREQUEST workRequest;
1793 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
1794 workRequest.hdr = WININET_AddRef(&req->hdr);
1795 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1797 INTERNET_AsyncCall(&workRequest);
1799 return ERROR_IO_PENDING;
1803 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1804 !(flags & IRF_NO_WAIT));
1806 if (res == ERROR_SUCCESS) {
1807 DWORD size = buffers->dwBufferLength;
1808 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1809 &size, sizeof(size));
1812 return res;
1815 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
1817 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
1818 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1819 INTERNET_ASYNC_RESULT iar;
1820 DWORD res;
1822 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
1824 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1825 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1827 iar.dwResult = res == ERROR_SUCCESS;
1828 iar.dwError = res;
1830 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1831 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1832 sizeof(INTERNET_ASYNC_RESULT));
1835 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
1836 DWORD flags, DWORD_PTR context)
1839 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1840 DWORD res;
1842 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1843 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1845 if (buffers->dwStructSize != sizeof(*buffers))
1846 return ERROR_INVALID_PARAMETER;
1848 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1850 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1851 DWORD available = 0;
1853 NETCON_query_data_available(&req->netConnection, &available);
1854 if (!available)
1856 WORKREQUEST workRequest;
1858 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
1859 workRequest.hdr = WININET_AddRef(&req->hdr);
1860 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
1862 INTERNET_AsyncCall(&workRequest);
1864 return ERROR_IO_PENDING;
1868 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1869 !(flags & IRF_NO_WAIT));
1871 if (res == ERROR_SUCCESS) {
1872 DWORD size = buffers->dwBufferLength;
1873 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1874 &size, sizeof(size));
1877 return res;
1880 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1882 BOOL ret;
1883 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1885 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1887 *written = 0;
1888 if ((ret = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written)))
1889 lpwhr->dwBytesWritten += *written;
1891 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
1892 return ret;
1895 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1897 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1899 HTTP_ReceiveRequestData(req, FALSE);
1902 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1904 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1905 BYTE buffer[4048];
1906 BOOL async;
1908 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1910 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1911 return ERROR_SUCCESS;
1913 /* Even if we are in async mode, we need to determine whether
1914 * there is actually more data available. We do this by trying
1915 * to peek only a single byte in async mode. */
1916 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1918 if (NETCON_recv(&req->netConnection, buffer,
1919 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1920 MSG_PEEK, (int *)available) && async && *available)
1922 WORKREQUEST workRequest;
1924 *available = 0;
1925 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1926 workRequest.hdr = WININET_AddRef( &req->hdr );
1928 INTERNET_AsyncCall(&workRequest);
1930 return ERROR_IO_PENDING;
1933 return ERROR_SUCCESS;
1936 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1937 HTTPREQ_Destroy,
1938 HTTPREQ_CloseConnection,
1939 HTTPREQ_QueryOption,
1940 HTTPREQ_SetOption,
1941 HTTPREQ_ReadFile,
1942 HTTPREQ_ReadFileExA,
1943 HTTPREQ_ReadFileExW,
1944 HTTPREQ_WriteFile,
1945 HTTPREQ_QueryDataAvailable,
1946 NULL
1949 /***********************************************************************
1950 * HTTP_HttpOpenRequestW (internal)
1952 * Open a HTTP request handle
1954 * RETURNS
1955 * HINTERNET a HTTP request handle on success
1956 * NULL on failure
1959 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1960 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1961 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1962 DWORD dwFlags, DWORD_PTR dwContext)
1964 LPWININETAPPINFOW hIC = NULL;
1965 LPWININETHTTPREQW lpwhr;
1966 LPWSTR lpszHostName = NULL;
1967 HINTERNET handle = NULL;
1968 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1969 DWORD len;
1971 TRACE("-->\n");
1973 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1974 hIC = lpwhs->lpAppInfo;
1976 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1977 if (NULL == lpwhr)
1979 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1980 goto lend;
1982 lpwhr->hdr.htype = WH_HHTTPREQ;
1983 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1984 lpwhr->hdr.dwFlags = dwFlags;
1985 lpwhr->hdr.dwContext = dwContext;
1986 lpwhr->hdr.refs = 1;
1987 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1988 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1990 WININET_AddRef( &lpwhs->hdr );
1991 lpwhr->lpHttpSession = lpwhs;
1992 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1994 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1995 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1996 if (NULL == lpszHostName)
1998 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1999 goto lend;
2002 handle = WININET_AllocHandle( &lpwhr->hdr );
2003 if (NULL == handle)
2005 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2006 goto lend;
2009 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
2011 InternetCloseHandle( handle );
2012 handle = NULL;
2013 goto lend;
2016 if (lpszObjectName && *lpszObjectName) {
2017 HRESULT rc;
2019 len = 0;
2020 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2021 if (rc != E_POINTER)
2022 len = strlenW(lpszObjectName)+1;
2023 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2024 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2025 URL_ESCAPE_SPACES_ONLY);
2026 if (rc != S_OK)
2028 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2029 strcpyW(lpwhr->lpszPath,lpszObjectName);
2033 if (lpszReferrer && *lpszReferrer)
2034 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2036 if (lpszAcceptTypes)
2038 int i;
2039 for (i = 0; lpszAcceptTypes[i]; i++)
2041 if (!*lpszAcceptTypes[i]) continue;
2042 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2043 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2044 HTTP_ADDHDR_FLAG_REQ |
2045 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2049 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2051 if (lpszVersion)
2052 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2053 else
2054 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2056 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2057 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2058 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2060 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2061 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2062 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2064 else
2065 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2066 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2068 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2069 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2070 INTERNET_DEFAULT_HTTPS_PORT :
2071 INTERNET_DEFAULT_HTTP_PORT);
2073 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2074 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2075 INTERNET_DEFAULT_HTTPS_PORT :
2076 INTERNET_DEFAULT_HTTP_PORT);
2078 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2079 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2081 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2082 INTERNET_STATUS_HANDLE_CREATED, &handle,
2083 sizeof(handle));
2085 lend:
2086 HeapFree(GetProcessHeap(), 0, lpszHostName);
2087 if( lpwhr )
2088 WININET_Release( &lpwhr->hdr );
2090 TRACE("<-- %p (%p)\n", handle, lpwhr);
2091 return handle;
2094 /* read any content returned by the server so that the connection can be
2095 * reused */
2096 static void HTTP_DrainContent(WININETHTTPREQW *req)
2098 DWORD bytes_read;
2100 if (!NETCON_connected(&req->netConnection)) return;
2102 if (req->dwContentLength == -1)
2103 NETCON_close(&req->netConnection);
2107 char buffer[2048];
2108 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2109 return;
2110 } while (bytes_read);
2113 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2114 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2115 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2116 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2117 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2118 static const WCHAR szAge[] = { 'A','g','e',0 };
2119 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2120 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2121 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2122 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2123 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2124 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2125 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2126 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2127 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2128 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2129 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2130 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 };
2131 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2132 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2133 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2134 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2135 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2136 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2137 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2138 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2139 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2140 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2141 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2142 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2143 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2144 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2145 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2146 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2147 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2148 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2149 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2150 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2151 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2152 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2153 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2154 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2155 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2156 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2157 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 };
2158 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2159 static const WCHAR szURI[] = { 'U','R','I',0 };
2160 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2161 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2162 static const WCHAR szVia[] = { 'V','i','a',0 };
2163 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2164 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2166 static const LPCWSTR header_lookup[] = {
2167 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2168 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2169 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2170 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2171 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2172 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2173 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2174 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2175 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2176 szDate, /* HTTP_QUERY_DATE = 9 */
2177 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2178 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2179 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2180 szURI, /* HTTP_QUERY_URI = 13 */
2181 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2182 NULL, /* HTTP_QUERY_COST = 15 */
2183 NULL, /* HTTP_QUERY_LINK = 16 */
2184 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2185 NULL, /* HTTP_QUERY_VERSION = 18 */
2186 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2187 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2188 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2189 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2190 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2191 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2192 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2193 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2194 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2195 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2196 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2197 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2198 NULL, /* HTTP_QUERY_FROM = 31 */
2199 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2200 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2201 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2202 szReferer, /* HTTP_QUERY_REFERER = 35 */
2203 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2204 szServer, /* HTTP_QUERY_SERVER = 37 */
2205 NULL, /* HTTP_TITLE = 38 */
2206 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2207 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2208 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2209 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2210 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2211 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2212 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2213 NULL, /* HTTP_QUERY_REFRESH = 46 */
2214 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2215 szAge, /* HTTP_QUERY_AGE = 48 */
2216 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2217 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2218 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2219 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2220 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2221 szETag, /* HTTP_QUERY_ETAG = 54 */
2222 szHost, /* HTTP_QUERY_HOST = 55 */
2223 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2224 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2225 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2226 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2227 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2228 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2229 szRange, /* HTTP_QUERY_RANGE = 62 */
2230 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2231 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2232 szVary, /* HTTP_QUERY_VARY = 65 */
2233 szVia, /* HTTP_QUERY_VIA = 66 */
2234 szWarning, /* HTTP_QUERY_WARNING = 67 */
2235 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2236 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2237 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2240 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2242 /***********************************************************************
2243 * HTTP_HttpQueryInfoW (internal)
2245 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2246 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2248 LPHTTPHEADERW lphttpHdr = NULL;
2249 BOOL bSuccess = FALSE;
2250 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2251 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2252 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2253 INT index = -1;
2255 /* Find requested header structure */
2256 switch (level)
2258 case HTTP_QUERY_CUSTOM:
2259 if (!lpBuffer) return FALSE;
2260 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2261 break;
2263 case HTTP_QUERY_RAW_HEADERS_CRLF:
2265 LPWSTR headers;
2266 DWORD len = 0;
2267 BOOL ret = FALSE;
2269 if (request_only)
2270 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2271 else
2272 headers = lpwhr->lpszRawHeaders;
2274 if (headers)
2275 len = strlenW(headers) * sizeof(WCHAR);
2277 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2279 len += sizeof(WCHAR);
2280 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2281 ret = FALSE;
2283 else if (lpBuffer)
2285 if (headers)
2286 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2287 else
2289 len = strlenW(szCrLf) * sizeof(WCHAR);
2290 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2292 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2293 ret = TRUE;
2295 *lpdwBufferLength = len;
2297 if (request_only)
2298 HeapFree(GetProcessHeap(), 0, headers);
2299 return ret;
2301 case HTTP_QUERY_RAW_HEADERS:
2303 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2304 DWORD i, size = 0;
2305 LPWSTR pszString = lpBuffer;
2307 for (i = 0; ppszRawHeaderLines[i]; i++)
2308 size += strlenW(ppszRawHeaderLines[i]) + 1;
2310 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2312 HTTP_FreeTokens(ppszRawHeaderLines);
2313 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2314 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2315 return FALSE;
2317 if (pszString)
2319 for (i = 0; ppszRawHeaderLines[i]; i++)
2321 DWORD len = strlenW(ppszRawHeaderLines[i]);
2322 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2323 pszString += len+1;
2325 *pszString = '\0';
2326 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2328 *lpdwBufferLength = size * sizeof(WCHAR);
2329 HTTP_FreeTokens(ppszRawHeaderLines);
2331 return TRUE;
2333 case HTTP_QUERY_STATUS_TEXT:
2334 if (lpwhr->lpszStatusText)
2336 DWORD len = strlenW(lpwhr->lpszStatusText);
2337 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2339 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2340 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2341 return FALSE;
2343 if (lpBuffer)
2345 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2346 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2348 *lpdwBufferLength = len * sizeof(WCHAR);
2349 return TRUE;
2351 break;
2352 case HTTP_QUERY_VERSION:
2353 if (lpwhr->lpszVersion)
2355 DWORD len = strlenW(lpwhr->lpszVersion);
2356 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2358 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2359 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2360 return FALSE;
2362 if (lpBuffer)
2364 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2365 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2367 *lpdwBufferLength = len * sizeof(WCHAR);
2368 return TRUE;
2370 break;
2371 default:
2372 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2374 if (level < LAST_TABLE_HEADER && header_lookup[level])
2375 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2376 requested_index,request_only);
2379 if (index >= 0)
2380 lphttpHdr = &lpwhr->pCustHeaders[index];
2382 /* Ensure header satisfies requested attributes */
2383 if (!lphttpHdr ||
2384 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2385 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2387 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2388 return bSuccess;
2391 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2393 /* coalesce value to requested type */
2394 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2396 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2397 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2398 bSuccess = TRUE;
2400 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2402 time_t tmpTime;
2403 struct tm tmpTM;
2404 SYSTEMTIME *STHook;
2406 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2408 tmpTM = *gmtime(&tmpTime);
2409 STHook = (SYSTEMTIME *)lpBuffer;
2410 STHook->wDay = tmpTM.tm_mday;
2411 STHook->wHour = tmpTM.tm_hour;
2412 STHook->wMilliseconds = 0;
2413 STHook->wMinute = tmpTM.tm_min;
2414 STHook->wDayOfWeek = tmpTM.tm_wday;
2415 STHook->wMonth = tmpTM.tm_mon + 1;
2416 STHook->wSecond = tmpTM.tm_sec;
2417 STHook->wYear = tmpTM.tm_year;
2418 bSuccess = TRUE;
2420 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2421 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2422 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2424 else if (lphttpHdr->lpszValue)
2426 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2428 if (len > *lpdwBufferLength)
2430 *lpdwBufferLength = len;
2431 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2432 return bSuccess;
2434 if (lpBuffer)
2436 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2437 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2439 *lpdwBufferLength = len - sizeof(WCHAR);
2440 bSuccess = TRUE;
2442 return bSuccess;
2445 /***********************************************************************
2446 * HttpQueryInfoW (WININET.@)
2448 * Queries for information about an HTTP request
2450 * RETURNS
2451 * TRUE on success
2452 * FALSE on failure
2455 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2456 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2458 BOOL bSuccess = FALSE;
2459 LPWININETHTTPREQW lpwhr;
2461 if (TRACE_ON(wininet)) {
2462 #define FE(x) { x, #x }
2463 static const wininet_flag_info query_flags[] = {
2464 FE(HTTP_QUERY_MIME_VERSION),
2465 FE(HTTP_QUERY_CONTENT_TYPE),
2466 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2467 FE(HTTP_QUERY_CONTENT_ID),
2468 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2469 FE(HTTP_QUERY_CONTENT_LENGTH),
2470 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2471 FE(HTTP_QUERY_ALLOW),
2472 FE(HTTP_QUERY_PUBLIC),
2473 FE(HTTP_QUERY_DATE),
2474 FE(HTTP_QUERY_EXPIRES),
2475 FE(HTTP_QUERY_LAST_MODIFIED),
2476 FE(HTTP_QUERY_MESSAGE_ID),
2477 FE(HTTP_QUERY_URI),
2478 FE(HTTP_QUERY_DERIVED_FROM),
2479 FE(HTTP_QUERY_COST),
2480 FE(HTTP_QUERY_LINK),
2481 FE(HTTP_QUERY_PRAGMA),
2482 FE(HTTP_QUERY_VERSION),
2483 FE(HTTP_QUERY_STATUS_CODE),
2484 FE(HTTP_QUERY_STATUS_TEXT),
2485 FE(HTTP_QUERY_RAW_HEADERS),
2486 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2487 FE(HTTP_QUERY_CONNECTION),
2488 FE(HTTP_QUERY_ACCEPT),
2489 FE(HTTP_QUERY_ACCEPT_CHARSET),
2490 FE(HTTP_QUERY_ACCEPT_ENCODING),
2491 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2492 FE(HTTP_QUERY_AUTHORIZATION),
2493 FE(HTTP_QUERY_CONTENT_ENCODING),
2494 FE(HTTP_QUERY_FORWARDED),
2495 FE(HTTP_QUERY_FROM),
2496 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2497 FE(HTTP_QUERY_LOCATION),
2498 FE(HTTP_QUERY_ORIG_URI),
2499 FE(HTTP_QUERY_REFERER),
2500 FE(HTTP_QUERY_RETRY_AFTER),
2501 FE(HTTP_QUERY_SERVER),
2502 FE(HTTP_QUERY_TITLE),
2503 FE(HTTP_QUERY_USER_AGENT),
2504 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2505 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2506 FE(HTTP_QUERY_ACCEPT_RANGES),
2507 FE(HTTP_QUERY_SET_COOKIE),
2508 FE(HTTP_QUERY_COOKIE),
2509 FE(HTTP_QUERY_REQUEST_METHOD),
2510 FE(HTTP_QUERY_REFRESH),
2511 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2512 FE(HTTP_QUERY_AGE),
2513 FE(HTTP_QUERY_CACHE_CONTROL),
2514 FE(HTTP_QUERY_CONTENT_BASE),
2515 FE(HTTP_QUERY_CONTENT_LOCATION),
2516 FE(HTTP_QUERY_CONTENT_MD5),
2517 FE(HTTP_QUERY_CONTENT_RANGE),
2518 FE(HTTP_QUERY_ETAG),
2519 FE(HTTP_QUERY_HOST),
2520 FE(HTTP_QUERY_IF_MATCH),
2521 FE(HTTP_QUERY_IF_NONE_MATCH),
2522 FE(HTTP_QUERY_IF_RANGE),
2523 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2524 FE(HTTP_QUERY_MAX_FORWARDS),
2525 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2526 FE(HTTP_QUERY_RANGE),
2527 FE(HTTP_QUERY_TRANSFER_ENCODING),
2528 FE(HTTP_QUERY_UPGRADE),
2529 FE(HTTP_QUERY_VARY),
2530 FE(HTTP_QUERY_VIA),
2531 FE(HTTP_QUERY_WARNING),
2532 FE(HTTP_QUERY_CUSTOM)
2534 static const wininet_flag_info modifier_flags[] = {
2535 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2536 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2537 FE(HTTP_QUERY_FLAG_NUMBER),
2538 FE(HTTP_QUERY_FLAG_COALESCE)
2540 #undef FE
2541 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2542 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2543 DWORD i;
2545 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2546 TRACE(" Attribute:");
2547 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2548 if (query_flags[i].val == info) {
2549 TRACE(" %s", query_flags[i].name);
2550 break;
2553 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2554 TRACE(" Unknown (%08x)", info);
2557 TRACE(" Modifier:");
2558 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2559 if (modifier_flags[i].val & info_mod) {
2560 TRACE(" %s", modifier_flags[i].name);
2561 info_mod &= ~ modifier_flags[i].val;
2565 if (info_mod) {
2566 TRACE(" Unknown (%08x)", info_mod);
2568 TRACE("\n");
2571 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2572 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2574 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2575 goto lend;
2578 if (lpBuffer == NULL)
2579 *lpdwBufferLength = 0;
2580 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2581 lpBuffer, lpdwBufferLength, lpdwIndex);
2583 lend:
2584 if( lpwhr )
2585 WININET_Release( &lpwhr->hdr );
2587 TRACE("%d <--\n", bSuccess);
2588 return bSuccess;
2591 /***********************************************************************
2592 * HttpQueryInfoA (WININET.@)
2594 * Queries for information about an HTTP request
2596 * RETURNS
2597 * TRUE on success
2598 * FALSE on failure
2601 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2602 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2604 BOOL result;
2605 DWORD len;
2606 WCHAR* bufferW;
2608 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2609 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2611 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2612 lpdwBufferLength, lpdwIndex );
2615 if (lpBuffer)
2617 DWORD alloclen;
2618 len = (*lpdwBufferLength)*sizeof(WCHAR);
2619 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2621 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2622 if (alloclen < len)
2623 alloclen = len;
2625 else
2626 alloclen = len;
2627 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2628 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2629 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2630 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2631 } else
2633 bufferW = NULL;
2634 len = 0;
2637 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2638 &len, lpdwIndex );
2639 if( result )
2641 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2642 lpBuffer, *lpdwBufferLength, NULL, NULL );
2643 *lpdwBufferLength = len - 1;
2645 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2647 else
2648 /* since the strings being returned from HttpQueryInfoW should be
2649 * only ASCII characters, it is reasonable to assume that all of
2650 * the Unicode characters can be reduced to a single byte */
2651 *lpdwBufferLength = len / sizeof(WCHAR);
2653 HeapFree(GetProcessHeap(), 0, bufferW );
2655 return result;
2658 /***********************************************************************
2659 * HttpSendRequestExA (WININET.@)
2661 * Sends the specified request to the HTTP server and allows chunked
2662 * transfers.
2664 * RETURNS
2665 * Success: TRUE
2666 * Failure: FALSE, call GetLastError() for more information.
2668 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2669 LPINTERNET_BUFFERSA lpBuffersIn,
2670 LPINTERNET_BUFFERSA lpBuffersOut,
2671 DWORD dwFlags, DWORD_PTR dwContext)
2673 INTERNET_BUFFERSW BuffersInW;
2674 BOOL rc = FALSE;
2675 DWORD headerlen;
2676 LPWSTR header = NULL;
2678 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2679 lpBuffersOut, dwFlags, dwContext);
2681 if (lpBuffersIn)
2683 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2684 if (lpBuffersIn->lpcszHeader)
2686 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2687 lpBuffersIn->dwHeadersLength,0,0);
2688 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2689 if (!(BuffersInW.lpcszHeader = header))
2691 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2692 return FALSE;
2694 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2695 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2696 header, headerlen);
2698 else
2699 BuffersInW.lpcszHeader = NULL;
2700 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2701 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2702 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2703 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2704 BuffersInW.Next = NULL;
2707 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2709 HeapFree(GetProcessHeap(),0,header);
2711 return rc;
2714 /***********************************************************************
2715 * HttpSendRequestExW (WININET.@)
2717 * Sends the specified request to the HTTP server and allows chunked
2718 * transfers
2720 * RETURNS
2721 * Success: TRUE
2722 * Failure: FALSE, call GetLastError() for more information.
2724 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2725 LPINTERNET_BUFFERSW lpBuffersIn,
2726 LPINTERNET_BUFFERSW lpBuffersOut,
2727 DWORD dwFlags, DWORD_PTR dwContext)
2729 BOOL ret = FALSE;
2730 LPWININETHTTPREQW lpwhr;
2731 LPWININETHTTPSESSIONW lpwhs;
2732 LPWININETAPPINFOW hIC;
2734 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2735 lpBuffersOut, dwFlags, dwContext);
2737 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2739 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2741 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2742 goto lend;
2745 lpwhs = lpwhr->lpHttpSession;
2746 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2747 hIC = lpwhs->lpAppInfo;
2748 assert(hIC->hdr.htype == WH_HINIT);
2750 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2752 WORKREQUEST workRequest;
2753 struct WORKREQ_HTTPSENDREQUESTW *req;
2755 workRequest.asyncproc = AsyncHttpSendRequestProc;
2756 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2757 req = &workRequest.u.HttpSendRequestW;
2758 if (lpBuffersIn)
2760 if (lpBuffersIn->lpcszHeader)
2761 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2762 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2763 else
2764 req->lpszHeader = NULL;
2765 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2766 req->lpOptional = lpBuffersIn->lpvBuffer;
2767 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2768 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2770 else
2772 req->lpszHeader = NULL;
2773 req->dwHeaderLength = 0;
2774 req->lpOptional = NULL;
2775 req->dwOptionalLength = 0;
2776 req->dwContentLength = 0;
2779 req->bEndRequest = FALSE;
2781 INTERNET_AsyncCall(&workRequest);
2783 * This is from windows.
2785 INTERNET_SetLastError(ERROR_IO_PENDING);
2787 else
2789 if (lpBuffersIn)
2790 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2791 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2792 lpBuffersIn->dwBufferTotal, FALSE);
2793 else
2794 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2797 lend:
2798 if ( lpwhr )
2799 WININET_Release( &lpwhr->hdr );
2801 TRACE("<---\n");
2802 return ret;
2805 /***********************************************************************
2806 * HttpSendRequestW (WININET.@)
2808 * Sends the specified request to the HTTP server
2810 * RETURNS
2811 * TRUE on success
2812 * FALSE on failure
2815 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2816 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2818 LPWININETHTTPREQW lpwhr;
2819 LPWININETHTTPSESSIONW lpwhs = NULL;
2820 LPWININETAPPINFOW hIC = NULL;
2821 BOOL r;
2823 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2824 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2826 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2827 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2829 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2830 r = FALSE;
2831 goto lend;
2834 lpwhs = lpwhr->lpHttpSession;
2835 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2837 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2838 r = FALSE;
2839 goto lend;
2842 hIC = lpwhs->lpAppInfo;
2843 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2845 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2846 r = FALSE;
2847 goto lend;
2850 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2852 WORKREQUEST workRequest;
2853 struct WORKREQ_HTTPSENDREQUESTW *req;
2855 workRequest.asyncproc = AsyncHttpSendRequestProc;
2856 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2857 req = &workRequest.u.HttpSendRequestW;
2858 if (lpszHeaders)
2860 DWORD size;
2862 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
2863 else size = dwHeaderLength * sizeof(WCHAR);
2865 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
2866 memcpy(req->lpszHeader, lpszHeaders, size);
2868 else
2869 req->lpszHeader = 0;
2870 req->dwHeaderLength = dwHeaderLength;
2871 req->lpOptional = lpOptional;
2872 req->dwOptionalLength = dwOptionalLength;
2873 req->dwContentLength = dwOptionalLength;
2874 req->bEndRequest = TRUE;
2876 INTERNET_AsyncCall(&workRequest);
2878 * This is from windows.
2880 INTERNET_SetLastError(ERROR_IO_PENDING);
2881 r = FALSE;
2883 else
2885 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2886 dwHeaderLength, lpOptional, dwOptionalLength,
2887 dwOptionalLength, TRUE);
2889 lend:
2890 if( lpwhr )
2891 WININET_Release( &lpwhr->hdr );
2892 return r;
2895 /***********************************************************************
2896 * HttpSendRequestA (WININET.@)
2898 * Sends the specified request to the HTTP server
2900 * RETURNS
2901 * TRUE on success
2902 * FALSE on failure
2905 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2906 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2908 BOOL result;
2909 LPWSTR szHeaders=NULL;
2910 DWORD nLen=dwHeaderLength;
2911 if(lpszHeaders!=NULL)
2913 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2914 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2915 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2917 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2918 HeapFree(GetProcessHeap(),0,szHeaders);
2919 return result;
2922 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2924 LPHTTPHEADERW host_header;
2926 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2928 host_header = HTTP_GetHeader(req, szHost);
2929 if(!host_header)
2930 return FALSE;
2932 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2933 return TRUE;
2936 /***********************************************************************
2937 * HTTP_HandleRedirect (internal)
2939 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2941 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2942 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2943 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2944 WCHAR path[INTERNET_MAX_URL_LENGTH];
2945 int index;
2947 if(lpszUrl[0]=='/')
2949 /* if it's an absolute path, keep the same session info */
2950 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2952 else
2954 URL_COMPONENTSW urlComponents;
2955 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2956 static WCHAR szHttp[] = {'h','t','t','p',0};
2957 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2958 DWORD url_length = 0;
2959 LPWSTR orig_url;
2960 LPWSTR combined_url;
2962 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2963 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2964 urlComponents.dwSchemeLength = 0;
2965 urlComponents.lpszHostName = lpwhs->lpszHostName;
2966 urlComponents.dwHostNameLength = 0;
2967 urlComponents.nPort = lpwhs->nHostPort;
2968 urlComponents.lpszUserName = lpwhs->lpszUserName;
2969 urlComponents.dwUserNameLength = 0;
2970 urlComponents.lpszPassword = NULL;
2971 urlComponents.dwPasswordLength = 0;
2972 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2973 urlComponents.dwUrlPathLength = 0;
2974 urlComponents.lpszExtraInfo = NULL;
2975 urlComponents.dwExtraInfoLength = 0;
2977 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2978 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2979 return FALSE;
2981 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2983 /* convert from bytes to characters */
2984 url_length = url_length / sizeof(WCHAR) - 1;
2985 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2987 HeapFree(GetProcessHeap(), 0, orig_url);
2988 return FALSE;
2991 url_length = 0;
2992 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2993 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2995 HeapFree(GetProcessHeap(), 0, orig_url);
2996 return FALSE;
2998 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
3000 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
3002 HeapFree(GetProcessHeap(), 0, orig_url);
3003 HeapFree(GetProcessHeap(), 0, combined_url);
3004 return FALSE;
3006 HeapFree(GetProcessHeap(), 0, orig_url);
3008 userName[0] = 0;
3009 hostName[0] = 0;
3010 protocol[0] = 0;
3012 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3013 urlComponents.lpszScheme = protocol;
3014 urlComponents.dwSchemeLength = 32;
3015 urlComponents.lpszHostName = hostName;
3016 urlComponents.dwHostNameLength = MAXHOSTNAME;
3017 urlComponents.lpszUserName = userName;
3018 urlComponents.dwUserNameLength = 1024;
3019 urlComponents.lpszPassword = NULL;
3020 urlComponents.dwPasswordLength = 0;
3021 urlComponents.lpszUrlPath = path;
3022 urlComponents.dwUrlPathLength = 2048;
3023 urlComponents.lpszExtraInfo = NULL;
3024 urlComponents.dwExtraInfoLength = 0;
3025 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
3027 HeapFree(GetProcessHeap(), 0, combined_url);
3028 return FALSE;
3031 HeapFree(GetProcessHeap(), 0, combined_url);
3033 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3034 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3036 TRACE("redirect from secure page to non-secure page\n");
3037 /* FIXME: warn about from secure redirect to non-secure page */
3038 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3040 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3041 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3043 TRACE("redirect from non-secure page to secure page\n");
3044 /* FIXME: notify about redirect to secure page */
3045 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3048 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3050 if (lstrlenW(protocol)>4) /*https*/
3051 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3052 else /*http*/
3053 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3056 #if 0
3058 * This upsets redirects to binary files on sourceforge.net
3059 * and gives an html page instead of the target file
3060 * Examination of the HTTP request sent by native wininet.dll
3061 * reveals that it doesn't send a referrer in that case.
3062 * Maybe there's a flag that enables this, or maybe a referrer
3063 * shouldn't be added in case of a redirect.
3066 /* consider the current host as the referrer */
3067 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3068 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3069 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3070 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3071 #endif
3073 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3074 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3075 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3077 int len;
3078 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3079 len = lstrlenW(hostName);
3080 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3081 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3082 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3084 else
3085 lpwhs->lpszHostName = WININET_strdupW(hostName);
3087 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3089 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3090 lpwhs->lpszUserName = NULL;
3091 if (userName[0])
3092 lpwhs->lpszUserName = WININET_strdupW(userName);
3094 if (!using_proxy)
3096 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3098 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3099 lpwhs->lpszServerName = WININET_strdupW(hostName);
3100 lpwhs->nServerPort = urlComponents.nPort;
3102 NETCON_close(&lpwhr->netConnection);
3103 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3104 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3107 else
3108 TRACE("Redirect through proxy\n");
3111 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3112 lpwhr->lpszPath=NULL;
3113 if (*path)
3115 DWORD needed = 0;
3116 HRESULT rc;
3118 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3119 if (rc != E_POINTER)
3120 needed = strlenW(path)+1;
3121 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3122 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3123 URL_ESCAPE_SPACES_ONLY);
3124 if (rc != S_OK)
3126 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3127 strcpyW(lpwhr->lpszPath,path);
3131 /* Remove custom content-type/length headers on redirects. */
3132 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3133 if (0 <= index)
3134 HTTP_DeleteCustomHeader(lpwhr, index);
3135 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3136 if (0 <= index)
3137 HTTP_DeleteCustomHeader(lpwhr, index);
3139 return TRUE;
3142 /***********************************************************************
3143 * HTTP_build_req (internal)
3145 * concatenate all the strings in the request together
3147 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3149 LPCWSTR *t;
3150 LPWSTR str;
3152 for( t = list; *t ; t++ )
3153 len += strlenW( *t );
3154 len++;
3156 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3157 *str = 0;
3159 for( t = list; *t ; t++ )
3160 strcatW( str, *t );
3162 return str;
3165 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3167 LPWSTR lpszPath;
3168 LPWSTR requestString;
3169 INT len;
3170 INT cnt;
3171 INT responseLen;
3172 char *ascii_req;
3173 BOOL ret;
3174 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3175 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3176 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3178 TRACE("\n");
3180 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3181 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3182 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3183 HeapFree( GetProcessHeap(), 0, lpszPath );
3185 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3186 NULL, 0, NULL, NULL );
3187 len--; /* the nul terminator isn't needed */
3188 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3189 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3190 ascii_req, len, NULL, NULL );
3191 HeapFree( GetProcessHeap(), 0, requestString );
3193 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3195 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3196 HeapFree( GetProcessHeap(), 0, ascii_req );
3197 if (!ret || cnt < 0)
3198 return FALSE;
3200 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3201 if (!responseLen)
3202 return FALSE;
3204 return TRUE;
3207 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3209 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3210 LPWSTR lpszCookies, lpszUrl = NULL;
3211 DWORD nCookieSize, size;
3212 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3214 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3215 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3216 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3218 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3220 int cnt = 0;
3221 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3223 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3224 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3226 cnt += sprintfW(lpszCookies, szCookie);
3227 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3228 strcatW(lpszCookies, szCrLf);
3230 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3231 HeapFree(GetProcessHeap(), 0, lpszCookies);
3234 HeapFree(GetProcessHeap(), 0, lpszUrl);
3237 /***********************************************************************
3238 * HTTP_HttpSendRequestW (internal)
3240 * Sends the specified request to the HTTP server
3242 * RETURNS
3243 * TRUE on success
3244 * FALSE on failure
3247 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3248 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3249 DWORD dwContentLength, BOOL bEndRequest)
3251 INT cnt;
3252 BOOL bSuccess = FALSE;
3253 LPWSTR requestString = NULL;
3254 INT responseLen;
3255 BOOL loop_next;
3256 INTERNET_ASYNC_RESULT iar;
3257 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3258 static const WCHAR szContentLength[] =
3259 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3260 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3262 TRACE("--> %p\n", lpwhr);
3264 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3266 /* if the verb is NULL default to GET */
3267 if (!lpwhr->lpszVerb)
3268 lpwhr->lpszVerb = WININET_strdupW(szGET);
3270 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3272 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3273 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3274 lpwhr->dwBytesToWrite = dwContentLength;
3276 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3278 WCHAR *agent_header;
3279 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3280 int len;
3282 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3283 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3284 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3286 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3287 HeapFree(GetProcessHeap(), 0, agent_header);
3289 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3291 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3292 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3294 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3296 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3297 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3298 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3303 DWORD len;
3304 char *ascii_req;
3306 loop_next = FALSE;
3308 /* like native, just in case the caller forgot to call InternetReadFile
3309 * for all the data */
3310 HTTP_DrainContent(lpwhr);
3311 lpwhr->dwContentRead = 0;
3313 if (TRACE_ON(wininet))
3315 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3316 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3319 HTTP_FixURL(lpwhr);
3320 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3322 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3324 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3325 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3327 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3328 HTTP_InsertCookies(lpwhr);
3330 /* add the headers the caller supplied */
3331 if( lpszHeaders && dwHeaderLength )
3333 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3334 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3337 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3339 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3340 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3341 HeapFree(GetProcessHeap(), 0, url);
3343 else
3344 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3347 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3349 /* Send the request and store the results */
3350 if (!HTTP_OpenConnection(lpwhr))
3351 goto lend;
3353 /* send the request as ASCII, tack on the optional data */
3354 if( !lpOptional )
3355 dwOptionalLength = 0;
3356 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3357 NULL, 0, NULL, NULL );
3358 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3359 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3360 ascii_req, len, NULL, NULL );
3361 if( lpOptional )
3362 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3363 len = (len + dwOptionalLength - 1);
3364 ascii_req[len] = 0;
3365 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3367 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3368 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3370 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3371 HeapFree( GetProcessHeap(), 0, ascii_req );
3373 lpwhr->dwBytesWritten = dwOptionalLength;
3375 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3376 INTERNET_STATUS_REQUEST_SENT,
3377 &len, sizeof(DWORD));
3379 if (bEndRequest)
3381 DWORD dwBufferSize;
3382 DWORD dwStatusCode;
3383 WCHAR encoding[20];
3384 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3386 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3387 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3389 if (cnt < 0)
3390 goto lend;
3392 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3393 if (responseLen)
3394 bSuccess = TRUE;
3396 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3397 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3398 sizeof(DWORD));
3400 HTTP_ProcessCookies(lpwhr);
3402 dwBufferSize = sizeof(lpwhr->dwContentLength);
3403 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3404 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3405 lpwhr->dwContentLength = -1;
3407 if (lpwhr->dwContentLength == 0)
3408 HTTP_FinishedReading(lpwhr);
3410 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3412 dwBufferSize = sizeof(encoding);
3413 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3414 !strcmpiW(encoding, szChunked))
3416 lpwhr->dwContentLength = -1;
3419 dwBufferSize = sizeof(dwStatusCode);
3420 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3421 &dwStatusCode,&dwBufferSize,NULL))
3422 dwStatusCode = 0;
3424 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3426 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3427 dwBufferSize=sizeof(szNewLocation);
3428 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3429 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3431 /* redirects are always GETs */
3432 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3433 lpwhr->lpszVerb = WININET_strdupW(szGET);
3435 HTTP_DrainContent(lpwhr);
3436 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3437 INTERNET_STATUS_REDIRECT, szNewLocation,
3438 dwBufferSize);
3439 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3440 if (bSuccess)
3442 HeapFree(GetProcessHeap(), 0, requestString);
3443 loop_next = TRUE;
3447 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3449 WCHAR szAuthValue[2048];
3450 dwBufferSize=2048;
3451 if (dwStatusCode == HTTP_STATUS_DENIED)
3453 DWORD dwIndex = 0;
3454 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3456 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3457 &lpwhr->pAuthInfo,
3458 lpwhr->lpHttpSession->lpszUserName,
3459 lpwhr->lpHttpSession->lpszPassword))
3461 loop_next = TRUE;
3462 break;
3466 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3468 DWORD dwIndex = 0;
3469 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3471 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3472 &lpwhr->pProxyAuthInfo,
3473 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3474 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3476 loop_next = TRUE;
3477 break;
3483 else
3484 bSuccess = TRUE;
3486 while (loop_next);
3488 /* FIXME: Better check, when we have to create the cache file */
3489 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3490 WCHAR url[INTERNET_MAX_URL_LENGTH];
3491 WCHAR cacheFileName[MAX_PATH+1];
3492 BOOL b;
3494 b = HTTP_GetRequestURL(lpwhr, url);
3495 if(!b) {
3496 WARN("Could not get URL\n");
3497 goto lend;
3500 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3501 if(b) {
3502 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3503 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3504 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3505 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3506 WARN("Could not create file: %u\n", GetLastError());
3507 lpwhr->hCacheFile = NULL;
3509 }else {
3510 WARN("Could not create cache entry: %08x\n", GetLastError());
3514 lend:
3516 HeapFree(GetProcessHeap(), 0, requestString);
3518 /* TODO: send notification for P3P header */
3520 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3522 if (bSuccess)
3524 if (lpwhr->dwBytesWritten == lpwhr->dwBytesToWrite) HTTP_ReceiveRequestData(lpwhr, TRUE);
3525 else
3527 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3528 iar.dwError = 0;
3530 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3531 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3532 sizeof(INTERNET_ASYNC_RESULT));
3535 else
3537 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3538 iar.dwError = INTERNET_GetLastError();
3540 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3541 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3542 sizeof(INTERNET_ASYNC_RESULT));
3546 TRACE("<--\n");
3547 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3548 return bSuccess;
3551 /***********************************************************************
3552 * HTTPSESSION_Destroy (internal)
3554 * Deallocate session handle
3557 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3559 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3561 TRACE("%p\n", lpwhs);
3563 WININET_Release(&lpwhs->lpAppInfo->hdr);
3565 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3566 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3567 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3568 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3569 HeapFree(GetProcessHeap(), 0, lpwhs);
3572 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3574 switch(option) {
3575 case INTERNET_OPTION_HANDLE_TYPE:
3576 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3578 if (*size < sizeof(ULONG))
3579 return ERROR_INSUFFICIENT_BUFFER;
3581 *size = sizeof(DWORD);
3582 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3583 return ERROR_SUCCESS;
3586 return INET_QueryOption(option, buffer, size, unicode);
3589 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3591 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3593 switch(option) {
3594 case INTERNET_OPTION_USERNAME:
3596 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3597 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3598 return ERROR_SUCCESS;
3600 case INTERNET_OPTION_PASSWORD:
3602 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3603 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3604 return ERROR_SUCCESS;
3606 default: break;
3609 return ERROR_INTERNET_INVALID_OPTION;
3612 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3613 HTTPSESSION_Destroy,
3614 NULL,
3615 HTTPSESSION_QueryOption,
3616 HTTPSESSION_SetOption,
3617 NULL,
3618 NULL,
3619 NULL,
3620 NULL,
3621 NULL
3625 /***********************************************************************
3626 * HTTP_Connect (internal)
3628 * Create http session handle
3630 * RETURNS
3631 * HINTERNET a session handle on success
3632 * NULL on failure
3635 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3636 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3637 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3638 DWORD dwInternalFlags)
3640 LPWININETHTTPSESSIONW lpwhs = NULL;
3641 HINTERNET handle = NULL;
3643 TRACE("-->\n");
3645 if (!lpszServerName || !lpszServerName[0])
3647 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3648 goto lerror;
3651 assert( hIC->hdr.htype == WH_HINIT );
3653 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3654 if (NULL == lpwhs)
3656 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3657 goto lerror;
3661 * According to my tests. The name is not resolved until a request is sent
3664 lpwhs->hdr.htype = WH_HHTTPSESSION;
3665 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3666 lpwhs->hdr.dwFlags = dwFlags;
3667 lpwhs->hdr.dwContext = dwContext;
3668 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3669 lpwhs->hdr.refs = 1;
3670 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3672 WININET_AddRef( &hIC->hdr );
3673 lpwhs->lpAppInfo = hIC;
3674 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3676 handle = WININET_AllocHandle( &lpwhs->hdr );
3677 if (NULL == handle)
3679 ERR("Failed to alloc handle\n");
3680 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3681 goto lerror;
3684 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3685 if(strchrW(hIC->lpszProxy, ' '))
3686 FIXME("Several proxies not implemented.\n");
3687 if(hIC->lpszProxyBypass)
3688 FIXME("Proxy bypass is ignored.\n");
3690 if (lpszServerName && lpszServerName[0])
3692 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3693 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3695 if (lpszUserName && lpszUserName[0])
3696 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3697 if (lpszPassword && lpszPassword[0])
3698 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3699 lpwhs->nServerPort = nServerPort;
3700 lpwhs->nHostPort = nServerPort;
3702 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3703 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3705 INTERNET_SendCallback(&hIC->hdr, dwContext,
3706 INTERNET_STATUS_HANDLE_CREATED, &handle,
3707 sizeof(handle));
3710 lerror:
3711 if( lpwhs )
3712 WININET_Release( &lpwhs->hdr );
3715 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3716 * windows
3719 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3720 return handle;
3724 /***********************************************************************
3725 * HTTP_OpenConnection (internal)
3727 * Connect to a web server
3729 * RETURNS
3731 * TRUE on success
3732 * FALSE on failure
3734 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3736 BOOL bSuccess = FALSE;
3737 LPWININETHTTPSESSIONW lpwhs;
3738 LPWININETAPPINFOW hIC = NULL;
3739 char szaddr[32];
3741 TRACE("-->\n");
3744 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3746 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3747 goto lend;
3750 if (NETCON_connected(&lpwhr->netConnection))
3752 bSuccess = TRUE;
3753 goto lend;
3755 if (!HTTP_ResolveName(lpwhr)) goto lend;
3757 lpwhs = lpwhr->lpHttpSession;
3759 hIC = lpwhs->lpAppInfo;
3760 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3761 szaddr, sizeof(szaddr));
3762 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3763 INTERNET_STATUS_CONNECTING_TO_SERVER,
3764 szaddr,
3765 strlen(szaddr)+1);
3767 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3768 SOCK_STREAM, 0))
3770 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3771 goto lend;
3774 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3775 sizeof(lpwhs->socketAddress)))
3776 goto lend;
3778 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3780 /* Note: we differ from Microsoft's WinINet here. they seem to have
3781 * a bug that causes no status callbacks to be sent when starting
3782 * a tunnel to a proxy server using the CONNECT verb. i believe our
3783 * behaviour to be more correct and to not cause any incompatibilities
3784 * because using a secure connection through a proxy server is a rare
3785 * case that would be hard for anyone to depend on */
3786 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3787 goto lend;
3789 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3791 WARN("Couldn't connect securely to host\n");
3792 goto lend;
3796 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3797 INTERNET_STATUS_CONNECTED_TO_SERVER,
3798 szaddr, strlen(szaddr)+1);
3800 bSuccess = TRUE;
3802 lend:
3803 TRACE("%d <--\n", bSuccess);
3804 return bSuccess;
3808 /***********************************************************************
3809 * HTTP_clear_response_headers (internal)
3811 * clear out any old response headers
3813 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3815 DWORD i;
3817 for( i=0; i<lpwhr->nCustHeaders; i++)
3819 if( !lpwhr->pCustHeaders[i].lpszField )
3820 continue;
3821 if( !lpwhr->pCustHeaders[i].lpszValue )
3822 continue;
3823 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3824 continue;
3825 HTTP_DeleteCustomHeader( lpwhr, i );
3826 i--;
3830 /***********************************************************************
3831 * HTTP_GetResponseHeaders (internal)
3833 * Read server response
3835 * RETURNS
3837 * TRUE on success
3838 * FALSE on error
3840 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3842 INT cbreaks = 0;
3843 WCHAR buffer[MAX_REPLY_LEN];
3844 DWORD buflen = MAX_REPLY_LEN;
3845 BOOL bSuccess = FALSE;
3846 INT rc = 0;
3847 static const WCHAR szHundred[] = {'1','0','0',0};
3848 char bufferA[MAX_REPLY_LEN];
3849 LPWSTR status_code, status_text;
3850 DWORD cchMaxRawHeaders = 1024;
3851 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3852 DWORD cchRawHeaders = 0;
3854 TRACE("-->\n");
3856 /* clear old response headers (eg. from a redirect response) */
3857 if (clear) HTTP_clear_response_headers( lpwhr );
3859 if (!NETCON_connected(&lpwhr->netConnection))
3860 goto lend;
3862 do {
3864 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3866 buflen = MAX_REPLY_LEN;
3867 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3868 goto lend;
3869 rc += buflen;
3870 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3872 /* split the version from the status code */
3873 status_code = strchrW( buffer, ' ' );
3874 if( !status_code )
3875 goto lend;
3876 *status_code++=0;
3878 /* split the status code from the status text */
3879 status_text = strchrW( status_code, ' ' );
3880 if( !status_text )
3881 goto lend;
3882 *status_text++=0;
3884 TRACE("version [%s] status code [%s] status text [%s]\n",
3885 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3887 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3889 /* Add status code */
3890 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3891 HTTP_ADDHDR_FLAG_REPLACE);
3893 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3894 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3896 lpwhr->lpszVersion= WININET_strdupW(buffer);
3897 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3899 /* Restore the spaces */
3900 *(status_code-1) = ' ';
3901 *(status_text-1) = ' ';
3903 /* regenerate raw headers */
3904 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3906 cchMaxRawHeaders *= 2;
3907 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3909 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3910 cchRawHeaders += (buflen-1);
3911 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3912 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3913 lpszRawHeaders[cchRawHeaders] = '\0';
3915 /* Parse each response line */
3918 buflen = MAX_REPLY_LEN;
3919 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3921 LPWSTR * pFieldAndValue;
3923 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3925 if (!bufferA[0]) break;
3926 if (!strchr(bufferA, ':'))
3928 WARN("invalid header\n");
3929 continue;
3931 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3933 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3935 cchMaxRawHeaders *= 2;
3936 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3938 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3939 cchRawHeaders += (buflen-1);
3940 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3941 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3942 lpszRawHeaders[cchRawHeaders] = '\0';
3944 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3945 if (!pFieldAndValue)
3946 break;
3948 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3949 HTTP_ADDREQ_FLAG_ADD );
3951 HTTP_FreeTokens(pFieldAndValue);
3953 else
3955 cbreaks++;
3956 if (cbreaks >= 2)
3957 break;
3959 }while(1);
3961 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3962 lpwhr->lpszRawHeaders = lpszRawHeaders;
3963 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3964 bSuccess = TRUE;
3966 lend:
3968 TRACE("<--\n");
3969 if (bSuccess)
3970 return rc;
3971 else
3973 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3974 return 0;
3979 static void strip_spaces(LPWSTR start)
3981 LPWSTR str = start;
3982 LPWSTR end;
3984 while (*str == ' ' && *str != '\0')
3985 str++;
3987 if (str != start)
3988 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3990 end = start + strlenW(start) - 1;
3991 while (end >= start && *end == ' ')
3993 *end = '\0';
3994 end--;
3999 /***********************************************************************
4000 * HTTP_InterpretHttpHeader (internal)
4002 * Parse server response
4004 * RETURNS
4006 * Pointer to array of field, value, NULL on success.
4007 * NULL on error.
4009 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
4011 LPWSTR * pTokenPair;
4012 LPWSTR pszColon;
4013 INT len;
4015 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4017 pszColon = strchrW(buffer, ':');
4018 /* must have two tokens */
4019 if (!pszColon)
4021 HTTP_FreeTokens(pTokenPair);
4022 if (buffer[0])
4023 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4024 return NULL;
4027 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4028 if (!pTokenPair[0])
4030 HTTP_FreeTokens(pTokenPair);
4031 return NULL;
4033 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4034 pTokenPair[0][pszColon - buffer] = '\0';
4036 /* skip colon */
4037 pszColon++;
4038 len = strlenW(pszColon);
4039 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4040 if (!pTokenPair[1])
4042 HTTP_FreeTokens(pTokenPair);
4043 return NULL;
4045 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4047 strip_spaces(pTokenPair[0]);
4048 strip_spaces(pTokenPair[1]);
4050 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4051 return pTokenPair;
4054 /***********************************************************************
4055 * HTTP_ProcessHeader (internal)
4057 * Stuff header into header tables according to <dwModifier>
4061 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4063 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4065 LPHTTPHEADERW lphttpHdr = NULL;
4066 BOOL bSuccess = FALSE;
4067 INT index = -1;
4068 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4070 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4072 /* REPLACE wins out over ADD */
4073 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4074 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4076 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4077 index = -1;
4078 else
4079 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4081 if (index >= 0)
4083 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4085 return FALSE;
4087 lphttpHdr = &lpwhr->pCustHeaders[index];
4089 else if (value)
4091 HTTPHEADERW hdr;
4093 hdr.lpszField = (LPWSTR)field;
4094 hdr.lpszValue = (LPWSTR)value;
4095 hdr.wFlags = hdr.wCount = 0;
4097 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4098 hdr.wFlags |= HDR_ISREQUEST;
4100 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4102 /* no value to delete */
4103 else return TRUE;
4105 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4106 lphttpHdr->wFlags |= HDR_ISREQUEST;
4107 else
4108 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4110 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4112 HTTP_DeleteCustomHeader( lpwhr, index );
4114 if (value)
4116 HTTPHEADERW hdr;
4118 hdr.lpszField = (LPWSTR)field;
4119 hdr.lpszValue = (LPWSTR)value;
4120 hdr.wFlags = hdr.wCount = 0;
4122 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4123 hdr.wFlags |= HDR_ISREQUEST;
4125 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4128 return TRUE;
4130 else if (dwModifier & COALESCEFLAGS)
4132 LPWSTR lpsztmp;
4133 WCHAR ch = 0;
4134 INT len = 0;
4135 INT origlen = strlenW(lphttpHdr->lpszValue);
4136 INT valuelen = strlenW(value);
4138 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4140 ch = ',';
4141 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4143 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4145 ch = ';';
4146 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4149 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4151 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4152 if (lpsztmp)
4154 lphttpHdr->lpszValue = lpsztmp;
4155 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4156 if (ch > 0)
4158 lphttpHdr->lpszValue[origlen] = ch;
4159 origlen++;
4160 lphttpHdr->lpszValue[origlen] = ' ';
4161 origlen++;
4164 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4165 lphttpHdr->lpszValue[len] = '\0';
4166 bSuccess = TRUE;
4168 else
4170 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4171 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4174 TRACE("<-- %d\n",bSuccess);
4175 return bSuccess;
4179 /***********************************************************************
4180 * HTTP_FinishedReading (internal)
4182 * Called when all content from server has been read by client.
4185 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4187 WCHAR szVersion[10];
4188 WCHAR szConnectionResponse[20];
4189 DWORD dwBufferSize = sizeof(szVersion);
4190 BOOL keepalive = FALSE;
4192 TRACE("\n");
4194 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4195 * the connection is keep-alive by default */
4196 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4197 &dwBufferSize, NULL) &&
4198 !strcmpiW(szVersion, g_szHttp1_1))
4200 keepalive = TRUE;
4203 dwBufferSize = sizeof(szConnectionResponse);
4204 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4205 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4207 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4210 if (!keepalive)
4212 HTTPREQ_CloseConnection(&lpwhr->hdr);
4215 /* FIXME: store data in the URL cache here */
4217 return TRUE;
4221 /***********************************************************************
4222 * HTTP_GetCustomHeaderIndex (internal)
4224 * Return index of custom header from header array
4227 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4228 int requested_index, BOOL request_only)
4230 DWORD index;
4232 TRACE("%s\n", debugstr_w(lpszField));
4234 for (index = 0; index < lpwhr->nCustHeaders; index++)
4236 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4237 continue;
4239 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4240 continue;
4242 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4243 continue;
4245 if (requested_index == 0)
4246 break;
4247 requested_index --;
4250 if (index >= lpwhr->nCustHeaders)
4251 index = -1;
4253 TRACE("Return: %d\n", index);
4254 return index;
4258 /***********************************************************************
4259 * HTTP_InsertCustomHeader (internal)
4261 * Insert header into array
4264 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4266 INT count;
4267 LPHTTPHEADERW lph = NULL;
4268 BOOL r = FALSE;
4270 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4271 count = lpwhr->nCustHeaders + 1;
4272 if (count > 1)
4273 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4274 else
4275 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4277 if (NULL != lph)
4279 lpwhr->pCustHeaders = lph;
4280 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4281 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4282 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4283 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4284 lpwhr->nCustHeaders++;
4285 r = TRUE;
4287 else
4289 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4292 return r;
4296 /***********************************************************************
4297 * HTTP_DeleteCustomHeader (internal)
4299 * Delete header from array
4300 * If this function is called, the indexs may change.
4302 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4304 if( lpwhr->nCustHeaders <= 0 )
4305 return FALSE;
4306 if( index >= lpwhr->nCustHeaders )
4307 return FALSE;
4308 lpwhr->nCustHeaders--;
4310 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4311 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4313 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4314 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4315 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4317 return TRUE;
4321 /***********************************************************************
4322 * HTTP_VerifyValidHeader (internal)
4324 * Verify the given header is not invalid for the given http request
4327 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4329 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4330 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4331 return FALSE;
4333 return TRUE;
4336 /***********************************************************************
4337 * IsHostInProxyBypassList (@)
4339 * Undocumented
4342 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4344 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4345 return FALSE;