winhttp: Implement WinHttpSetCredentials.
[wine] / dlls / winhttp / request.c
1 /*
2  * Copyright 2008 Hans Leidekker for CodeWeavers
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21 #include "wine/debug.h"
22
23 #include <stdarg.h>
24 #ifdef HAVE_ARPA_INET_H
25 # include <arpa/inet.h>
26 #endif
27
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winhttp.h"
31
32 #include "winhttp_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
35
36 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
37 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
38 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
39 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
40 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
41 static const WCHAR attr_age[] = {'A','g','e',0};
42 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
43 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
44 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
45 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
46 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
47 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
48 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
49 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
50 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
51 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
52 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
53 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
54 static const WCHAR attr_content_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};
55 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
56 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
57 static const WCHAR attr_date[] = {'D','a','t','e',0};
58 static const WCHAR attr_from[] = {'F','r','o','m',0};
59 static const WCHAR attr_etag[] = {'E','T','a','g',0};
60 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
61 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
62 static const WCHAR attr_host[] = {'H','o','s','t',0};
63 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
64 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
65 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
66 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
67 static const WCHAR attr_if_unmodified_since[] = {'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
68 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
69 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
70 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
71 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
72 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
73 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
74 static const WCHAR attr_proxy_authorization[] = {'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0};
75 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
76 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
77 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
78 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
79 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
80 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
81 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
82 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
83 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
84 static const WCHAR attr_unless_modified_since[] = {'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
85 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
86 static const WCHAR attr_uri[] = {'U','R','I',0};
87 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
88 static const WCHAR attr_vary[] = {'V','a','r','y',0};
89 static const WCHAR attr_via[] = {'V','i','a',0};
90 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
91 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
92
93 static const WCHAR *attribute_table[] =
94 {
95     attr_mime_version,              /* WINHTTP_QUERY_MIME_VERSION               = 0  */
96     attr_content_type,              /* WINHTTP_QUERY_CONTENT_TYPE               = 1  */
97     attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING  = 2  */
98     attr_content_id,                /* WINHTTP_QUERY_CONTENT_ID                 = 3  */
99     NULL,                           /* WINHTTP_QUERY_CONTENT_DESCRIPTION        = 4  */
100     attr_content_length,            /* WINHTTP_QUERY_CONTENT_LENGTH             = 5  */
101     attr_content_language,          /* WINHTTP_QUERY_CONTENT_LANGUAGE           = 6  */
102     attr_allow,                     /* WINHTTP_QUERY_ALLOW                      = 7  */
103     attr_public,                    /* WINHTTP_QUERY_PUBLIC                     = 8  */
104     attr_date,                      /* WINHTTP_QUERY_DATE                       = 9  */
105     attr_expires,                   /* WINHTTP_QUERY_EXPIRES                    = 10 */
106     attr_last_modified,             /* WINHTTP_QUERY_LAST_MODIFIEDcw            = 11 */
107     NULL,                           /* WINHTTP_QUERY_MESSAGE_ID                 = 12 */
108     attr_uri,                       /* WINHTTP_QUERY_URI                        = 13 */
109     attr_from,                      /* WINHTTP_QUERY_DERIVED_FROM               = 14 */
110     NULL,                           /* WINHTTP_QUERY_COST                       = 15 */
111     NULL,                           /* WINHTTP_QUERY_LINK                       = 16 */
112     attr_pragma,                    /* WINHTTP_QUERY_PRAGMA                     = 17 */
113     NULL,                           /* WINHTTP_QUERY_VERSION                    = 18 */
114     attr_status,                    /* WINHTTP_QUERY_STATUS_CODE                = 19 */
115     NULL,                           /* WINHTTP_QUERY_STATUS_TEXT                = 20 */
116     NULL,                           /* WINHTTP_QUERY_RAW_HEADERS                = 21 */
117     NULL,                           /* WINHTTP_QUERY_RAW_HEADERS_CRLF           = 22 */
118     attr_connection,                /* WINHTTP_QUERY_CONNECTION                 = 23 */
119     attr_accept,                    /* WINHTTP_QUERY_ACCEPT                     = 24 */
120     attr_accept_charset,            /* WINHTTP_QUERY_ACCEPT_CHARSET             = 25 */
121     attr_accept_encoding,           /* WINHTTP_QUERY_ACCEPT_ENCODING            = 26 */
122     attr_accept_language,           /* WINHTTP_QUERY_ACCEPT_LANGUAGE            = 27 */
123     attr_authorization,             /* WINHTTP_QUERY_AUTHORIZATION              = 28 */
124     attr_content_encoding,          /* WINHTTP_QUERY_CONTENT_ENCODING           = 29 */
125     NULL,                           /* WINHTTP_QUERY_FORWARDED                  = 30 */
126     NULL,                           /* WINHTTP_QUERY_FROM                       = 31 */
127     attr_if_modified_since,         /* WINHTTP_QUERY_IF_MODIFIED_SINCE          = 32 */
128     attr_location,                  /* WINHTTP_QUERY_LOCATION                   = 33 */
129     NULL,                           /* WINHTTP_QUERY_ORIG_URI                   = 34 */
130     attr_referer,                   /* WINHTTP_QUERY_REFERER                    = 35 */
131     attr_retry_after,               /* WINHTTP_QUERY_RETRY_AFTER                = 36 */
132     attr_server,                    /* WINHTTP_QUERY_SERVER                     = 37 */
133     NULL,                           /* WINHTTP_TITLE                            = 38 */
134     attr_user_agent,                /* WINHTTP_QUERY_USER_AGENT                 = 39 */
135     attr_www_authenticate,          /* WINHTTP_QUERY_WWW_AUTHENTICATE           = 40 */
136     attr_proxy_authenticate,        /* WINHTTP_QUERY_PROXY_AUTHENTICATE         = 41 */
137     attr_accept_ranges,             /* WINHTTP_QUERY_ACCEPT_RANGES              = 42 */
138     attr_set_cookie,                /* WINHTTP_QUERY_SET_COOKIE                 = 43 */
139     attr_cookie,                    /* WINHTTP_QUERY_COOKIE                     = 44 */
140     NULL,                           /* WINHTTP_QUERY_REQUEST_METHOD             = 45 */
141     NULL,                           /* WINHTTP_QUERY_REFRESH                    = 46 */
142     NULL,                           /* WINHTTP_QUERY_CONTENT_DISPOSITION        = 47 */
143     attr_age,                       /* WINHTTP_QUERY_AGE                        = 48 */
144     attr_cache_control,             /* WINHTTP_QUERY_CACHE_CONTROL              = 49 */
145     attr_content_base,              /* WINHTTP_QUERY_CONTENT_BASE               = 50 */
146     attr_content_location,          /* WINHTTP_QUERY_CONTENT_LOCATION           = 51 */
147     attr_content_md5,               /* WINHTTP_QUERY_CONTENT_MD5                = 52 */
148     attr_content_range,             /* WINHTTP_QUERY_CONTENT_RANGE              = 53 */
149     attr_etag,                      /* WINHTTP_QUERY_ETAG                       = 54 */
150     attr_host,                      /* WINHTTP_QUERY_HOST                       = 55 */
151     attr_if_match,                  /* WINHTTP_QUERY_IF_MATCH                   = 56 */
152     attr_if_none_match,             /* WINHTTP_QUERY_IF_NONE_MATCH              = 57 */
153     attr_if_range,                  /* WINHTTP_QUERY_IF_RANGE                   = 58 */
154     attr_if_unmodified_since,       /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE        = 59 */
155     attr_max_forwards,              /* WINHTTP_QUERY_MAX_FORWARDS               = 60 */
156     attr_proxy_authorization,       /* WINHTTP_QUERY_PROXY_AUTHORIZATION        = 61 */
157     attr_range,                     /* WINHTTP_QUERY_RANGE                      = 62 */
158     attr_transfer_encoding,         /* WINHTTP_QUERY_TRANSFER_ENCODING          = 63 */
159     attr_upgrade,                   /* WINHTTP_QUERY_UPGRADE                    = 64 */
160     attr_vary,                      /* WINHTTP_QUERY_VARY                       = 65 */
161     attr_via,                       /* WINHTTP_QUERY_VIA                        = 66 */
162     attr_warning,                   /* WINHTTP_QUERY_WARNING                    = 67 */
163     attr_expect,                    /* WINHTTP_QUERY_EXPECT                     = 68 */
164     attr_proxy_connection,          /* WINHTTP_QUERY_PROXY_CONNECTION           = 69 */
165     attr_unless_modified_since,     /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE      = 70 */
166     NULL,                           /* WINHTTP_QUERY_PROXY_SUPPORT              = 75 */
167     NULL,                           /* WINHTTP_QUERY_AUTHENTICATION_INFO        = 76 */
168     NULL,                           /* WINHTTP_QUERY_PASSPORT_URLS              = 77 */
169     NULL                            /* WINHTTP_QUERY_PASSPORT_CONFIG            = 78 */
170 };
171
172 static void free_header( header_t *header )
173 {
174     heap_free( header->field );
175     heap_free( header->value );
176     heap_free( header );
177 }
178
179 static BOOL valid_token_char( WCHAR c )
180 {
181     if (c < 32 || c == 127) return FALSE;
182     switch (c)
183     {
184     case '(': case ')':
185     case '<': case '>':
186     case '@': case ',':
187     case ';': case ':':
188     case '\\': case '\"':
189     case '/': case '[':
190     case ']': case '?':
191     case '=': case '{':
192     case '}': case ' ':
193     case '\t':
194         return FALSE;
195     default:
196         return TRUE;
197     }
198 }
199
200 static header_t *parse_header( LPCWSTR string )
201 {
202     const WCHAR *p, *q;
203     header_t *header;
204     int len;
205
206     p = string;
207     if (!(q = strchrW( p, ':' )))
208     {
209         WARN("no ':' in line %s\n", debugstr_w(string));
210         return NULL;
211     }
212     if (q == string)
213     {
214         WARN("empty field name in line %s\n", debugstr_w(string));
215         return NULL;
216     }
217     while (*p != ':')
218     {
219         if (!valid_token_char( *p ))
220         {
221             WARN("invalid character in field name %s\n", debugstr_w(string));
222             return NULL;
223         }
224         p++;
225     }
226     len = q - string;
227     if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
228     if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
229     {
230         heap_free( header );
231         return NULL;
232     }
233     memcpy( header->field, string, len * sizeof(WCHAR) );
234     header->field[len] = 0;
235
236     q++; /* skip past colon */
237     while (*q == ' ') q++;
238     if (!*q)
239     {
240         WARN("no value in line %s\n", debugstr_w(string));
241         return header;
242     }
243     len = strlenW( q );
244     if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
245     {
246         free_header( header );
247         return NULL;
248     }
249     memcpy( header->value, q, len * sizeof(WCHAR) );
250     header->value[len] = 0;
251
252     return header;
253 }
254
255 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
256 {
257     int index;
258
259     TRACE("%s\n", debugstr_w(field));
260
261     for (index = 0; index < request->num_headers; index++)
262     {
263         if (strcmpiW( request->headers[index].field, field )) continue;
264         if (request_only && !request->headers[index].is_request) continue;
265         if (!request_only && request->headers[index].is_request) continue;
266
267         if (!requested_index) break;
268         requested_index--;
269     }
270     if (index >= request->num_headers) index = -1;
271     TRACE("returning %d\n", index);
272     return index;
273 }
274
275 static BOOL insert_header( request_t *request, header_t *header )
276 {
277     DWORD count;
278     header_t *hdrs;
279
280     count = request->num_headers + 1;
281     if (count > 1)
282         hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
283     else
284         hdrs = heap_alloc_zero( sizeof(header_t) * count );
285
286     if (hdrs)
287     {
288         request->headers = hdrs;
289         request->headers[count - 1].field = strdupW( header->field );
290         request->headers[count - 1].value = strdupW( header->value );
291         request->headers[count - 1].is_request = header->is_request;
292         request->num_headers++;
293         return TRUE;
294     }
295     return FALSE;
296 }
297
298 static BOOL delete_header( request_t *request, DWORD index )
299 {
300     if (!request->num_headers) return FALSE;
301     if (index >= request->num_headers) return FALSE;
302     request->num_headers--;
303
304     heap_free( request->headers[index].field );
305     heap_free( request->headers[index].value );
306
307     memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
308     memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
309     return TRUE;
310 }
311
312 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
313 {
314     int index;
315     header_t *header;
316
317     TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
318
319     /* replace wins out over add */
320     if (flags & WINHTTP_ADDREQ_FLAG_REPLACE) flags &= ~WINHTTP_ADDREQ_FLAG_ADD;
321
322     if (flags & WINHTTP_ADDREQ_FLAG_ADD) index = -1;
323     else
324         index = get_header_index( request, field, 0, request_only );
325
326     if (index >= 0)
327     {
328         if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
329         header = &request->headers[index];
330     }
331     else if (value)
332     {
333         header_t hdr;
334
335         hdr.field = (LPWSTR)field;
336         hdr.value = (LPWSTR)value;
337         hdr.is_request = request_only;
338
339         return insert_header( request, &hdr );
340     }
341     /* no value to delete */
342     else return TRUE;
343
344     if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
345     {
346         delete_header( request, index );
347         if (value)
348         {
349             header_t hdr;
350
351             hdr.field = (LPWSTR)field;
352             hdr.value = (LPWSTR)value;
353             hdr.is_request = request_only;
354
355             return insert_header( request, &hdr );
356         }
357         return TRUE;
358     }
359     else if (flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON))
360     {
361         WCHAR sep, *tmp;
362         int len, orig_len, value_len;
363
364         orig_len = strlenW( header->value );
365         value_len = strlenW( value );
366
367         if (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) sep = ',';
368         else sep = ';';
369
370         len = orig_len + value_len + 2;
371         if ((tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) )))
372         {
373             header->value = tmp;
374
375             header->value[orig_len] = sep;
376             orig_len++;
377             header->value[orig_len] = ' ';
378             orig_len++;
379
380             memcpy( &header->value[orig_len], value, value_len * sizeof(WCHAR) );
381             header->value[len] = 0;
382             return TRUE;
383         }
384     }
385     return TRUE;
386 }
387
388 static BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
389 {
390     BOOL ret = FALSE;
391     WCHAR *buffer, *p, *q;
392     header_t *header;
393
394     if (len == ~0UL) len = strlenW( headers );
395     if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
396     strcpyW( buffer, headers );
397
398     p = buffer;
399     do
400     {
401         q = p;
402         while (*q)
403         {
404             if (q[0] == '\r' && q[1] == '\n') break;
405             q++;
406         }
407         if (!*p) break;
408         if (*q == '\r')
409         {
410             *q = 0;
411             q += 2; /* jump over \r\n */
412         }
413         if ((header = parse_header( p )))
414         {
415             ret = process_header( request, header->field, header->value, flags, TRUE );
416             free_header( header );
417         }
418         p = q;
419     } while (ret);
420
421     heap_free( buffer );
422     return ret;
423 }
424
425 /***********************************************************************
426  *          WinHttpAddRequestHeaders (winhttp.@)
427  */
428 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
429 {
430     BOOL ret;
431     request_t *request;
432
433     TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest, debugstr_w(headers), len, flags);
434
435     if (!headers)
436     {
437         set_last_error( ERROR_INVALID_PARAMETER );
438         return FALSE;
439     }
440     if (!(request = (request_t *)grab_object( hrequest )))
441     {
442         set_last_error( ERROR_INVALID_HANDLE );
443         return FALSE;
444     }
445     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
446     {
447         release_object( &request->hdr );
448         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
449         return FALSE;
450     }
451
452     ret = add_request_headers( request, headers, len, flags );
453
454     release_object( &request->hdr );
455     return ret;
456 }
457
458 static WCHAR *build_request_string( request_t *request, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
459 {
460     static const WCHAR space[]   = {' ',0};
461     static const WCHAR crlf[]    = {'\r','\n',0};
462     static const WCHAR colon[]   = {':',' ',0};
463     static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
464
465     WCHAR *ret;
466     const WCHAR **headers, **p;
467     unsigned int len, i = 0, j;
468
469     /* allocate space for an array of all the string pointers to be added */
470     len = request->num_headers * 4 + 7;
471     if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
472
473     headers[i++] = verb;
474     headers[i++] = space;
475     headers[i++] = path;
476     headers[i++] = space;
477     headers[i++] = version;
478
479     for (j = 0; j < request->num_headers; j++)
480     {
481         if (request->headers[j].is_request)
482         {
483             headers[i++] = crlf;
484             headers[i++] = request->headers[j].field;
485             headers[i++] = colon;
486             headers[i++] = request->headers[j].value;
487
488             TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
489                   debugstr_w(request->headers[j].value));
490         }
491     }
492     headers[i++] = twocrlf;
493     headers[i] = NULL;
494
495     len = 0;
496     for (p = headers; *p; p++) len += strlenW( *p );
497     len++;
498
499     if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
500     {
501         heap_free( headers );
502         return NULL;
503     }
504     *ret = 0;
505     for (p = headers; *p; p++) strcatW( ret, *p );
506
507     heap_free( headers );
508     return ret;
509 }
510
511 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
512
513 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
514 {
515     header_t *header = NULL;
516     BOOL request_only, ret = FALSE;
517     int requested_index, header_index = -1;
518     DWORD attr;
519
520     request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
521     requested_index = index ? *index : 0;
522
523     attr = level & ~QUERY_MODIFIER_MASK;
524     switch (attr)
525     {
526     case WINHTTP_QUERY_CUSTOM:
527     {
528         header_index = get_header_index( request, name, requested_index, request_only );
529         break;
530     }
531     case WINHTTP_QUERY_RAW_HEADERS_CRLF:
532     {
533         WCHAR *headers;
534         DWORD len;
535
536         if (request_only)
537             headers = build_request_string( request, request->verb, request->path, request->version );
538         else
539             headers = request->raw_headers;
540
541         len = strlenW( headers ) * sizeof(WCHAR);
542         if (len + sizeof(WCHAR) > *buflen)
543         {
544             len += sizeof(WCHAR);
545             set_last_error( ERROR_INSUFFICIENT_BUFFER );
546         }
547         else if (buffer)
548         {
549             memcpy( buffer, headers, len + sizeof(WCHAR) );
550             TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
551             ret = TRUE;
552         }
553         *buflen = len;
554         if (request_only) heap_free( headers );
555         return ret;
556     }
557     default:
558     {
559         if (attr > sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
560         {
561             FIXME("attribute %u not implemented\n", attr);
562             return FALSE;
563         }
564         TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
565         header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
566     }
567     }
568
569     if (header_index >= 0)
570     {
571         header = &request->headers[header_index];
572     }
573     if (!header || (request_only && !header->is_request))
574     {
575         set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
576         return FALSE;
577     }
578     if (index) *index += 1;
579     if (level & WINHTTP_QUERY_FLAG_NUMBER)
580     {
581         int *number = buffer;
582         if (sizeof(int) > *buflen)
583         {
584             set_last_error( ERROR_INSUFFICIENT_BUFFER );
585         }
586         else if (number)
587         {
588             *number = atoiW( header->value );
589             TRACE("returning number: %d\n", *number);
590             ret = TRUE;
591         }
592         *buflen = sizeof(int);
593     }
594     else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
595     {
596         SYSTEMTIME *st = buffer;
597         if (sizeof(SYSTEMTIME) > *buflen)
598         {
599             set_last_error( ERROR_INSUFFICIENT_BUFFER );
600         }
601         else if (st && (ret = WinHttpTimeToSystemTime( header->value, st )))
602         {
603             TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
604                   st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
605                   st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
606         }
607         *buflen = sizeof(SYSTEMTIME);
608     }
609     else if (header->value)
610     {
611         WCHAR *string = buffer;
612         DWORD len = (strlenW( header->value ) + 1) * sizeof(WCHAR);
613         if (len > *buflen)
614         {
615             set_last_error( ERROR_INSUFFICIENT_BUFFER );
616             *buflen = len;
617             return FALSE;
618         }
619         else if (string)
620         {
621             strcpyW( string, header->value );
622             TRACE("returning string: %s\n", debugstr_w(string));
623             ret = TRUE;
624         }
625         *buflen = len - sizeof(WCHAR);
626     }
627     return ret;
628 }
629
630 /***********************************************************************
631  *          WinHttpQueryHeaders (winhttp.@)
632  */
633 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
634 {
635     BOOL ret;
636     request_t *request;
637
638     TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
639
640     if (!(request = (request_t *)grab_object( hrequest )))
641     {
642         set_last_error( ERROR_INVALID_HANDLE );
643         return FALSE;
644     }
645     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
646     {
647         release_object( &request->hdr );
648         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
649         return FALSE;
650     }
651
652     ret = query_headers( request, level, name, buffer, buflen, index );
653
654     release_object( &request->hdr );
655     return ret;
656 }
657
658 static BOOL open_connection( request_t *request )
659 {
660     connect_t *connect;
661     char address[32];
662     WCHAR *addressW;
663
664     if (netconn_connected( &request->netconn )) return TRUE;
665
666     connect = request->connect;
667     if (!netconn_resolve( connect->servername, connect->serverport, &connect->sockaddr )) return FALSE;
668
669     inet_ntop( connect->sockaddr.sin_family, &connect->sockaddr.sin_addr, address, sizeof(address) );
670     TRACE("connecting to %s:%u\n", address, ntohs(connect->sockaddr.sin_port));
671     addressW = strdupAW( address );
672
673     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
674
675     if (!netconn_create( &request->netconn, connect->sockaddr.sin_family, SOCK_STREAM, 0 ))
676     {
677         heap_free( addressW );
678         return FALSE;
679     }
680     if (!netconn_connect( &request->netconn, (struct sockaddr *)&connect->sockaddr, sizeof(struct sockaddr_in) ))
681     {
682         netconn_close( &request->netconn );
683         heap_free( addressW );
684         return FALSE;
685     }
686
687     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, 0 );
688
689     heap_free( addressW );
690     return TRUE;
691 }
692
693 void close_connection( request_t *request )
694 {
695     if (!netconn_connected( &request->netconn )) return;
696
697     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
698     netconn_close( &request->netconn );
699     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
700 }
701
702 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
703                           DWORD optional_len, DWORD total_len, DWORD_PTR context )
704 {
705     static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
706     static const WCHAR no_cache[]   = {'n','o','-','c','a','c','h','e',0};
707     static const WCHAR length_fmt[] = {'%','l','d',0};
708
709     BOOL ret = FALSE;
710     connect_t *connect = request->connect;
711     session_t *session = connect->session;
712     WCHAR *req = NULL;
713     char *req_ascii;
714     int bytes_sent;
715     DWORD len;
716
717     if (session->agent)
718         process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
719
720     if (connect->hostname)
721         process_header( request, attr_host, connect->hostname, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
722
723     if (optional_len)
724     {
725         WCHAR length[21]; /* decimal long int + null */
726         sprintfW( length, length_fmt, optional_len );
727         process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
728     }
729     if (!(request->hdr.flags & WINHTTP_DISABLE_KEEP_ALIVE))
730     {
731         process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
732     }
733     if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
734     {
735         process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
736         process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
737     }
738     if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
739     {
740         TRACE("failed to add request headers\n");
741         return FALSE;
742     }
743
744     if (!(ret = open_connection( request ))) goto end;
745     if (!(req = build_request_string( request, request->verb, request->path, request->version ))) goto end;
746
747     if (!(req_ascii = strdupWA( req ))) goto end;
748     TRACE("full request: %s\n", debugstr_a(req_ascii));
749     len = strlen(req_ascii);
750
751     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
752
753     ret = netconn_send( &request->netconn, req_ascii, len, 0, &bytes_sent );
754     heap_free( req_ascii );
755     if (!ret) goto end;
756
757     if (optional_len && !netconn_send( &request->netconn, optional, optional_len, 0, &bytes_sent )) goto end;
758     len += optional_len;
759
760     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(DWORD) );
761
762 end:
763     heap_free( req );
764     return ret;
765 }
766
767 /***********************************************************************
768  *          WinHttpSendRequest (winhttp.@)
769  */
770 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
771                                 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
772 {
773     BOOL ret;
774     request_t *request;
775
776     TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
777           hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
778
779     if (!(request = (request_t *)grab_object( hrequest )))
780     {
781         set_last_error( ERROR_INVALID_HANDLE );
782         return FALSE;
783     }
784     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
785     {
786         release_object( &request->hdr );
787         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
788         return FALSE;
789     }
790
791     ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context );
792
793     release_object( &request->hdr );
794     return ret;
795 }
796
797 static void clear_response_headers( request_t *request )
798 {
799     unsigned int i;
800
801     for (i = 0; i < request->num_headers; i++)
802     {
803         if (!request->headers[i].field) continue;
804         if (!request->headers[i].value) continue;
805         if (request->headers[i].is_request) continue;
806         delete_header( request, i );
807         i--;
808     }
809 }
810
811 #define MAX_REPLY_LEN   1460
812 #define INITIAL_HEADER_BUFFER_SIZE  512
813
814 static BOOL receive_response( request_t *request, BOOL clear )
815 {
816     static const WCHAR crlf[] = {'\r','\n',0};
817
818     char buffer[MAX_REPLY_LEN];
819     DWORD buflen, len, offset, received_len, crlf_len = 2; /* strlenW(crlf) */
820     char *status_code, *status_text;
821     WCHAR *versionW, *status_textW, *raw_headers;
822     WCHAR status_codeW[4]; /* sizeof("nnn") */
823
824     if (!netconn_connected( &request->netconn )) return FALSE;
825
826     /* clear old response headers (eg. from a redirect response) */
827     if (clear) clear_response_headers( request );
828
829     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
830
831     received_len = 0;
832     do
833     {
834         buflen = MAX_REPLY_LEN;
835         if (!netconn_get_next_line( &request->netconn, buffer, &buflen )) return FALSE;
836         received_len += buflen;
837
838         /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
839         if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
840         status_code++;
841         if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
842         if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
843         status_text++;
844
845         TRACE("version [%s] status code [%s] status text [%s]\n",
846               debugstr_an(buffer, status_code - buffer - 1),
847               debugstr_an(status_code, len),
848               debugstr_a(status_text));
849
850     } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
851
852     /*  we rely on the fact that the protocol is ascii */
853     MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
854     status_codeW[len] = 0;
855     if (!(process_header( request, attr_status, status_codeW, WINHTTP_ADDREQ_FLAG_REPLACE, FALSE ))) return FALSE;
856
857     len = status_code - buffer;
858     if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
859     MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
860     versionW[len - 1] = 0;
861
862     heap_free( request->version );
863     request->version = versionW;
864
865     len = buflen - (status_text - buffer);
866     if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
867     MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
868
869     heap_free( request->status_text );
870     request->status_text = status_textW;
871
872     len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_SIZE );
873     if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
874     MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
875     memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
876
877     heap_free( request->raw_headers );
878     request->raw_headers = raw_headers;
879
880     offset = buflen + crlf_len - 1;
881     for (;;)
882     {
883         header_t *header;
884
885         buflen = MAX_REPLY_LEN;
886         if (!netconn_get_next_line( &request->netconn, buffer, &buflen )) goto end;
887         received_len += buflen;
888         if (!*buffer) break;
889
890         while (len - offset < buflen + crlf_len)
891         {
892             WCHAR *tmp;
893             len *= 2;
894             if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
895             request->raw_headers = raw_headers = tmp;
896         }
897         MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
898
899         if (!(header = parse_header( raw_headers + offset ))) break;
900         if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
901         {
902             free_header( header );
903             break;
904         }
905         free_header( header );
906         memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
907         offset += buflen + crlf_len - 1;
908     }
909
910     TRACE("raw headers: %s\n", debugstr_w(raw_headers));
911
912 end:
913     send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &received_len, sizeof(DWORD) );
914     return TRUE;
915 }
916
917 /***********************************************************************
918  *          WinHttpReceiveResponse (winhttp.@)
919  */
920 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
921 {
922     BOOL ret = TRUE;
923     request_t *request;
924     DWORD size, query;
925
926     TRACE("%p, %p\n", hrequest, reserved);
927
928     if (!(request = (request_t *)grab_object( hrequest )))
929     {
930         set_last_error( ERROR_INVALID_HANDLE );
931         return FALSE;
932     }
933     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
934     {
935         release_object( &request->hdr );
936         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
937         return FALSE;
938     }
939
940     ret = receive_response( request, TRUE );
941
942     size = sizeof(DWORD);
943     query = WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER;
944     if (!query_headers( request, query, NULL, &request->content_length, &size, NULL ))
945         request->content_length = ~0UL;
946
947     release_object( &request->hdr );
948     return ret;
949 }
950
951 /***********************************************************************
952  *          WinHttpQueryDataAvailable (winhttp.@)
953  */
954 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
955 {
956     BOOL ret;
957     request_t *request;
958
959     TRACE("%p, %p\n", hrequest, available);
960
961     if (!(request = (request_t *)grab_object( hrequest )))
962     {
963         set_last_error( ERROR_INVALID_HANDLE );
964         return FALSE;
965     }
966     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
967     {
968         release_object( &request->hdr );
969         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
970         return FALSE;
971     }
972
973     ret = netconn_query_data_available( &request->netconn, available );
974
975     release_object( &request->hdr );
976     return ret;
977 }
978
979 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
980 {
981     DWORD to_read;
982     int bytes_read;
983
984     to_read = min( size, request->content_length - request->content_read );
985     if (!netconn_recv( &request->netconn, buffer, to_read, async ? 0 : MSG_WAITALL, &bytes_read ))
986     {
987         if (bytes_read != to_read)
988         {
989             ERR("not all data received %d/%d\n", bytes_read, to_read);
990         }
991         /* always return success, even if the network layer returns an error */
992         *read = 0;
993         return TRUE;
994     }
995     request->content_read += bytes_read;
996     *read = bytes_read;
997     return TRUE;
998 }
999
1000 static DWORD get_chunk_size( const char *buffer )
1001 {
1002     const char *p;
1003     DWORD size = 0;
1004
1005     for (p = buffer; *p; p++)
1006     {
1007         if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1008         else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1009         else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1010         else if (*p == ';') break;
1011     }
1012     return size;
1013 }
1014
1015 static BOOL read_data_chunked( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
1016 {
1017     char reply[MAX_REPLY_LEN], *p = buffer;
1018     DWORD buflen, to_read, to_write = size;
1019     int bytes_read;
1020
1021     *read = 0;
1022     for (;;)
1023     {
1024         if (*read == size) break;
1025
1026         if (request->content_length == ~0UL) /* new chunk */
1027         {
1028             buflen = sizeof(reply);
1029             if (!netconn_get_next_line( &request->netconn, reply, &buflen )) break;
1030
1031             if (!(request->content_length = get_chunk_size( reply )))
1032             {
1033                 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1034                 receive_response( request, FALSE );
1035                 break;
1036             }
1037         }
1038         to_read = min( to_write, request->content_length - request->content_read );
1039
1040         if (!netconn_recv( &request->netconn, p, to_read, async ? 0 : MSG_WAITALL, &bytes_read ))
1041         {
1042             if (bytes_read != to_read)
1043             {
1044                 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1045             }
1046             /* always return success, even if the network layer returns an error */
1047             *read = 0;
1048             break;
1049         }
1050         if (!bytes_read) break;
1051
1052         request->content_read += bytes_read;
1053         to_write -= bytes_read;
1054         *read += bytes_read;
1055         p += bytes_read;
1056
1057         if (request->content_read == request->content_length) /* chunk complete */
1058         {
1059             request->content_read = 0;
1060             request->content_length = ~0UL;
1061
1062             buflen = sizeof(reply);
1063             if (!netconn_get_next_line( &request->netconn, reply, &buflen ))
1064             {
1065                 ERR("Malformed chunk\n");
1066                 *read = 0;
1067                 break;
1068             }
1069         }
1070     }
1071     return TRUE;
1072 }
1073
1074 /***********************************************************************
1075  *          WinHttpReadData (winhttp.@)
1076  */
1077 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
1078 {
1079     static const WCHAR chunked[] = {'c','h','u','n','k','e','d',0};
1080
1081     BOOL ret;
1082     request_t *request;
1083     WCHAR encoding[20];
1084     DWORD buflen = sizeof(encoding);
1085
1086     TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
1087
1088     if (!(request = (request_t *)grab_object( hrequest )))
1089     {
1090         set_last_error( ERROR_INVALID_HANDLE );
1091         return FALSE;
1092     }
1093     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1094     {
1095         release_object( &request->hdr );
1096         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1097         return FALSE;
1098     }
1099
1100     if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
1101         !strcmpiW( encoding, chunked ))
1102     {
1103         ret = read_data_chunked( request, buffer, to_read, read, request->hdr.flags & WINHTTP_FLAG_ASYNC );
1104     }
1105     else
1106         ret = read_data( request, buffer, to_read, read, request->hdr.flags & WINHTTP_FLAG_ASYNC );
1107
1108     release_object( &request->hdr );
1109     return ret;
1110 }
1111
1112 /***********************************************************************
1113  *          WinHttpWriteData (winhttp.@)
1114  */
1115 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
1116 {
1117     BOOL ret;
1118     request_t *request;
1119
1120     TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
1121
1122     if (!(request = (request_t *)grab_object( hrequest )))
1123     {
1124         set_last_error( ERROR_INVALID_HANDLE );
1125         return FALSE;
1126     }
1127     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1128     {
1129         release_object( &request->hdr );
1130         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1131         return FALSE;
1132     }
1133
1134     ret = netconn_send( &request->netconn, buffer, to_write, 0, (int *)written );
1135
1136     release_object( &request->hdr );
1137     return ret;
1138 }
1139
1140 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1141
1142 static DWORD auth_scheme_from_header( WCHAR *header )
1143 {
1144     static const WCHAR basic[]     = {'B','a','s','i','c'};
1145     static const WCHAR ntlm[]      = {'N','T','L','M'};
1146     static const WCHAR passport[]  = {'P','a','s','s','p','o','r','t'};
1147     static const WCHAR digest[]    = {'D','i','g','e','s','t'};
1148     static const WCHAR negotiate[] = {'N','e','g','o','t','i','a','t','e'};
1149
1150     if (!strncmpiW( header, basic, ARRAYSIZE(basic) ) &&
1151         (header[ARRAYSIZE(basic)] == ' ' || !header[ARRAYSIZE(basic)])) return WINHTTP_AUTH_SCHEME_BASIC;
1152
1153     if (!strncmpiW( header, ntlm, ARRAYSIZE(ntlm) ) &&
1154         (header[ARRAYSIZE(ntlm)] == ' ' || !header[ARRAYSIZE(ntlm)])) return WINHTTP_AUTH_SCHEME_NTLM;
1155
1156     if (!strncmpiW( header, passport, ARRAYSIZE(passport) ) &&
1157         (header[ARRAYSIZE(passport)] == ' ' || !header[ARRAYSIZE(passport)])) return WINHTTP_AUTH_SCHEME_PASSPORT;
1158
1159     if (!strncmpiW( header, digest, ARRAYSIZE(digest) ) &&
1160         (header[ARRAYSIZE(digest)] == ' ' || !header[ARRAYSIZE(digest)])) return WINHTTP_AUTH_SCHEME_DIGEST;
1161
1162     if (!strncmpiW( header, negotiate, ARRAYSIZE(negotiate) ) &&
1163         (header[ARRAYSIZE(negotiate)] == ' ' || !header[ARRAYSIZE(negotiate)])) return WINHTTP_AUTH_SCHEME_NEGOTIATE;
1164
1165     return 0;
1166 }
1167
1168 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1169 {
1170     DWORD index = 0;
1171     BOOL ret = FALSE;
1172
1173     for (;;)
1174     {
1175         WCHAR *buffer;
1176         DWORD size, scheme;
1177
1178         size = 0;
1179         query_headers( request, level, NULL, NULL, &size, &index );
1180         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) break;
1181
1182         index--;
1183         if (!(buffer = heap_alloc( size ))) return FALSE;
1184         if (!query_headers( request, level, NULL, buffer, &size, &index ))
1185         {
1186             heap_free( buffer );
1187             return FALSE;
1188         }
1189         scheme = auth_scheme_from_header( buffer );
1190         if (index == 1) *first = scheme;
1191         *supported |= scheme;
1192
1193         heap_free( buffer );
1194         ret = TRUE;
1195     }
1196     return ret;
1197 }
1198
1199 /***********************************************************************
1200  *          WinHttpQueryAuthSchemes (winhttp.@)
1201  */
1202 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1203 {
1204     BOOL ret = FALSE;
1205     request_t *request;
1206
1207     TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1208
1209     if (!(request = (request_t *)grab_object( hrequest )))
1210     {
1211         set_last_error( ERROR_INVALID_HANDLE );
1212         return FALSE;
1213     }
1214     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1215     {
1216         release_object( &request->hdr );
1217         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1218         return FALSE;
1219     }
1220
1221     if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1222     {
1223         *target = WINHTTP_AUTH_TARGET_SERVER;
1224         ret = TRUE;
1225     }
1226     else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1227     {
1228         *target = WINHTTP_AUTH_TARGET_PROXY;
1229         ret = TRUE;
1230     }
1231
1232     release_object( &request->hdr );
1233     return ret;
1234 }
1235
1236 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1237 {
1238     UINT n = 0, x;
1239     static const char base64enc[] =
1240         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1241
1242     while (len > 0)
1243     {
1244         /* first 6 bits, all from bin[0] */
1245         base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1246         x = (bin[0] & 3) << 4;
1247
1248         /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1249         if (len == 1)
1250         {
1251             base64[n++] = base64enc[x];
1252             base64[n++] = '=';
1253             base64[n++] = '=';
1254             break;
1255         }
1256         base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1257         x = (bin[1] & 0x0f) << 2;
1258
1259         /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1260         if (len == 2)
1261         {
1262             base64[n++] = base64enc[x];
1263             base64[n++] = '=';
1264             break;
1265         }
1266         base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1267
1268         /* last 6 bits, all from bin [2] */
1269         base64[n++] = base64enc[bin[2] & 0x3f];
1270         bin += 3;
1271         len -= 3;
1272     }
1273     base64[n] = 0;
1274     return n;
1275 }
1276
1277 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme, LPCWSTR username, LPCWSTR password )
1278 {
1279     static const WCHAR basic[] = {'B','a','s','i','c',' ',0};
1280
1281     const WCHAR *auth_scheme, *auth_target;
1282     WCHAR *auth_header;
1283     DWORD len, auth_data_len;
1284     char *auth_data;
1285     BOOL ret;
1286
1287     switch (target)
1288     {
1289     case WINHTTP_AUTH_TARGET_SERVER: auth_target = attr_authorization; break;
1290     case WINHTTP_AUTH_TARGET_PROXY:  auth_target = attr_proxy_authorization; break;
1291     default:
1292         WARN("unknown target %x\n", target);
1293         return FALSE;
1294     }
1295     switch (scheme)
1296     {
1297     case WINHTTP_AUTH_SCHEME_BASIC:
1298     {
1299         int userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1300         int passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1301
1302         TRACE("basic authentication\n");
1303
1304         auth_scheme = basic;
1305         auth_data_len = userlen + 1 + passlen;
1306         if (!(auth_data = heap_alloc( auth_data_len ))) return FALSE;
1307
1308         WideCharToMultiByte( CP_UTF8, 0, username, -1, auth_data, userlen, NULL, NULL );
1309         auth_data[userlen] = ':';
1310         WideCharToMultiByte( CP_UTF8, 0, password, -1, auth_data + userlen + 1, passlen, NULL, NULL );
1311         break;
1312     }
1313     case WINHTTP_AUTH_SCHEME_NTLM:
1314     case WINHTTP_AUTH_SCHEME_PASSPORT:
1315     case WINHTTP_AUTH_SCHEME_DIGEST:
1316     case WINHTTP_AUTH_SCHEME_NEGOTIATE:
1317         FIXME("unimplemented authentication scheme %x\n", scheme);
1318         return FALSE;
1319     default:
1320         WARN("unknown authentication scheme %x\n", scheme);
1321         return FALSE;
1322     }
1323
1324     len = strlenW( auth_scheme ) + ((auth_data_len + 2) * 4) / 3;
1325     if (!(auth_header = heap_alloc( (len + 1) * sizeof(WCHAR) )))
1326     {
1327         heap_free( auth_data );
1328         return FALSE;
1329     }
1330     strcpyW( auth_header, auth_scheme );
1331     encode_base64( auth_data, auth_data_len, auth_header + strlenW( auth_header ) );
1332
1333     ret = process_header( request, auth_target, auth_header, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, TRUE );
1334
1335     heap_free( auth_data );
1336     heap_free( auth_header );
1337     return ret;
1338 }
1339
1340 /***********************************************************************
1341  *          WinHttpSetCredentials (winhttp.@)
1342  */
1343 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
1344                                    LPCWSTR password, LPVOID params )
1345 {
1346     BOOL ret;
1347     request_t *request;
1348
1349     TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
1350
1351     if (!(request = (request_t *)grab_object( hrequest )))
1352     {
1353         set_last_error( ERROR_INVALID_HANDLE );
1354         return FALSE;
1355     }
1356     if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1357     {
1358         release_object( &request->hdr );
1359         set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1360         return FALSE;
1361     }
1362
1363     ret = set_credentials( request, target, scheme, username, password );
1364
1365     release_object( &request->hdr );
1366     return ret;
1367 }