sane.ds: More correctly detect an end of scan job from sane; this enables Acrobat...
[wine/multimedia.git] / dlls / wininet / http.c
blob7b260705c55b0acaaa013d9dcd687edbf000f1f4
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 LPINTERNET_BUFFERSA ptr;
718 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
719 BOOL rc = FALSE;
721 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
722 dwContext);
724 ptr = lpBuffersOut;
725 if (ptr)
726 lpBuffersOutW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
727 sizeof(INTERNET_BUFFERSW));
728 else
729 lpBuffersOutW = NULL;
731 ptrW = lpBuffersOutW;
732 while (ptr)
734 if (ptr->lpvBuffer && ptr->dwBufferLength)
735 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
736 ptrW->dwBufferLength = ptr->dwBufferLength;
737 ptrW->dwBufferTotal= ptr->dwBufferTotal;
739 if (ptr->Next)
740 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
741 sizeof(INTERNET_BUFFERSW));
743 ptr = ptr->Next;
744 ptrW = ptrW->Next;
747 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
749 if (lpBuffersOutW)
751 ptrW = lpBuffersOutW;
752 while (ptrW)
754 LPINTERNET_BUFFERSW ptrW2;
756 FIXME("Do we need to translate info out of these buffer?\n");
758 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
759 ptrW2 = ptrW->Next;
760 HeapFree(GetProcessHeap(),0,ptrW);
761 ptrW = ptrW2;
765 return rc;
768 /***********************************************************************
769 * HttpEndRequestW (WININET.@)
771 * Ends an HTTP request that was started by HttpSendRequestEx
773 * RETURNS
774 * TRUE if successful
775 * FALSE on failure
778 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
779 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
781 BOOL rc = FALSE;
782 LPWININETHTTPREQW lpwhr;
783 INT responseLen;
784 DWORD dwBufferSize;
786 TRACE("-->\n");
787 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
789 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
791 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
792 if (lpwhr)
793 WININET_Release( &lpwhr->hdr );
794 return FALSE;
797 lpwhr->hdr.dwFlags |= dwFlags;
798 lpwhr->hdr.dwContext = dwContext;
800 /* We appear to do nothing with lpBuffersOut.. is that correct? */
802 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
803 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
805 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
806 if (responseLen)
807 rc = TRUE;
809 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
810 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
812 /* process cookies here. Is this right? */
813 HTTP_ProcessCookies(lpwhr);
815 dwBufferSize = sizeof(lpwhr->dwContentLength);
816 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
817 &lpwhr->dwContentLength,&dwBufferSize,NULL))
818 lpwhr->dwContentLength = -1;
820 if (lpwhr->dwContentLength == 0)
821 HTTP_FinishedReading(lpwhr);
823 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
825 DWORD dwCode,dwCodeLength=sizeof(DWORD);
826 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
827 (dwCode==302 || dwCode==301 || dwCode==303))
829 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
830 dwBufferSize=sizeof(szNewLocation);
831 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
833 /* redirects are always GETs */
834 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
835 lpwhr->lpszVerb = WININET_strdupW(szGET);
836 HTTP_DrainContent(lpwhr);
837 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
838 INTERNET_STATUS_REDIRECT, szNewLocation,
839 dwBufferSize);
840 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
841 if (rc)
842 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
847 WININET_Release( &lpwhr->hdr );
848 TRACE("%i <--\n",rc);
849 return rc;
852 /***********************************************************************
853 * HttpOpenRequestW (WININET.@)
855 * Open a HTTP request handle
857 * RETURNS
858 * HINTERNET a HTTP request handle on success
859 * NULL on failure
862 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
863 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
864 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
865 DWORD dwFlags, DWORD_PTR dwContext)
867 LPWININETHTTPSESSIONW lpwhs;
868 HINTERNET handle = NULL;
870 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
871 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
872 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
873 dwFlags, dwContext);
874 if(lpszAcceptTypes!=NULL)
876 int i;
877 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
878 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
881 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
882 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
884 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
885 goto lend;
889 * My tests seem to show that the windows version does not
890 * become asynchronous until after this point. And anyhow
891 * if this call was asynchronous then how would you get the
892 * necessary HINTERNET pointer returned by this function.
895 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
896 lpszVersion, lpszReferrer, lpszAcceptTypes,
897 dwFlags, dwContext);
898 lend:
899 if( lpwhs )
900 WININET_Release( &lpwhs->hdr );
901 TRACE("returning %p\n", handle);
902 return handle;
906 /***********************************************************************
907 * HttpOpenRequestA (WININET.@)
909 * Open a HTTP request handle
911 * RETURNS
912 * HINTERNET a HTTP request handle on success
913 * NULL on failure
916 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
917 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
918 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
919 DWORD dwFlags, DWORD_PTR dwContext)
921 LPWSTR szVerb = NULL, szObjectName = NULL;
922 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
923 INT len, acceptTypesCount;
924 HINTERNET rc = FALSE;
925 LPCSTR *types;
927 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
928 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
929 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
930 dwFlags, dwContext);
932 if (lpszVerb)
934 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
935 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
936 if ( !szVerb )
937 goto end;
938 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
941 if (lpszObjectName)
943 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
944 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
945 if ( !szObjectName )
946 goto end;
947 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
950 if (lpszVersion)
952 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
953 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
954 if ( !szVersion )
955 goto end;
956 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
959 if (lpszReferrer)
961 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
962 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
963 if ( !szReferrer )
964 goto end;
965 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
968 if (lpszAcceptTypes)
970 acceptTypesCount = 0;
971 types = lpszAcceptTypes;
972 while (*types)
974 __TRY
976 /* find out how many there are */
977 if (*types && **types)
979 TRACE("accept type: %s\n", debugstr_a(*types));
980 acceptTypesCount++;
983 __EXCEPT_PAGE_FAULT
985 WARN("invalid accept type pointer\n");
987 __ENDTRY;
988 types++;
990 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
991 if (!szAcceptTypes) goto end;
993 acceptTypesCount = 0;
994 types = lpszAcceptTypes;
995 while (*types)
997 __TRY
999 if (*types && **types)
1001 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1002 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1004 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1005 acceptTypesCount++;
1008 __EXCEPT_PAGE_FAULT
1010 /* ignore invalid pointer */
1012 __ENDTRY;
1013 types++;
1015 szAcceptTypes[acceptTypesCount] = NULL;
1018 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1019 szVersion, szReferrer,
1020 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1022 end:
1023 if (szAcceptTypes)
1025 acceptTypesCount = 0;
1026 while (szAcceptTypes[acceptTypesCount])
1028 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1029 acceptTypesCount++;
1031 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1033 HeapFree(GetProcessHeap(), 0, szReferrer);
1034 HeapFree(GetProcessHeap(), 0, szVersion);
1035 HeapFree(GetProcessHeap(), 0, szObjectName);
1036 HeapFree(GetProcessHeap(), 0, szVerb);
1038 return rc;
1041 /***********************************************************************
1042 * HTTP_EncodeBase64
1044 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1046 UINT n = 0, x;
1047 static const CHAR HTTP_Base64Enc[] =
1048 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1050 while( len > 0 )
1052 /* first 6 bits, all from bin[0] */
1053 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1054 x = (bin[0] & 3) << 4;
1056 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1057 if( len == 1 )
1059 base64[n++] = HTTP_Base64Enc[x];
1060 base64[n++] = '=';
1061 base64[n++] = '=';
1062 break;
1064 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1065 x = ( bin[1] & 0x0f ) << 2;
1067 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1068 if( len == 2 )
1070 base64[n++] = HTTP_Base64Enc[x];
1071 base64[n++] = '=';
1072 break;
1074 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1076 /* last 6 bits, all from bin [2] */
1077 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1078 bin += 3;
1079 len -= 3;
1081 base64[n] = 0;
1082 return n;
1085 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1086 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1087 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1088 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1089 static const signed char HTTP_Base64Dec[256] =
1091 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1092 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1093 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1094 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1095 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1096 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1097 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1098 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1099 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1100 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1101 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1102 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1103 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1104 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1105 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1106 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1107 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1108 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1109 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1110 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1111 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1112 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1113 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1114 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1115 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1116 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1118 #undef CH
1120 /***********************************************************************
1121 * HTTP_DecodeBase64
1123 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1125 unsigned int n = 0;
1127 while(*base64)
1129 signed char in[4];
1131 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1132 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1133 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1134 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1136 WARN("invalid base64: %s\n", debugstr_w(base64));
1137 return 0;
1139 if (bin)
1140 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1141 n++;
1143 if ((base64[2] == '=') && (base64[3] == '='))
1144 break;
1145 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1146 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1148 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1149 return 0;
1151 if (bin)
1152 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1153 n++;
1155 if (base64[3] == '=')
1156 break;
1157 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1158 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1160 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1161 return 0;
1163 if (bin)
1164 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1165 n++;
1167 base64 += 4;
1170 return n;
1173 /***********************************************************************
1174 * HTTP_InsertAuthorization
1176 * Insert or delete the authorization field in the request header.
1178 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1180 if (pAuthInfo)
1182 static const WCHAR wszSpace[] = {' ',0};
1183 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1184 unsigned int len;
1185 WCHAR *authorization = NULL;
1187 if (pAuthInfo->auth_data_len)
1189 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1190 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1191 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1192 if (!authorization)
1193 return FALSE;
1195 strcpyW(authorization, pAuthInfo->scheme);
1196 strcatW(authorization, wszSpace);
1197 HTTP_EncodeBase64(pAuthInfo->auth_data,
1198 pAuthInfo->auth_data_len,
1199 authorization+strlenW(authorization));
1201 /* clear the data as it isn't valid now that it has been sent to the
1202 * server, unless it's Basic authentication which doesn't do
1203 * connection tracking */
1204 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1206 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1207 pAuthInfo->auth_data = NULL;
1208 pAuthInfo->auth_data_len = 0;
1212 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1214 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1216 HeapFree(GetProcessHeap(), 0, authorization);
1218 return TRUE;
1221 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1223 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1224 DWORD size;
1226 size = sizeof(new_location);
1227 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1229 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1230 strcpyW( url, new_location );
1232 else
1234 static const WCHAR slash[] = { '/',0 };
1235 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1236 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1237 WININETHTTPSESSIONW *session = req->lpHttpSession;
1239 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1240 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1242 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1244 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1245 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1246 else
1247 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1248 if (req->lpszPath[0] != '/') strcatW( url, slash );
1249 strcatW( url, req->lpszPath );
1251 TRACE("url=%s\n", debugstr_w(url));
1252 return url;
1255 /***********************************************************************
1256 * HTTP_DealWithProxy
1258 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1259 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1261 WCHAR buf[MAXHOSTNAME];
1262 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1263 static WCHAR szNul[] = { 0 };
1264 URL_COMPONENTSW UrlComponents;
1265 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1266 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1268 memset( &UrlComponents, 0, sizeof UrlComponents );
1269 UrlComponents.dwStructSize = sizeof UrlComponents;
1270 UrlComponents.lpszHostName = buf;
1271 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1273 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1274 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1275 sprintfW(proxy, szFormat, hIC->lpszProxy);
1276 else
1277 strcpyW(proxy, hIC->lpszProxy);
1278 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1279 return FALSE;
1280 if( UrlComponents.dwHostNameLength == 0 )
1281 return FALSE;
1283 if( !lpwhr->lpszPath )
1284 lpwhr->lpszPath = szNul;
1286 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1287 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1289 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1290 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1291 lpwhs->nServerPort = UrlComponents.nPort;
1293 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1294 return TRUE;
1297 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1299 char szaddr[32];
1300 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1302 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1303 INTERNET_STATUS_RESOLVING_NAME,
1304 lpwhs->lpszServerName,
1305 strlenW(lpwhs->lpszServerName)+1);
1307 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1308 &lpwhs->socketAddress))
1310 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1311 return FALSE;
1314 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1315 szaddr, sizeof(szaddr));
1316 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1317 INTERNET_STATUS_NAME_RESOLVED,
1318 szaddr, strlen(szaddr)+1);
1320 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1321 return TRUE;
1325 /***********************************************************************
1326 * HTTPREQ_Destroy (internal)
1328 * Deallocate request handle
1331 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1333 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1334 DWORD i;
1336 TRACE("\n");
1338 if(lpwhr->hCacheFile)
1339 CloseHandle(lpwhr->hCacheFile);
1341 if(lpwhr->lpszCacheFile) {
1342 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1343 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1346 WININET_Release(&lpwhr->lpHttpSession->hdr);
1348 if (lpwhr->pAuthInfo)
1350 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1351 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1352 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1353 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1355 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1356 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1357 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1358 lpwhr->pAuthInfo = NULL;
1361 if (lpwhr->pProxyAuthInfo)
1363 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1364 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1365 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1366 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1368 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1369 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1370 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1371 lpwhr->pProxyAuthInfo = NULL;
1374 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1375 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1376 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1377 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1380 for (i = 0; i < lpwhr->nCustHeaders; i++)
1382 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1383 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1386 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1387 HeapFree(GetProcessHeap(), 0, lpwhr);
1390 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1392 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1394 TRACE("%p\n",lpwhr);
1396 if (!NETCON_connected(&lpwhr->netConnection))
1397 return;
1399 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1400 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1402 NETCON_close(&lpwhr->netConnection);
1404 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1405 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1408 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1410 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1412 switch(option) {
1413 case INTERNET_OPTION_HANDLE_TYPE:
1414 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1416 if (*size < sizeof(ULONG))
1417 return ERROR_INSUFFICIENT_BUFFER;
1419 *size = sizeof(DWORD);
1420 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1421 return ERROR_SUCCESS;
1423 case INTERNET_OPTION_URL: {
1424 WCHAR url[INTERNET_MAX_URL_LENGTH];
1425 HTTPHEADERW *host;
1426 DWORD len;
1427 WCHAR *pch;
1429 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1430 static const WCHAR hostW[] = {'H','o','s','t',0};
1432 TRACE("INTERNET_OPTION_URL\n");
1434 host = HTTP_GetHeader(req, hostW);
1435 strcpyW(url, httpW);
1436 strcatW(url, host->lpszValue);
1437 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1438 *pch = 0;
1439 strcatW(url, req->lpszPath);
1441 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1443 if(unicode) {
1444 len = (strlenW(url)+1) * sizeof(WCHAR);
1445 if(*size < len)
1446 return ERROR_INSUFFICIENT_BUFFER;
1448 *size = len;
1449 strcpyW(buffer, url);
1450 return ERROR_SUCCESS;
1451 }else {
1452 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1453 if(len > *size)
1454 return ERROR_INSUFFICIENT_BUFFER;
1456 *size = len;
1457 return ERROR_SUCCESS;
1461 case INTERNET_OPTION_DATAFILE_NAME: {
1462 DWORD req_size;
1464 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1466 if(!req->lpszCacheFile) {
1467 *size = 0;
1468 return ERROR_INTERNET_ITEM_NOT_FOUND;
1471 if(unicode) {
1472 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1473 if(*size < req_size)
1474 return ERROR_INSUFFICIENT_BUFFER;
1476 *size = req_size;
1477 memcpy(buffer, req->lpszCacheFile, *size);
1478 return ERROR_SUCCESS;
1479 }else {
1480 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1481 if (req_size > *size)
1482 return ERROR_INSUFFICIENT_BUFFER;
1484 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1485 -1, buffer, *size, NULL, NULL);
1486 return ERROR_SUCCESS;
1490 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1491 PCCERT_CONTEXT context;
1493 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1494 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1495 return ERROR_INSUFFICIENT_BUFFER;
1498 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1499 if(context) {
1500 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1501 DWORD len;
1503 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1504 info->ftExpiry = context->pCertInfo->NotAfter;
1505 info->ftStart = context->pCertInfo->NotBefore;
1506 if(unicode) {
1507 len = CertNameToStrW(context->dwCertEncodingType,
1508 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1509 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1510 if(info->lpszSubjectInfo)
1511 CertNameToStrW(context->dwCertEncodingType,
1512 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1513 info->lpszSubjectInfo, len);
1514 len = CertNameToStrW(context->dwCertEncodingType,
1515 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1516 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1517 if (info->lpszIssuerInfo)
1518 CertNameToStrW(context->dwCertEncodingType,
1519 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1520 info->lpszIssuerInfo, len);
1521 }else {
1522 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1524 len = CertNameToStrA(context->dwCertEncodingType,
1525 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1526 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1527 if(infoA->lpszSubjectInfo)
1528 CertNameToStrA(context->dwCertEncodingType,
1529 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1530 infoA->lpszSubjectInfo, len);
1531 len = CertNameToStrA(context->dwCertEncodingType,
1532 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1533 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1534 if(infoA->lpszIssuerInfo)
1535 CertNameToStrA(context->dwCertEncodingType,
1536 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1537 infoA->lpszIssuerInfo, len);
1541 * Contrary to MSDN, these do not appear to be set.
1542 * lpszProtocolName
1543 * lpszSignatureAlgName
1544 * lpszEncryptionAlgName
1545 * dwKeySize
1547 CertFreeCertificateContext(context);
1548 return ERROR_SUCCESS;
1553 return INET_QueryOption(option, buffer, size, unicode);
1556 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1558 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1560 switch(option) {
1561 case INTERNET_OPTION_SEND_TIMEOUT:
1562 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1563 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1565 if (size != sizeof(DWORD))
1566 return ERROR_INVALID_PARAMETER;
1568 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1569 *(DWORD*)buffer);
1571 case INTERNET_OPTION_USERNAME:
1572 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1573 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1574 return ERROR_SUCCESS;
1576 case INTERNET_OPTION_PASSWORD:
1577 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1578 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1579 return ERROR_SUCCESS;
1582 return ERROR_INTERNET_INVALID_OPTION;
1585 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1587 INTERNET_ASYNC_RESULT iar;
1588 BYTE buffer[4096];
1589 int available;
1590 BOOL res;
1592 TRACE("%p\n", req);
1594 res = NETCON_recv(&req->netConnection, buffer,
1595 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1596 MSG_PEEK, &available);
1598 if(res) {
1599 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1600 iar.dwError = first_notif ? 0 : available;
1601 }else {
1602 iar.dwResult = 0;
1603 iar.dwError = INTERNET_GetLastError();
1606 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1607 sizeof(INTERNET_ASYNC_RESULT));
1610 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1612 int bytes_read;
1614 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1615 sync ? MSG_WAITALL : 0, &bytes_read)) {
1616 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1617 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1619 /* always return success, even if the network layer returns an error */
1620 *read = 0;
1621 HTTP_FinishedReading(req);
1622 return ERROR_SUCCESS;
1625 req->dwContentRead += bytes_read;
1626 *read = bytes_read;
1628 if(req->lpszCacheFile) {
1629 BOOL res;
1630 DWORD dwBytesWritten;
1632 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1633 if(!res)
1634 WARN("WriteFile failed: %u\n", GetLastError());
1637 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1638 HTTP_FinishedReading(req);
1640 return ERROR_SUCCESS;
1643 static DWORD get_chunk_size(const char *buffer)
1645 const char *p;
1646 DWORD size = 0;
1648 for (p = buffer; *p; p++)
1650 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1651 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1652 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1653 else if (*p == ';') break;
1655 return size;
1658 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1660 char reply[MAX_REPLY_LEN], *p = buffer;
1661 DWORD buflen, to_read, to_write = size;
1662 int bytes_read;
1664 *read = 0;
1665 for (;;)
1667 if (*read == size) break;
1669 if (req->dwContentLength == ~0u) /* new chunk */
1671 buflen = sizeof(reply);
1672 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1674 if (!(req->dwContentLength = get_chunk_size(reply)))
1676 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1677 HTTP_GetResponseHeaders(req, FALSE);
1678 break;
1681 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1683 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1685 if (bytes_read != to_read)
1686 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1688 /* always return success, even if the network layer returns an error */
1689 *read = 0;
1690 break;
1692 if (!bytes_read) break;
1694 req->dwContentRead += bytes_read;
1695 to_write -= bytes_read;
1696 *read += bytes_read;
1698 if (req->lpszCacheFile)
1700 DWORD dwBytesWritten;
1702 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1703 WARN("WriteFile failed: %u\n", GetLastError());
1705 p += bytes_read;
1707 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1709 req->dwContentRead = 0;
1710 req->dwContentLength = ~0u;
1712 buflen = sizeof(reply);
1713 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1715 ERR("Malformed chunk\n");
1716 *read = 0;
1717 break;
1721 if (!*read) HTTP_FinishedReading(req);
1722 return ERROR_SUCCESS;
1725 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1727 WCHAR encoding[20];
1728 DWORD buflen = sizeof(encoding);
1729 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1731 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1732 !strcmpiW(encoding, szChunked))
1734 return HTTP_ReadChunked(req, buffer, size, read, sync);
1736 else
1737 return HTTP_Read(req, buffer, size, read, sync);
1740 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1742 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1743 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1746 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
1748 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1749 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1750 INTERNET_ASYNC_RESULT iar;
1751 DWORD res;
1753 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1755 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1756 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1758 iar.dwResult = res == ERROR_SUCCESS;
1759 iar.dwError = res;
1761 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1762 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1763 sizeof(INTERNET_ASYNC_RESULT));
1766 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1767 DWORD flags, DWORD_PTR context)
1770 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1771 DWORD res;
1773 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1774 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1776 if (buffers->dwStructSize != sizeof(*buffers))
1777 return ERROR_INVALID_PARAMETER;
1779 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1781 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1782 DWORD available = 0;
1784 NETCON_query_data_available(&req->netConnection, &available);
1785 if (!available)
1787 WORKREQUEST workRequest;
1789 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
1790 workRequest.hdr = WININET_AddRef(&req->hdr);
1791 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1793 INTERNET_AsyncCall(&workRequest);
1795 return ERROR_IO_PENDING;
1799 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1800 !(flags & IRF_NO_WAIT));
1802 if (res == ERROR_SUCCESS) {
1803 DWORD size = buffers->dwBufferLength;
1804 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1805 &size, sizeof(size));
1808 return res;
1811 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
1813 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
1814 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1815 INTERNET_ASYNC_RESULT iar;
1816 DWORD res;
1818 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
1820 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1821 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1823 iar.dwResult = res == ERROR_SUCCESS;
1824 iar.dwError = res;
1826 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1827 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1828 sizeof(INTERNET_ASYNC_RESULT));
1831 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
1832 DWORD flags, DWORD_PTR context)
1835 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1836 DWORD res;
1838 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1839 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1841 if (buffers->dwStructSize != sizeof(*buffers))
1842 return ERROR_INVALID_PARAMETER;
1844 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1846 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1847 DWORD available = 0;
1849 NETCON_query_data_available(&req->netConnection, &available);
1850 if (!available)
1852 WORKREQUEST workRequest;
1854 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
1855 workRequest.hdr = WININET_AddRef(&req->hdr);
1856 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
1858 INTERNET_AsyncCall(&workRequest);
1860 return ERROR_IO_PENDING;
1864 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1865 !(flags & IRF_NO_WAIT));
1867 if (res == ERROR_SUCCESS) {
1868 DWORD size = buffers->dwBufferLength;
1869 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1870 &size, sizeof(size));
1873 return res;
1876 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1878 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1880 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1883 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1885 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1887 HTTP_ReceiveRequestData(req, FALSE);
1890 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1892 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1893 BYTE buffer[4048];
1894 BOOL async;
1896 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1898 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1899 return ERROR_SUCCESS;
1901 /* Even if we are in async mode, we need to determine whether
1902 * there is actually more data available. We do this by trying
1903 * to peek only a single byte in async mode. */
1904 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1906 if (NETCON_recv(&req->netConnection, buffer,
1907 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1908 MSG_PEEK, (int *)available) && async && *available)
1910 WORKREQUEST workRequest;
1912 *available = 0;
1913 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1914 workRequest.hdr = WININET_AddRef( &req->hdr );
1916 INTERNET_AsyncCall(&workRequest);
1918 return ERROR_IO_PENDING;
1921 return ERROR_SUCCESS;
1924 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1925 HTTPREQ_Destroy,
1926 HTTPREQ_CloseConnection,
1927 HTTPREQ_QueryOption,
1928 HTTPREQ_SetOption,
1929 HTTPREQ_ReadFile,
1930 HTTPREQ_ReadFileExA,
1931 HTTPREQ_ReadFileExW,
1932 HTTPREQ_WriteFile,
1933 HTTPREQ_QueryDataAvailable,
1934 NULL
1937 /***********************************************************************
1938 * HTTP_HttpOpenRequestW (internal)
1940 * Open a HTTP request handle
1942 * RETURNS
1943 * HINTERNET a HTTP request handle on success
1944 * NULL on failure
1947 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1948 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1949 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1950 DWORD dwFlags, DWORD_PTR dwContext)
1952 LPWININETAPPINFOW hIC = NULL;
1953 LPWININETHTTPREQW lpwhr;
1954 LPWSTR lpszHostName = NULL;
1955 HINTERNET handle = NULL;
1956 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1957 DWORD len;
1959 TRACE("-->\n");
1961 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1962 hIC = lpwhs->lpAppInfo;
1964 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1965 if (NULL == lpwhr)
1967 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1968 goto lend;
1970 lpwhr->hdr.htype = WH_HHTTPREQ;
1971 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1972 lpwhr->hdr.dwFlags = dwFlags;
1973 lpwhr->hdr.dwContext = dwContext;
1974 lpwhr->hdr.refs = 1;
1975 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1976 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1978 WININET_AddRef( &lpwhs->hdr );
1979 lpwhr->lpHttpSession = lpwhs;
1980 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1982 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1983 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1984 if (NULL == lpszHostName)
1986 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1987 goto lend;
1990 handle = WININET_AllocHandle( &lpwhr->hdr );
1991 if (NULL == handle)
1993 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1994 goto lend;
1997 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1999 InternetCloseHandle( handle );
2000 handle = NULL;
2001 goto lend;
2004 if (lpszObjectName && *lpszObjectName) {
2005 HRESULT rc;
2007 len = 0;
2008 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2009 if (rc != E_POINTER)
2010 len = strlenW(lpszObjectName)+1;
2011 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2012 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2013 URL_ESCAPE_SPACES_ONLY);
2014 if (rc != S_OK)
2016 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2017 strcpyW(lpwhr->lpszPath,lpszObjectName);
2021 if (lpszReferrer && *lpszReferrer)
2022 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2024 if (lpszAcceptTypes)
2026 int i;
2027 for (i = 0; lpszAcceptTypes[i]; i++)
2029 if (!*lpszAcceptTypes[i]) continue;
2030 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2031 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2032 HTTP_ADDHDR_FLAG_REQ |
2033 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2037 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2039 if (lpszVersion)
2040 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2041 else
2042 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2044 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2045 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2046 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2048 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2049 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2050 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2052 else
2053 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2054 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2056 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2057 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2058 INTERNET_DEFAULT_HTTPS_PORT :
2059 INTERNET_DEFAULT_HTTP_PORT);
2061 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2062 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2063 INTERNET_DEFAULT_HTTPS_PORT :
2064 INTERNET_DEFAULT_HTTP_PORT);
2066 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2067 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2069 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2070 INTERNET_STATUS_HANDLE_CREATED, &handle,
2071 sizeof(handle));
2073 lend:
2074 HeapFree(GetProcessHeap(), 0, lpszHostName);
2075 if( lpwhr )
2076 WININET_Release( &lpwhr->hdr );
2078 TRACE("<-- %p (%p)\n", handle, lpwhr);
2079 return handle;
2082 /* read any content returned by the server so that the connection can be
2083 * reused */
2084 static void HTTP_DrainContent(WININETHTTPREQW *req)
2086 DWORD bytes_read;
2088 if (!NETCON_connected(&req->netConnection)) return;
2090 if (req->dwContentLength == -1)
2091 NETCON_close(&req->netConnection);
2095 char buffer[2048];
2096 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2097 return;
2098 } while (bytes_read);
2101 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2102 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2103 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2104 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2105 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2106 static const WCHAR szAge[] = { 'A','g','e',0 };
2107 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2108 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2109 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2110 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2111 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2112 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2113 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2114 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2115 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2116 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2117 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2118 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 };
2119 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2120 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2121 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2122 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2123 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2124 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2125 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2126 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2127 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2128 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2129 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2130 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2131 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2132 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2133 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2134 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2135 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2136 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2137 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2138 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2139 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2140 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2141 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2142 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2143 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2144 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2145 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 };
2146 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2147 static const WCHAR szURI[] = { 'U','R','I',0 };
2148 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2149 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2150 static const WCHAR szVia[] = { 'V','i','a',0 };
2151 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2152 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2154 static const LPCWSTR header_lookup[] = {
2155 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2156 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2157 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2158 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2159 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2160 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2161 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2162 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2163 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2164 szDate, /* HTTP_QUERY_DATE = 9 */
2165 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2166 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2167 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2168 szURI, /* HTTP_QUERY_URI = 13 */
2169 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2170 NULL, /* HTTP_QUERY_COST = 15 */
2171 NULL, /* HTTP_QUERY_LINK = 16 */
2172 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2173 NULL, /* HTTP_QUERY_VERSION = 18 */
2174 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2175 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2176 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2177 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2178 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2179 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2180 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2181 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2182 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2183 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2184 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2185 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2186 NULL, /* HTTP_QUERY_FROM = 31 */
2187 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2188 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2189 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2190 szReferer, /* HTTP_QUERY_REFERER = 35 */
2191 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2192 szServer, /* HTTP_QUERY_SERVER = 37 */
2193 NULL, /* HTTP_TITLE = 38 */
2194 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2195 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2196 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2197 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2198 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2199 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2200 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2201 NULL, /* HTTP_QUERY_REFRESH = 46 */
2202 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2203 szAge, /* HTTP_QUERY_AGE = 48 */
2204 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2205 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2206 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2207 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2208 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2209 szETag, /* HTTP_QUERY_ETAG = 54 */
2210 szHost, /* HTTP_QUERY_HOST = 55 */
2211 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2212 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2213 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2214 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2215 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2216 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2217 szRange, /* HTTP_QUERY_RANGE = 62 */
2218 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2219 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2220 szVary, /* HTTP_QUERY_VARY = 65 */
2221 szVia, /* HTTP_QUERY_VIA = 66 */
2222 szWarning, /* HTTP_QUERY_WARNING = 67 */
2223 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2224 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2225 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2228 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2230 /***********************************************************************
2231 * HTTP_HttpQueryInfoW (internal)
2233 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2234 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2236 LPHTTPHEADERW lphttpHdr = NULL;
2237 BOOL bSuccess = FALSE;
2238 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2239 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2240 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2241 INT index = -1;
2243 /* Find requested header structure */
2244 switch (level)
2246 case HTTP_QUERY_CUSTOM:
2247 if (!lpBuffer) return FALSE;
2248 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2249 break;
2251 case HTTP_QUERY_RAW_HEADERS_CRLF:
2253 LPWSTR headers;
2254 DWORD len = 0;
2255 BOOL ret = FALSE;
2257 if (request_only)
2258 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2259 else
2260 headers = lpwhr->lpszRawHeaders;
2262 if (headers)
2263 len = strlenW(headers) * sizeof(WCHAR);
2265 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2267 len += sizeof(WCHAR);
2268 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2269 ret = FALSE;
2271 else if (lpBuffer)
2273 if (headers)
2274 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2275 else
2277 len = strlenW(szCrLf) * sizeof(WCHAR);
2278 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2280 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2281 ret = TRUE;
2283 *lpdwBufferLength = len;
2285 if (request_only)
2286 HeapFree(GetProcessHeap(), 0, headers);
2287 return ret;
2289 case HTTP_QUERY_RAW_HEADERS:
2291 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2292 DWORD i, size = 0;
2293 LPWSTR pszString = lpBuffer;
2295 for (i = 0; ppszRawHeaderLines[i]; i++)
2296 size += strlenW(ppszRawHeaderLines[i]) + 1;
2298 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2300 HTTP_FreeTokens(ppszRawHeaderLines);
2301 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2302 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2303 return FALSE;
2305 if (pszString)
2307 for (i = 0; ppszRawHeaderLines[i]; i++)
2309 DWORD len = strlenW(ppszRawHeaderLines[i]);
2310 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2311 pszString += len+1;
2313 *pszString = '\0';
2314 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2316 *lpdwBufferLength = size * sizeof(WCHAR);
2317 HTTP_FreeTokens(ppszRawHeaderLines);
2319 return TRUE;
2321 case HTTP_QUERY_STATUS_TEXT:
2322 if (lpwhr->lpszStatusText)
2324 DWORD len = strlenW(lpwhr->lpszStatusText);
2325 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2327 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2328 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2329 return FALSE;
2331 if (lpBuffer)
2333 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2334 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2336 *lpdwBufferLength = len * sizeof(WCHAR);
2337 return TRUE;
2339 break;
2340 case HTTP_QUERY_VERSION:
2341 if (lpwhr->lpszVersion)
2343 DWORD len = strlenW(lpwhr->lpszVersion);
2344 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2346 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2347 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2348 return FALSE;
2350 if (lpBuffer)
2352 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2353 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2355 *lpdwBufferLength = len * sizeof(WCHAR);
2356 return TRUE;
2358 break;
2359 default:
2360 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2362 if (level < LAST_TABLE_HEADER && header_lookup[level])
2363 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2364 requested_index,request_only);
2367 if (index >= 0)
2368 lphttpHdr = &lpwhr->pCustHeaders[index];
2370 /* Ensure header satisfies requested attributes */
2371 if (!lphttpHdr ||
2372 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2373 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2375 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2376 return bSuccess;
2379 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2381 /* coalesce value to requested type */
2382 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2384 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2385 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2386 bSuccess = TRUE;
2388 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2390 time_t tmpTime;
2391 struct tm tmpTM;
2392 SYSTEMTIME *STHook;
2394 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2396 tmpTM = *gmtime(&tmpTime);
2397 STHook = (SYSTEMTIME *)lpBuffer;
2398 STHook->wDay = tmpTM.tm_mday;
2399 STHook->wHour = tmpTM.tm_hour;
2400 STHook->wMilliseconds = 0;
2401 STHook->wMinute = tmpTM.tm_min;
2402 STHook->wDayOfWeek = tmpTM.tm_wday;
2403 STHook->wMonth = tmpTM.tm_mon + 1;
2404 STHook->wSecond = tmpTM.tm_sec;
2405 STHook->wYear = tmpTM.tm_year;
2406 bSuccess = TRUE;
2408 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2409 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2410 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2412 else if (lphttpHdr->lpszValue)
2414 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2416 if (len > *lpdwBufferLength)
2418 *lpdwBufferLength = len;
2419 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2420 return bSuccess;
2422 if (lpBuffer)
2424 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2425 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2427 *lpdwBufferLength = len - sizeof(WCHAR);
2428 bSuccess = TRUE;
2430 return bSuccess;
2433 /***********************************************************************
2434 * HttpQueryInfoW (WININET.@)
2436 * Queries for information about an HTTP request
2438 * RETURNS
2439 * TRUE on success
2440 * FALSE on failure
2443 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2444 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2446 BOOL bSuccess = FALSE;
2447 LPWININETHTTPREQW lpwhr;
2449 if (TRACE_ON(wininet)) {
2450 #define FE(x) { x, #x }
2451 static const wininet_flag_info query_flags[] = {
2452 FE(HTTP_QUERY_MIME_VERSION),
2453 FE(HTTP_QUERY_CONTENT_TYPE),
2454 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2455 FE(HTTP_QUERY_CONTENT_ID),
2456 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2457 FE(HTTP_QUERY_CONTENT_LENGTH),
2458 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2459 FE(HTTP_QUERY_ALLOW),
2460 FE(HTTP_QUERY_PUBLIC),
2461 FE(HTTP_QUERY_DATE),
2462 FE(HTTP_QUERY_EXPIRES),
2463 FE(HTTP_QUERY_LAST_MODIFIED),
2464 FE(HTTP_QUERY_MESSAGE_ID),
2465 FE(HTTP_QUERY_URI),
2466 FE(HTTP_QUERY_DERIVED_FROM),
2467 FE(HTTP_QUERY_COST),
2468 FE(HTTP_QUERY_LINK),
2469 FE(HTTP_QUERY_PRAGMA),
2470 FE(HTTP_QUERY_VERSION),
2471 FE(HTTP_QUERY_STATUS_CODE),
2472 FE(HTTP_QUERY_STATUS_TEXT),
2473 FE(HTTP_QUERY_RAW_HEADERS),
2474 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2475 FE(HTTP_QUERY_CONNECTION),
2476 FE(HTTP_QUERY_ACCEPT),
2477 FE(HTTP_QUERY_ACCEPT_CHARSET),
2478 FE(HTTP_QUERY_ACCEPT_ENCODING),
2479 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2480 FE(HTTP_QUERY_AUTHORIZATION),
2481 FE(HTTP_QUERY_CONTENT_ENCODING),
2482 FE(HTTP_QUERY_FORWARDED),
2483 FE(HTTP_QUERY_FROM),
2484 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2485 FE(HTTP_QUERY_LOCATION),
2486 FE(HTTP_QUERY_ORIG_URI),
2487 FE(HTTP_QUERY_REFERER),
2488 FE(HTTP_QUERY_RETRY_AFTER),
2489 FE(HTTP_QUERY_SERVER),
2490 FE(HTTP_QUERY_TITLE),
2491 FE(HTTP_QUERY_USER_AGENT),
2492 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2493 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2494 FE(HTTP_QUERY_ACCEPT_RANGES),
2495 FE(HTTP_QUERY_SET_COOKIE),
2496 FE(HTTP_QUERY_COOKIE),
2497 FE(HTTP_QUERY_REQUEST_METHOD),
2498 FE(HTTP_QUERY_REFRESH),
2499 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2500 FE(HTTP_QUERY_AGE),
2501 FE(HTTP_QUERY_CACHE_CONTROL),
2502 FE(HTTP_QUERY_CONTENT_BASE),
2503 FE(HTTP_QUERY_CONTENT_LOCATION),
2504 FE(HTTP_QUERY_CONTENT_MD5),
2505 FE(HTTP_QUERY_CONTENT_RANGE),
2506 FE(HTTP_QUERY_ETAG),
2507 FE(HTTP_QUERY_HOST),
2508 FE(HTTP_QUERY_IF_MATCH),
2509 FE(HTTP_QUERY_IF_NONE_MATCH),
2510 FE(HTTP_QUERY_IF_RANGE),
2511 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2512 FE(HTTP_QUERY_MAX_FORWARDS),
2513 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2514 FE(HTTP_QUERY_RANGE),
2515 FE(HTTP_QUERY_TRANSFER_ENCODING),
2516 FE(HTTP_QUERY_UPGRADE),
2517 FE(HTTP_QUERY_VARY),
2518 FE(HTTP_QUERY_VIA),
2519 FE(HTTP_QUERY_WARNING),
2520 FE(HTTP_QUERY_CUSTOM)
2522 static const wininet_flag_info modifier_flags[] = {
2523 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2524 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2525 FE(HTTP_QUERY_FLAG_NUMBER),
2526 FE(HTTP_QUERY_FLAG_COALESCE)
2528 #undef FE
2529 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2530 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2531 DWORD i;
2533 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2534 TRACE(" Attribute:");
2535 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2536 if (query_flags[i].val == info) {
2537 TRACE(" %s", query_flags[i].name);
2538 break;
2541 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2542 TRACE(" Unknown (%08x)", info);
2545 TRACE(" Modifier:");
2546 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2547 if (modifier_flags[i].val & info_mod) {
2548 TRACE(" %s", modifier_flags[i].name);
2549 info_mod &= ~ modifier_flags[i].val;
2553 if (info_mod) {
2554 TRACE(" Unknown (%08x)", info_mod);
2556 TRACE("\n");
2559 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2560 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2562 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2563 goto lend;
2566 if (lpBuffer == NULL)
2567 *lpdwBufferLength = 0;
2568 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2569 lpBuffer, lpdwBufferLength, lpdwIndex);
2571 lend:
2572 if( lpwhr )
2573 WININET_Release( &lpwhr->hdr );
2575 TRACE("%d <--\n", bSuccess);
2576 return bSuccess;
2579 /***********************************************************************
2580 * HttpQueryInfoA (WININET.@)
2582 * Queries for information about an HTTP request
2584 * RETURNS
2585 * TRUE on success
2586 * FALSE on failure
2589 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2590 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2592 BOOL result;
2593 DWORD len;
2594 WCHAR* bufferW;
2596 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2597 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2599 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2600 lpdwBufferLength, lpdwIndex );
2603 if (lpBuffer)
2605 DWORD alloclen;
2606 len = (*lpdwBufferLength)*sizeof(WCHAR);
2607 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2609 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2610 if (alloclen < len)
2611 alloclen = len;
2613 else
2614 alloclen = len;
2615 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2616 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2617 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2618 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2619 } else
2621 bufferW = NULL;
2622 len = 0;
2625 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2626 &len, lpdwIndex );
2627 if( result )
2629 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2630 lpBuffer, *lpdwBufferLength, NULL, NULL );
2631 *lpdwBufferLength = len - 1;
2633 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2635 else
2636 /* since the strings being returned from HttpQueryInfoW should be
2637 * only ASCII characters, it is reasonable to assume that all of
2638 * the Unicode characters can be reduced to a single byte */
2639 *lpdwBufferLength = len / sizeof(WCHAR);
2641 HeapFree(GetProcessHeap(), 0, bufferW );
2643 return result;
2646 /***********************************************************************
2647 * HttpSendRequestExA (WININET.@)
2649 * Sends the specified request to the HTTP server and allows chunked
2650 * transfers.
2652 * RETURNS
2653 * Success: TRUE
2654 * Failure: FALSE, call GetLastError() for more information.
2656 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2657 LPINTERNET_BUFFERSA lpBuffersIn,
2658 LPINTERNET_BUFFERSA lpBuffersOut,
2659 DWORD dwFlags, DWORD_PTR dwContext)
2661 INTERNET_BUFFERSW BuffersInW;
2662 BOOL rc = FALSE;
2663 DWORD headerlen;
2664 LPWSTR header = NULL;
2666 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2667 lpBuffersOut, dwFlags, dwContext);
2669 if (lpBuffersIn)
2671 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2672 if (lpBuffersIn->lpcszHeader)
2674 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2675 lpBuffersIn->dwHeadersLength,0,0);
2676 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2677 if (!(BuffersInW.lpcszHeader = header))
2679 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2680 return FALSE;
2682 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2683 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2684 header, headerlen);
2686 else
2687 BuffersInW.lpcszHeader = NULL;
2688 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2689 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2690 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2691 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2692 BuffersInW.Next = NULL;
2695 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2697 HeapFree(GetProcessHeap(),0,header);
2699 return rc;
2702 /***********************************************************************
2703 * HttpSendRequestExW (WININET.@)
2705 * Sends the specified request to the HTTP server and allows chunked
2706 * transfers
2708 * RETURNS
2709 * Success: TRUE
2710 * Failure: FALSE, call GetLastError() for more information.
2712 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2713 LPINTERNET_BUFFERSW lpBuffersIn,
2714 LPINTERNET_BUFFERSW lpBuffersOut,
2715 DWORD dwFlags, DWORD_PTR dwContext)
2717 BOOL ret = FALSE;
2718 LPWININETHTTPREQW lpwhr;
2719 LPWININETHTTPSESSIONW lpwhs;
2720 LPWININETAPPINFOW hIC;
2722 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2723 lpBuffersOut, dwFlags, dwContext);
2725 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2727 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2729 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2730 goto lend;
2733 lpwhs = lpwhr->lpHttpSession;
2734 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2735 hIC = lpwhs->lpAppInfo;
2736 assert(hIC->hdr.htype == WH_HINIT);
2738 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2740 WORKREQUEST workRequest;
2741 struct WORKREQ_HTTPSENDREQUESTW *req;
2743 workRequest.asyncproc = AsyncHttpSendRequestProc;
2744 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2745 req = &workRequest.u.HttpSendRequestW;
2746 if (lpBuffersIn)
2748 if (lpBuffersIn->lpcszHeader)
2749 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2750 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2751 else
2752 req->lpszHeader = NULL;
2753 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2754 req->lpOptional = lpBuffersIn->lpvBuffer;
2755 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2756 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2758 else
2760 req->lpszHeader = NULL;
2761 req->dwHeaderLength = 0;
2762 req->lpOptional = NULL;
2763 req->dwOptionalLength = 0;
2764 req->dwContentLength = 0;
2767 req->bEndRequest = FALSE;
2769 INTERNET_AsyncCall(&workRequest);
2771 * This is from windows.
2773 INTERNET_SetLastError(ERROR_IO_PENDING);
2775 else
2777 if (lpBuffersIn)
2778 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2779 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2780 lpBuffersIn->dwBufferTotal, FALSE);
2781 else
2782 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2785 lend:
2786 if ( lpwhr )
2787 WININET_Release( &lpwhr->hdr );
2789 TRACE("<---\n");
2790 return ret;
2793 /***********************************************************************
2794 * HttpSendRequestW (WININET.@)
2796 * Sends the specified request to the HTTP server
2798 * RETURNS
2799 * TRUE on success
2800 * FALSE on failure
2803 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2804 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2806 LPWININETHTTPREQW lpwhr;
2807 LPWININETHTTPSESSIONW lpwhs = NULL;
2808 LPWININETAPPINFOW hIC = NULL;
2809 BOOL r;
2811 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2812 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2814 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2815 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2817 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2818 r = FALSE;
2819 goto lend;
2822 lpwhs = lpwhr->lpHttpSession;
2823 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2825 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2826 r = FALSE;
2827 goto lend;
2830 hIC = lpwhs->lpAppInfo;
2831 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2833 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2834 r = FALSE;
2835 goto lend;
2838 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2840 WORKREQUEST workRequest;
2841 struct WORKREQ_HTTPSENDREQUESTW *req;
2843 workRequest.asyncproc = AsyncHttpSendRequestProc;
2844 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2845 req = &workRequest.u.HttpSendRequestW;
2846 if (lpszHeaders)
2848 DWORD size;
2850 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
2851 else size = dwHeaderLength * sizeof(WCHAR);
2853 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
2854 memcpy(req->lpszHeader, lpszHeaders, size);
2856 else
2857 req->lpszHeader = 0;
2858 req->dwHeaderLength = dwHeaderLength;
2859 req->lpOptional = lpOptional;
2860 req->dwOptionalLength = dwOptionalLength;
2861 req->dwContentLength = dwOptionalLength;
2862 req->bEndRequest = TRUE;
2864 INTERNET_AsyncCall(&workRequest);
2866 * This is from windows.
2868 INTERNET_SetLastError(ERROR_IO_PENDING);
2869 r = FALSE;
2871 else
2873 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2874 dwHeaderLength, lpOptional, dwOptionalLength,
2875 dwOptionalLength, TRUE);
2877 lend:
2878 if( lpwhr )
2879 WININET_Release( &lpwhr->hdr );
2880 return r;
2883 /***********************************************************************
2884 * HttpSendRequestA (WININET.@)
2886 * Sends the specified request to the HTTP server
2888 * RETURNS
2889 * TRUE on success
2890 * FALSE on failure
2893 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2894 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2896 BOOL result;
2897 LPWSTR szHeaders=NULL;
2898 DWORD nLen=dwHeaderLength;
2899 if(lpszHeaders!=NULL)
2901 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2902 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2903 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2905 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2906 HeapFree(GetProcessHeap(),0,szHeaders);
2907 return result;
2910 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2912 LPHTTPHEADERW host_header;
2914 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2916 host_header = HTTP_GetHeader(req, szHost);
2917 if(!host_header)
2918 return FALSE;
2920 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2921 return TRUE;
2924 /***********************************************************************
2925 * HTTP_HandleRedirect (internal)
2927 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2929 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2930 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2931 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2932 WCHAR path[INTERNET_MAX_URL_LENGTH];
2933 int index;
2935 if(lpszUrl[0]=='/')
2937 /* if it's an absolute path, keep the same session info */
2938 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2940 else
2942 URL_COMPONENTSW urlComponents;
2943 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2944 static WCHAR szHttp[] = {'h','t','t','p',0};
2945 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2946 DWORD url_length = 0;
2947 LPWSTR orig_url;
2948 LPWSTR combined_url;
2950 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2951 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2952 urlComponents.dwSchemeLength = 0;
2953 urlComponents.lpszHostName = lpwhs->lpszHostName;
2954 urlComponents.dwHostNameLength = 0;
2955 urlComponents.nPort = lpwhs->nHostPort;
2956 urlComponents.lpszUserName = lpwhs->lpszUserName;
2957 urlComponents.dwUserNameLength = 0;
2958 urlComponents.lpszPassword = NULL;
2959 urlComponents.dwPasswordLength = 0;
2960 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2961 urlComponents.dwUrlPathLength = 0;
2962 urlComponents.lpszExtraInfo = NULL;
2963 urlComponents.dwExtraInfoLength = 0;
2965 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2966 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2967 return FALSE;
2969 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2971 /* convert from bytes to characters */
2972 url_length = url_length / sizeof(WCHAR) - 1;
2973 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2975 HeapFree(GetProcessHeap(), 0, orig_url);
2976 return FALSE;
2979 url_length = 0;
2980 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2981 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2983 HeapFree(GetProcessHeap(), 0, orig_url);
2984 return FALSE;
2986 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2988 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2990 HeapFree(GetProcessHeap(), 0, orig_url);
2991 HeapFree(GetProcessHeap(), 0, combined_url);
2992 return FALSE;
2994 HeapFree(GetProcessHeap(), 0, orig_url);
2996 userName[0] = 0;
2997 hostName[0] = 0;
2998 protocol[0] = 0;
3000 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3001 urlComponents.lpszScheme = protocol;
3002 urlComponents.dwSchemeLength = 32;
3003 urlComponents.lpszHostName = hostName;
3004 urlComponents.dwHostNameLength = MAXHOSTNAME;
3005 urlComponents.lpszUserName = userName;
3006 urlComponents.dwUserNameLength = 1024;
3007 urlComponents.lpszPassword = NULL;
3008 urlComponents.dwPasswordLength = 0;
3009 urlComponents.lpszUrlPath = path;
3010 urlComponents.dwUrlPathLength = 2048;
3011 urlComponents.lpszExtraInfo = NULL;
3012 urlComponents.dwExtraInfoLength = 0;
3013 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
3015 HeapFree(GetProcessHeap(), 0, combined_url);
3016 return FALSE;
3019 HeapFree(GetProcessHeap(), 0, combined_url);
3021 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3022 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3024 TRACE("redirect from secure page to non-secure page\n");
3025 /* FIXME: warn about from secure redirect to non-secure page */
3026 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3028 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3029 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3031 TRACE("redirect from non-secure page to secure page\n");
3032 /* FIXME: notify about redirect to secure page */
3033 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3036 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3038 if (lstrlenW(protocol)>4) /*https*/
3039 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3040 else /*http*/
3041 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3044 #if 0
3046 * This upsets redirects to binary files on sourceforge.net
3047 * and gives an html page instead of the target file
3048 * Examination of the HTTP request sent by native wininet.dll
3049 * reveals that it doesn't send a referrer in that case.
3050 * Maybe there's a flag that enables this, or maybe a referrer
3051 * shouldn't be added in case of a redirect.
3054 /* consider the current host as the referrer */
3055 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3056 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3057 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3058 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3059 #endif
3061 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3062 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3063 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3065 int len;
3066 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3067 len = lstrlenW(hostName);
3068 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3069 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3070 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3072 else
3073 lpwhs->lpszHostName = WININET_strdupW(hostName);
3075 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3077 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3078 lpwhs->lpszUserName = NULL;
3079 if (userName[0])
3080 lpwhs->lpszUserName = WININET_strdupW(userName);
3082 if (!using_proxy)
3084 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3086 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3087 lpwhs->lpszServerName = WININET_strdupW(hostName);
3088 lpwhs->nServerPort = urlComponents.nPort;
3090 NETCON_close(&lpwhr->netConnection);
3091 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3092 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3095 else
3096 TRACE("Redirect through proxy\n");
3099 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3100 lpwhr->lpszPath=NULL;
3101 if (*path)
3103 DWORD needed = 0;
3104 HRESULT rc;
3106 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3107 if (rc != E_POINTER)
3108 needed = strlenW(path)+1;
3109 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3110 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3111 URL_ESCAPE_SPACES_ONLY);
3112 if (rc != S_OK)
3114 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3115 strcpyW(lpwhr->lpszPath,path);
3119 /* Remove custom content-type/length headers on redirects. */
3120 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3121 if (0 <= index)
3122 HTTP_DeleteCustomHeader(lpwhr, index);
3123 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3124 if (0 <= index)
3125 HTTP_DeleteCustomHeader(lpwhr, index);
3127 return TRUE;
3130 /***********************************************************************
3131 * HTTP_build_req (internal)
3133 * concatenate all the strings in the request together
3135 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3137 LPCWSTR *t;
3138 LPWSTR str;
3140 for( t = list; *t ; t++ )
3141 len += strlenW( *t );
3142 len++;
3144 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3145 *str = 0;
3147 for( t = list; *t ; t++ )
3148 strcatW( str, *t );
3150 return str;
3153 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3155 LPWSTR lpszPath;
3156 LPWSTR requestString;
3157 INT len;
3158 INT cnt;
3159 INT responseLen;
3160 char *ascii_req;
3161 BOOL ret;
3162 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3163 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3164 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3166 TRACE("\n");
3168 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3169 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3170 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3171 HeapFree( GetProcessHeap(), 0, lpszPath );
3173 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3174 NULL, 0, NULL, NULL );
3175 len--; /* the nul terminator isn't needed */
3176 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3177 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3178 ascii_req, len, NULL, NULL );
3179 HeapFree( GetProcessHeap(), 0, requestString );
3181 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3183 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3184 HeapFree( GetProcessHeap(), 0, ascii_req );
3185 if (!ret || cnt < 0)
3186 return FALSE;
3188 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3189 if (!responseLen)
3190 return FALSE;
3192 return TRUE;
3195 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3197 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3198 LPWSTR lpszCookies, lpszUrl = NULL;
3199 DWORD nCookieSize, size;
3200 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3202 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3203 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3204 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3206 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3208 int cnt = 0;
3209 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3211 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3212 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3214 cnt += sprintfW(lpszCookies, szCookie);
3215 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3216 strcatW(lpszCookies, szCrLf);
3218 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3219 HeapFree(GetProcessHeap(), 0, lpszCookies);
3222 HeapFree(GetProcessHeap(), 0, lpszUrl);
3225 /***********************************************************************
3226 * HTTP_HttpSendRequestW (internal)
3228 * Sends the specified request to the HTTP server
3230 * RETURNS
3231 * TRUE on success
3232 * FALSE on failure
3235 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3236 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3237 DWORD dwContentLength, BOOL bEndRequest)
3239 INT cnt;
3240 BOOL bSuccess = FALSE;
3241 LPWSTR requestString = NULL;
3242 INT responseLen;
3243 BOOL loop_next;
3244 INTERNET_ASYNC_RESULT iar;
3245 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3246 static const WCHAR szContentLength[] =
3247 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3248 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3250 TRACE("--> %p\n", lpwhr);
3252 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3254 /* if the verb is NULL default to GET */
3255 if (!lpwhr->lpszVerb)
3256 lpwhr->lpszVerb = WININET_strdupW(szGET);
3258 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3260 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3261 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3263 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3265 WCHAR *agent_header;
3266 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3267 int len;
3269 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3270 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3271 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3273 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3274 HeapFree(GetProcessHeap(), 0, agent_header);
3276 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3278 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3279 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3281 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3283 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3284 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3285 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3290 DWORD len;
3291 char *ascii_req;
3293 loop_next = FALSE;
3295 /* like native, just in case the caller forgot to call InternetReadFile
3296 * for all the data */
3297 HTTP_DrainContent(lpwhr);
3298 lpwhr->dwContentRead = 0;
3300 if (TRACE_ON(wininet))
3302 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3303 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3306 HTTP_FixURL(lpwhr);
3307 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3309 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3311 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3312 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3314 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3315 HTTP_InsertCookies(lpwhr);
3317 /* add the headers the caller supplied */
3318 if( lpszHeaders && dwHeaderLength )
3320 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3321 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3324 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3326 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3327 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3328 HeapFree(GetProcessHeap(), 0, url);
3330 else
3331 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3334 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3336 /* Send the request and store the results */
3337 if (!HTTP_OpenConnection(lpwhr))
3338 goto lend;
3340 /* send the request as ASCII, tack on the optional data */
3341 if( !lpOptional )
3342 dwOptionalLength = 0;
3343 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3344 NULL, 0, NULL, NULL );
3345 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3346 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3347 ascii_req, len, NULL, NULL );
3348 if( lpOptional )
3349 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3350 len = (len + dwOptionalLength - 1);
3351 ascii_req[len] = 0;
3352 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3354 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3355 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3357 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3358 HeapFree( GetProcessHeap(), 0, ascii_req );
3360 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3361 INTERNET_STATUS_REQUEST_SENT,
3362 &len, sizeof(DWORD));
3364 if (bEndRequest)
3366 DWORD dwBufferSize;
3367 DWORD dwStatusCode;
3368 WCHAR encoding[20];
3369 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3371 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3372 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3374 if (cnt < 0)
3375 goto lend;
3377 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3378 if (responseLen)
3379 bSuccess = TRUE;
3381 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3382 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3383 sizeof(DWORD));
3385 HTTP_ProcessCookies(lpwhr);
3387 dwBufferSize = sizeof(lpwhr->dwContentLength);
3388 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3389 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3390 lpwhr->dwContentLength = -1;
3392 if (lpwhr->dwContentLength == 0)
3393 HTTP_FinishedReading(lpwhr);
3395 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3397 dwBufferSize = sizeof(encoding);
3398 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3399 !strcmpiW(encoding, szChunked))
3401 lpwhr->dwContentLength = -1;
3404 dwBufferSize = sizeof(dwStatusCode);
3405 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3406 &dwStatusCode,&dwBufferSize,NULL))
3407 dwStatusCode = 0;
3409 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3411 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3412 dwBufferSize=sizeof(szNewLocation);
3413 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3414 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3416 /* redirects are always GETs */
3417 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3418 lpwhr->lpszVerb = WININET_strdupW(szGET);
3420 HTTP_DrainContent(lpwhr);
3421 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3422 INTERNET_STATUS_REDIRECT, szNewLocation,
3423 dwBufferSize);
3424 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3425 if (bSuccess)
3427 HeapFree(GetProcessHeap(), 0, requestString);
3428 loop_next = TRUE;
3432 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3434 WCHAR szAuthValue[2048];
3435 dwBufferSize=2048;
3436 if (dwStatusCode == HTTP_STATUS_DENIED)
3438 DWORD dwIndex = 0;
3439 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3441 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3442 &lpwhr->pAuthInfo,
3443 lpwhr->lpHttpSession->lpszUserName,
3444 lpwhr->lpHttpSession->lpszPassword))
3446 loop_next = TRUE;
3447 break;
3451 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3453 DWORD dwIndex = 0;
3454 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3456 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3457 &lpwhr->pProxyAuthInfo,
3458 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3459 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3461 loop_next = TRUE;
3462 break;
3468 else
3469 bSuccess = TRUE;
3471 while (loop_next);
3473 /* FIXME: Better check, when we have to create the cache file */
3474 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3475 WCHAR url[INTERNET_MAX_URL_LENGTH];
3476 WCHAR cacheFileName[MAX_PATH+1];
3477 BOOL b;
3479 b = HTTP_GetRequestURL(lpwhr, url);
3480 if(!b) {
3481 WARN("Could not get URL\n");
3482 goto lend;
3485 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3486 if(b) {
3487 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3488 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3489 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3490 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3491 WARN("Could not create file: %u\n", GetLastError());
3492 lpwhr->hCacheFile = NULL;
3494 }else {
3495 WARN("Could not create cache entry: %08x\n", GetLastError());
3499 lend:
3501 HeapFree(GetProcessHeap(), 0, requestString);
3503 /* TODO: send notification for P3P header */
3505 if(lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) {
3506 if(bSuccess) {
3507 HTTP_ReceiveRequestData(lpwhr, TRUE);
3508 }else {
3509 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3510 iar.dwError = INTERNET_GetLastError();
3512 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3513 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3514 sizeof(INTERNET_ASYNC_RESULT));
3518 TRACE("<--\n");
3519 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3520 return bSuccess;
3523 /***********************************************************************
3524 * HTTPSESSION_Destroy (internal)
3526 * Deallocate session handle
3529 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3531 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3533 TRACE("%p\n", lpwhs);
3535 WININET_Release(&lpwhs->lpAppInfo->hdr);
3537 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3538 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3539 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3540 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3541 HeapFree(GetProcessHeap(), 0, lpwhs);
3544 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3546 switch(option) {
3547 case INTERNET_OPTION_HANDLE_TYPE:
3548 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3550 if (*size < sizeof(ULONG))
3551 return ERROR_INSUFFICIENT_BUFFER;
3553 *size = sizeof(DWORD);
3554 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3555 return ERROR_SUCCESS;
3558 return INET_QueryOption(option, buffer, size, unicode);
3561 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3563 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3565 switch(option) {
3566 case INTERNET_OPTION_USERNAME:
3568 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3569 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3570 return ERROR_SUCCESS;
3572 case INTERNET_OPTION_PASSWORD:
3574 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3575 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3576 return ERROR_SUCCESS;
3578 default: break;
3581 return ERROR_INTERNET_INVALID_OPTION;
3584 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3585 HTTPSESSION_Destroy,
3586 NULL,
3587 HTTPSESSION_QueryOption,
3588 HTTPSESSION_SetOption,
3589 NULL,
3590 NULL,
3591 NULL,
3592 NULL,
3593 NULL
3597 /***********************************************************************
3598 * HTTP_Connect (internal)
3600 * Create http session handle
3602 * RETURNS
3603 * HINTERNET a session handle on success
3604 * NULL on failure
3607 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3608 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3609 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3610 DWORD dwInternalFlags)
3612 LPWININETHTTPSESSIONW lpwhs = NULL;
3613 HINTERNET handle = NULL;
3615 TRACE("-->\n");
3617 if (!lpszServerName || !lpszServerName[0])
3619 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3620 goto lerror;
3623 assert( hIC->hdr.htype == WH_HINIT );
3625 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3626 if (NULL == lpwhs)
3628 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3629 goto lerror;
3633 * According to my tests. The name is not resolved until a request is sent
3636 lpwhs->hdr.htype = WH_HHTTPSESSION;
3637 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3638 lpwhs->hdr.dwFlags = dwFlags;
3639 lpwhs->hdr.dwContext = dwContext;
3640 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3641 lpwhs->hdr.refs = 1;
3642 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3644 WININET_AddRef( &hIC->hdr );
3645 lpwhs->lpAppInfo = hIC;
3646 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3648 handle = WININET_AllocHandle( &lpwhs->hdr );
3649 if (NULL == handle)
3651 ERR("Failed to alloc handle\n");
3652 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3653 goto lerror;
3656 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3657 if(strchrW(hIC->lpszProxy, ' '))
3658 FIXME("Several proxies not implemented.\n");
3659 if(hIC->lpszProxyBypass)
3660 FIXME("Proxy bypass is ignored.\n");
3662 if (lpszServerName && lpszServerName[0])
3664 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3665 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3667 if (lpszUserName && lpszUserName[0])
3668 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3669 if (lpszPassword && lpszPassword[0])
3670 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3671 lpwhs->nServerPort = nServerPort;
3672 lpwhs->nHostPort = nServerPort;
3674 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3675 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3677 INTERNET_SendCallback(&hIC->hdr, dwContext,
3678 INTERNET_STATUS_HANDLE_CREATED, &handle,
3679 sizeof(handle));
3682 lerror:
3683 if( lpwhs )
3684 WININET_Release( &lpwhs->hdr );
3687 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3688 * windows
3691 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3692 return handle;
3696 /***********************************************************************
3697 * HTTP_OpenConnection (internal)
3699 * Connect to a web server
3701 * RETURNS
3703 * TRUE on success
3704 * FALSE on failure
3706 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3708 BOOL bSuccess = FALSE;
3709 LPWININETHTTPSESSIONW lpwhs;
3710 LPWININETAPPINFOW hIC = NULL;
3711 char szaddr[32];
3713 TRACE("-->\n");
3716 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3718 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3719 goto lend;
3722 if (NETCON_connected(&lpwhr->netConnection))
3724 bSuccess = TRUE;
3725 goto lend;
3727 if (!HTTP_ResolveName(lpwhr)) goto lend;
3729 lpwhs = lpwhr->lpHttpSession;
3731 hIC = lpwhs->lpAppInfo;
3732 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3733 szaddr, sizeof(szaddr));
3734 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3735 INTERNET_STATUS_CONNECTING_TO_SERVER,
3736 szaddr,
3737 strlen(szaddr)+1);
3739 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3740 SOCK_STREAM, 0))
3742 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3743 goto lend;
3746 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3747 sizeof(lpwhs->socketAddress)))
3748 goto lend;
3750 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3752 /* Note: we differ from Microsoft's WinINet here. they seem to have
3753 * a bug that causes no status callbacks to be sent when starting
3754 * a tunnel to a proxy server using the CONNECT verb. i believe our
3755 * behaviour to be more correct and to not cause any incompatibilities
3756 * because using a secure connection through a proxy server is a rare
3757 * case that would be hard for anyone to depend on */
3758 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3759 goto lend;
3761 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3763 WARN("Couldn't connect securely to host\n");
3764 goto lend;
3768 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3769 INTERNET_STATUS_CONNECTED_TO_SERVER,
3770 szaddr, strlen(szaddr)+1);
3772 bSuccess = TRUE;
3774 lend:
3775 TRACE("%d <--\n", bSuccess);
3776 return bSuccess;
3780 /***********************************************************************
3781 * HTTP_clear_response_headers (internal)
3783 * clear out any old response headers
3785 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3787 DWORD i;
3789 for( i=0; i<lpwhr->nCustHeaders; i++)
3791 if( !lpwhr->pCustHeaders[i].lpszField )
3792 continue;
3793 if( !lpwhr->pCustHeaders[i].lpszValue )
3794 continue;
3795 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3796 continue;
3797 HTTP_DeleteCustomHeader( lpwhr, i );
3798 i--;
3802 /***********************************************************************
3803 * HTTP_GetResponseHeaders (internal)
3805 * Read server response
3807 * RETURNS
3809 * TRUE on success
3810 * FALSE on error
3812 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3814 INT cbreaks = 0;
3815 WCHAR buffer[MAX_REPLY_LEN];
3816 DWORD buflen = MAX_REPLY_LEN;
3817 BOOL bSuccess = FALSE;
3818 INT rc = 0;
3819 static const WCHAR szHundred[] = {'1','0','0',0};
3820 char bufferA[MAX_REPLY_LEN];
3821 LPWSTR status_code, status_text;
3822 DWORD cchMaxRawHeaders = 1024;
3823 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3824 DWORD cchRawHeaders = 0;
3826 TRACE("-->\n");
3828 /* clear old response headers (eg. from a redirect response) */
3829 if (clear) HTTP_clear_response_headers( lpwhr );
3831 if (!NETCON_connected(&lpwhr->netConnection))
3832 goto lend;
3834 do {
3836 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3838 buflen = MAX_REPLY_LEN;
3839 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3840 goto lend;
3841 rc += buflen;
3842 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3844 /* split the version from the status code */
3845 status_code = strchrW( buffer, ' ' );
3846 if( !status_code )
3847 goto lend;
3848 *status_code++=0;
3850 /* split the status code from the status text */
3851 status_text = strchrW( status_code, ' ' );
3852 if( !status_text )
3853 goto lend;
3854 *status_text++=0;
3856 TRACE("version [%s] status code [%s] status text [%s]\n",
3857 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3859 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3861 /* Add status code */
3862 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3863 HTTP_ADDHDR_FLAG_REPLACE);
3865 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3866 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3868 lpwhr->lpszVersion= WININET_strdupW(buffer);
3869 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3871 /* Restore the spaces */
3872 *(status_code-1) = ' ';
3873 *(status_text-1) = ' ';
3875 /* regenerate raw headers */
3876 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3878 cchMaxRawHeaders *= 2;
3879 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3881 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3882 cchRawHeaders += (buflen-1);
3883 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3884 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3885 lpszRawHeaders[cchRawHeaders] = '\0';
3887 /* Parse each response line */
3890 buflen = MAX_REPLY_LEN;
3891 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3893 LPWSTR * pFieldAndValue;
3895 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3897 if (!bufferA[0]) break;
3898 if (!strchr(bufferA, ':'))
3900 WARN("invalid header\n");
3901 continue;
3903 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3905 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3907 cchMaxRawHeaders *= 2;
3908 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3910 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3911 cchRawHeaders += (buflen-1);
3912 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3913 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3914 lpszRawHeaders[cchRawHeaders] = '\0';
3916 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3917 if (!pFieldAndValue)
3918 break;
3920 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3921 HTTP_ADDREQ_FLAG_ADD );
3923 HTTP_FreeTokens(pFieldAndValue);
3925 else
3927 cbreaks++;
3928 if (cbreaks >= 2)
3929 break;
3931 }while(1);
3933 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3934 lpwhr->lpszRawHeaders = lpszRawHeaders;
3935 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3936 bSuccess = TRUE;
3938 lend:
3940 TRACE("<--\n");
3941 if (bSuccess)
3942 return rc;
3943 else
3945 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3946 return 0;
3951 static void strip_spaces(LPWSTR start)
3953 LPWSTR str = start;
3954 LPWSTR end;
3956 while (*str == ' ' && *str != '\0')
3957 str++;
3959 if (str != start)
3960 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3962 end = start + strlenW(start) - 1;
3963 while (end >= start && *end == ' ')
3965 *end = '\0';
3966 end--;
3971 /***********************************************************************
3972 * HTTP_InterpretHttpHeader (internal)
3974 * Parse server response
3976 * RETURNS
3978 * Pointer to array of field, value, NULL on success.
3979 * NULL on error.
3981 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3983 LPWSTR * pTokenPair;
3984 LPWSTR pszColon;
3985 INT len;
3987 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3989 pszColon = strchrW(buffer, ':');
3990 /* must have two tokens */
3991 if (!pszColon)
3993 HTTP_FreeTokens(pTokenPair);
3994 if (buffer[0])
3995 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3996 return NULL;
3999 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4000 if (!pTokenPair[0])
4002 HTTP_FreeTokens(pTokenPair);
4003 return NULL;
4005 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4006 pTokenPair[0][pszColon - buffer] = '\0';
4008 /* skip colon */
4009 pszColon++;
4010 len = strlenW(pszColon);
4011 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4012 if (!pTokenPair[1])
4014 HTTP_FreeTokens(pTokenPair);
4015 return NULL;
4017 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4019 strip_spaces(pTokenPair[0]);
4020 strip_spaces(pTokenPair[1]);
4022 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4023 return pTokenPair;
4026 /***********************************************************************
4027 * HTTP_ProcessHeader (internal)
4029 * Stuff header into header tables according to <dwModifier>
4033 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4035 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4037 LPHTTPHEADERW lphttpHdr = NULL;
4038 BOOL bSuccess = FALSE;
4039 INT index = -1;
4040 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4042 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4044 /* REPLACE wins out over ADD */
4045 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4046 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4048 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4049 index = -1;
4050 else
4051 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4053 if (index >= 0)
4055 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4057 return FALSE;
4059 lphttpHdr = &lpwhr->pCustHeaders[index];
4061 else if (value)
4063 HTTPHEADERW hdr;
4065 hdr.lpszField = (LPWSTR)field;
4066 hdr.lpszValue = (LPWSTR)value;
4067 hdr.wFlags = hdr.wCount = 0;
4069 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4070 hdr.wFlags |= HDR_ISREQUEST;
4072 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4074 /* no value to delete */
4075 else return TRUE;
4077 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4078 lphttpHdr->wFlags |= HDR_ISREQUEST;
4079 else
4080 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4082 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4084 HTTP_DeleteCustomHeader( lpwhr, index );
4086 if (value)
4088 HTTPHEADERW hdr;
4090 hdr.lpszField = (LPWSTR)field;
4091 hdr.lpszValue = (LPWSTR)value;
4092 hdr.wFlags = hdr.wCount = 0;
4094 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4095 hdr.wFlags |= HDR_ISREQUEST;
4097 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4100 return TRUE;
4102 else if (dwModifier & COALESCEFLAGS)
4104 LPWSTR lpsztmp;
4105 WCHAR ch = 0;
4106 INT len = 0;
4107 INT origlen = strlenW(lphttpHdr->lpszValue);
4108 INT valuelen = strlenW(value);
4110 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4112 ch = ',';
4113 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4115 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4117 ch = ';';
4118 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4121 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4123 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4124 if (lpsztmp)
4126 lphttpHdr->lpszValue = lpsztmp;
4127 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4128 if (ch > 0)
4130 lphttpHdr->lpszValue[origlen] = ch;
4131 origlen++;
4132 lphttpHdr->lpszValue[origlen] = ' ';
4133 origlen++;
4136 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4137 lphttpHdr->lpszValue[len] = '\0';
4138 bSuccess = TRUE;
4140 else
4142 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4143 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4146 TRACE("<-- %d\n",bSuccess);
4147 return bSuccess;
4151 /***********************************************************************
4152 * HTTP_FinishedReading (internal)
4154 * Called when all content from server has been read by client.
4157 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4159 WCHAR szVersion[10];
4160 WCHAR szConnectionResponse[20];
4161 DWORD dwBufferSize = sizeof(szVersion);
4162 BOOL keepalive = FALSE;
4164 TRACE("\n");
4166 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4167 * the connection is keep-alive by default */
4168 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4169 &dwBufferSize, NULL) &&
4170 !strcmpiW(szVersion, g_szHttp1_1))
4172 keepalive = TRUE;
4175 dwBufferSize = sizeof(szConnectionResponse);
4176 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4177 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4179 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4182 if (!keepalive)
4184 HTTPREQ_CloseConnection(&lpwhr->hdr);
4187 /* FIXME: store data in the URL cache here */
4189 return TRUE;
4193 /***********************************************************************
4194 * HTTP_GetCustomHeaderIndex (internal)
4196 * Return index of custom header from header array
4199 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4200 int requested_index, BOOL request_only)
4202 DWORD index;
4204 TRACE("%s\n", debugstr_w(lpszField));
4206 for (index = 0; index < lpwhr->nCustHeaders; index++)
4208 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4209 continue;
4211 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4212 continue;
4214 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4215 continue;
4217 if (requested_index == 0)
4218 break;
4219 requested_index --;
4222 if (index >= lpwhr->nCustHeaders)
4223 index = -1;
4225 TRACE("Return: %d\n", index);
4226 return index;
4230 /***********************************************************************
4231 * HTTP_InsertCustomHeader (internal)
4233 * Insert header into array
4236 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4238 INT count;
4239 LPHTTPHEADERW lph = NULL;
4240 BOOL r = FALSE;
4242 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4243 count = lpwhr->nCustHeaders + 1;
4244 if (count > 1)
4245 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4246 else
4247 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4249 if (NULL != lph)
4251 lpwhr->pCustHeaders = lph;
4252 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4253 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4254 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4255 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4256 lpwhr->nCustHeaders++;
4257 r = TRUE;
4259 else
4261 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4264 return r;
4268 /***********************************************************************
4269 * HTTP_DeleteCustomHeader (internal)
4271 * Delete header from array
4272 * If this function is called, the indexs may change.
4274 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4276 if( lpwhr->nCustHeaders <= 0 )
4277 return FALSE;
4278 if( index >= lpwhr->nCustHeaders )
4279 return FALSE;
4280 lpwhr->nCustHeaders--;
4282 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4283 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4285 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4286 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4287 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4289 return TRUE;
4293 /***********************************************************************
4294 * HTTP_VerifyValidHeader (internal)
4296 * Verify the given header is not invalid for the given http request
4299 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4301 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4302 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4303 return FALSE;
4305 return TRUE;
4308 /***********************************************************************
4309 * IsHostInProxyBypassList (@)
4311 * Undocumented
4314 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4316 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4317 return FALSE;