setupapi: Implement SetupDiGetDeviceInterfaceDetailA/W.
[wine] / dlls / urlmon / http.c
1 /*
2  * Copyright 2005 Jacek Caban
3  * Copyright 2007 Misha Koshelev
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19
20 /*
21  * TODO:
22  * - Handle redirects as native.
23  */
24
25 #include <stdarg.h>
26
27 #define COBJMACROS
28 #define NONAMELESSUNION
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winuser.h"
33 #include "ole2.h"
34 #include "urlmon.h"
35 #include "wininet.h"
36 #include "urlmon_main.h"
37
38 #include "wine/debug.h"
39 #include "wine/unicode.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
42
43 /* Flags are needed for, among other things, return HRESULTs from the Read function
44  * to conform to native. For example, Read returns:
45  *
46  * 1. E_PENDING if called before the request has completed,
47  *        (flags = 0)
48  * 2. S_FALSE after all data has been read and S_OK has been reported,
49  *        (flags = FLAG_REQUEST_COMPLETE | FLAG_ALL_DATA_READ | FLAG_RESULT_REPORTED)
50  * 3. INET_E_DATA_NOT_AVAILABLE if InternetQueryDataAvailable fails. The first time
51  *    this occurs, INET_E_DATA_NOT_AVAILABLE will also be reported to the sink,
52  *        (flags = FLAG_REQUEST_COMPLETE)
53  *    but upon subsequent calls to Read no reporting will take place, yet
54  *    InternetQueryDataAvailable will still be called, and, on failure,
55  *    INET_E_DATA_NOT_AVAILABLE will still be returned.
56  *        (flags = FLAG_REQUEST_COMPLETE | FLAG_RESULT_REPORTED)
57  *
58  * FLAG_FIRST_DATA_REPORTED and FLAG_LAST_DATA_REPORTED are needed for proper
59  * ReportData reporting. For example, if OnResponse returns S_OK, Continue will
60  * report BSCF_FIRSTDATANOTIFICATION, and when all data has been read Read will
61  * report BSCF_INTERMEDIATEDATANOTIFICATION|BSCF_LASTDATANOTIFICATION. However,
62  * if OnResponse does not return S_OK, Continue will not report data, and Read
63  * will report BSCF_FIRSTDATANOTIFICATION|BSCF_LASTDATANOTIFICATION when all
64  * data has been read.
65  */
66 #define FLAG_REQUEST_COMPLETE 0x1
67 #define FLAG_FIRST_CONTINUE_COMPLETE 0x2
68 #define FLAG_FIRST_DATA_REPORTED 0x4
69 #define FLAG_ALL_DATA_READ 0x8
70 #define FLAG_LAST_DATA_REPORTED 0x10
71 #define FLAG_RESULT_REPORTED 0x20
72
73 typedef struct {
74     const IInternetProtocolVtbl *lpInternetProtocolVtbl;
75     const IInternetPriorityVtbl *lpInternetPriorityVtbl;
76
77     DWORD flags, grfBINDF;
78     BINDINFO bind_info;
79     IInternetProtocolSink *protocol_sink;
80     IHttpNegotiate *http_negotiate;
81     HINTERNET internet, connect, request;
82     LPWSTR full_header;
83     HANDLE lock;
84     ULONG current_position, content_length, available_bytes;
85     LONG priority;
86
87     LONG ref;
88 } HttpProtocol;
89
90 /* Default headers from native */
91 static const WCHAR wszHeaders[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',
92                                    ':',' ','g','z','i','p',',',' ','d','e','f','l','a','t','e',0};
93
94 /*
95  * Helpers
96  */
97
98 static void HTTPPROTOCOL_ReportResult(HttpProtocol *This, HRESULT hres)
99 {
100     if (!(This->flags & FLAG_RESULT_REPORTED) &&
101         This->protocol_sink)
102     {
103         This->flags |= FLAG_RESULT_REPORTED;
104         IInternetProtocolSink_ReportResult(This->protocol_sink, hres, 0, NULL);
105     }
106 }
107
108 static void HTTPPROTOCOL_ReportData(HttpProtocol *This)
109 {
110     DWORD bscf;
111     if (!(This->flags & FLAG_LAST_DATA_REPORTED) &&
112         This->protocol_sink)
113     {
114         if (This->flags & FLAG_FIRST_DATA_REPORTED)
115         {
116             bscf = BSCF_INTERMEDIATEDATANOTIFICATION;
117         }
118         else
119         {
120             This->flags |= FLAG_FIRST_DATA_REPORTED;
121             bscf = BSCF_FIRSTDATANOTIFICATION;
122         }
123         if (This->flags & FLAG_ALL_DATA_READ &&
124             !(This->flags & FLAG_LAST_DATA_REPORTED))
125         {
126             This->flags |= FLAG_LAST_DATA_REPORTED;
127             bscf |= BSCF_LASTDATANOTIFICATION;
128         }
129         IInternetProtocolSink_ReportData(This->protocol_sink, bscf,
130                                          This->current_position+This->available_bytes,
131                                          This->content_length);
132     }
133 }
134
135 static void HTTPPROTOCOL_AllDataRead(HttpProtocol *This)
136 {
137     if (!(This->flags & FLAG_ALL_DATA_READ))
138         This->flags |= FLAG_ALL_DATA_READ;
139     HTTPPROTOCOL_ReportData(This);
140     HTTPPROTOCOL_ReportResult(This, S_OK);
141 }
142
143 static void HTTPPROTOCOL_Close(HttpProtocol *This)
144 {
145     if (This->http_negotiate)
146     {
147         IHttpNegotiate_Release(This->http_negotiate);
148         This->http_negotiate = 0;
149     }
150     if (This->request)
151     {
152         InternetCloseHandle(This->request);
153         This->request = 0;
154     }
155     if (This->connect)
156     {
157         InternetCloseHandle(This->connect);
158         This->connect = 0;
159     }
160     if (This->internet)
161     {
162         InternetCloseHandle(This->internet);
163         This->internet = 0;
164     }
165     if (This->full_header)
166     {
167         if (This->full_header != wszHeaders)
168             HeapFree(GetProcessHeap(), 0, This->full_header);
169         This->full_header = 0;
170     }
171     This->flags = 0;
172 }
173
174 static void CALLBACK HTTPPROTOCOL_InternetStatusCallback(
175     HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus,
176     LPVOID lpvStatusInformation, DWORD dwStatusInformationLength)
177 {
178     HttpProtocol *This = (HttpProtocol *)dwContext;
179     PROTOCOLDATA data;
180     ULONG ulStatusCode;
181
182     switch (dwInternetStatus)
183     {
184     case INTERNET_STATUS_RESOLVING_NAME:
185         ulStatusCode = BINDSTATUS_FINDINGRESOURCE;
186         break;
187     case INTERNET_STATUS_CONNECTING_TO_SERVER:
188         ulStatusCode = BINDSTATUS_CONNECTING;
189         break;
190     case INTERNET_STATUS_SENDING_REQUEST:
191         ulStatusCode = BINDSTATUS_SENDINGREQUEST;
192         break;
193     case INTERNET_STATUS_REQUEST_COMPLETE:
194         This->flags |= FLAG_REQUEST_COMPLETE;
195         /* PROTOCOLDATA same as native */
196         memset(&data, 0, sizeof(data));
197         data.dwState = 0xf1000000;
198         if (This->flags & FLAG_FIRST_CONTINUE_COMPLETE)
199             data.pData = (LPVOID)BINDSTATUS_ENDDOWNLOADCOMPONENTS;
200         else
201             data.pData = (LPVOID)BINDSTATUS_DOWNLOADINGDATA;
202         if (This->grfBINDF & BINDF_FROMURLMON)
203             IInternetProtocolSink_Switch(This->protocol_sink, &data);
204         else
205             IInternetProtocol_Continue((IInternetProtocol *)This, &data);
206         return;
207     case INTERNET_STATUS_HANDLE_CLOSING:
208         if (This->protocol_sink)
209         {
210             IInternetProtocolSink_Release(This->protocol_sink);
211             This->protocol_sink = 0;
212         }
213         if (This->bind_info.cbSize)
214         {
215             ReleaseBindInfo(&This->bind_info);
216             memset(&This->bind_info, 0, sizeof(This->bind_info));
217         }
218         return;
219     default:
220         WARN("Unhandled Internet status callback %d\n", dwInternetStatus);
221         return;
222     }
223
224     IInternetProtocolSink_ReportProgress(This->protocol_sink, ulStatusCode, (LPWSTR)lpvStatusInformation);
225 }
226
227 static inline LPWSTR strndupW(LPWSTR string, int len)
228 {
229     LPWSTR ret = NULL;
230     if (string &&
231         (ret = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR))) != NULL)
232     {
233         memcpy(ret, string, len*sizeof(WCHAR));
234         ret[len] = 0;
235     }
236     return ret;
237 }
238
239 /*
240  * Interface implementations
241  */
242
243 #define PROTOCOL(x)  ((IInternetProtocol*)  &(x)->lpInternetProtocolVtbl)
244 #define PRIORITY(x)  ((IInternetPriority*)  &(x)->lpInternetPriorityVtbl)
245
246 #define PROTOCOL_THIS(iface) DEFINE_THIS(HttpProtocol, InternetProtocol, iface)
247
248 static HRESULT WINAPI HttpProtocol_QueryInterface(IInternetProtocol *iface, REFIID riid, void **ppv)
249 {
250     HttpProtocol *This = PROTOCOL_THIS(iface);
251
252     *ppv = NULL;
253     if(IsEqualGUID(&IID_IUnknown, riid)) {
254         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
255         *ppv = PROTOCOL(This);
256     }else if(IsEqualGUID(&IID_IInternetProtocolRoot, riid)) {
257         TRACE("(%p)->(IID_IInternetProtocolRoot %p)\n", This, ppv);
258         *ppv = PROTOCOL(This);
259     }else if(IsEqualGUID(&IID_IInternetProtocol, riid)) {
260         TRACE("(%p)->(IID_IInternetProtocol %p)\n", This, ppv);
261         *ppv = PROTOCOL(This);
262     }else if(IsEqualGUID(&IID_IInternetPriority, riid)) {
263         TRACE("(%p)->(IID_IInternetPriority %p)\n", This, ppv);
264         *ppv = PRIORITY(This);
265     }
266
267     if(*ppv) {
268         IInternetProtocol_AddRef(iface);
269         return S_OK;
270     }
271
272     WARN("not supported interface %s\n", debugstr_guid(riid));
273     return E_NOINTERFACE;
274 }
275
276 static ULONG WINAPI HttpProtocol_AddRef(IInternetProtocol *iface)
277 {
278     HttpProtocol *This = PROTOCOL_THIS(iface);
279     LONG ref = InterlockedIncrement(&This->ref);
280     TRACE("(%p) ref=%d\n", This, ref);
281     return ref;
282 }
283
284 static ULONG WINAPI HttpProtocol_Release(IInternetProtocol *iface)
285 {
286     HttpProtocol *This = PROTOCOL_THIS(iface);
287     LONG ref = InterlockedDecrement(&This->ref);
288
289     TRACE("(%p) ref=%d\n", This, ref);
290
291     if(!ref) {
292         HTTPPROTOCOL_Close(This);
293         HeapFree(GetProcessHeap(), 0, This);
294
295         URLMON_UnlockModule();
296     }
297
298     return ref;
299 }
300
301 static HRESULT WINAPI HttpProtocol_Start(IInternetProtocol *iface, LPCWSTR szUrl,
302         IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
303         DWORD grfPI, DWORD dwReserved)
304 {
305     HttpProtocol *This = PROTOCOL_THIS(iface);
306     URL_COMPONENTSW url;
307     DWORD len = 0, request_flags = INTERNET_FLAG_KEEP_CONNECTION;
308     ULONG num = 0;
309     IServiceProvider *service_provider = 0;
310     IHttpNegotiate2 *http_negotiate2 = 0;
311     LPWSTR host = 0, path = 0, user = 0, pass = 0, addl_header = 0,
312         post_cookie = 0, optional = 0;
313     BYTE security_id[512];
314     LPOLESTR user_agent, accept_mimes[257];
315     HRESULT hres;
316
317     static const WCHAR wszHttp[] = {'h','t','t','p',':'};
318     static const WCHAR wszBindVerb[BINDVERB_CUSTOM][5] =
319         {{'G','E','T',0},
320          {'P','O','S','T',0},
321          {'P','U','T',0}};
322
323     TRACE("(%p)->(%s %p %p %08x %d)\n", This, debugstr_w(szUrl), pOIProtSink,
324             pOIBindInfo, grfPI, dwReserved);
325
326     IInternetProtocolSink_AddRef(pOIProtSink);
327     This->protocol_sink = pOIProtSink;
328
329     memset(&This->bind_info, 0, sizeof(This->bind_info));
330     This->bind_info.cbSize = sizeof(BINDINFO);
331     hres = IInternetBindInfo_GetBindInfo(pOIBindInfo, &This->grfBINDF, &This->bind_info);
332     if (hres != S_OK)
333     {
334         WARN("GetBindInfo failed: %08x\n", hres);
335         goto done;
336     }
337
338     if (lstrlenW(szUrl) < sizeof(wszHttp)/sizeof(WCHAR)
339         || memcmp(szUrl, wszHttp, sizeof(wszHttp)))
340     {
341         hres = MK_E_SYNTAX;
342         goto done;
343     }
344
345     memset(&url, 0, sizeof(url));
346     url.dwStructSize = sizeof(url);
347     url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = url.dwUserNameLength =
348         url.dwPasswordLength = 1;
349     if (!InternetCrackUrlW(szUrl, 0, 0, &url))
350     {
351         hres = MK_E_SYNTAX;
352         goto done;
353     }
354     host = strndupW(url.lpszHostName, url.dwHostNameLength);
355     path = strndupW(url.lpszUrlPath, url.dwUrlPathLength);
356     user = strndupW(url.lpszUserName, url.dwUserNameLength);
357     pass = strndupW(url.lpszPassword, url.dwPasswordLength);
358     if (!url.nPort)
359         url.nPort = INTERNET_DEFAULT_HTTP_PORT;
360
361     if(!(This->grfBINDF & BINDF_FROMURLMON))
362         IInternetProtocolSink_ReportProgress(This->protocol_sink, BINDSTATUS_DIRECTBIND, NULL);
363
364     hres = IInternetBindInfo_GetBindString(pOIBindInfo, BINDSTRING_USER_AGENT, &user_agent,
365                                            1, &num);
366     if (hres != S_OK || !num)
367     {
368         CHAR null_char = 0;
369         LPSTR user_agenta = NULL;
370         len = 0;
371         if ((hres = ObtainUserAgentString(0, &null_char, &len)) != E_OUTOFMEMORY)
372         {
373             WARN("ObtainUserAgentString failed: %08x\n", hres);
374         }
375         else if (!(user_agenta = HeapAlloc(GetProcessHeap(), 0, len*sizeof(CHAR))))
376         {
377             WARN("Out of memory\n");
378         }
379         else if ((hres = ObtainUserAgentString(0, user_agenta, &len)) != S_OK)
380         {
381             WARN("ObtainUserAgentString failed: %08x\n", hres);
382         }
383         else
384         {
385             if (!(user_agent = CoTaskMemAlloc((len)*sizeof(WCHAR))))
386                 WARN("Out of memory\n");
387             else
388                 MultiByteToWideChar(CP_ACP, 0, user_agenta, -1, user_agent, len*sizeof(WCHAR));
389         }
390         HeapFree(GetProcessHeap(), 0, user_agenta);
391     }
392
393     This->internet = InternetOpenW(user_agent, 0, NULL, NULL, INTERNET_FLAG_ASYNC);
394     if (!This->internet)
395     {
396         WARN("InternetOpen failed: %d\n", GetLastError());
397         hres = INET_E_NO_SESSION;
398         goto done;
399     }
400
401     /* Native does not check for success of next call, so we won't either */
402     InternetSetStatusCallbackW(This->internet, HTTPPROTOCOL_InternetStatusCallback);
403
404     This->connect = InternetConnectW(This->internet, host, url.nPort, user,
405                                      pass, INTERNET_SERVICE_HTTP, 0, (DWORD)This);
406     if (!This->connect)
407     {
408         WARN("InternetConnect failed: %d\n", GetLastError());
409         hres = INET_E_CANNOT_CONNECT;
410         goto done;
411     }
412
413     num = sizeof(accept_mimes)/sizeof(accept_mimes[0])-1;
414     hres = IInternetBindInfo_GetBindString(pOIBindInfo, BINDSTRING_ACCEPT_MIMES,
415                                            accept_mimes,
416                                            num, &num);
417     if (hres != S_OK)
418     {
419         WARN("GetBindString BINDSTRING_ACCEPT_MIMES failed: %08x\n", hres);
420         hres = INET_E_NO_VALID_MEDIA;
421         goto done;
422     }
423     accept_mimes[num] = 0;
424
425     if (This->grfBINDF & BINDF_NOWRITECACHE)
426         request_flags |= INTERNET_FLAG_NO_CACHE_WRITE;
427     This->request = HttpOpenRequestW(This->connect, This->bind_info.dwBindVerb < BINDVERB_CUSTOM ?
428                                      wszBindVerb[This->bind_info.dwBindVerb] :
429                                      This->bind_info.szCustomVerb,
430                                      path, NULL, NULL, (LPCWSTR *)accept_mimes,
431                                      request_flags, (DWORD)This);
432     if (!This->request)
433     {
434         WARN("HttpOpenRequest failed: %d\n", GetLastError());
435         hres = INET_E_RESOURCE_NOT_FOUND;
436         goto done;
437     }
438
439     hres = IInternetProtocolSink_QueryInterface(This->protocol_sink, &IID_IServiceProvider,
440                                                 (void **)&service_provider);
441     if (hres != S_OK)
442     {
443         WARN("IInternetProtocolSink_QueryInterface IID_IServiceProvider failed: %08x\n", hres);
444         goto done;
445     }
446
447     hres = IServiceProvider_QueryService(service_provider, &IID_IHttpNegotiate,
448                                          &IID_IHttpNegotiate, (void **)&This->http_negotiate);
449     if (hres != S_OK)
450     {
451         WARN("IServiceProvider_QueryService IID_IHttpNegotiate failed: %08x\n", hres);
452         goto done;
453     }
454
455     hres = IHttpNegotiate_BeginningTransaction(This->http_negotiate, szUrl, wszHeaders,
456                                                0, &addl_header);
457     if (hres != S_OK)
458     {
459         WARN("IHttpNegotiate_BeginningTransaction failed: %08x\n", hres);
460         goto done;
461     }
462     else if (addl_header == NULL)
463     {
464         This->full_header = (LPWSTR)wszHeaders;
465     }
466     else
467     {
468         int len_addl_header = lstrlenW(addl_header);
469         This->full_header = HeapAlloc(GetProcessHeap(), 0,
470                                       len_addl_header*sizeof(WCHAR)+sizeof(wszHeaders));
471         if (!This->full_header)
472         {
473             WARN("Out of memory\n");
474             hres = E_OUTOFMEMORY;
475             goto done;
476         }
477         lstrcpyW(This->full_header, addl_header);
478         lstrcpyW(&This->full_header[len_addl_header], wszHeaders);
479     }
480
481     hres = IServiceProvider_QueryService(service_provider, &IID_IHttpNegotiate2,
482                                          &IID_IHttpNegotiate2, (void **)&http_negotiate2);
483     if (hres != S_OK)
484     {
485         WARN("IServiceProvider_QueryService IID_IHttpNegotiate2 failed: %08x\n", hres);
486         /* No goto done as per native */
487     }
488     else
489     {
490         len = sizeof(security_id)/sizeof(security_id[0]);
491         hres = IHttpNegotiate2_GetRootSecurityId(http_negotiate2, security_id, &len, 0);
492         if (hres != S_OK)
493         {
494             WARN("IHttpNegotiate2_GetRootSecurityId failed: %08x\n", hres);
495             /* No goto done as per native */
496         }
497     }
498
499     /* FIXME: Handle security_id. Native calls undocumented function IsHostInProxyBypassList. */
500
501     if (This->bind_info.dwBindVerb == BINDVERB_POST)
502     {
503         num = 0;
504         hres = IInternetBindInfo_GetBindString(pOIBindInfo, BINDSTRING_POST_COOKIE, &post_cookie,
505                                                1, &num);
506         if (hres == S_OK && num &&
507             !InternetSetOptionW(This->request, INTERNET_OPTION_SECONDARY_CACHE_KEY,
508                                 post_cookie, lstrlenW(post_cookie)))
509         {
510             WARN("InternetSetOption INTERNET_OPTION_SECONDARY_CACHE_KEY failed: %d\n",
511                  GetLastError());
512         }
513     }
514
515     if (This->bind_info.dwBindVerb != BINDVERB_GET)
516     {
517         /* Native does not use GlobalLock/GlobalUnlock, so we won't either */
518         if (This->bind_info.stgmedData.tymed != TYMED_HGLOBAL)
519             WARN("Expected This->bind_info.stgmedData.tymed to be TYMED_HGLOBAL, not %d\n",
520                  This->bind_info.stgmedData.tymed);
521         else
522             optional = (LPWSTR)This->bind_info.stgmedData.u.hGlobal;
523     }
524     if (!HttpSendRequestW(This->request, This->full_header, lstrlenW(This->full_header),
525                           optional,
526                           optional ? This->bind_info.cbstgmedData : 0) &&
527         GetLastError() != ERROR_IO_PENDING)
528     {
529         WARN("HttpSendRequest failed: %d\n", GetLastError());
530         hres = INET_E_DOWNLOAD_FAILURE;
531         goto done;
532     }
533
534     hres = S_OK;
535 done:
536     if (hres != S_OK)
537     {
538         IInternetProtocolSink_ReportResult(This->protocol_sink, hres, 0, NULL);
539         HTTPPROTOCOL_Close(This);
540     }
541
542     CoTaskMemFree(post_cookie);
543     CoTaskMemFree(addl_header);
544     if (http_negotiate2)
545         IHttpNegotiate2_Release(http_negotiate2);
546     if (service_provider)
547         IServiceProvider_Release(service_provider);
548
549     while (num<sizeof(accept_mimes)/sizeof(accept_mimes[0]) &&
550            accept_mimes[num])
551         CoTaskMemFree(accept_mimes[num++]);
552     CoTaskMemFree(user_agent);
553
554     HeapFree(GetProcessHeap(), 0, pass);
555     HeapFree(GetProcessHeap(), 0, user);
556     HeapFree(GetProcessHeap(), 0, path);
557     HeapFree(GetProcessHeap(), 0, host);
558
559     return hres;
560 }
561
562 static HRESULT WINAPI HttpProtocol_Continue(IInternetProtocol *iface, PROTOCOLDATA *pProtocolData)
563 {
564     HttpProtocol *This = PROTOCOL_THIS(iface);
565     DWORD len = sizeof(DWORD), status_code;
566     LPWSTR response_headers = 0, content_type = 0, content_length = 0;
567
568     static const WCHAR wszDefaultContentType[] =
569         {'t','e','x','t','/','h','t','m','l',0};
570
571     TRACE("(%p)->(%p)\n", This, pProtocolData);
572
573     if (!pProtocolData)
574     {
575         WARN("Expected pProtocolData to be non-NULL\n");
576         return S_OK;
577     }
578     else if (!This->request)
579     {
580         WARN("Expected request to be non-NULL\n");
581         return S_OK;
582     }
583     else if (!This->http_negotiate)
584     {
585         WARN("Expected IHttpNegotiate pointer to be non-NULL\n");
586         return S_OK;
587     }
588     else if (!This->protocol_sink)
589     {
590         WARN("Expected IInternetProtocolSink pointer to be non-NULL\n");
591         return S_OK;
592     }
593
594     if (pProtocolData->pData == (LPVOID)BINDSTATUS_DOWNLOADINGDATA)
595     {
596         if (!HttpQueryInfoW(This->request, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
597                             &status_code, &len, NULL))
598         {
599             WARN("HttpQueryInfo failed: %d\n", GetLastError());
600         }
601         else
602         {
603             len = 0;
604             if ((!HttpQueryInfoW(This->request, HTTP_QUERY_RAW_HEADERS_CRLF, response_headers, &len,
605                                  NULL) &&
606                  GetLastError() != ERROR_INSUFFICIENT_BUFFER) ||
607                 !(response_headers = HeapAlloc(GetProcessHeap(), 0, len)) ||
608                 !HttpQueryInfoW(This->request, HTTP_QUERY_RAW_HEADERS_CRLF, response_headers, &len,
609                                 NULL))
610             {
611                 WARN("HttpQueryInfo failed: %d\n", GetLastError());
612             }
613             else
614             {
615                 HRESULT hres = IHttpNegotiate_OnResponse(This->http_negotiate, status_code,
616                                                          response_headers, NULL, NULL);
617                 if (hres != S_OK)
618                 {
619                     WARN("IHttpNegotiate_OnResponse failed: %08x\n", hres);
620                     goto done;
621                 }
622             }
623         }
624
625         len = 0;
626         if ((!HttpQueryInfoW(This->request, HTTP_QUERY_CONTENT_TYPE, content_type, &len, NULL) &&
627              GetLastError() != ERROR_INSUFFICIENT_BUFFER) ||
628             !(content_type = HeapAlloc(GetProcessHeap(), 0, len)) ||
629             !HttpQueryInfoW(This->request, HTTP_QUERY_CONTENT_TYPE, content_type, &len, NULL))
630         {
631             WARN("HttpQueryInfo failed: %d\n", GetLastError());
632             IInternetProtocolSink_ReportProgress(This->protocol_sink,
633                                                  (This->grfBINDF & BINDF_FROMURLMON) ?
634                                                  BINDSTATUS_MIMETYPEAVAILABLE :
635                                                  BINDSTATUS_RAWMIMETYPE,
636                                                  wszDefaultContentType);
637         }
638         else
639         {
640             IInternetProtocolSink_ReportProgress(This->protocol_sink,
641                                                  (This->grfBINDF & BINDF_FROMURLMON) ?
642                                                  BINDSTATUS_MIMETYPEAVAILABLE :
643                                                  BINDSTATUS_RAWMIMETYPE,
644                                                  content_type);
645         }
646
647         len = 0;
648         if ((!HttpQueryInfoW(This->request, HTTP_QUERY_CONTENT_LENGTH, content_length, &len, NULL) &&
649              GetLastError() != ERROR_INSUFFICIENT_BUFFER) ||
650             !(content_length = HeapAlloc(GetProcessHeap(), 0, len)) ||
651             !HttpQueryInfoW(This->request, HTTP_QUERY_CONTENT_LENGTH, content_length, &len, NULL))
652         {
653             WARN("HttpQueryInfo failed: %d\n", GetLastError());
654             This->content_length = 0;
655         }
656         else
657         {
658             This->content_length = atoiW(content_length);
659         }
660
661         This->flags |= FLAG_FIRST_CONTINUE_COMPLETE;
662     }
663
664     if (pProtocolData->pData >= (LPVOID)BINDSTATUS_DOWNLOADINGDATA)
665     {
666         /* InternetQueryDataAvailable may immediately fork and perform its asynchronous
667          * read, so clear the flag _before_ calling so it does not incorrectly get cleared
668          * after the status callback is called */
669         This->flags &= ~FLAG_REQUEST_COMPLETE;
670         if (!InternetQueryDataAvailable(This->request, &This->available_bytes, 0, 0))
671         {
672             if (GetLastError() != ERROR_IO_PENDING)
673             {
674                 This->flags |= FLAG_REQUEST_COMPLETE;
675                 WARN("InternetQueryDataAvailable failed: %d\n", GetLastError());
676                 HTTPPROTOCOL_ReportResult(This, INET_E_DATA_NOT_AVAILABLE);
677             }
678         }
679         else
680         {
681             This->flags |= FLAG_REQUEST_COMPLETE;
682             HTTPPROTOCOL_ReportData(This);
683         }
684     }
685
686 done:
687     HeapFree(GetProcessHeap(), 0, response_headers);
688     HeapFree(GetProcessHeap(), 0, content_type);
689     HeapFree(GetProcessHeap(), 0, content_length);
690
691     /* Returns S_OK on native */
692     return S_OK;
693 }
694
695 static HRESULT WINAPI HttpProtocol_Abort(IInternetProtocol *iface, HRESULT hrReason,
696         DWORD dwOptions)
697 {
698     HttpProtocol *This = PROTOCOL_THIS(iface);
699     FIXME("(%p)->(%08x %08x)\n", This, hrReason, dwOptions);
700     return E_NOTIMPL;
701 }
702
703 static HRESULT WINAPI HttpProtocol_Terminate(IInternetProtocol *iface, DWORD dwOptions)
704 {
705     HttpProtocol *This = PROTOCOL_THIS(iface);
706
707     TRACE("(%p)->(%08x)\n", This, dwOptions);
708     HTTPPROTOCOL_Close(This);
709
710     return S_OK;
711 }
712
713 static HRESULT WINAPI HttpProtocol_Suspend(IInternetProtocol *iface)
714 {
715     HttpProtocol *This = PROTOCOL_THIS(iface);
716     FIXME("(%p)\n", This);
717     return E_NOTIMPL;
718 }
719
720 static HRESULT WINAPI HttpProtocol_Resume(IInternetProtocol *iface)
721 {
722     HttpProtocol *This = PROTOCOL_THIS(iface);
723     FIXME("(%p)\n", This);
724     return E_NOTIMPL;
725 }
726
727 static HRESULT WINAPI HttpProtocol_Read(IInternetProtocol *iface, void *pv,
728         ULONG cb, ULONG *pcbRead)
729 {
730     HttpProtocol *This = PROTOCOL_THIS(iface);
731     ULONG read = 0, len = 0;
732     HRESULT hres = S_FALSE;
733
734     TRACE("(%p)->(%p %u %p)\n", This, pv, cb, pcbRead);
735
736     if (!(This->flags & FLAG_REQUEST_COMPLETE))
737     {
738         hres = E_PENDING;
739     }
740     else while (!(This->flags & FLAG_ALL_DATA_READ) &&
741                 read < cb)
742     {
743         if (This->available_bytes == 0)
744         {
745             /* InternetQueryDataAvailable may immediately fork and perform its asynchronous
746              * read, so clear the flag _before_ calling so it does not incorrectly get cleared
747              * after the status callback is called */
748             This->flags &= ~FLAG_REQUEST_COMPLETE;
749             if (!InternetQueryDataAvailable(This->request, &This->available_bytes, 0, 0))
750             {
751                 if (GetLastError() == ERROR_IO_PENDING)
752                 {
753                     hres = E_PENDING;
754                 }
755                 else
756                 {
757                     WARN("InternetQueryDataAvailable failed: %d\n", GetLastError());
758                     hres = INET_E_DATA_NOT_AVAILABLE;
759                     HTTPPROTOCOL_ReportResult(This, hres);
760                 }
761                 goto done;
762             }
763             else if (This->available_bytes == 0)
764             {
765                 HTTPPROTOCOL_AllDataRead(This);
766             }
767         }
768         else
769         {
770             if (!InternetReadFile(This->request, ((BYTE *)pv)+read,
771                                   This->available_bytes > cb-read ?
772                                   cb-read : This->available_bytes, &len))
773             {
774                 WARN("InternetReadFile failed: %d\n", GetLastError());
775                 hres = INET_E_DOWNLOAD_FAILURE;
776                 HTTPPROTOCOL_ReportResult(This, hres);
777                 goto done;
778             }
779             else if (len == 0)
780             {
781                 HTTPPROTOCOL_AllDataRead(This);
782             }
783             else
784             {
785                 read += len;
786                 This->current_position += len;
787                 This->available_bytes -= len;
788             }
789         }
790     }
791
792     /* Per MSDN this should be if (read == cb), but native returns S_OK
793      * if any bytes were read, so we will too */
794     if (read)
795         hres = S_OK;
796
797 done:
798     if (pcbRead)
799         *pcbRead = read;
800
801     if (hres != E_PENDING)
802         This->flags |= FLAG_REQUEST_COMPLETE;
803
804     return hres;
805 }
806
807 static HRESULT WINAPI HttpProtocol_Seek(IInternetProtocol *iface, LARGE_INTEGER dlibMove,
808         DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition)
809 {
810     HttpProtocol *This = PROTOCOL_THIS(iface);
811     FIXME("(%p)->(%d %d %p)\n", This, dlibMove.u.LowPart, dwOrigin, plibNewPosition);
812     return E_NOTIMPL;
813 }
814
815 static HRESULT WINAPI HttpProtocol_LockRequest(IInternetProtocol *iface, DWORD dwOptions)
816 {
817     HttpProtocol *This = PROTOCOL_THIS(iface);
818
819     TRACE("(%p)->(%08x)\n", This, dwOptions);
820
821     if (!InternetLockRequestFile(This->request, &This->lock))
822         WARN("InternetLockRequest failed: %d\n", GetLastError());
823
824     return S_OK;
825 }
826
827 static HRESULT WINAPI HttpProtocol_UnlockRequest(IInternetProtocol *iface)
828 {
829     HttpProtocol *This = PROTOCOL_THIS(iface);
830
831     TRACE("(%p)\n", This);
832
833     if (This->lock)
834     {
835         if (!InternetUnlockRequestFile(This->lock))
836             WARN("InternetUnlockRequest failed: %d\n", GetLastError());
837         This->lock = 0;
838     }
839
840     return S_OK;
841 }
842
843 #undef PROTOCOL_THIS
844
845 #define PRIORITY_THIS(iface) DEFINE_THIS(HttpProtocol, InternetPriority, iface)
846
847 static HRESULT WINAPI HttpPriority_QueryInterface(IInternetPriority *iface, REFIID riid, void **ppv)
848 {
849     HttpProtocol *This = PRIORITY_THIS(iface);
850     return IInternetProtocol_QueryInterface(PROTOCOL(This), riid, ppv);
851 }
852
853 static ULONG WINAPI HttpPriority_AddRef(IInternetPriority *iface)
854 {
855     HttpProtocol *This = PRIORITY_THIS(iface);
856     return IInternetProtocol_AddRef(PROTOCOL(This));
857 }
858
859 static ULONG WINAPI HttpPriority_Release(IInternetPriority *iface)
860 {
861     HttpProtocol *This = PRIORITY_THIS(iface);
862     return IInternetProtocol_Release(PROTOCOL(This));
863 }
864
865 static HRESULT WINAPI HttpPriority_SetPriority(IInternetPriority *iface, LONG nPriority)
866 {
867     HttpProtocol *This = PRIORITY_THIS(iface);
868
869     TRACE("(%p)->(%d)\n", This, nPriority);
870
871     This->priority = nPriority;
872     return S_OK;
873 }
874
875 static HRESULT WINAPI HttpPriority_GetPriority(IInternetPriority *iface, LONG *pnPriority)
876 {
877     HttpProtocol *This = PRIORITY_THIS(iface);
878
879     TRACE("(%p)->(%p)\n", This, pnPriority);
880
881     *pnPriority = This->priority;
882     return S_OK;
883 }
884
885 #undef PRIORITY_THIS
886
887 static const IInternetPriorityVtbl HttpPriorityVtbl = {
888     HttpPriority_QueryInterface,
889     HttpPriority_AddRef,
890     HttpPriority_Release,
891     HttpPriority_SetPriority,
892     HttpPriority_GetPriority
893 };
894
895 static const IInternetProtocolVtbl HttpProtocolVtbl = {
896     HttpProtocol_QueryInterface,
897     HttpProtocol_AddRef,
898     HttpProtocol_Release,
899     HttpProtocol_Start,
900     HttpProtocol_Continue,
901     HttpProtocol_Abort,
902     HttpProtocol_Terminate,
903     HttpProtocol_Suspend,
904     HttpProtocol_Resume,
905     HttpProtocol_Read,
906     HttpProtocol_Seek,
907     HttpProtocol_LockRequest,
908     HttpProtocol_UnlockRequest
909 };
910
911 HRESULT HttpProtocol_Construct(IUnknown *pUnkOuter, LPVOID *ppobj)
912 {
913     HttpProtocol *ret;
914
915     TRACE("(%p %p)\n", pUnkOuter, ppobj);
916
917     URLMON_LockModule();
918
919     ret = HeapAlloc(GetProcessHeap(), 0, sizeof(HttpProtocol));
920
921     ret->lpInternetProtocolVtbl = &HttpProtocolVtbl;
922     ret->lpInternetPriorityVtbl = &HttpPriorityVtbl;
923     ret->flags = ret->grfBINDF = 0;
924     memset(&ret->bind_info, 0, sizeof(ret->bind_info));
925     ret->protocol_sink = 0;
926     ret->http_negotiate = 0;
927     ret->internet = ret->connect = ret->request = 0;
928     ret->full_header = 0;
929     ret->lock = 0;
930     ret->current_position = ret->content_length = ret->available_bytes = 0;
931     ret->priority = 0;
932     ret->ref = 1;
933
934     *ppobj = PROTOCOL(ret);
935     
936     return S_OK;
937 }