internet.c 113 KB
Newer Older
1 2 3 4
/*
 * Wininet
 *
 * Copyright 1999 Corel Corporation
5
 * Copyright 2002 CodeWeavers Inc.
6 7
 * Copyright 2002 Jaco Greeff
 * Copyright 2002 TransGaming Technologies Inc.
8
 * Copyright 2004 Mike McCormack for CodeWeavers
9 10
 *
 * Ulrich Czekalla
11
 * Aric Stewart
12
 * David Hammerton
13
 *
14 15 16 17 18 19 20 21 22 23 24 25
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
27 28
 */

29
#include "config.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
30
#include "wine/port.h"
31

32 33
#define MAXHOSTNAME 100 /* from http.c */

34
#include <string.h>
35
#include <stdarg.h>
36
#include <stdio.h>
37
#include <sys/types.h>
38 39 40
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
41 42 43 44 45 46
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
#ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
#endif
47 48 49
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
50
#include <stdlib.h>
51
#include <ctype.h>
52 53 54
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
55
#include <assert.h>
56

57 58
#include "windef.h"
#include "winbase.h"
59
#include "winreg.h"
60
#include "winuser.h"
61
#include "wininet.h"
62
#include "winineti.h"
63
#include "winnls.h"
64
#include "wine/debug.h"
65
#include "winerror.h"
66
#define NO_SHLWAPI_STREAM
67
#include "shlwapi.h"
68

69 70
#include "wine/exception.h"

71
#include "internet.h"
72
#include "resource.h"
73

74 75
#include "wine/unicode.h"

76
WINE_DEFAULT_DEBUG_CHANNEL(wininet);
77

78
#define RESPONSE_TIMEOUT        30
79 80 81 82 83 84 85

typedef struct
{
    DWORD  dwError;
    CHAR   response[MAX_REPLY_LEN];
} WITHREADERROR, *LPWITHREADERROR;

86 87
static DWORD g_dwTlsErrIndex = TLS_OUT_OF_INDEXES;
static HMODULE WININET_hModule;
88

89 90 91 92 93 94 95
#define HANDLE_CHUNK_SIZE 0x10

static CRITICAL_SECTION WININET_cs;
static CRITICAL_SECTION_DEBUG WININET_cs_debug = 
{
    0, 0, &WININET_cs,
    { &WININET_cs_debug.ProcessLocksList, &WININET_cs_debug.ProcessLocksList },
96
      0, 0, { (DWORD_PTR)(__FILE__ ": WININET_cs") }
97 98 99 100 101 102 103 104 105 106 107 108
};
static CRITICAL_SECTION WININET_cs = { &WININET_cs_debug, -1, 0, 0, 0, 0 };

static LPWININETHANDLEHEADER *WININET_Handles;
static UINT WININET_dwNextHandle;
static UINT WININET_dwMaxHandles;

HINTERNET WININET_AllocHandle( LPWININETHANDLEHEADER info )
{
    LPWININETHANDLEHEADER *p;
    UINT handle = 0, num;

109 110
    list_init( &info->children );

111 112 113 114 115
    EnterCriticalSection( &WININET_cs );
    if( !WININET_dwMaxHandles )
    {
        num = HANDLE_CHUNK_SIZE;
        p = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
116
                   sizeof (*WININET_Handles)* num);
117 118 119 120 121 122 123 124 125
        if( !p )
            goto end;
        WININET_Handles = p;
        WININET_dwMaxHandles = num;
    }
    if( WININET_dwMaxHandles == WININET_dwNextHandle )
    {
        num = WININET_dwMaxHandles + HANDLE_CHUNK_SIZE;
        p = HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
126
                   WININET_Handles, sizeof (*WININET_Handles)* num);
127 128 129 130 131 132 133 134 135
        if( !p )
            goto end;
        WININET_Handles = p;
        WININET_dwMaxHandles = num;
    }

    handle = WININET_dwNextHandle;
    if( WININET_Handles[handle] )
        ERR("handle isn't free but should be\n");
136
    WININET_Handles[handle] = WININET_AddRef( info );
137 138 139 140 141 142 143 144

    while( WININET_Handles[WININET_dwNextHandle] && 
           (WININET_dwNextHandle < WININET_dwMaxHandles ) )
        WININET_dwNextHandle++;
    
end:
    LeaveCriticalSection( &WININET_cs );

145
    return info->hInternet = (HINTERNET) (handle+1);
146 147
}

148 149
LPWININETHANDLEHEADER WININET_AddRef( LPWININETHANDLEHEADER info )
{
150 151
    ULONG refs = InterlockedIncrement(&info->refs);
    TRACE("%p -> refcount = %d\n", info, refs );
152 153 154
    return info;
}

155 156 157 158 159 160 161
LPWININETHANDLEHEADER WININET_GetObject( HINTERNET hinternet )
{
    LPWININETHANDLEHEADER info = NULL;
    UINT handle = (UINT) hinternet;

    EnterCriticalSection( &WININET_cs );

162 163
    if( (handle > 0) && ( handle <= WININET_dwMaxHandles ) && 
        WININET_Handles[handle-1] )
164
        info = WININET_AddRef( WININET_Handles[handle-1] );
165 166 167 168 169 170 171 172

    LeaveCriticalSection( &WININET_cs );

    TRACE("handle %d -> %p\n", handle, info);

    return info;
}

173 174
BOOL WININET_Release( LPWININETHANDLEHEADER info )
{
175 176 177
    ULONG refs = InterlockedDecrement(&info->refs);
    TRACE( "object %p refcount = %d\n", info, refs );
    if( !refs )
178
    {
179
        if ( info->vtbl->CloseConnection )
180 181
        {
            TRACE( "closing connection %p\n", info);
182
            info->vtbl->CloseConnection( info );
183
        }
184 185 186 187 188 189 190
        /* Don't send a callback if this is a session handle created with InternetOpenUrl */
        if (info->htype != WH_HHTTPSESSION || !(info->dwInternalFlags & INET_OPENURL))
        {
            INTERNET_SendCallback(info, info->dwContext,
                                  INTERNET_STATUS_HANDLE_CLOSING, &info->hInternet,
                                  sizeof(HINTERNET));
        }
191
        TRACE( "destroying object %p\n", info);
192 193
        if ( info->htype != WH_HINIT )
            list_remove( &info->entry );
194
        info->vtbl->Destroy( info );
195 196 197 198
    }
    return TRUE;
}

199 200 201 202
BOOL WININET_FreeHandle( HINTERNET hinternet )
{
    BOOL ret = FALSE;
    UINT handle = (UINT) hinternet;
203
    LPWININETHANDLEHEADER info = NULL, child, next;
204 205 206

    EnterCriticalSection( &WININET_cs );

207
    if( (handle > 0) && ( handle <= WININET_dwMaxHandles ) )
208 209 210 211
    {
        handle--;
        if( WININET_Handles[handle] )
        {
212 213
            info = WININET_Handles[handle];
            TRACE( "destroying handle %d for object %p\n", handle+1, info);
214 215 216 217 218 219 220
            WININET_Handles[handle] = NULL;
            ret = TRUE;
        }
    }

    LeaveCriticalSection( &WININET_cs );

221 222 223
    /* As on native when the equivalent of WININET_Release is called, the handle
     * is already invalid, but if a new handle is created at this time it does
     * not yet get assigned the freed handle number */
224
    if( info )
225 226 227 228 229 230 231 232
    {
        /* Free all children as native does */
        LIST_FOR_EACH_ENTRY_SAFE( child, next, &info->children, WININETHANDLEHEADER, entry )
        {
            TRACE( "freeing child handle %d for parent handle %d\n",
                   (UINT)child->hInternet, handle+1);
            WININET_FreeHandle( child->hInternet );
        }
233
        WININET_Release( info );
234
    }
235

236 237 238 239 240 241 242
    EnterCriticalSection( &WININET_cs );

    if( WININET_dwNextHandle > handle && !WININET_Handles[handle] )
        WININET_dwNextHandle = handle;

    LeaveCriticalSection( &WININET_cs );

243 244 245
    return ret;
}

246
/***********************************************************************
247
 * DllMain [Internal] Initializes the internal 'WININET.DLL'.
248 249
 *
 * PARAMS
Andreas Mohr's avatar
Andreas Mohr committed
250
 *     hinstDLL    [I] handle to the DLL's instance
251
 *     fdwReason   [I]
Andreas Mohr's avatar
Andreas Mohr committed
252
 *     lpvReserved [I] reserved, must be NULL
253 254 255 256 257 258
 *
 * RETURNS
 *     Success: TRUE
 *     Failure: FALSE
 */

259
BOOL WINAPI DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
260
{
261
    TRACE("%p,%x,%p\n", hinstDLL, fdwReason, lpvReserved);
262 263 264 265 266 267 268 269 270

    switch (fdwReason) {
        case DLL_PROCESS_ATTACH:

            g_dwTlsErrIndex = TlsAlloc();

	    if (g_dwTlsErrIndex == TLS_OUT_OF_INDEXES)
		return FALSE;

271 272
            URLCacheContainers_CreateDefaults();

273
            WININET_hModule = hinstDLL;
274

275 276 277 278 279
        case DLL_THREAD_ATTACH:
	    break;

        case DLL_THREAD_DETACH:
	    if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
280 281
			{
				LPVOID lpwite = TlsGetValue(g_dwTlsErrIndex);
282
                                HeapFree(GetProcessHeap(), 0, lpwite);
283
			}
284 285 286 287
	    break;

        case DLL_PROCESS_DETACH:

288 289
	    URLCacheContainers_DeleteAll();

290 291 292 293 294 295 296 297 298 299 300 301
	    if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
	    {
	        HeapFree(GetProcessHeap(), 0, TlsGetValue(g_dwTlsErrIndex));
	        TlsFree(g_dwTlsErrIndex);
	    }
            break;
    }

    return TRUE;
}


302 303 304 305 306 307 308 309 310 311 312 313
/***********************************************************************
 *           InternetInitializeAutoProxyDll   (WININET.@)
 *
 * Setup the internal proxy
 *
 * PARAMETERS
 *     dwReserved
 *
 * RETURNS
 *     FALSE on failure
 *
 */
314
BOOL WINAPI InternetInitializeAutoProxyDll(DWORD dwReserved)
315 316 317 318 319 320
{
    FIXME("STUB\n");
    INTERNET_SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
/***********************************************************************
 *           DetectAutoProxyUrl   (WININET.@)
 *
 * Auto detect the proxy url
 *
 * RETURNS
 *     FALSE on failure
 *
 */
BOOL WINAPI DetectAutoProxyUrl(LPSTR lpszAutoProxyUrl,
	DWORD dwAutoProxyUrlLength, DWORD dwDetectFlags)
{
    FIXME("STUB\n");
    INTERNET_SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

338

339
/***********************************************************************
340
 *           INTERNET_ConfigureProxy
341 342 343 344 345
 *
 * FIXME:
 * The proxy may be specified in the form 'http=proxy.my.org'
 * Presumably that means there can be ftp=ftpproxy.my.org too.
 */
346
static BOOL INTERNET_ConfigureProxy( LPWININETAPPINFOW lpwai )
347 348
{
    HKEY key;
349 350 351 352 353 354
    DWORD type, len, enabled = 0;
    LPCSTR envproxy;
    static const WCHAR szInternetSettings[] =
        { 'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
          'W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
          'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',0 };
355
    static const WCHAR szProxyServer[] = { 'P','r','o','x','y','S','e','r','v','e','r', 0 };
356
    static const WCHAR szProxyEnable[] = { 'P','r','o','x','y','E','n','a','b','l','e', 0 };
357

358
    if (RegOpenKeyW( HKEY_CURRENT_USER, szInternetSettings, &key )) return FALSE;
359 360

    len = sizeof enabled;
361 362 363 364
    if (RegQueryValueExW( key, szProxyEnable, NULL, &type, (BYTE *)&enabled, &len ) || type != REG_DWORD)
        RegSetValueExW( key, szProxyEnable, 0, REG_DWORD, (BYTE *)&enabled, sizeof(REG_DWORD) );

    if (enabled)
365
    {
366 367 368 369
        TRACE("Proxy is enabled.\n");

        /* figure out how much memory the proxy setting takes */
        if (!RegQueryValueExW( key, szProxyServer, NULL, &type, NULL, &len ) && len && (type == REG_SZ))
370
        {
371 372
            LPWSTR szProxy, p;
            static const WCHAR szHttp[] = {'h','t','t','p','=',0};
373

374
            if (!(szProxy = HeapAlloc( GetProcessHeap(), 0, len )))
375
            {
376 377
                RegCloseKey( key );
                return FALSE;
378
            }
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
            RegQueryValueExW( key, szProxyServer, NULL, &type, (BYTE*)szProxy, &len );

            /* find the http proxy, and strip away everything else */
            p = strstrW( szProxy, szHttp );
            if (p)
            {
                p += lstrlenW( szHttp );
                lstrcpyW( szProxy, p );
            }
            p = strchrW( szProxy, ' ' );
            if (p) *p = 0;

            lpwai->dwAccessType = INTERNET_OPEN_TYPE_PROXY;
            lpwai->lpszProxy = szProxy;

            TRACE("http proxy = %s\n", debugstr_w(lpwai->lpszProxy));
395
        }
396 397
        else
            ERR("Couldn't read proxy server settings from registry.\n");
398
    }
399 400 401 402 403 404 405 406 407 408 409 410 411 412
    else if ((envproxy = getenv( "http_proxy" )))
    {
        WCHAR *envproxyW;

        len = MultiByteToWideChar( CP_UNIXCP, 0, envproxy, -1, NULL, 0 );
        if (!(envproxyW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
        MultiByteToWideChar( CP_UNIXCP, 0, envproxy, -1, envproxyW, len );

        lpwai->dwAccessType = INTERNET_OPEN_TYPE_PROXY;
        lpwai->lpszProxy = envproxyW;

        TRACE("http proxy (from environment) = %s\n", debugstr_w(lpwai->lpszProxy));
        enabled = 1;
    }
413 414 415 416 417
    if (!enabled)
    {
        TRACE("Proxy is not enabled.\n");
        lpwai->dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
    }
418 419
    RegCloseKey( key );
    return (enabled > 0);
420 421
}

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
/***********************************************************************
 *           dump_INTERNET_FLAGS
 *
 * Helper function to TRACE the internet flags.
 *
 * RETURNS
 *    None
 *
 */
static void dump_INTERNET_FLAGS(DWORD dwFlags) 
{
#define FE(x) { x, #x }
    static const wininet_flag_info flag[] = {
        FE(INTERNET_FLAG_RELOAD),
        FE(INTERNET_FLAG_RAW_DATA),
        FE(INTERNET_FLAG_EXISTING_CONNECT),
        FE(INTERNET_FLAG_ASYNC),
        FE(INTERNET_FLAG_PASSIVE),
        FE(INTERNET_FLAG_NO_CACHE_WRITE),
        FE(INTERNET_FLAG_MAKE_PERSISTENT),
        FE(INTERNET_FLAG_FROM_CACHE),
        FE(INTERNET_FLAG_SECURE),
        FE(INTERNET_FLAG_KEEP_CONNECTION),
        FE(INTERNET_FLAG_NO_AUTO_REDIRECT),
        FE(INTERNET_FLAG_READ_PREFETCH),
        FE(INTERNET_FLAG_NO_COOKIES),
        FE(INTERNET_FLAG_NO_AUTH),
        FE(INTERNET_FLAG_CACHE_IF_NET_FAIL),
        FE(INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP),
        FE(INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS),
        FE(INTERNET_FLAG_IGNORE_CERT_DATE_INVALID),
        FE(INTERNET_FLAG_IGNORE_CERT_CN_INVALID),
        FE(INTERNET_FLAG_RESYNCHRONIZE),
        FE(INTERNET_FLAG_HYPERLINK),
        FE(INTERNET_FLAG_NO_UI),
        FE(INTERNET_FLAG_PRAGMA_NOCACHE),
        FE(INTERNET_FLAG_CACHE_ASYNC),
        FE(INTERNET_FLAG_FORMS_SUBMIT),
        FE(INTERNET_FLAG_NEED_FILE),
        FE(INTERNET_FLAG_TRANSFER_ASCII),
        FE(INTERNET_FLAG_TRANSFER_BINARY)
    };
#undef FE
    int i;
    
    for (i = 0; i < (sizeof(flag) / sizeof(flag[0])); i++) {
	if (flag[i].val & dwFlags) {
	    TRACE(" %s", flag[i].name);
	    dwFlags &= ~flag[i].val;
	}
    }	
    if (dwFlags)
474
        TRACE(" Unknown flags (%08x)\n", dwFlags);
475 476 477 478
    else
        TRACE("\n");
}

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
/***********************************************************************
 *           INTERNET_CloseHandle (internal)
 *
 * Close internet handle
 *
 */
static VOID APPINFO_Destroy(WININETHANDLEHEADER *hdr)
{
    LPWININETAPPINFOW lpwai = (LPWININETAPPINFOW) hdr;

    TRACE("%p\n",lpwai);

    HeapFree(GetProcessHeap(), 0, lpwai->lpszAgent);
    HeapFree(GetProcessHeap(), 0, lpwai->lpszProxy);
    HeapFree(GetProcessHeap(), 0, lpwai->lpszProxyBypass);
    HeapFree(GetProcessHeap(), 0, lpwai->lpszProxyUsername);
    HeapFree(GetProcessHeap(), 0, lpwai->lpszProxyPassword);
    HeapFree(GetProcessHeap(), 0, lpwai);
}

499 500
static DWORD APPINFO_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
{
501 502
    LPWININETAPPINFOW ai = (LPWININETAPPINFOW)hdr;

503 504 505 506 507 508 509 510 511 512
    switch(option) {
    case INTERNET_OPTION_HANDLE_TYPE:
        TRACE("INTERNET_OPTION_HANDLE_TYPE\n");

        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD*)buffer = INTERNET_HANDLE_TYPE_INTERNET;
        return ERROR_SUCCESS;
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

    case INTERNET_OPTION_USER_AGENT: {
        DWORD bufsize;

        TRACE("INTERNET_OPTION_USER_AGENT\n");

        bufsize = *size;

        if (unicode) {
            *size = (strlenW(ai->lpszAgent) + 1) * sizeof(WCHAR);
            if(!buffer || bufsize < *size)
                return ERROR_INSUFFICIENT_BUFFER;

            strcpyW(buffer, ai->lpszAgent);
        }else {
            *size = WideCharToMultiByte(CP_ACP, 0, ai->lpszAgent, -1, NULL, 0, NULL, NULL);
            if(!buffer || bufsize < *size)
                return ERROR_INSUFFICIENT_BUFFER;

            WideCharToMultiByte(CP_ACP, 0, ai->lpszAgent, -1, buffer, *size, NULL, NULL);
        }

        return ERROR_SUCCESS;
    }
537 538 539 540 541 542 543 544 545 546 547 548

    case INTERNET_OPTION_PROXY:
        if (unicode) {
            INTERNET_PROXY_INFOW *pi = (INTERNET_PROXY_INFOW *)buffer;
            DWORD proxyBytesRequired = 0, proxyBypassBytesRequired = 0;
            LPWSTR proxy, proxy_bypass;

            if (ai->lpszProxy)
                proxyBytesRequired = (lstrlenW(ai->lpszProxy) + 1) * sizeof(WCHAR);
            if (ai->lpszProxyBypass)
                proxyBypassBytesRequired = (lstrlenW(ai->lpszProxyBypass) + 1) * sizeof(WCHAR);
            if (*size < sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired + proxyBypassBytesRequired)
549 550 551 552
            {
                *size = sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired + proxyBypassBytesRequired;
                return ERROR_INSUFFICIENT_BUFFER;
            }
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
            proxy = (LPWSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOW));
            proxy_bypass = (LPWSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired);

            pi->dwAccessType = ai->dwAccessType;
            pi->lpszProxy = NULL;
            pi->lpszProxyBypass = NULL;
            if (ai->lpszProxy) {
                lstrcpyW(proxy, ai->lpszProxy);
                pi->lpszProxy = proxy;
            }

            if (ai->lpszProxyBypass) {
                lstrcpyW(proxy_bypass, ai->lpszProxyBypass);
                pi->lpszProxyBypass = proxy_bypass;
            }

            *size = sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired + proxyBypassBytesRequired;
            return ERROR_SUCCESS;
        }else {
            INTERNET_PROXY_INFOA *pi = (INTERNET_PROXY_INFOA *)buffer;
            DWORD proxyBytesRequired = 0, proxyBypassBytesRequired = 0;
            LPSTR proxy, proxy_bypass;

            if (ai->lpszProxy)
                proxyBytesRequired = WideCharToMultiByte(CP_ACP, 0, ai->lpszProxy, -1, NULL, 0, NULL, NULL);
            if (ai->lpszProxyBypass)
                proxyBypassBytesRequired = WideCharToMultiByte(CP_ACP, 0, ai->lpszProxyBypass, -1,
                        NULL, 0, NULL, NULL);
            if (*size < sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired + proxyBypassBytesRequired)
582 583
            {
                *size = sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired + proxyBypassBytesRequired;
584
                return ERROR_INSUFFICIENT_BUFFER;
585
            }
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
            proxy = (LPSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOA));
            proxy_bypass = (LPSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired);

            pi->dwAccessType = ai->dwAccessType;
            pi->lpszProxy = NULL;
            pi->lpszProxyBypass = NULL;
            if (ai->lpszProxy) {
                WideCharToMultiByte(CP_ACP, 0, ai->lpszProxy, -1, proxy, proxyBytesRequired, NULL, NULL);
                pi->lpszProxy = proxy;
            }

            if (ai->lpszProxyBypass) {
                WideCharToMultiByte(CP_ACP, 0, ai->lpszProxyBypass, -1, proxy_bypass,
                        proxyBypassBytesRequired, NULL, NULL);
                pi->lpszProxyBypass = proxy_bypass;
            }

            *size = sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired + proxyBypassBytesRequired;
            return ERROR_SUCCESS;
        }
606 607
    }

608
    return INET_QueryOption(option, buffer, size, unicode);
609 610
}

611
static const HANDLEHEADERVtbl APPINFOVtbl = {
612
    APPINFO_Destroy,
613
    NULL,
614
    APPINFO_QueryOption,
615
    NULL,
616
    NULL,
617
    NULL,
618
    NULL,
619
    NULL,
620
    NULL
621 622 623
};


624
/***********************************************************************
625
 *           InternetOpenW   (WININET.@)
626 627 628 629 630 631 632 633
 *
 * Per-application initialization of wininet
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
634 635
HINTERNET WINAPI InternetOpenW(LPCWSTR lpszAgent, DWORD dwAccessType,
    LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags)
636
{
637
    LPWININETAPPINFOW lpwai = NULL;
638 639 640 641 642 643 644 645 646 647 648
    HINTERNET handle = NULL;

    if (TRACE_ON(wininet)) {
#define FE(x) { x, #x }
	static const wininet_flag_info access_type[] = {
	    FE(INTERNET_OPEN_TYPE_PRECONFIG),
	    FE(INTERNET_OPEN_TYPE_DIRECT),
	    FE(INTERNET_OPEN_TYPE_PROXY),
	    FE(INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY)
	};
#undef FE
649
	DWORD i;
650 651
	const char *access_type_str = "Unknown";
	
652
	TRACE("(%s, %i, %s, %s, %i)\n", debugstr_w(lpszAgent), dwAccessType,
653
	      debugstr_w(lpszProxy), debugstr_w(lpszProxyBypass), dwFlags);
654 655 656 657 658 659 660 661
	for (i = 0; i < (sizeof(access_type) / sizeof(access_type[0])); i++) {
	    if (access_type[i].val == dwAccessType) {
		access_type_str = access_type[i].name;
		break;
	    }
	}
	TRACE("  access type : %s\n", access_type_str);
	TRACE("  flags       :");
Lionel Ulmer's avatar
Lionel Ulmer committed
662
	dump_INTERNET_FLAGS(dwFlags);
663
    }
664 665 666 667

    /* Clear any error information */
    INTERNET_SetLastError(0);

668
    lpwai = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETAPPINFOW));
669
    if (NULL == lpwai)
670
    {
671
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
672
	goto lend;
673
    }
674

675
    lpwai->hdr.htype = WH_HINIT;
676
    lpwai->hdr.vtbl = &APPINFOVtbl;
677
    lpwai->hdr.dwFlags = dwFlags;
678
    lpwai->hdr.refs = 1;
679 680 681 682
    lpwai->dwAccessType = dwAccessType;
    lpwai->lpszProxyUsername = NULL;
    lpwai->lpszProxyPassword = NULL;

683 684 685 686 687
    handle = WININET_AllocHandle( &lpwai->hdr );
    if( !handle )
    {
        HeapFree( GetProcessHeap(), 0, lpwai );
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
688
	goto lend;
689 690
    }

691
    if (NULL != lpszAgent)
692
    {
693
        lpwai->lpszAgent = HeapAlloc( GetProcessHeap(),0,
694
                                      (strlenW(lpszAgent)+1)*sizeof(WCHAR));
695
        if (lpwai->lpszAgent)
696
            lstrcpyW( lpwai->lpszAgent, lpszAgent );
697 698
    }
    if(dwAccessType == INTERNET_OPEN_TYPE_PRECONFIG)
699
        INTERNET_ConfigureProxy( lpwai );
700 701 702
    else if (NULL != lpszProxy)
    {
        lpwai->lpszProxy = HeapAlloc( GetProcessHeap(), 0,
703
                                      (strlenW(lpszProxy)+1)*sizeof(WCHAR));
704
        if (lpwai->lpszProxy)
705
            lstrcpyW( lpwai->lpszProxy, lpszProxy );
706 707 708 709 710
    }

    if (NULL != lpszProxyBypass)
    {
        lpwai->lpszProxyBypass = HeapAlloc( GetProcessHeap(), 0,
711
                                     (strlenW(lpszProxyBypass)+1)*sizeof(WCHAR));
712
        if (lpwai->lpszProxyBypass)
713
            lstrcpyW( lpwai->lpszProxyBypass, lpszProxyBypass );
714 715
    }

716 717 718 719 720
lend:
    if( lpwai )
        WININET_Release( &lpwai->hdr );

    TRACE("returning %p\n", lpwai);
721 722

    return handle;
723 724 725
}


726
/***********************************************************************
727
 *           InternetOpenA   (WININET.@)
728 729 730 731 732 733 734 735
 *
 * Per-application initialization of wininet
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
736 737
HINTERNET WINAPI InternetOpenA(LPCSTR lpszAgent, DWORD dwAccessType,
    LPCSTR lpszProxy, LPCSTR lpszProxyBypass, DWORD dwFlags)
738
{
739
    HINTERNET rc = NULL;
740 741
    INT len;
    WCHAR *szAgent = NULL, *szProxy = NULL, *szBypass = NULL;
742

743
    TRACE("(%s, 0x%08x, %s, %s, 0x%08x)\n", debugstr_a(lpszAgent),
744
       dwAccessType, debugstr_a(lpszProxy), debugstr_a(lpszProxyBypass), dwFlags);
745

746
    if( lpszAgent )
747
    {
748 749 750
        len = MultiByteToWideChar(CP_ACP, 0, lpszAgent, -1, NULL, 0);
        szAgent = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszAgent, -1, szAgent, len);
751 752
    }

753 754 755 756 757 758 759 760 761 762 763 764 765
    if( lpszProxy )
    {
        len = MultiByteToWideChar(CP_ACP, 0, lpszProxy, -1, NULL, 0);
        szProxy = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszProxy, -1, szProxy, len);
    }

    if( lpszProxyBypass )
    {
        len = MultiByteToWideChar(CP_ACP, 0, lpszProxyBypass, -1, NULL, 0);
        szBypass = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszProxyBypass, -1, szBypass, len);
    }
766

767
    rc = InternetOpenW(szAgent, dwAccessType, szProxy, szBypass, dwFlags);
768

769 770 771
    HeapFree(GetProcessHeap(), 0, szAgent);
    HeapFree(GetProcessHeap(), 0, szProxy);
    HeapFree(GetProcessHeap(), 0, szBypass);
772 773 774 775

    return rc;
}

776
/***********************************************************************
777
 *           InternetGetLastResponseInfoA (WININET.@)
778 779 780 781
 *
 * Return last wininet error description on the calling thread
 *
 * RETURNS
782
 *    TRUE on success of writing to buffer
783 784 785
 *    FALSE on failure
 *
 */
786
BOOL WINAPI InternetGetLastResponseInfoA(LPDWORD lpdwError,
787 788 789 790 791 792
    LPSTR lpszBuffer, LPDWORD lpdwBufferLength)
{
    LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);

    TRACE("\n");

793
    if (lpwite)
794
    {
795 796 797 798 799 800 801 802
        *lpdwError = lpwite->dwError;
        if (lpwite->dwError)
        {
            memcpy(lpszBuffer, lpwite->response, *lpdwBufferLength);
            *lpdwBufferLength = strlen(lpszBuffer);
        }
        else
            *lpdwBufferLength = 0;
803 804
    }
    else
805 806
    {
        *lpdwError = 0;
807
        *lpdwBufferLength = 0;
808
    }
809 810 811 812

    return TRUE;
}

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
/***********************************************************************
 *           InternetGetLastResponseInfoW (WININET.@)
 *
 * Return last wininet error description on the calling thread
 *
 * RETURNS
 *    TRUE on success of writing to buffer
 *    FALSE on failure
 *
 */
BOOL WINAPI InternetGetLastResponseInfoW(LPDWORD lpdwError,
    LPWSTR lpszBuffer, LPDWORD lpdwBufferLength)
{
    LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);

    TRACE("\n");

830
    if (lpwite)
831
    {
832 833 834 835 836 837 838 839
        *lpdwError = lpwite->dwError;
        if (lpwite->dwError)
        {
            memcpy(lpszBuffer, lpwite->response, *lpdwBufferLength);
            *lpdwBufferLength = lstrlenW(lpszBuffer);
        }
        else
            *lpdwBufferLength = 0;
840 841
    }
    else
842 843
    {
        *lpdwError = 0;
844
        *lpdwBufferLength = 0;
845
    }
846 847 848

    return TRUE;
}
849

850
/***********************************************************************
851
 *           InternetGetConnectedState (WININET.@)
852 853 854 855 856
 *
 * Return connected state
 *
 * RETURNS
 *    TRUE if connected
857
 *    if lpdwStatus is not null, return the status (off line,
858 859 860 861 862
 *    modem, lan...) in it.
 *    FALSE if not connected
 */
BOOL WINAPI InternetGetConnectedState(LPDWORD lpdwStatus, DWORD dwReserved)
{
863
    TRACE("(%p, 0x%08x)\n", lpdwStatus, dwReserved);
864

865
    if (lpdwStatus) {
866
	WARN("always returning LAN connection.\n");
867 868 869
	*lpdwStatus = INTERNET_CONNECTION_LAN;
    }
    return TRUE;
870 871
}

872

873
/***********************************************************************
874
 *           InternetGetConnectedStateExW (WININET.@)
875 876 877
 *
 * Return connected state
 *
878 879 880 881 882 883 884
 * PARAMS
 *
 * lpdwStatus         [O] Flags specifying the status of the internet connection.
 * lpszConnectionName [O] Pointer to buffer to receive the friendly name of the internet connection.
 * dwNameLen          [I] Size of the buffer, in characters.
 * dwReserved         [I] Reserved. Must be set to 0.
 *
885 886 887 888 889
 * RETURNS
 *    TRUE if connected
 *    if lpdwStatus is not null, return the status (off line,
 *    modem, lan...) in it.
 *    FALSE if not connected
890 891 892 893 894 895 896 897 898
 *
 * NOTES
 *   If the system has no available network connections, an empty string is
 *   stored in lpszConnectionName. If there is a LAN connection, a localized
 *   "LAN Connection" string is stored. Presumably, if only a dial-up
 *   connection is available then the name of the dial-up connection is
 *   returned. Why any application, other than the "Internet Settings" CPL,
 *   would want to use this function instead of the simpler InternetGetConnectedStateW
 *   function is beyond me.
899 900 901 902
 */
BOOL WINAPI InternetGetConnectedStateExW(LPDWORD lpdwStatus, LPWSTR lpszConnectionName,
                                         DWORD dwNameLen, DWORD dwReserved)
{
903
    TRACE("(%p, %p, %d, 0x%08x)\n", lpdwStatus, lpszConnectionName, dwNameLen, dwReserved);
904

905 906 907 908 909
    /* Must be zero */
    if(dwReserved)
	return FALSE;

    if (lpdwStatus) {
910
        WARN("always returning LAN connection.\n");
911 912
        *lpdwStatus = INTERNET_CONNECTION_LAN;
    }
913
    return LoadStringW(WININET_hModule, IDS_LANCONNECTION, lpszConnectionName, dwNameLen);
914
}
915

916 917 918 919 920 921 922 923 924 925

/***********************************************************************
 *           InternetGetConnectedStateExA (WININET.@)
 */
BOOL WINAPI InternetGetConnectedStateExA(LPDWORD lpdwStatus, LPSTR lpszConnectionName,
                                         DWORD dwNameLen, DWORD dwReserved)
{
    LPWSTR lpwszConnectionName = NULL;
    BOOL rc;

926
    TRACE("(%p, %p, %d, 0x%08x)\n", lpdwStatus, lpszConnectionName, dwNameLen, dwReserved);
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944

    if (lpszConnectionName && dwNameLen > 0)
        lpwszConnectionName= HeapAlloc(GetProcessHeap(), 0, dwNameLen * sizeof(WCHAR));

    rc = InternetGetConnectedStateExW(lpdwStatus,lpwszConnectionName, dwNameLen,
                                      dwReserved);
    if (rc && lpwszConnectionName)
    {
        WideCharToMultiByte(CP_ACP,0,lpwszConnectionName,-1,lpszConnectionName,
                            dwNameLen, NULL, NULL);

        HeapFree(GetProcessHeap(),0,lpwszConnectionName);
    }

    return rc;
}


945
/***********************************************************************
946
 *           InternetConnectW (WININET.@)
947 948 949 950 951 952 953 954
 *
 * Open a ftp, gopher or http session
 *
 * RETURNS
 *    HINTERNET a session handle on success
 *    NULL on failure
 *
 */
955 956 957
HINTERNET WINAPI InternetConnectW(HINTERNET hInternet,
    LPCWSTR lpszServerName, INTERNET_PORT nServerPort,
    LPCWSTR lpszUserName, LPCWSTR lpszPassword,
958
    DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext)
959
{
960
    LPWININETAPPINFOW hIC;
961
    HINTERNET rc = NULL;
962

963
    TRACE("(%p, %s, %i, %s, %s, %i, %i, %lx)\n", hInternet, debugstr_w(lpszServerName),
964
	  nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword),
965
	  dwService, dwFlags, dwContext);
966

967 968
    if (!lpszServerName)
    {
969
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
970 971 972
        return NULL;
    }

973 974
    /* Clear any error information */
    INTERNET_SetLastError(0);
975 976
    hIC = (LPWININETAPPINFOW) WININET_GetObject( hInternet );
    if ( (hIC == NULL) || (hIC->hdr.htype != WH_HINIT) )
977
    {
978
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
979
        goto lend;
980
    }
981 982 983 984

    switch (dwService)
    {
        case INTERNET_SERVICE_FTP:
985
            rc = FTP_Connect(hIC, lpszServerName, nServerPort,
986
            lpszUserName, lpszPassword, dwFlags, dwContext, 0);
987 988 989
            break;

        case INTERNET_SERVICE_HTTP:
990
	    rc = HTTP_Connect(hIC, lpszServerName, nServerPort,
991
            lpszUserName, lpszPassword, dwFlags, dwContext, 0);
992 993 994 995 996 997
            break;

        case INTERNET_SERVICE_GOPHER:
        default:
            break;
    }
998 999 1000
lend:
    if( hIC )
        WININET_Release( &hIC->hdr );
1001

1002
    TRACE("returning %p\n", rc);
1003 1004 1005
    return rc;
}

1006 1007

/***********************************************************************
1008
 *           InternetConnectA (WININET.@)
1009 1010 1011 1012 1013 1014 1015 1016
 *
 * Open a ftp, gopher or http session
 *
 * RETURNS
 *    HINTERNET a session handle on success
 *    NULL on failure
 *
 */
1017 1018 1019
HINTERNET WINAPI InternetConnectA(HINTERNET hInternet,
    LPCSTR lpszServerName, INTERNET_PORT nServerPort,
    LPCSTR lpszUserName, LPCSTR lpszPassword,
1020
    DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext)
1021
{
1022
    HINTERNET rc = NULL;
1023 1024 1025 1026
    INT len = 0;
    LPWSTR szServerName = NULL;
    LPWSTR szUserName = NULL;
    LPWSTR szPassword = NULL;
1027 1028

    if (lpszServerName)
1029
    {
1030 1031 1032
	len = MultiByteToWideChar(CP_ACP, 0, lpszServerName, -1, NULL, 0);
        szServerName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszServerName, -1, szServerName, len);
1033 1034 1035
    }
    if (lpszUserName)
    {
1036 1037 1038
	len = MultiByteToWideChar(CP_ACP, 0, lpszUserName, -1, NULL, 0);
        szUserName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszUserName, -1, szUserName, len);
1039 1040 1041
    }
    if (lpszPassword)
    {
1042 1043 1044
	len = MultiByteToWideChar(CP_ACP, 0, lpszPassword, -1, NULL, 0);
        szPassword = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpszPassword, -1, szPassword, len);
1045 1046 1047
    }


1048
    rc = InternetConnectW(hInternet, szServerName, nServerPort,
1049 1050
        szUserName, szPassword, dwService, dwFlags, dwContext);

1051 1052 1053
    HeapFree(GetProcessHeap(), 0, szServerName);
    HeapFree(GetProcessHeap(), 0, szUserName);
    HeapFree(GetProcessHeap(), 0, szPassword);
1054 1055 1056 1057
    return rc;
}


1058
/***********************************************************************
1059
 *           InternetFindNextFileA (WININET.@)
1060 1061 1062 1063 1064 1065 1066 1067
 *
 * Continues a file search from a previous call to FindFirstFile
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1068
BOOL WINAPI InternetFindNextFileA(HINTERNET hFind, LPVOID lpvFindData)
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
{
    BOOL ret;
    WIN32_FIND_DATAW fd;
    
    ret = InternetFindNextFileW(hFind, lpvFindData?&fd:NULL);
    if(lpvFindData)
        WININET_find_data_WtoA(&fd, (LPWIN32_FIND_DATAA)lpvFindData);
    return ret;
}

/***********************************************************************
 *           InternetFindNextFileW (WININET.@)
 *
 * Continues a file search from a previous call to FindFirstFile
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI InternetFindNextFileW(HINTERNET hFind, LPVOID lpvFindData)
1090
{
1091 1092
    WININETHANDLEHEADER *hdr;
    DWORD res;
1093 1094 1095

    TRACE("\n");

1096 1097 1098 1099 1100
    hdr = WININET_GetObject(hFind);
    if(!hdr) {
        WARN("Invalid handle\n");
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
1101 1102
    }

1103 1104 1105 1106 1107 1108
    if(hdr->vtbl->FindNextFileW) {
        res = hdr->vtbl->FindNextFileW(hdr, lpvFindData);
    }else {
        WARN("Handle doesn't support NextFile\n");
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
    }
1109

1110
    WININET_Release(hdr);
1111

1112 1113 1114
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
1115 1116 1117
}

/***********************************************************************
1118
 *           InternetCloseHandle (WININET.@)
1119
 *
1120
 * Generic close handle function
1121 1122 1123 1124 1125 1126
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1127
BOOL WINAPI InternetCloseHandle(HINTERNET hInternet)
1128
{
1129
    LPWININETHANDLEHEADER lpwh;
1130
    
1131
    TRACE("%p\n",hInternet);
1132 1133

    lpwh = WININET_GetObject( hInternet );
1134
    if (NULL == lpwh)
1135
    {
1136
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1137
        return FALSE;
1138
    }
1139

1140
    WININET_Release( lpwh );
1141
    WININET_FreeHandle( hInternet );
1142

1143
    return TRUE;
1144 1145 1146
}


1147
/***********************************************************************
1148
 *           ConvertUrlComponentValue (Internal)
1149
 *
1150
 * Helper function for InternetCrackUrlA
1151 1152
 *
 */
1153 1154 1155
static void ConvertUrlComponentValue(LPSTR* lppszComponent, LPDWORD dwComponentLen,
                                     LPWSTR lpwszComponent, DWORD dwwComponentLen,
                                     LPCSTR lpszStart, LPCWSTR lpwszStart)
1156
{
1157
    TRACE("%p %d %p %d %p %p\n", *lppszComponent, *dwComponentLen, lpwszComponent, dwwComponentLen, lpszStart, lpwszStart);
1158 1159
    if (*dwComponentLen != 0)
    {
1160
        DWORD nASCIILength=WideCharToMultiByte(CP_ACP,0,lpwszComponent,dwwComponentLen,NULL,0,NULL,NULL);
1161 1162 1163
        if (*lppszComponent == NULL)
        {
            int nASCIIOffset=WideCharToMultiByte(CP_ACP,0,lpwszStart,lpwszComponent-lpwszStart,NULL,0,NULL,NULL);
1164 1165 1166 1167
            if (lpwszComponent)
                *lppszComponent = (LPSTR)lpszStart+nASCIIOffset;
            else
                *lppszComponent = NULL;
1168 1169 1170 1171
            *dwComponentLen = nASCIILength;
        }
        else
        {
1172
            DWORD ncpylen = min((*dwComponentLen)-1, nASCIILength);
1173 1174 1175 1176
            WideCharToMultiByte(CP_ACP,0,lpwszComponent,dwwComponentLen,*lppszComponent,ncpylen+1,NULL,NULL);
            (*lppszComponent)[ncpylen]=0;
            *dwComponentLen = ncpylen;
        }
1177 1178 1179 1180
    }
}


1181
/***********************************************************************
1182
 *           InternetCrackUrlA (WININET.@)
1183
 *
1184
 * See InternetCrackUrlW.
1185
 */
1186
BOOL WINAPI InternetCrackUrlA(LPCSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags,
1187
    LPURL_COMPONENTSA lpUrlComponents)
1188 1189 1190
{
  DWORD nLength;
  URL_COMPONENTSW UCW;
1191 1192 1193
  BOOL ret = FALSE;
  WCHAR *lpwszUrl, *hostname = NULL, *username = NULL, *password = NULL, *path = NULL,
        *scheme = NULL, *extra = NULL;
1194

1195 1196 1197
  TRACE("(%s %u %x %p)\n",
        lpszUrl ? debugstr_an(lpszUrl, dwUrlLength ? dwUrlLength : strlen(lpszUrl)) : "(null)",
        dwUrlLength, dwFlags, lpUrlComponents);
1198

1199 1200
  if (!lpszUrl || !*lpszUrl || !lpUrlComponents ||
          lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSA))
1201 1202 1203 1204 1205
  {
      INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
      return FALSE;
  }

1206 1207 1208
  if(dwUrlLength<=0)
      dwUrlLength=-1;
  nLength=MultiByteToWideChar(CP_ACP,0,lpszUrl,dwUrlLength,NULL,0);
1209 1210 1211 1212 1213

  /* if dwUrlLength=-1 then nLength includes null but length to 
       InternetCrackUrlW should not include it                  */
  if (dwUrlLength == -1) nLength--;

1214 1215 1216
  lpwszUrl=HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WCHAR)*nLength);
  MultiByteToWideChar(CP_ACP,0,lpszUrl,dwUrlLength,lpwszUrl,nLength);

1217
  memset(&UCW,0,sizeof(UCW));
1218
  UCW.dwStructSize = sizeof(URL_COMPONENTSW);
1219
  if (lpUrlComponents->dwHostNameLength)
1220
  {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    UCW.dwHostNameLength = lpUrlComponents->dwHostNameLength;
    if (lpUrlComponents->lpszHostName)
    {
      hostname = HeapAlloc(GetProcessHeap(), 0, UCW.dwHostNameLength * sizeof(WCHAR));
      UCW.lpszHostName = hostname;
    }
  }
  if (lpUrlComponents->dwUserNameLength)
  {
    UCW.dwUserNameLength = lpUrlComponents->dwUserNameLength;
    if (lpUrlComponents->lpszUserName)
    {
      username = HeapAlloc(GetProcessHeap(), 0, UCW.dwUserNameLength * sizeof(WCHAR));
      UCW.lpszUserName = username;
    }
  }
  if (lpUrlComponents->dwPasswordLength)
  {
    UCW.dwPasswordLength = lpUrlComponents->dwPasswordLength;
    if (lpUrlComponents->lpszPassword)
    {
      password = HeapAlloc(GetProcessHeap(), 0, UCW.dwPasswordLength * sizeof(WCHAR));
      UCW.lpszPassword = password;
    }
  }
  if (lpUrlComponents->dwUrlPathLength)
  {
    UCW.dwUrlPathLength = lpUrlComponents->dwUrlPathLength;
    if (lpUrlComponents->lpszUrlPath)
    {
      path = HeapAlloc(GetProcessHeap(), 0, UCW.dwUrlPathLength * sizeof(WCHAR));
      UCW.lpszUrlPath = path;
    }
  }
  if (lpUrlComponents->dwSchemeLength)
  {
    UCW.dwSchemeLength = lpUrlComponents->dwSchemeLength;
    if (lpUrlComponents->lpszScheme)
    {
      scheme = HeapAlloc(GetProcessHeap(), 0, UCW.dwSchemeLength * sizeof(WCHAR));
      UCW.lpszScheme = scheme;
    }
  }
  if (lpUrlComponents->dwExtraInfoLength)
  {
    UCW.dwExtraInfoLength = lpUrlComponents->dwExtraInfoLength;
    if (lpUrlComponents->lpszExtraInfo)
    {
      extra = HeapAlloc(GetProcessHeap(), 0, UCW.dwExtraInfoLength * sizeof(WCHAR));
      UCW.lpszExtraInfo = extra;
    }
  }
  if ((ret = InternetCrackUrlW(lpwszUrl, nLength, dwFlags, &UCW)))
  {
    ConvertUrlComponentValue(&lpUrlComponents->lpszHostName, &lpUrlComponents->dwHostNameLength,
                             UCW.lpszHostName, UCW.dwHostNameLength, lpszUrl, lpwszUrl);
    ConvertUrlComponentValue(&lpUrlComponents->lpszUserName, &lpUrlComponents->dwUserNameLength,
                             UCW.lpszUserName, UCW.dwUserNameLength, lpszUrl, lpwszUrl);
    ConvertUrlComponentValue(&lpUrlComponents->lpszPassword, &lpUrlComponents->dwPasswordLength,
                             UCW.lpszPassword, UCW.dwPasswordLength, lpszUrl, lpwszUrl);
    ConvertUrlComponentValue(&lpUrlComponents->lpszUrlPath, &lpUrlComponents->dwUrlPathLength,
                             UCW.lpszUrlPath, UCW.dwUrlPathLength, lpszUrl, lpwszUrl);
    ConvertUrlComponentValue(&lpUrlComponents->lpszScheme, &lpUrlComponents->dwSchemeLength,
                             UCW.lpszScheme, UCW.dwSchemeLength, lpszUrl, lpwszUrl);
    ConvertUrlComponentValue(&lpUrlComponents->lpszExtraInfo, &lpUrlComponents->dwExtraInfoLength,
                             UCW.lpszExtraInfo, UCW.dwExtraInfoLength, lpszUrl, lpwszUrl);

    lpUrlComponents->nScheme = UCW.nScheme;
    lpUrlComponents->nPort = UCW.nPort;

    TRACE("%s: scheme(%s) host(%s) path(%s) extra(%s)\n", lpszUrl,
          debugstr_an(lpUrlComponents->lpszScheme, lpUrlComponents->dwSchemeLength),
          debugstr_an(lpUrlComponents->lpszHostName, lpUrlComponents->dwHostNameLength),
          debugstr_an(lpUrlComponents->lpszUrlPath, lpUrlComponents->dwUrlPathLength),
          debugstr_an(lpUrlComponents->lpszExtraInfo, lpUrlComponents->dwExtraInfoLength));
1296 1297
  }
  HeapFree(GetProcessHeap(), 0, lpwszUrl);
1298 1299 1300 1301 1302 1303 1304
  HeapFree(GetProcessHeap(), 0, hostname);
  HeapFree(GetProcessHeap(), 0, username);
  HeapFree(GetProcessHeap(), 0, password);
  HeapFree(GetProcessHeap(), 0, path);
  HeapFree(GetProcessHeap(), 0, scheme);
  HeapFree(GetProcessHeap(), 0, extra);
  return ret;
1305 1306
}

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
static const WCHAR url_schemes[][7] =
{
    {'f','t','p',0},
    {'g','o','p','h','e','r',0},
    {'h','t','t','p',0},
    {'h','t','t','p','s',0},
    {'f','i','l','e',0},
    {'n','e','w','s',0},
    {'m','a','i','l','t','o',0},
    {'r','e','s',0},
};

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/***********************************************************************
 *           GetInternetSchemeW (internal)
 *
 * Get scheme of url
 *
 * RETURNS
 *    scheme on success
 *    INTERNET_SCHEME_UNKNOWN on failure
 *
 */
1329
static INTERNET_SCHEME GetInternetSchemeW(LPCWSTR lpszScheme, DWORD nMaxCmp)
1330
{
1331 1332
    int i;

1333
    TRACE("%s %d\n",debugstr_wn(lpszScheme, nMaxCmp), nMaxCmp);
1334

1335 1336 1337
    if(lpszScheme==NULL)
        return INTERNET_SCHEME_UNKNOWN;

1338 1339 1340 1341 1342
    for (i = 0; i < sizeof(url_schemes)/sizeof(url_schemes[0]); i++)
        if (!strncmpW(lpszScheme, url_schemes[i], nMaxCmp))
            return INTERNET_SCHEME_FIRST + i;

    return INTERNET_SCHEME_UNKNOWN;
1343 1344 1345 1346 1347 1348 1349
}

/***********************************************************************
 *           SetUrlComponentValueW (Internal)
 *
 * Helper function for InternetCrackUrlW
 *
1350 1351 1352 1353 1354 1355 1356
 * PARAMS
 *     lppszComponent [O] Holds the returned string
 *     dwComponentLen [I] Holds the size of lppszComponent
 *                    [O] Holds the length of the string in lppszComponent without '\0'
 *     lpszStart      [I] Holds the string to copy from
 *     len            [I] Holds the length of lpszStart without '\0'
 *
1357 1358 1359 1360 1361
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1362
static BOOL SetUrlComponentValueW(LPWSTR* lppszComponent, LPDWORD dwComponentLen, LPCWSTR lpszStart, DWORD len)
1363
{
1364
    TRACE("%s (%d)\n", debugstr_wn(lpszStart,len), len);
1365

1366 1367 1368
    if ( (*dwComponentLen == 0) && (*lppszComponent == NULL) )
        return FALSE;

1369
    if (*dwComponentLen != 0 || *lppszComponent == NULL)
1370 1371 1372 1373 1374 1375 1376 1377
    {
        if (*lppszComponent == NULL)
        {
            *lppszComponent = (LPWSTR)lpszStart;
            *dwComponentLen = len;
        }
        else
        {
1378
            DWORD ncpylen = min((*dwComponentLen)-1, len);
1379
            memcpy(*lppszComponent, lpszStart, ncpylen*sizeof(WCHAR));
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
            (*lppszComponent)[ncpylen] = '\0';
            *dwComponentLen = ncpylen;
        }
    }

    return TRUE;
}

/***********************************************************************
 *           InternetCrackUrlW   (WININET.@)
1390 1391 1392 1393 1394 1395
 *
 * Break up URL into its components
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
1396
 */
1397
BOOL WINAPI InternetCrackUrlW(LPCWSTR lpszUrl_orig, DWORD dwUrlLength_orig, DWORD dwFlags,
1398
                              LPURL_COMPONENTSW lpUC)
1399 1400 1401 1402 1403 1404
{
  /*
   * RFC 1808
   * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
   *
   */
1405
    LPCWSTR lpszParam    = NULL;
1406
    BOOL  bIsAbsolute = FALSE;
1407
    LPCWSTR lpszap, lpszUrl = lpszUrl_orig;
1408
    LPCWSTR lpszcp = NULL;
1409 1410
    LPWSTR  lpszUrl_decode = NULL;
    DWORD dwUrlLength = dwUrlLength_orig;
1411

1412 1413 1414
    TRACE("(%s %u %x %p)\n",
          lpszUrl ? debugstr_wn(lpszUrl, dwUrlLength ? dwUrlLength : strlenW(lpszUrl)) : "(null)",
          dwUrlLength, dwFlags, lpUC);
1415

1416
    if (!lpszUrl_orig || !*lpszUrl_orig || !lpUC)
1417
    {
1418
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1419 1420
        return FALSE;
    }
1421
    if (!dwUrlLength) dwUrlLength = strlenW(lpszUrl);
1422

1423 1424
    if (dwFlags & ICU_DECODE)
    {
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
        WCHAR *url_tmp;
        DWORD len = dwUrlLength + 1;

        if (!(url_tmp = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
        {
            INTERNET_SetLastError(ERROR_OUTOFMEMORY);
            return FALSE;
        }
        memcpy(url_tmp, lpszUrl_orig, dwUrlLength * sizeof(WCHAR));
        url_tmp[dwUrlLength] = 0;
        if (!(lpszUrl_decode = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
        {
            HeapFree(GetProcessHeap(), 0, url_tmp);
            INTERNET_SetLastError(ERROR_OUTOFMEMORY);
            return FALSE;
        }
        if (InternetCanonicalizeUrlW(url_tmp, lpszUrl_decode, &len, ICU_DECODE | ICU_NO_ENCODE))
        {
            dwUrlLength = len;
            lpszUrl = lpszUrl_decode;
        }
        HeapFree(GetProcessHeap(), 0, url_tmp);
1447 1448 1449
    }
    lpszap = lpszUrl;
    
1450
    /* Determine if the URI is absolute. */
1451
    while (lpszap - lpszUrl < dwUrlLength)
1452
    {
1453
        if (isalnumW(*lpszap))
1454
        {
1455
            lpszap++;
1456 1457
            continue;
        }
1458
        if ((*lpszap == ':') && (lpszap - lpszUrl >= 2))
1459 1460
        {
            bIsAbsolute = TRUE;
1461 1462
            lpszcp = lpszap;
        }
1463 1464
        else
        {
1465
            lpszcp = lpszUrl; /* Relative url */
1466
        }
1467

1468 1469 1470
        break;
    }

1471 1472 1473
    lpUC->nScheme = INTERNET_SCHEME_UNKNOWN;
    lpUC->nPort = INTERNET_INVALID_PORT_NUMBER;

1474
    /* Parse <params> */
1475 1476 1477
    if (!(lpszParam = memchrW(lpszap, ';', dwUrlLength - (lpszap - lpszUrl))))
        lpszParam = memchrW(lpszap, '?', dwUrlLength - (lpszap - lpszUrl));

1478 1479
    SetUrlComponentValueW(&lpUC->lpszExtraInfo, &lpUC->dwExtraInfoLength,
                          lpszParam, lpszParam ? dwUrlLength-(lpszParam-lpszUrl) : 0);
1480

1481
    if (bIsAbsolute) /* Parse <protocol>:[//<net_loc>] */
1482
    {
1483
        LPCWSTR lpszNetLoc;
1484 1485

        /* Get scheme first. */
1486
        lpUC->nScheme = GetInternetSchemeW(lpszUrl, lpszcp - lpszUrl);
1487 1488
        SetUrlComponentValueW(&lpUC->lpszScheme, &lpUC->dwSchemeLength,
                                   lpszUrl, lpszcp - lpszUrl);
1489 1490 1491 1492

        /* Eat ':' in protocol. */
        lpszcp++;

1493 1494
        /* double slash indicates the net_loc portion is present */
        if ((lpszcp[0] == '/') && (lpszcp[1] == '/'))
1495
        {
1496
            lpszcp += 2;
1497

1498
            lpszNetLoc = memchrW(lpszcp, '/', dwUrlLength - (lpszcp - lpszUrl));
1499 1500 1501 1502 1503 1504 1505 1506 1507
            if (lpszParam)
            {
                if (lpszNetLoc)
                    lpszNetLoc = min(lpszNetLoc, lpszParam);
                else
                    lpszNetLoc = lpszParam;
            }
            else if (!lpszNetLoc)
                lpszNetLoc = lpszcp + dwUrlLength-(lpszcp-lpszUrl);
1508

1509 1510 1511
            /* Parse net-loc */
            if (lpszNetLoc)
            {
1512 1513
                LPCWSTR lpszHost;
                LPCWSTR lpszPort;
1514

1515
                /* [<user>[<:password>]@]<host>[:<port>] */
1516
                /* First find the user and password if they exist */
1517

1518
                lpszHost = memchrW(lpszcp, '@', dwUrlLength - (lpszcp - lpszUrl));
1519
                if (lpszHost == NULL || lpszHost > lpszNetLoc)
1520
                {
1521 1522 1523
                    /* username and password not specified. */
                    SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
                    SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
1524
                }
1525
                else /* Parse out username and password */
1526
                {
1527 1528
                    LPCWSTR lpszUser = lpszcp;
                    LPCWSTR lpszPasswd = lpszHost;
1529

1530 1531 1532 1533
                    while (lpszcp < lpszHost)
                    {
                        if (*lpszcp == ':')
                            lpszPasswd = lpszcp;
1534

1535
                        lpszcp++;
1536 1537
                    }

1538 1539
                    SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength,
                                          lpszUser, lpszPasswd - lpszUser);
1540

1541 1542 1543 1544 1545
                    if (lpszPasswd != lpszHost)
                        lpszPasswd++;
                    SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength,
                                          lpszPasswd == lpszHost ? NULL : lpszPasswd,
                                          lpszHost - lpszPasswd);
1546

1547
                    lpszcp++; /* Advance to beginning of host */
1548 1549
                }

1550
                /* Parse <host><:port> */
1551

1552 1553
                lpszHost = lpszcp;
                lpszPort = lpszNetLoc;
1554

1555 1556 1557 1558 1559 1560 1561
                /* special case for res:// URLs: there is no port here, so the host is the
                   entire string up to the first '/' */
                if(lpUC->nScheme==INTERNET_SCHEME_RES)
                {
                    SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
                                          lpszHost, lpszPort - lpszHost);
                    lpszcp=lpszNetLoc;
1562
                }
1563 1564 1565 1566 1567 1568
                else
                {
                    while (lpszcp < lpszNetLoc)
                    {
                        if (*lpszcp == ':')
                            lpszPort = lpszcp;
1569

1570 1571
                        lpszcp++;
                    }
1572

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
                    /* If the scheme is "file" and the host is just one letter, it's not a host */
                    if(lpUC->nScheme==INTERNET_SCHEME_FILE && (lpszPort-lpszHost)==1)
                    {
                        lpszcp=lpszHost;
                        SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
                                              NULL, 0);
                    }
                    else
                    {
                        SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
                                              lpszHost, lpszPort - lpszHost);
                        if (lpszPort != lpszNetLoc)
                            lpUC->nPort = atoiW(++lpszPort);
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
                        else switch (lpUC->nScheme)
                        {
                        case INTERNET_SCHEME_HTTP:
                            lpUC->nPort = INTERNET_DEFAULT_HTTP_PORT;
                            break;
                        case INTERNET_SCHEME_HTTPS:
                            lpUC->nPort = INTERNET_DEFAULT_HTTPS_PORT;
                            break;
                        case INTERNET_SCHEME_FTP:
                            lpUC->nPort = INTERNET_DEFAULT_FTP_PORT;
                            break;
                        case INTERNET_SCHEME_GOPHER:
                            lpUC->nPort = INTERNET_DEFAULT_GOPHER_PORT;
                            break;
                        default:
1601
                            break;
1602
                        }
1603 1604
                    }
                }
1605 1606
            }
        }
1607 1608 1609 1610 1611 1612
        else
        {
            SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
            SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
            SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength, NULL, 0);
        }
1613
    }
1614 1615 1616 1617 1618 1619 1620
    else
    {
        SetUrlComponentValueW(&lpUC->lpszScheme, &lpUC->dwSchemeLength, NULL, 0);
        SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
        SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
        SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength, NULL, 0);
    }
1621 1622 1623 1624 1625 1626

    /* Here lpszcp points to:
     *
     * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
     *                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     */
1627
    if (lpszcp != 0 && lpszcp - lpszUrl < dwUrlLength && (!lpszParam || lpszcp < lpszParam))
1628
    {
1629 1630 1631
        INT len;

        /* Only truncate the parameter list if it's already been saved
1632
         * in lpUC->lpszExtraInfo.
1633
         */
1634
        if (lpszParam && lpUC->dwExtraInfoLength && lpUC->lpszExtraInfo)
1635 1636 1637 1638 1639 1640
            len = lpszParam - lpszcp;
        else
        {
            /* Leave the parameter list in lpszUrlPath.  Strip off any trailing
             * newlines if necessary.
             */
1641
            LPWSTR lpsznewline = memchrW(lpszcp, '\n', dwUrlLength - (lpszcp - lpszUrl));
1642 1643 1644
            if (lpsznewline != NULL)
                len = lpsznewline - lpszcp;
            else
1645
                len = dwUrlLength-(lpszcp-lpszUrl);
1646
        }
1647 1648
        SetUrlComponentValueW(&lpUC->lpszUrlPath, &lpUC->dwUrlPathLength,
                                   lpszcp, len);
1649 1650
    }
    else
1651
    {
1652 1653
        if (lpUC->lpszUrlPath && (lpUC->dwUrlPathLength > 0))
            lpUC->lpszUrlPath[0] = 0;
1654
        lpUC->dwUrlPathLength = 0;
1655 1656
    }

1657 1658
    TRACE("%s: scheme(%s) host(%s) path(%s) extra(%s)\n", debugstr_wn(lpszUrl,dwUrlLength),
             debugstr_wn(lpUC->lpszScheme,lpUC->dwSchemeLength),
1659 1660 1661
             debugstr_wn(lpUC->lpszHostName,lpUC->dwHostNameLength),
             debugstr_wn(lpUC->lpszUrlPath,lpUC->dwUrlPathLength),
             debugstr_wn(lpUC->lpszExtraInfo,lpUC->dwExtraInfoLength));
1662

1663
    HeapFree(GetProcessHeap(), 0, lpszUrl_decode );
1664 1665 1666 1667
    return TRUE;
}

/***********************************************************************
1668
 *           InternetAttemptConnect (WININET.@)
1669 1670 1671 1672 1673 1674 1675 1676
 *
 * Attempt to make a connection to the internet
 *
 * RETURNS
 *    ERROR_SUCCESS on success
 *    Error value   on failure
 *
 */
1677
DWORD WINAPI InternetAttemptConnect(DWORD dwReserved)
1678 1679 1680 1681 1682 1683 1684
{
    FIXME("Stub\n");
    return ERROR_SUCCESS;
}


/***********************************************************************
1685
 *           InternetCanonicalizeUrlA (WININET.@)
1686 1687 1688 1689 1690 1691 1692 1693
 *
 * Escape unsafe characters and spaces
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1694
BOOL WINAPI InternetCanonicalizeUrlA(LPCSTR lpszUrl, LPSTR lpszBuffer,
1695 1696
	LPDWORD lpdwBufferLength, DWORD dwFlags)
{
1697
    HRESULT hr;
1698 1699 1700 1701 1702
    DWORD dwURLFlags = URL_WININET_COMPATIBILITY | URL_ESCAPE_UNSAFE;

    TRACE("(%s, %p, %p, 0x%08x) bufferlength: %d\n", debugstr_a(lpszUrl), lpszBuffer,
        lpdwBufferLength, lpdwBufferLength ? *lpdwBufferLength : -1, dwFlags);

1703 1704
    if(dwFlags & ICU_DECODE)
    {
1705 1706
        dwURLFlags |= URL_UNESCAPE;
        dwFlags &= ~ICU_DECODE;
1707 1708 1709 1710
    }

    if(dwFlags & ICU_ESCAPE)
    {
1711 1712
        dwURLFlags |= URL_UNESCAPE;
        dwFlags &= ~ICU_ESCAPE;
1713
    }
1714

1715 1716 1717 1718 1719
    if(dwFlags & ICU_BROWSER_MODE)
    {
        dwURLFlags |= URL_BROWSER_MODE;
        dwFlags &= ~ICU_BROWSER_MODE;
    }
1720

1721 1722 1723 1724 1725 1726 1727 1728
    if(dwFlags & ICU_NO_ENCODE)
    {
        /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
        dwURLFlags ^= URL_ESCAPE_UNSAFE;
        dwFlags &= ~ICU_NO_ENCODE;
    }

    if (dwFlags) FIXME("Unhandled flags 0x%08x\n", dwFlags);
1729

1730
    hr = UrlCanonicalizeA(lpszUrl, lpszBuffer, lpdwBufferLength, dwURLFlags);
1731 1732
    if (hr == E_POINTER) SetLastError(ERROR_INSUFFICIENT_BUFFER);
    if (hr == E_INVALIDARG) SetLastError(ERROR_INVALID_PARAMETER);
1733

1734 1735
    return (hr == S_OK) ? TRUE : FALSE;
}
1736

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
/***********************************************************************
 *           InternetCanonicalizeUrlW (WININET.@)
 *
 * Escape unsafe characters and spaces
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI InternetCanonicalizeUrlW(LPCWSTR lpszUrl, LPWSTR lpszBuffer,
    LPDWORD lpdwBufferLength, DWORD dwFlags)
{
    HRESULT hr;
1751 1752 1753
    DWORD dwURLFlags = URL_WININET_COMPATIBILITY | URL_ESCAPE_UNSAFE;

    TRACE("(%s, %p, %p, 0x%08x) bufferlength: %d\n", debugstr_w(lpszUrl), lpszBuffer,
1754
          lpdwBufferLength, dwFlags, lpdwBufferLength ? *lpdwBufferLength : -1);
1755

1756 1757
    if(dwFlags & ICU_DECODE)
    {
1758 1759
        dwURLFlags |= URL_UNESCAPE;
        dwFlags &= ~ICU_DECODE;
1760 1761 1762 1763
    }

    if(dwFlags & ICU_ESCAPE)
    {
1764 1765
        dwURLFlags |= URL_UNESCAPE;
        dwFlags &= ~ICU_ESCAPE;
1766
    }
1767

1768 1769 1770 1771 1772
    if(dwFlags & ICU_BROWSER_MODE)
    {
        dwURLFlags |= URL_BROWSER_MODE;
        dwFlags &= ~ICU_BROWSER_MODE;
    }
1773

1774 1775 1776 1777 1778 1779 1780 1781
    if(dwFlags & ICU_NO_ENCODE)
    {
        /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
        dwURLFlags ^= URL_ESCAPE_UNSAFE;
        dwFlags &= ~ICU_NO_ENCODE;
    }

    if (dwFlags) FIXME("Unhandled flags 0x%08x\n", dwFlags);
1782

1783
    hr = UrlCanonicalizeW(lpszUrl, lpszBuffer, lpdwBufferLength, dwURLFlags);
1784 1785
    if (hr == E_POINTER) SetLastError(ERROR_INSUFFICIENT_BUFFER);
    if (hr == E_INVALIDARG) SetLastError(ERROR_INVALID_PARAMETER);
1786 1787 1788 1789

    return (hr == S_OK) ? TRUE : FALSE;
}

1790 1791
/* #################################################### */

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
static INTERNET_STATUS_CALLBACK set_status_callback(
    LPWININETHANDLEHEADER lpwh, INTERNET_STATUS_CALLBACK callback, BOOL unicode)
{
    INTERNET_STATUS_CALLBACK ret;

    if (unicode) lpwh->dwInternalFlags |= INET_CALLBACKW;
    else lpwh->dwInternalFlags &= ~INET_CALLBACKW;

    ret = lpwh->lpfnStatusCB;
    lpwh->lpfnStatusCB = callback;

    return ret;
}
1805

1806
/***********************************************************************
1807
 *           InternetSetStatusCallbackA (WININET.@)
1808 1809
 *
 * Sets up a callback function which is called as progress is made
1810
 * during an operation.
1811 1812 1813 1814 1815 1816
 *
 * RETURNS
 *    Previous callback or NULL 	on success
 *    INTERNET_INVALID_STATUS_CALLBACK  on failure
 *
 */
1817
INTERNET_STATUS_CALLBACK WINAPI InternetSetStatusCallbackA(
1818 1819
	HINTERNET hInternet ,INTERNET_STATUS_CALLBACK lpfnIntCB)
{
1820 1821
    INTERNET_STATUS_CALLBACK retVal;
    LPWININETHANDLEHEADER lpwh;
1822

1823
    TRACE("0x%08x\n", (ULONG)hInternet);
1824
    
1825
    if (!(lpwh = WININET_GetObject(hInternet)))
1826
        return INTERNET_INVALID_STATUS_CALLBACK;
1827

1828
    retVal = set_status_callback(lpwh, lpfnIntCB, FALSE);
1829 1830

    WININET_Release( lpwh );
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
    return retVal;
}

/***********************************************************************
 *           InternetSetStatusCallbackW (WININET.@)
 *
 * Sets up a callback function which is called as progress is made
 * during an operation.
 *
 * RETURNS
 *    Previous callback or NULL 	on success
 *    INTERNET_INVALID_STATUS_CALLBACK  on failure
 *
 */
INTERNET_STATUS_CALLBACK WINAPI InternetSetStatusCallbackW(
	HINTERNET hInternet ,INTERNET_STATUS_CALLBACK lpfnIntCB)
{
1848 1849
    INTERNET_STATUS_CALLBACK retVal;
    LPWININETHANDLEHEADER lpwh;
1850

1851
    TRACE("0x%08x\n", (ULONG)hInternet);
1852 1853

    if (!(lpwh = WININET_GetObject(hInternet)))
1854
        return INTERNET_INVALID_STATUS_CALLBACK;
1855

1856
    retVal = set_status_callback(lpwh, lpfnIntCB, TRUE);
1857

1858
    WININET_Release( lpwh );
1859 1860 1861
    return retVal;
}

Kirill Smelkov's avatar
Kirill Smelkov committed
1862 1863 1864
/***********************************************************************
 *           InternetSetFilePointer (WININET.@)
 */
1865
DWORD WINAPI InternetSetFilePointer(HINTERNET hFile, LONG lDistanceToMove,
1866
    PVOID pReserved, DWORD dwMoveContext, DWORD_PTR dwContext)
Kirill Smelkov's avatar
Kirill Smelkov committed
1867 1868 1869 1870
{
    FIXME("stub\n");
    return FALSE;
}
1871 1872

/***********************************************************************
1873
 *           InternetWriteFile (WININET.@)
1874
 *
1875
 * Write data to an open internet file
1876 1877 1878 1879 1880 1881
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
1882
BOOL WINAPI InternetWriteFile(HINTERNET hFile, LPCVOID lpBuffer,
1883 1884
	DWORD dwNumOfBytesToWrite, LPDWORD lpdwNumOfBytesWritten)
{
1885
    LPWININETHANDLEHEADER lpwh;
1886
    BOOL retval = FALSE;
1887

1888
    TRACE("(%p %p %d %p)\n", hFile, lpBuffer, dwNumOfBytesToWrite, lpdwNumOfBytesWritten);
1889

1890
    lpwh = WININET_GetObject( hFile );
1891 1892 1893 1894 1895
    if (!lpwh) {
        WARN("Invalid handle\n");
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }
1896

1897
    if(lpwh->vtbl->WriteFile) {
1898 1899
        retval = lpwh->vtbl->WriteFile(lpwh, lpBuffer, dwNumOfBytesToWrite, lpdwNumOfBytesWritten);
    }else {
1900
        WARN("No Writefile method.\n");
1901 1902
        SetLastError(ERROR_INVALID_HANDLE);
        retval = FALSE;
1903 1904
    }

1905
    WININET_Release( lpwh );
1906 1907 1908 1909 1910

    return retval;
}


1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
/***********************************************************************
 *           InternetReadFile (WININET.@)
 *
 * Read data from an open internet file
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI InternetReadFile(HINTERNET hFile, LPVOID lpBuffer,
1922
        DWORD dwNumOfBytesToRead, LPDWORD pdwNumOfBytesRead)
1923
{
1924 1925
    LPWININETHANDLEHEADER hdr;
    DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1926

1927
    TRACE("%p %p %d %p\n", hFile, lpBuffer, dwNumOfBytesToRead, pdwNumOfBytesRead);
1928

1929 1930
    hdr = WININET_GetObject(hFile);
    if (!hdr) {
1931
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1932 1933 1934
        return FALSE;
    }

1935 1936
    if(hdr->vtbl->ReadFile)
        res = hdr->vtbl->ReadFile(hdr, lpBuffer, dwNumOfBytesToRead, pdwNumOfBytesRead);
1937

1938 1939 1940 1941 1942 1943 1944 1945
    WININET_Release(hdr);

    TRACE("-- %s (%u) (bytes read: %d)\n", res == ERROR_SUCCESS ? "TRUE": "FALSE", res,
          pdwNumOfBytesRead ? *pdwNumOfBytesRead : -1);

    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
1946 1947
}

1948 1949 1950 1951 1952
/***********************************************************************
 *           InternetReadFileExA (WININET.@)
 *
 * Read data from an open internet file
 *
1953 1954 1955 1956 1957 1958
 * PARAMS
 *  hFile         [I] Handle returned by InternetOpenUrl or HttpOpenRequest.
 *  lpBuffersOut  [I/O] Buffer.
 *  dwFlags       [I] Flags. See notes.
 *  dwContext     [I] Context for callbacks.
 *
1959 1960 1961 1962
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
 * NOTES
 *  The parameter dwFlags include zero or more of the following flags:
 *|IRF_ASYNC - Makes the call asynchronous.
 *|IRF_SYNC - Makes the call synchronous.
 *|IRF_USE_CONTEXT - Forces dwContext to be used.
 *|IRF_NO_WAIT - Don't block if the data is not available, just return what is available.
 *
 * However, in testing IRF_USE_CONTEXT seems to have no effect - dwContext isn't used.
 *
 * SEE
 *  InternetOpenUrlA(), HttpOpenRequestA()
1974
 */
1975
BOOL WINAPI InternetReadFileExA(HINTERNET hFile, LPINTERNET_BUFFERSA lpBuffersOut,
1976
	DWORD dwFlags, DWORD_PTR dwContext)
1977
{
1978 1979
    LPWININETHANDLEHEADER hdr;
    DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1980

1981
    TRACE("(%p %p 0x%x 0x%lx)\n", hFile, lpBuffersOut, dwFlags, dwContext);
1982

1983 1984
    hdr = WININET_GetObject(hFile);
    if (!hdr) {
1985
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1986 1987 1988
        return FALSE;
    }

1989 1990
    if(hdr->vtbl->ReadFileExA)
        res = hdr->vtbl->ReadFileExA(hdr, lpBuffersOut, dwFlags, dwContext);
1991

1992
    WININET_Release(hdr);
1993

1994 1995
    TRACE("-- %s (%u, bytes read: %d)\n", res == ERROR_SUCCESS ? "TRUE": "FALSE",
          res, lpBuffersOut->dwBufferLength);
1996

1997 1998 1999
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
2000 2001 2002 2003 2004
}

/***********************************************************************
 *           InternetReadFileExW (WININET.@)
 *
2005 2006 2007 2008 2009 2010 2011
 * Read data from an open internet file.
 *
 * PARAMS
 *  hFile         [I] Handle returned by InternetOpenUrl() or HttpOpenRequest().
 *  lpBuffersOut  [I/O] Buffer.
 *  dwFlags       [I] Flags.
 *  dwContext     [I] Context for callbacks.
2012 2013
 *
 * RETURNS
2014 2015 2016 2017
 *    FALSE, last error is set to ERROR_CALL_NOT_IMPLEMENTED
 *
 * NOTES
 *  Not implemented in Wine or native either (as of IE6 SP2).
2018 2019 2020
 *
 */
BOOL WINAPI InternetReadFileExW(HINTERNET hFile, LPINTERNET_BUFFERSW lpBuffer,
2021
	DWORD dwFlags, DWORD_PTR dwContext)
2022
{
2023
  ERR("(%p, %p, 0x%x, 0x%lx): not implemented in native\n", hFile, lpBuffer, dwFlags, dwContext);
2024 2025 2026 2027

  INTERNET_SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
  return FALSE;
}
2028

2029 2030
DWORD INET_QueryOption(DWORD option, void *buffer, DWORD *size, BOOL unicode)
{
2031 2032
    static BOOL warn = TRUE;

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
    switch(option) {
    case INTERNET_OPTION_REQUEST_FLAGS:
        TRACE("INTERNET_OPTION_REQUEST_FLAGS\n");

        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;

        *(ULONG*)buffer = 4;
        *size = sizeof(ULONG);

        return ERROR_SUCCESS;

    case INTERNET_OPTION_HTTP_VERSION:
        if (*size < sizeof(HTTP_VERSION_INFO))
            return ERROR_INSUFFICIENT_BUFFER;

        /*
         * Presently hardcoded to 1.1
         */
        ((HTTP_VERSION_INFO*)buffer)->dwMajorVersion = 1;
        ((HTTP_VERSION_INFO*)buffer)->dwMinorVersion = 1;
        *size = sizeof(HTTP_VERSION_INFO);

        return ERROR_SUCCESS;

    case INTERNET_OPTION_CONNECTED_STATE:

2060 2061 2062 2063
        if (warn) {
            FIXME("INTERNET_OPTION_CONNECTED_STATE: semi-stub\n");
            warn = FALSE;
        }
2064 2065 2066 2067 2068 2069 2070
        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;

        *(ULONG*)buffer = INTERNET_STATE_CONNECTED;
        *size = sizeof(ULONG);

        return ERROR_SUCCESS;
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080

    case INTERNET_OPTION_PROXY: {
        WININETAPPINFOW ai;

        TRACE("Getting global proxy info\n");
        memset(&ai, 0, sizeof(WININETAPPINFOW));
        INTERNET_ConfigureProxy(&ai);

        return APPINFO_QueryOption(&ai.hdr, INTERNET_OPTION_PROXY, buffer, size, unicode); /* FIXME */
    }
2081

2082 2083
    case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
        TRACE("INTERNET_OPTION_MAX_CONNS_PER_SERVER\n");
2084

2085 2086
        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;
2087

2088 2089
        *(ULONG*)buffer = 2;
        *size = sizeof(ULONG);
2090

2091
        return ERROR_SUCCESS;
2092

2093 2094
    case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
            TRACE("INTERNET_OPTION_MAX_CONNS_1_0_SERVER\n");
2095

2096 2097
            if (*size < sizeof(ULONG))
                return ERROR_INSUFFICIENT_BUFFER;
2098

2099 2100
            *(ULONG*)size = 4;
            *size = sizeof(ULONG);
2101

2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
            return ERROR_SUCCESS;

    case INTERNET_OPTION_SECURITY_FLAGS:
        FIXME("INTERNET_OPTION_SECURITY_FLAGS: Stub\n");
        return ERROR_SUCCESS;

    case INTERNET_OPTION_VERSION: {
        static const INTERNET_VERSION_INFO info = { 1, 2 };

        TRACE("INTERNET_OPTION_VERSION\n");

        if (*size < sizeof(INTERNET_VERSION_INFO))
            return ERROR_INSUFFICIENT_BUFFER;

        memcpy(buffer, &info, sizeof(info));
        *size = sizeof(info);

        return ERROR_SUCCESS;
    }

    case INTERNET_OPTION_PER_CONNECTION_OPTION: {
        INTERNET_PER_CONN_OPTION_LISTW *con = buffer;
        DWORD res = ERROR_SUCCESS, i;

        FIXME("INTERNET_OPTION_PER_CONNECTION_OPTION stub\n");

        if (*size < sizeof(INTERNET_PER_CONN_OPTION_LISTW))
            return ERROR_INSUFFICIENT_BUFFER;

        for (i = 0; i < con->dwOptionCount; i++) {
            INTERNET_PER_CONN_OPTIONW *option = con->pOptions + i;

            switch (option->dwOption) {
            case INTERNET_PER_CONN_FLAGS:
                option->Value.dwValue = PROXY_TYPE_DIRECT;
                break;

            case INTERNET_PER_CONN_PROXY_SERVER:
            case INTERNET_PER_CONN_PROXY_BYPASS:
            case INTERNET_PER_CONN_AUTOCONFIG_URL:
            case INTERNET_PER_CONN_AUTODISCOVERY_FLAGS:
            case INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL:
            case INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS:
            case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME:
            case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL:
                FIXME("Unhandled dwOption %d\n", option->dwOption);
                option->Value.dwValue = 0;
                res = ERROR_INVALID_PARAMETER;
                break;

            default:
                FIXME("Unknown dwOption %d\n", option->dwOption);
                res = ERROR_INVALID_PARAMETER;
                break;
            }
2157
        }
2158 2159 2160

        return res;
    }
2161 2162
    }

2163 2164
    FIXME("Stub for %d\n", option);
    return ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2165 2166
}

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
/***********************************************************************
 *           InternetQueryOptionW (WININET.@)
 *
 * Queries an options on the specified handle
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI InternetQueryOptionW(HINTERNET hInternet, DWORD dwOption,
                                 LPVOID lpBuffer, LPDWORD lpdwBufferLength)
{
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
    LPWININETHANDLEHEADER hdr;
    DWORD res = ERROR_INVALID_HANDLE;

    TRACE("%p %d %p %p\n", hInternet, dwOption, lpBuffer, lpdwBufferLength);

    if(hInternet) {
        hdr = WININET_GetObject(hInternet);
        if (hdr) {
            res = hdr->vtbl->QueryOption(hdr, dwOption, lpBuffer, lpdwBufferLength, TRUE);
            WININET_Release(hdr);
        }
    }else {
        res = INET_QueryOption(dwOption, lpBuffer, lpdwBufferLength, TRUE);
    }

    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
}

/***********************************************************************
 *           InternetQueryOptionA (WININET.@)
 *
 * Queries an options on the specified handle
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI InternetQueryOptionA(HINTERNET hInternet, DWORD dwOption,
                                 LPVOID lpBuffer, LPDWORD lpdwBufferLength)
{
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
    LPWININETHANDLEHEADER hdr;
    DWORD res = ERROR_INVALID_HANDLE;

    TRACE("%p %d %p %p\n", hInternet, dwOption, lpBuffer, lpdwBufferLength);

    if(hInternet) {
        hdr = WININET_GetObject(hInternet);
        if (hdr) {
            res = hdr->vtbl->QueryOption(hdr, dwOption, lpBuffer, lpdwBufferLength, FALSE);
            WININET_Release(hdr);
        }
    }else {
        res = INET_QueryOption(dwOption, lpBuffer, lpdwBufferLength, FALSE);
    }

    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
2231 2232
}

2233

2234
/***********************************************************************
2235
 *           InternetSetOptionW (WININET.@)
2236 2237 2238 2239 2240 2241 2242 2243
 *
 * Sets an options on the specified handle
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
2244
BOOL WINAPI InternetSetOptionW(HINTERNET hInternet, DWORD dwOption,
2245 2246 2247
                           LPVOID lpBuffer, DWORD dwBufferLength)
{
    LPWININETHANDLEHEADER lpwhh;
2248
    BOOL ret = TRUE;
2249

2250
    TRACE("(%p %d %p %d)\n", hInternet, dwOption, lpBuffer, dwBufferLength);
2251

2252
    lpwhh = (LPWININETHANDLEHEADER) WININET_GetObject( hInternet );
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
    if(lpwhh && lpwhh->vtbl->SetOption) {
        DWORD res;

        res = lpwhh->vtbl->SetOption(lpwhh, dwOption, lpBuffer, dwBufferLength);
        if(res != ERROR_INTERNET_INVALID_OPTION) {
            WININET_Release( lpwhh );

            if(res != ERROR_SUCCESS)
                SetLastError(res);

            return res == ERROR_SUCCESS;
        }
    }
2266 2267 2268

    switch (dwOption)
    {
2269 2270
    case INTERNET_OPTION_CALLBACK:
      {
2271 2272 2273 2274 2275 2276 2277 2278
        if (!lpwhh)
        {
            INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
            return FALSE;
        }
        WININET_Release(lpwhh);
        INTERNET_SetLastError(ERROR_INTERNET_OPTION_NOT_SETTABLE);
        return FALSE;
2279
      }
2280 2281 2282
    case INTERNET_OPTION_HTTP_VERSION:
      {
        HTTP_VERSION_INFO* pVersion=(HTTP_VERSION_INFO*)lpBuffer;
2283
        FIXME("Option INTERNET_OPTION_HTTP_VERSION(%d,%d): STUB\n",pVersion->dwMajorVersion,pVersion->dwMinorVersion);
2284 2285 2286 2287
      }
      break;
    case INTERNET_OPTION_ERROR_MASK:
      {
2288 2289
        ULONG flags = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_ERROR_MASK(%d): STUB\n", flags);
2290 2291 2292 2293
      }
      break;
    case INTERNET_OPTION_CODEPAGE:
      {
2294 2295
        ULONG codepage = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_CODEPAGE (%d): STUB\n", codepage);
2296 2297 2298 2299
      }
      break;
    case INTERNET_OPTION_REQUEST_PRIORITY:
      {
2300 2301
        ULONG priority = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_REQUEST_PRIORITY (%d): STUB\n", priority);
2302 2303
      }
      break;
2304 2305
    case INTERNET_OPTION_CONNECT_TIMEOUT:
      {
2306 2307
        ULONG connecttimeout = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_CONNECT_TIMEOUT (%d): STUB\n", connecttimeout);
2308 2309 2310 2311
      }
      break;
    case INTERNET_OPTION_DATA_RECEIVE_TIMEOUT:
      {
2312 2313
        ULONG receivetimeout = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_DATA_RECEIVE_TIMEOUT (%d): STUB\n", receivetimeout);
2314 2315
      }
      break;
2316 2317
    case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
      {
2318 2319
        ULONG conns = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_MAX_CONNS_PER_SERVER (%d): STUB\n", conns);
2320 2321 2322 2323
      }
      break;
    case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
      {
2324 2325
        ULONG conns = *(ULONG *)lpBuffer;
        FIXME("Option INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER (%d): STUB\n", conns);
2326 2327
      }
      break;
2328 2329 2330 2331 2332 2333 2334 2335 2336
    case INTERNET_OPTION_RESET_URLCACHE_SESSION:
        FIXME("Option INTERNET_OPTION_RESET_URLCACHE_SESSION: STUB\n");
        break;
    case INTERNET_OPTION_END_BROWSER_SESSION:
        FIXME("Option INTERNET_OPTION_END_BROWSER_SESSION: STUB\n");
        break;
    case INTERNET_OPTION_CONNECTED_STATE:
        FIXME("Option INTERNET_OPTION_CONNECTED_STATE: STUB\n");
        break;
2337 2338 2339
    case INTERNET_OPTION_DISABLE_PASSPORT_AUTH:
	TRACE("Option INTERNET_OPTION_DISABLE_PASSPORT_AUTH: harmless stub, since not enabled\n");
	break;
2340
    case INTERNET_OPTION_SEND_TIMEOUT:
2341
    case INTERNET_OPTION_RECEIVE_TIMEOUT:
2342 2343 2344
    {
        ULONG timeout = *(ULONG *)lpBuffer;
        FIXME("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT %d\n", timeout);
2345
        break;
2346
    }
2347
    case INTERNET_OPTION_CONNECT_RETRIES:
2348 2349 2350
    {
        ULONG retries = *(ULONG *)lpBuffer;
        FIXME("INTERNET_OPTION_CONNECT_RETRIES %d\n", retries);
2351
        break;
2352
    }
2353 2354 2355
    case INTERNET_OPTION_CONTEXT_VALUE:
	 FIXME("Option INTERNET_OPTION_CONTEXT_VALUE; STUB\n");
	 break;
2356 2357 2358
    case INTERNET_OPTION_SECURITY_FLAGS:
	 FIXME("Option INTERNET_OPTION_SECURITY_FLAGS; STUB\n");
	 break;
2359 2360 2361
    case INTERNET_OPTION_DISABLE_AUTODIAL:
	 FIXME("Option INTERNET_OPTION_DISABLE_AUTODIAL; STUB\n");
	 break;
2362 2363 2364
    case 86:
        FIXME("86\n");
        break;
2365
    default:
2366
        FIXME("Option %d STUB\n",dwOption);
2367
        INTERNET_SetLastError(ERROR_INTERNET_INVALID_OPTION);
2368 2369
        ret = FALSE;
        break;
2370
    }
2371 2372 2373

    if(lpwhh)
        WININET_Release( lpwhh );
2374

2375
    return ret;
2376 2377 2378 2379
}


/***********************************************************************
2380
 *           InternetSetOptionA (WININET.@)
2381 2382 2383 2384 2385 2386 2387 2388
 *
 * Sets an options on the specified handle.
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
2389
BOOL WINAPI InternetSetOptionA(HINTERNET hInternet, DWORD dwOption,
2390 2391
                           LPVOID lpBuffer, DWORD dwBufferLength)
{
2392 2393 2394 2395 2396 2397
    LPVOID wbuffer;
    DWORD wlen;
    BOOL r;

    switch( dwOption )
    {
2398 2399 2400 2401
    case INTERNET_OPTION_CALLBACK:
        {
        LPWININETHANDLEHEADER lpwh;

2402 2403 2404 2405 2406
        if (!(lpwh = WININET_GetObject(hInternet)))
        {
            INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
            return FALSE;
        }
2407
        WININET_Release(lpwh);
2408 2409
        INTERNET_SetLastError(ERROR_INTERNET_OPTION_NOT_SETTABLE);
        return FALSE;
2410
        }
2411 2412 2413 2414 2415 2416 2417 2418 2419
    case INTERNET_OPTION_PROXY:
        {
        LPINTERNET_PROXY_INFOA pi = (LPINTERNET_PROXY_INFOA) lpBuffer;
        LPINTERNET_PROXY_INFOW piw;
        DWORD proxlen, prbylen;
        LPWSTR prox, prby;

        proxlen = MultiByteToWideChar( CP_ACP, 0, pi->lpszProxy, -1, NULL, 0);
        prbylen= MultiByteToWideChar( CP_ACP, 0, pi->lpszProxyBypass, -1, NULL, 0);
2420
        wlen = sizeof(*piw) + proxlen + prbylen;
2421
        wbuffer = HeapAlloc( GetProcessHeap(), 0, wlen*sizeof(WCHAR) );
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
        piw = (LPINTERNET_PROXY_INFOW) wbuffer;
        piw->dwAccessType = pi->dwAccessType;
        prox = (LPWSTR) &piw[1];
        prby = &prox[proxlen+1];
        MultiByteToWideChar( CP_ACP, 0, pi->lpszProxy, -1, prox, proxlen);
        MultiByteToWideChar( CP_ACP, 0, pi->lpszProxyBypass, -1, prby, prbylen);
        piw->lpszProxy = prox;
        piw->lpszProxyBypass = prby;
        }
        break;
    case INTERNET_OPTION_USER_AGENT:
    case INTERNET_OPTION_USERNAME:
    case INTERNET_OPTION_PASSWORD:
        wlen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, dwBufferLength,
                                   NULL, 0 );
2437
        wbuffer = HeapAlloc( GetProcessHeap(), 0, wlen*sizeof(WCHAR) );
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
        MultiByteToWideChar( CP_ACP, 0, lpBuffer, dwBufferLength,
                                   wbuffer, wlen );
        break;
    default:
        wbuffer = lpBuffer;
        wlen = dwBufferLength;
    }

    r = InternetSetOptionW(hInternet,dwOption, wbuffer, wlen);

    if( lpBuffer != wbuffer )
        HeapFree( GetProcessHeap(), 0, wbuffer );

    return r;
}


/***********************************************************************
 *           InternetSetOptionExA (WININET.@)
 */
BOOL WINAPI InternetSetOptionExA(HINTERNET hInternet, DWORD dwOption,
                           LPVOID lpBuffer, DWORD dwBufferLength, DWORD dwFlags)
{
2461
    FIXME("Flags %08x ignored\n", dwFlags);
2462 2463 2464 2465 2466 2467 2468 2469 2470
    return InternetSetOptionA( hInternet, dwOption, lpBuffer, dwBufferLength );
}

/***********************************************************************
 *           InternetSetOptionExW (WININET.@)
 */
BOOL WINAPI InternetSetOptionExW(HINTERNET hInternet, DWORD dwOption,
                           LPVOID lpBuffer, DWORD dwBufferLength, DWORD dwFlags)
{
2471
    FIXME("Flags %08x ignored\n", dwFlags);
2472 2473
    if( dwFlags & ~ISO_VALID_FLAGS )
    {
2474
        INTERNET_SetLastError( ERROR_INVALID_PARAMETER );
2475 2476 2477
        return FALSE;
    }
    return InternetSetOptionW( hInternet, dwOption, lpBuffer, dwBufferLength );
2478 2479
}

2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
static const WCHAR WININET_wkday[7][4] =
    { { 'S','u','n', 0 }, { 'M','o','n', 0 }, { 'T','u','e', 0 }, { 'W','e','d', 0 },
      { 'T','h','u', 0 }, { 'F','r','i', 0 }, { 'S','a','t', 0 } };
static const WCHAR WININET_month[12][4] =
    { { 'J','a','n', 0 }, { 'F','e','b', 0 }, { 'M','a','r', 0 }, { 'A','p','r', 0 },
      { 'M','a','y', 0 }, { 'J','u','n', 0 }, { 'J','u','l', 0 }, { 'A','u','g', 0 },
      { 'S','e','p', 0 }, { 'O','c','t', 0 }, { 'N','o','v', 0 }, { 'D','e','c', 0 } };

/***********************************************************************
 *           InternetTimeFromSystemTimeA (WININET.@)
 */
BOOL WINAPI InternetTimeFromSystemTimeA( const SYSTEMTIME* time, DWORD format, LPSTR string, DWORD size )
{
    BOOL ret;
    WCHAR stringW[INTERNET_RFC1123_BUFSIZE];

2496
    TRACE( "%p 0x%08x %p 0x%08x\n", time, format, string, size );
2497

2498 2499 2500 2501 2502 2503
    if (!time || !string || format != INTERNET_RFC1123_FORMAT)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

2504 2505 2506 2507 2508 2509
    if (size < INTERNET_RFC1123_BUFSIZE * sizeof(*string))
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
    ret = InternetTimeFromSystemTimeW( time, format, stringW, sizeof(stringW) );
    if (ret) WideCharToMultiByte( CP_ACP, 0, stringW, -1, string, size, NULL, NULL );

    return ret;
}

/***********************************************************************
 *           InternetTimeFromSystemTimeW (WININET.@)
 */
BOOL WINAPI InternetTimeFromSystemTimeW( const SYSTEMTIME* time, DWORD format, LPWSTR string, DWORD size )
{
    static const WCHAR date[] =
        { '%','s',',',' ','%','0','2','d',' ','%','s',' ','%','4','d',' ','%','0',
          '2','d',':','%','0','2','d',':','%','0','2','d',' ','G','M','T', 0 };

2525
    TRACE( "%p 0x%08x %p 0x%08x\n", time, format, string, size );
2526

2527
    if (!time || !string || format != INTERNET_RFC1123_FORMAT)
2528 2529
    {
        SetLastError(ERROR_INVALID_PARAMETER);
2530
        return FALSE;
2531
    }
2532

2533 2534 2535
    if (size < INTERNET_RFC1123_BUFSIZE * sizeof(*string))
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
2536
        return FALSE;
2537
    }
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559

    sprintfW( string, date,
              WININET_wkday[time->wDayOfWeek],
              time->wDay,
              WININET_month[time->wMonth - 1],
              time->wYear,
              time->wHour,
              time->wMinute,
              time->wSecond );

    return TRUE;
}

/***********************************************************************
 *           InternetTimeToSystemTimeA (WININET.@)
 */
BOOL WINAPI InternetTimeToSystemTimeA( LPCSTR string, SYSTEMTIME* time, DWORD reserved )
{
    BOOL ret = FALSE;
    WCHAR *stringW;
    int len;

2560
    TRACE( "%s %p 0x%08x\n", debugstr_a(string), time, reserved );
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579

    len = MultiByteToWideChar( CP_ACP, 0, string, -1, NULL, 0 );
    stringW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );

    if (stringW)
    {
        MultiByteToWideChar( CP_ACP, 0, string, -1, stringW, len );
        ret = InternetTimeToSystemTimeW( stringW, time, reserved );
        HeapFree( GetProcessHeap(), 0, stringW );
    }
    return ret;
}

/***********************************************************************
 *           InternetTimeToSystemTimeW (WININET.@)
 */
BOOL WINAPI InternetTimeToSystemTimeW( LPCWSTR string, SYSTEMTIME* time, DWORD reserved )
{
    unsigned int i;
2580 2581
    const WCHAR *s = string;
    WCHAR       *end;
2582

2583
    TRACE( "%s %p 0x%08x\n", debugstr_w(string), time, reserved );
2584

2585 2586 2587 2588
    if (!string || !time) return FALSE;

    /* Windows does this too */
    GetSystemTime( time );
2589 2590 2591 2592 2593 2594

    /*  Convert an RFC1123 time such as 'Fri, 07 Jan 2005 12:06:35 GMT' into
     *  a SYSTEMTIME structure.
     */

    while (*s && !isalphaW( *s )) s++;
2595
    if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0') return TRUE;
2596 2597 2598 2599
    time->wDayOfWeek = 7;

    for (i = 0; i < 7; i++)
    {
2600 2601 2602
        if (toupperW( WININET_wkday[i][0] ) == toupperW( s[0] ) &&
            toupperW( WININET_wkday[i][1] ) == toupperW( s[1] ) &&
            toupperW( WININET_wkday[i][2] ) == toupperW( s[2] ) )
2603 2604 2605 2606 2607 2608
        {
            time->wDayOfWeek = i;
            break;
        }
    }

2609
    if (time->wDayOfWeek > 6) return TRUE;
2610
    while (*s && !isdigitW( *s )) s++;
2611 2612
    time->wDay = strtolW( s, &end, 10 );
    s = end;
2613 2614

    while (*s && !isalphaW( *s )) s++;
2615
    if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0') return TRUE;
2616 2617 2618 2619
    time->wMonth = 0;

    for (i = 0; i < 12; i++)
    {
2620 2621 2622
        if (toupperW( WININET_month[i][0]) == toupperW( s[0] ) &&
            toupperW( WININET_month[i][1]) == toupperW( s[1] ) &&
            toupperW( WININET_month[i][2]) == toupperW( s[2] ) )
2623 2624 2625 2626 2627
        {
            time->wMonth = i + 1;
            break;
        }
    }
2628
    if (time->wMonth == 0) return TRUE;
2629 2630

    while (*s && !isdigitW( *s )) s++;
2631
    if (*s == '\0') return TRUE;
2632 2633
    time->wYear = strtolW( s, &end, 10 );
    s = end;
2634 2635

    while (*s && !isdigitW( *s )) s++;
2636
    if (*s == '\0') return TRUE;
2637 2638
    time->wHour = strtolW( s, &end, 10 );
    s = end;
2639 2640

    while (*s && !isdigitW( *s )) s++;
2641
    if (*s == '\0') return TRUE;
2642 2643
    time->wMinute = strtolW( s, &end, 10 );
    s = end;
2644 2645

    while (*s && !isdigitW( *s )) s++;
2646
    if (*s == '\0') return TRUE;
2647 2648
    time->wSecond = strtolW( s, &end, 10 );
    s = end;
2649 2650 2651 2652

    time->wMilliseconds = 0;
    return TRUE;
}
2653

2654
/***********************************************************************
2655
 *	InternetCheckConnectionW (WININET.@)
2656 2657 2658 2659
 *
 * Pings a requested host to check internet connection
 *
 * RETURNS
2660
 *   TRUE on success and FALSE on failure. If a failure then
2661
 *   ERROR_NOT_CONNECTED is placed into GetLastError
2662 2663
 *
 */
2664
BOOL WINAPI InternetCheckConnectionW( LPCWSTR lpszUrl, DWORD dwFlags, DWORD dwReserved )
2665 2666 2667 2668 2669 2670 2671 2672
{
/*
 * this is a kludge which runs the resident ping program and reads the output.
 *
 * Anyone have a better idea?
 */

  BOOL   rc = FALSE;
2673
  static const CHAR ping[] = "ping -c 1 ";
2674 2675 2676 2677
  static const CHAR redirect[] = " >/dev/null 2>/dev/null";
  CHAR *command = NULL;
  WCHAR hostW[1024];
  DWORD len;
2678
  INTERNET_PORT port;
2679 2680
  int status = -1;

2681 2682
  FIXME("\n");

2683
  /*
2684 2685 2686 2687
   * Crack or set the Address
   */
  if (lpszUrl == NULL)
  {
2688
     /*
Austin English's avatar
Austin English committed
2689
      * According to the doc we are supposed to use the ip for the next
2690
      * server in the WnInet internal server database. I have
2691 2692 2693 2694
      * no idea what that is or how to get it.
      *
      * So someone needs to implement this.
      */
2695
     FIXME("Unimplemented with URL of NULL\n");
2696 2697 2698 2699
     return TRUE;
  }
  else
  {
2700
     URL_COMPONENTSW components;
2701

2702
     ZeroMemory(&components,sizeof(URL_COMPONENTSW));
2703
     components.lpszHostName = (LPWSTR)hostW;
2704
     components.dwHostNameLength = 1024;
2705

2706
     if (!InternetCrackUrlW(lpszUrl,0,0,&components))
2707
       goto End;
2708

2709
     TRACE("host name : %s\n",debugstr_w(components.lpszHostName));
2710 2711
     port = components.nPort;
     TRACE("port: %d\n", port);
2712 2713
  }

2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738
  if (dwFlags & FLAG_ICC_FORCE_CONNECTION)
  {
      struct sockaddr_in sin;
      int fd;

      if (!GetAddress(hostW, port, &sin))
          goto End;
      fd = socket(sin.sin_family, SOCK_STREAM, 0);
      if (fd != -1)
      {
          if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) == 0)
              rc = TRUE;
          close(fd);
      }
  }
  else
  {
      /*
       * Build our ping command
       */
      len = WideCharToMultiByte(CP_UNIXCP, 0, hostW, -1, NULL, 0, NULL, NULL);
      command = HeapAlloc( GetProcessHeap(), 0, strlen(ping)+len+strlen(redirect) );
      strcpy(command,ping);
      WideCharToMultiByte(CP_UNIXCP, 0, hostW, -1, command+strlen(ping), len, NULL, NULL);
      strcat(command,redirect);
2739

2740
      TRACE("Ping command is : %s\n",command);
2741

2742
      status = system(command);
2743

2744
      TRACE("Ping returned a code of %i\n",status);
2745

2746 2747 2748 2749
      /* Ping return code of 0 indicates success */
      if (status == 0)
         rc = TRUE;
  }
2750 2751

End:
2752

2753
  HeapFree( GetProcessHeap(), 0, command );
2754
  if (rc == FALSE)
2755
    INTERNET_SetLastError(ERROR_NOT_CONNECTED);
2756 2757 2758 2759

  return rc;
}

2760 2761

/***********************************************************************
2762
 *	InternetCheckConnectionA (WININET.@)
2763 2764 2765 2766 2767 2768 2769 2770
 *
 * Pings a requested host to check internet connection
 *
 * RETURNS
 *   TRUE on success and FALSE on failure. If a failure then
 *   ERROR_NOT_CONNECTED is placed into GetLastError
 *
 */
2771
BOOL WINAPI InternetCheckConnectionA(LPCSTR lpszUrl, DWORD dwFlags, DWORD dwReserved)
2772
{
2773
    WCHAR *szUrl;
2774 2775 2776
    INT len;
    BOOL rc;

2777 2778
    len = MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, NULL, 0);
    if (!(szUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
2779
        return FALSE;
2780 2781
    MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, szUrl, len);
    rc = InternetCheckConnectionW(szUrl, dwFlags, dwReserved);
2782
    HeapFree(GetProcessHeap(), 0, szUrl);
2783 2784 2785 2786 2787
    
    return rc;
}


2788
/**********************************************************
2789
 *	INTERNET_InternetOpenUrlW (internal)
2790 2791
 *
 * Opens an URL
2792
 *
2793 2794 2795
 * RETURNS
 *   handle of connection or NULL on failure
 */
2796
static HINTERNET INTERNET_InternetOpenUrlW(LPWININETAPPINFOW hIC, LPCWSTR lpszUrl,
2797
    LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
2798
{
2799 2800 2801
    URL_COMPONENTSW urlComponents;
    WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
    WCHAR password[1024], path[2048], extra[1024];
2802 2803
    HINTERNET client = NULL, client1 = NULL;
    
2804
    TRACE("(%p, %s, %s, %08x, %08x, %08lx)\n", hIC, debugstr_w(lpszUrl), debugstr_w(lpszHeaders),
2805 2806
	  dwHeadersLength, dwFlags, dwContext);
    
2807
    urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
    urlComponents.lpszScheme = protocol;
    urlComponents.dwSchemeLength = 32;
    urlComponents.lpszHostName = hostName;
    urlComponents.dwHostNameLength = MAXHOSTNAME;
    urlComponents.lpszUserName = userName;
    urlComponents.dwUserNameLength = 1024;
    urlComponents.lpszPassword = password;
    urlComponents.dwPasswordLength = 1024;
    urlComponents.lpszUrlPath = path;
    urlComponents.dwUrlPathLength = 2048;
    urlComponents.lpszExtraInfo = extra;
    urlComponents.dwExtraInfoLength = 1024;
2820
    if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
2821 2822 2823 2824 2825
	return NULL;
    switch(urlComponents.nScheme) {
    case INTERNET_SCHEME_FTP:
	if(urlComponents.nPort == 0)
	    urlComponents.nPort = INTERNET_DEFAULT_FTP_PORT;
2826
	client = FTP_Connect(hIC, hostName, urlComponents.nPort,
2827
			     userName, password, dwFlags, dwContext, INET_OPENURL);
2828 2829
	if(client == NULL)
	    break;
2830
	client1 = FtpOpenFileW(client, path, GENERIC_READ, dwFlags, dwContext);
2831 2832 2833 2834
	if(client1 == NULL) {
	    InternetCloseHandle(client);
	    break;
	}
2835 2836 2837 2838
	break;
	
    case INTERNET_SCHEME_HTTP:
    case INTERNET_SCHEME_HTTPS: {
2839
	static const WCHAR szStars[] = { '*','/','*', 0 };
2840
	LPCWSTR accept[2] = { szStars, NULL };
2841 2842 2843 2844 2845 2846
	if(urlComponents.nPort == 0) {
	    if(urlComponents.nScheme == INTERNET_SCHEME_HTTP)
		urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
	    else
		urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
	}
2847 2848
        /* FIXME: should use pointers, not handles, as handles are not thread-safe */
	client = HTTP_Connect(hIC, hostName, urlComponents.nPort,
2849
			      userName, password, dwFlags, dwContext, INET_OPENURL);
2850 2851
	if(client == NULL)
	    break;
2852 2853 2854

	if (urlComponents.dwExtraInfoLength) {
		WCHAR *path_extra;
2855
		DWORD len = urlComponents.dwUrlPathLength + urlComponents.dwExtraInfoLength + 1;
2856

2857
		if (!(path_extra = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
		{
			InternetCloseHandle(client);
			break;
		}
		strcpyW(path_extra, urlComponents.lpszUrlPath);
		strcatW(path_extra, urlComponents.lpszExtraInfo);
		client1 = HttpOpenRequestW(client, NULL, path_extra, NULL, NULL, accept, dwFlags, dwContext);
		HeapFree(GetProcessHeap(), 0, path_extra);
	}
	else
		client1 = HttpOpenRequestW(client, NULL, path, NULL, NULL, accept, dwFlags, dwContext);

2870 2871 2872 2873
	if(client1 == NULL) {
	    InternetCloseHandle(client);
	    break;
	}
2874
	HttpAddRequestHeadersW(client1, lpszHeaders, dwHeadersLength, HTTP_ADDREQ_FLAG_ADD);
2875 2876
	if (!HttpSendRequestW(client1, NULL, 0, NULL, 0) &&
            GetLastError() != ERROR_IO_PENDING) {
2877 2878 2879 2880
	    InternetCloseHandle(client1);
	    client1 = NULL;
	    break;
	}
2881
    }
2882 2883 2884 2885
    case INTERNET_SCHEME_GOPHER:
	/* gopher doesn't seem to be implemented in wine, but it's supposed
	 * to be supported by InternetOpenUrlA. */
    default:
2886
        INTERNET_SetLastError(ERROR_INTERNET_UNRECOGNIZED_SCHEME);
2887
	break;
2888
    }
2889 2890 2891

    TRACE(" %p <--\n", client1);
    
2892 2893
    return client1;
}
2894

2895
/**********************************************************
2896
 *	InternetOpenUrlW (WININET.@)
2897 2898 2899 2900 2901 2902
 *
 * Opens an URL
 *
 * RETURNS
 *   handle of connection or NULL on failure
 */
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
static void AsyncInternetOpenUrlProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_INTERNETOPENURLW const *req = &workRequest->u.InternetOpenUrlW;
    LPWININETAPPINFOW hIC = (LPWININETAPPINFOW) workRequest->hdr;

    TRACE("%p\n", hIC);

    INTERNET_InternetOpenUrlW(hIC, req->lpszUrl,
                              req->lpszHeaders, req->dwHeadersLength, req->dwFlags, req->dwContext);
    HeapFree(GetProcessHeap(), 0, req->lpszUrl);
    HeapFree(GetProcessHeap(), 0, req->lpszHeaders);
}

2916
HINTERNET WINAPI InternetOpenUrlW(HINTERNET hInternet, LPCWSTR lpszUrl,
2917
    LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
2918 2919
{
    HINTERNET ret = NULL;
2920
    LPWININETAPPINFOW hIC = NULL;
2921

Lionel Ulmer's avatar
Lionel Ulmer committed
2922
    if (TRACE_ON(wininet)) {
2923
	TRACE("(%p, %s, %s, %08x, %08x, %08lx)\n", hInternet, debugstr_w(lpszUrl), debugstr_w(lpszHeaders),
Lionel Ulmer's avatar
Lionel Ulmer committed
2924 2925 2926 2927 2928
	      dwHeadersLength, dwFlags, dwContext);
	TRACE("  flags :");
	dump_INTERNET_FLAGS(dwFlags);
    }

2929 2930
    if (!lpszUrl)
    {
2931
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2932 2933 2934
        goto lend;
    }

2935
    hIC = (LPWININETAPPINFOW) WININET_GetObject( hInternet );
2936 2937 2938 2939 2940 2941 2942
    if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT) {
	INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
 	goto lend;
    }
    
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC) {
	WORKREQUEST workRequest;
2943
	struct WORKREQ_INTERNETOPENURLW *req;
2944 2945

	workRequest.asyncproc = AsyncInternetOpenUrlProc;
2946
	workRequest.hdr = WININET_AddRef( &hIC->hdr );
2947
	req = &workRequest.u.InternetOpenUrlW;
2948
	req->lpszUrl = WININET_strdupW(lpszUrl);
2949
	if (lpszHeaders)
2950
	    req->lpszHeaders = WININET_strdupW(lpszHeaders);
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
	else
	    req->lpszHeaders = 0;
	req->dwHeadersLength = dwHeadersLength;
	req->dwFlags = dwFlags;
	req->dwContext = dwContext;
	
	INTERNET_AsyncCall(&workRequest);
	/*
	 * This is from windows.
	 */
2961
	INTERNET_SetLastError(ERROR_IO_PENDING);
2962
    } else {
2963
	ret = INTERNET_InternetOpenUrlW(hIC, lpszUrl, lpszHeaders, dwHeadersLength, dwFlags, dwContext);
2964 2965 2966
    }
    
  lend:
2967 2968
    if( hIC )
        WININET_Release( &hIC->hdr );
2969 2970 2971 2972
    TRACE(" %p <--\n", ret);
    
    return ret;
}
2973

2974
/**********************************************************
2975
 *	InternetOpenUrlA (WININET.@)
2976 2977 2978 2979 2980 2981
 *
 * Opens an URL
 *
 * RETURNS
 *   handle of connection or NULL on failure
 */
2982
HINTERNET WINAPI InternetOpenUrlA(HINTERNET hInternet, LPCSTR lpszUrl,
2983
    LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
2984
{
2985
    HINTERNET rc = NULL;
2986

2987 2988 2989 2990
    INT lenUrl;
    INT lenHeaders = 0;
    LPWSTR szUrl = NULL;
    LPWSTR szHeaders = NULL;
2991

2992 2993
    TRACE("\n");

2994 2995 2996 2997
    if(lpszUrl) {
        lenUrl = MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, NULL, 0 );
        szUrl = HeapAlloc(GetProcessHeap(), 0, lenUrl*sizeof(WCHAR));
        if(!szUrl)
2998
            return NULL;
2999
        MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, szUrl, lenUrl);
3000
    }
3001

3002 3003 3004 3005
    if(lpszHeaders) {
        lenHeaders = MultiByteToWideChar(CP_ACP, 0, lpszHeaders, dwHeadersLength, NULL, 0 );
        szHeaders = HeapAlloc(GetProcessHeap(), 0, lenHeaders*sizeof(WCHAR));
        if(!szHeaders) {
3006
            HeapFree(GetProcessHeap(), 0, szUrl);
3007
            return NULL;
3008 3009 3010 3011
        }
        MultiByteToWideChar(CP_ACP, 0, lpszHeaders, dwHeadersLength, szHeaders, lenHeaders);
    }
    
3012
    rc = InternetOpenUrlW(hInternet, szUrl, szHeaders,
3013
        lenHeaders, dwFlags, dwContext);
3014

3015 3016
    HeapFree(GetProcessHeap(), 0, szUrl);
    HeapFree(GetProcessHeap(), 0, szHeaders);
3017 3018 3019 3020 3021

    return rc;
}


3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
static LPWITHREADERROR INTERNET_AllocThreadError(void)
{
    LPWITHREADERROR lpwite = HeapAlloc(GetProcessHeap(), 0, sizeof(*lpwite));

    if (lpwite)
    {
        lpwite->dwError = 0;
        lpwite->response[0] = '\0';
    }

    if (!TlsSetValue(g_dwTlsErrIndex, lpwite))
    {
        HeapFree(GetProcessHeap(), 0, lpwite);
        return NULL;
    }

    return lpwite;
}


3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
/***********************************************************************
 *           INTERNET_SetLastError (internal)
 *
 * Set last thread specific error
 *
 * RETURNS
 *
 */
void INTERNET_SetLastError(DWORD dwError)
{
    LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);

3054
    if (!lpwite)
3055
        lpwite = INTERNET_AllocThreadError();
3056

3057
    SetLastError(dwError);
3058 3059
    if(lpwite)
        lpwite->dwError = dwError;
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
}


/***********************************************************************
 *           INTERNET_GetLastError (internal)
 *
 * Get last thread specific error
 *
 * RETURNS
 *
 */
3071
DWORD INTERNET_GetLastError(void)
3072 3073
{
    LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
3074
    if (!lpwite) return 0;
3075 3076
    /* TlsGetValue clears last error, so set it again here */
    SetLastError(lpwite->dwError);
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
    return lpwite->dwError;
}


/***********************************************************************
 *           INTERNET_WorkerThreadFunc (internal)
 *
 * Worker thread execution function
 *
 * RETURNS
 *
 */
3089
static DWORD CALLBACK INTERNET_WorkerThreadFunc(LPVOID lpvParam)
3090
{
3091 3092
    LPWORKREQUEST lpRequest = lpvParam;
    WORKREQUEST workRequest;
3093 3094 3095

    TRACE("\n");

3096
    workRequest = *lpRequest;
3097
    HeapFree(GetProcessHeap(), 0, lpRequest);
3098

3099
    workRequest.asyncproc(&workRequest);
3100

3101 3102
    WININET_Release( workRequest.hdr );
    return TRUE;
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
}


/***********************************************************************
 *           INTERNET_AsyncCall (internal)
 *
 * Retrieves work request from queue
 *
 * RETURNS
 *
 */
BOOL INTERNET_AsyncCall(LPWORKREQUEST lpWorkRequest)
{
3116 3117
    BOOL bSuccess;
    LPWORKREQUEST lpNewRequest;
3118 3119 3120

    TRACE("\n");

3121 3122 3123
    lpNewRequest = HeapAlloc(GetProcessHeap(), 0, sizeof(WORKREQUEST));
    if (!lpNewRequest)
        return FALSE;
3124

3125
    *lpNewRequest = *lpWorkRequest;
3126

3127 3128 3129 3130 3131
    bSuccess = QueueUserWorkItem(INTERNET_WorkerThreadFunc, lpNewRequest, WT_EXECUTELONGFUNCTION);
    if (!bSuccess)
    {
        HeapFree(GetProcessHeap(), 0, lpNewRequest);
        INTERNET_SetLastError(ERROR_INTERNET_ASYNC_THREAD_FAILED);
3132 3133 3134 3135 3136 3137 3138
    }

    return bSuccess;
}


/***********************************************************************
3139
 *          INTERNET_GetResponseBuffer  (internal)
3140 3141 3142 3143
 *
 * RETURNS
 *
 */
3144
LPSTR INTERNET_GetResponseBuffer(void)
3145 3146
{
    LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
3147
    if (!lpwite)
3148
        lpwite = INTERNET_AllocThreadError();
3149
    TRACE("\n");
3150 3151
    return lpwite->response;
}
3152 3153 3154 3155 3156 3157 3158

/***********************************************************************
 *           INTERNET_GetNextLine  (internal)
 *
 * Parse next line in directory string listing
 *
 * RETURNS
3159
 *   Pointer to beginning of next line
3160 3161 3162 3163
 *   NULL on failure
 *
 */

3164
LPSTR INTERNET_GetNextLine(INT nSocket, LPDWORD dwLen)
3165
{
3166
    struct pollfd pfd;
3167 3168
    BOOL bSuccess = FALSE;
    INT nRecv = 0;
3169
    LPSTR lpszBuffer = INTERNET_GetResponseBuffer();
3170 3171 3172

    TRACE("\n");

3173 3174
    pfd.fd = nSocket;
    pfd.events = POLLIN;
3175

3176
    while (nRecv < MAX_REPLY_LEN)
3177
    {
3178
        if (poll(&pfd,1, RESPONSE_TIMEOUT * 1000) > 0)
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
        {
            if (recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
            {
                INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
                goto lend;
            }

            if (lpszBuffer[nRecv] == '\n')
	    {
		bSuccess = TRUE;
                break;
	    }
            if (lpszBuffer[nRecv] != '\r')
                nRecv++;
        }
	else
	{
            INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
            goto lend;
3198
        }
3199 3200 3201 3202 3203 3204
    }

lend:
    if (bSuccess)
    {
        lpszBuffer[nRecv] = '\0';
3205
	*dwLen = nRecv - 1;
3206 3207 3208 3209 3210 3211 3212 3213
        TRACE(":%d %s\n", nRecv, lpszBuffer);
        return lpszBuffer;
    }
    else
    {
        return NULL;
    }
}
3214

3215 3216 3217 3218
/**********************************************************
 *	InternetQueryDataAvailable (WININET.@)
 *
 * Determines how much data is available to be read.
3219
 *
3220
 * RETURNS
3221 3222 3223 3224 3225 3226
 *   TRUE on success, FALSE if an error occurred. If
 *   INTERNET_FLAG_ASYNC was specified in InternetOpen, and
 *   no data is presently available, FALSE is returned with
 *   the last error ERROR_IO_PENDING; a callback with status
 *   INTERNET_STATUS_REQUEST_COMPLETE will be sent when more
 *   data is available.
3227 3228 3229
 */
BOOL WINAPI InternetQueryDataAvailable( HINTERNET hFile,
                                LPDWORD lpdwNumberOfBytesAvailble,
3230
                                DWORD dwFlags, DWORD_PTR dwContext)
3231
{
3232 3233
    WININETHANDLEHEADER *hdr;
    DWORD res;
3234

3235 3236 3237 3238 3239
    TRACE("(%p %p %x %lx)\n", hFile, lpdwNumberOfBytesAvailble, dwFlags, dwContext);

    hdr = WININET_GetObject( hFile );
    if (!hdr) {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
3240 3241 3242
        return FALSE;
    }

3243 3244 3245 3246 3247
    if(hdr->vtbl->QueryDataAvailable) {
        res = hdr->vtbl->QueryDataAvailable(hdr, lpdwNumberOfBytesAvailble, dwFlags, dwContext);
    }else {
        WARN("wrong handle\n");
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3248 3249
    }

3250 3251 3252 3253 3254
    WININET_Release(hdr);

    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
3255 3256 3257 3258
}


/***********************************************************************
3259
 *      InternetLockRequestFile (WININET.@)
3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
 */
BOOL WINAPI InternetLockRequestFile( HINTERNET hInternet, HANDLE
*lphLockReqHandle)
{
    FIXME("STUB\n");
    return FALSE;
}

BOOL WINAPI InternetUnlockRequestFile( HANDLE hLockHandle)
{
    FIXME("STUB\n");
    return FALSE;
}
3273 3274 3275


/***********************************************************************
3276
 *      InternetAutodial (WININET.@)
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
 *
 * On windows this function is supposed to dial the default internet
 * connection. We don't want to have Wine dial out to the internet so
 * we return TRUE by default. It might be nice to check if we are connected.
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3287
BOOL WINAPI InternetAutodial(DWORD dwFlags, HWND hwndParent)
3288 3289 3290 3291 3292 3293
{
    FIXME("STUB\n");

    /* Tell that we are connected to the internet. */
    return TRUE;
}
3294 3295

/***********************************************************************
3296
 *      InternetAutodialHangup (WININET.@)
3297
 *
3298
 * Hangs up a connection made with InternetAutodial
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
 *
 * PARAM
 *    dwReserved
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
BOOL WINAPI InternetAutodialHangup(DWORD dwReserved)
{
    FIXME("STUB\n");

    /* we didn't dial, we don't disconnect */
    return TRUE;
}
3314 3315

/***********************************************************************
3316
 *      InternetCombineUrlA (WININET.@)
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
 *
 * Combine a base URL with a relative URL
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */

BOOL WINAPI InternetCombineUrlA(LPCSTR lpszBaseUrl, LPCSTR lpszRelativeUrl,
                                LPSTR lpszBuffer, LPDWORD lpdwBufferLength,
                                DWORD dwFlags)
{
    HRESULT hr=S_OK;
3331

3332
    TRACE("(%s, %s, %p, %p, 0x%08x)\n", debugstr_a(lpszBaseUrl), debugstr_a(lpszRelativeUrl), lpszBuffer, lpdwBufferLength, dwFlags);
3333

3334 3335 3336 3337 3338 3339 3340 3341
    /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
    dwFlags ^= ICU_NO_ENCODE;
    hr=UrlCombineA(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);

    return (hr==S_OK);
}

/***********************************************************************
3342
 *      InternetCombineUrlW (WININET.@)
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
 *
 * Combine a base URL with a relative URL
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */

BOOL WINAPI InternetCombineUrlW(LPCWSTR lpszBaseUrl, LPCWSTR lpszRelativeUrl,
                                LPWSTR lpszBuffer, LPDWORD lpdwBufferLength,
                                DWORD dwFlags)
{
    HRESULT hr=S_OK;
3357

3358
    TRACE("(%s, %s, %p, %p, 0x%08x)\n", debugstr_w(lpszBaseUrl), debugstr_w(lpszRelativeUrl), lpszBuffer, lpdwBufferLength, dwFlags);
3359

3360 3361 3362 3363 3364 3365
    /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
    dwFlags ^= ICU_NO_ENCODE;
    hr=UrlCombineW(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);

    return (hr==S_OK);
}
3366

3367 3368 3369
/* max port num is 65535 => 5 digits */
#define MAX_WORD_DIGITS 5

3370 3371 3372 3373 3374
#define URL_GET_COMP_LENGTH(url, component) ((url)->dw##component##Length ? \
    (url)->dw##component##Length : strlenW((url)->lpsz##component))
#define URL_GET_COMP_LENGTHA(url, component) ((url)->dw##component##Length ? \
    (url)->dw##component##Length : strlen((url)->lpsz##component))

3375
static BOOL url_uses_default_port(INTERNET_SCHEME nScheme, INTERNET_PORT nPort)
3376
{
3377 3378
    if ((nScheme == INTERNET_SCHEME_HTTP) &&
        (nPort == INTERNET_DEFAULT_HTTP_PORT))
3379
        return TRUE;
3380 3381
    if ((nScheme == INTERNET_SCHEME_HTTPS) &&
        (nPort == INTERNET_DEFAULT_HTTPS_PORT))
3382
        return TRUE;
3383 3384
    if ((nScheme == INTERNET_SCHEME_FTP) &&
        (nPort == INTERNET_DEFAULT_FTP_PORT))
3385
        return TRUE;
3386 3387
    if ((nScheme == INTERNET_SCHEME_GOPHER) &&
        (nPort == INTERNET_DEFAULT_GOPHER_PORT))
3388 3389
        return TRUE;

3390 3391 3392
    if (nPort == INTERNET_INVALID_PORT_NUMBER)
        return TRUE;

3393 3394 3395
    return FALSE;
}

3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
/* opaque urls do not fit into the standard url hierarchy and don't have
 * two following slashes */
static inline BOOL scheme_is_opaque(INTERNET_SCHEME nScheme)
{
    return (nScheme != INTERNET_SCHEME_FTP) &&
           (nScheme != INTERNET_SCHEME_GOPHER) &&
           (nScheme != INTERNET_SCHEME_HTTP) &&
           (nScheme != INTERNET_SCHEME_HTTPS) &&
           (nScheme != INTERNET_SCHEME_FILE);
}

3407 3408 3409 3410 3411 3412 3413 3414
static LPCWSTR INTERNET_GetSchemeString(INTERNET_SCHEME scheme)
{
    int index;
    if (scheme < INTERNET_SCHEME_FIRST)
        return NULL;
    index = scheme - INTERNET_SCHEME_FIRST;
    if (index >= sizeof(url_schemes)/sizeof(url_schemes[0]))
        return NULL;
3415
    return (LPCWSTR)url_schemes[index];
3416 3417
}

3418 3419 3420 3421
/* we can calculate using ansi strings because we're just
 * calculating string length, not size
 */
static BOOL calc_url_length(LPURL_COMPONENTSW lpUrlComponents,
3422
                            LPDWORD lpdwUrlLength)
3423
{
3424 3425
    INTERNET_SCHEME nScheme;

3426 3427
    *lpdwUrlLength = 0;

3428
    if (lpUrlComponents->lpszScheme)
3429 3430 3431 3432 3433
    {
        DWORD dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Scheme);
        *lpdwUrlLength += dwLen;
        nScheme = GetInternetSchemeW(lpUrlComponents->lpszScheme, dwLen);
    }
3434 3435
    else
    {
3436 3437 3438 3439 3440 3441 3442
        LPCWSTR scheme;

        nScheme = lpUrlComponents->nScheme;

        if (nScheme == INTERNET_SCHEME_DEFAULT)
            nScheme = INTERNET_SCHEME_HTTP;
        scheme = INTERNET_GetSchemeString(nScheme);
3443 3444 3445
        *lpdwUrlLength += strlenW(scheme);
    }

3446 3447 3448
    (*lpdwUrlLength)++; /* ':' */
    if (!scheme_is_opaque(nScheme) || lpUrlComponents->lpszHostName)
        *lpdwUrlLength += strlen("//");
3449 3450 3451

    if (lpUrlComponents->lpszUserName)
    {
3452
        *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, UserName);
3453 3454 3455 3456 3457 3458
        *lpdwUrlLength += strlen("@");
    }
    else
    {
        if (lpUrlComponents->lpszPassword)
        {
3459
            INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3460 3461 3462 3463 3464 3465 3466
            return FALSE;
        }
    }

    if (lpUrlComponents->lpszPassword)
    {
        *lpdwUrlLength += strlen(":");
3467
        *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, Password);
3468 3469
    }

3470
    if (lpUrlComponents->lpszHostName)
3471
    {
3472
        *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, HostName);
3473 3474 3475

        if (!url_uses_default_port(nScheme, lpUrlComponents->nPort))
        {
3476
            char szPort[MAX_WORD_DIGITS+1];
3477 3478 3479 3480 3481 3482

            sprintf(szPort, "%d", lpUrlComponents->nPort);
            *lpdwUrlLength += strlen(szPort);
            *lpdwUrlLength += strlen(":");
        }

3483 3484 3485
        if (lpUrlComponents->lpszUrlPath && *lpUrlComponents->lpszUrlPath != '/')
            (*lpdwUrlLength)++; /* '/' */
    }
3486

3487 3488
    if (lpUrlComponents->lpszUrlPath)
        *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, UrlPath);
3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510

    return TRUE;
}

static void convert_urlcomp_atow(LPURL_COMPONENTSA lpUrlComponents, LPURL_COMPONENTSW urlCompW)
{
    INT len;

    ZeroMemory(urlCompW, sizeof(URL_COMPONENTSW));

    urlCompW->dwStructSize = sizeof(URL_COMPONENTSW);
    urlCompW->dwSchemeLength = lpUrlComponents->dwSchemeLength;
    urlCompW->nScheme = lpUrlComponents->nScheme;
    urlCompW->dwHostNameLength = lpUrlComponents->dwHostNameLength;
    urlCompW->nPort = lpUrlComponents->nPort;
    urlCompW->dwUserNameLength = lpUrlComponents->dwUserNameLength;
    urlCompW->dwPasswordLength = lpUrlComponents->dwPasswordLength;
    urlCompW->dwUrlPathLength = lpUrlComponents->dwUrlPathLength;
    urlCompW->dwExtraInfoLength = lpUrlComponents->dwExtraInfoLength;

    if (lpUrlComponents->lpszScheme)
    {
3511
        len = URL_GET_COMP_LENGTHA(lpUrlComponents, Scheme) + 1;
3512 3513 3514 3515 3516 3517 3518
        urlCompW->lpszScheme = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszScheme,
                            -1, urlCompW->lpszScheme, len);
    }

    if (lpUrlComponents->lpszHostName)
    {
3519
        len = URL_GET_COMP_LENGTHA(lpUrlComponents, HostName) + 1;
3520 3521 3522 3523 3524 3525 3526
        urlCompW->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszHostName,
                            -1, urlCompW->lpszHostName, len);
    }

    if (lpUrlComponents->lpszUserName)
    {
3527
        len = URL_GET_COMP_LENGTHA(lpUrlComponents, UserName) + 1;
3528 3529 3530 3531 3532 3533 3534
        urlCompW->lpszUserName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszUserName,
                            -1, urlCompW->lpszUserName, len);
    }

    if (lpUrlComponents->lpszPassword)
    {
3535
        len = URL_GET_COMP_LENGTHA(lpUrlComponents, Password) + 1;
3536 3537 3538 3539 3540 3541 3542
        urlCompW->lpszPassword = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszPassword,
                            -1, urlCompW->lpszPassword, len);
    }

    if (lpUrlComponents->lpszUrlPath)
    {
3543
        len = URL_GET_COMP_LENGTHA(lpUrlComponents, UrlPath) + 1;
3544 3545 3546 3547 3548 3549 3550
        urlCompW->lpszUrlPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszUrlPath,
                            -1, urlCompW->lpszUrlPath, len);
    }

    if (lpUrlComponents->lpszExtraInfo)
    {
3551
        len = URL_GET_COMP_LENGTHA(lpUrlComponents, ExtraInfo) + 1;
3552 3553 3554 3555 3556 3557
        urlCompW->lpszExtraInfo = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszExtraInfo,
                            -1, urlCompW->lpszExtraInfo, len);
    }
}

3558
/***********************************************************************
3559
 *      InternetCreateUrlA (WININET.@)
3560
 *
3561
 * See InternetCreateUrlW.
3562
 */
3563 3564 3565
BOOL WINAPI InternetCreateUrlA(LPURL_COMPONENTSA lpUrlComponents, DWORD dwFlags,
                               LPSTR lpszUrl, LPDWORD lpdwUrlLength)
{
3566 3567 3568 3569
    BOOL ret;
    LPWSTR urlW = NULL;
    URL_COMPONENTSW urlCompW;

3570
    TRACE("(%p,%d,%p,%p)\n", lpUrlComponents, dwFlags, lpszUrl, lpdwUrlLength);
3571

3572
    if (!lpUrlComponents || lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSW) || !lpdwUrlLength)
3573
    {
3574
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584
        return FALSE;
    }

    convert_urlcomp_atow(lpUrlComponents, &urlCompW);

    if (lpszUrl)
        urlW = HeapAlloc(GetProcessHeap(), 0, *lpdwUrlLength * sizeof(WCHAR));

    ret = InternetCreateUrlW(&urlCompW, dwFlags, urlW, lpdwUrlLength);

3585 3586 3587
    if (!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
        *lpdwUrlLength /= sizeof(WCHAR);

3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605
    /* on success, lpdwUrlLength points to the size of urlW in WCHARS
    * minus one, so add one to leave room for NULL terminator
    */
    if (ret)
        WideCharToMultiByte(CP_ACP, 0, urlW, -1, lpszUrl, *lpdwUrlLength + 1, NULL, NULL);

    HeapFree(GetProcessHeap(), 0, urlCompW.lpszScheme);
    HeapFree(GetProcessHeap(), 0, urlCompW.lpszHostName);
    HeapFree(GetProcessHeap(), 0, urlCompW.lpszUserName);
    HeapFree(GetProcessHeap(), 0, urlCompW.lpszPassword);
    HeapFree(GetProcessHeap(), 0, urlCompW.lpszUrlPath);
    HeapFree(GetProcessHeap(), 0, urlCompW.lpszExtraInfo);
    HeapFree(GetProcessHeap(), 0, urlW);

    return ret;
}

/***********************************************************************
3606
 *      InternetCreateUrlW (WININET.@)
3607
 *
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
 * Creates a URL from its component parts.
 *
 * PARAMS
 *  lpUrlComponents [I] URL Components.
 *  dwFlags         [I] Flags. See notes.
 *  lpszUrl         [I] Buffer in which to store the created URL.
 *  lpdwUrlLength   [I/O] On input, the length of the buffer pointed to by
 *                        lpszUrl in characters. On output, the number of bytes
 *                        required to store the URL including terminator.
 *
 * NOTES
 *
 * The dwFlags parameter can be zero or more of the following:
 *|ICU_ESCAPE - Generates escape sequences for unsafe characters in the path and extra info of the URL.
 *
3623 3624 3625 3626 3627 3628 3629 3630
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
BOOL WINAPI InternetCreateUrlW(LPURL_COMPONENTSW lpUrlComponents, DWORD dwFlags,
                               LPWSTR lpszUrl, LPDWORD lpdwUrlLength)
{
3631
    DWORD dwLen;
3632
    INTERNET_SCHEME nScheme;
3633

3634
    static const WCHAR slashSlashW[] = {'/','/'};
3635 3636
    static const WCHAR percentD[] = {'%','d',0};

3637
    TRACE("(%p,%d,%p,%p)\n", lpUrlComponents, dwFlags, lpszUrl, lpdwUrlLength);
3638

3639
    if (!lpUrlComponents || lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSW) || !lpdwUrlLength)
3640
    {
3641
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3642 3643 3644
        return FALSE;
    }

3645
    if (!calc_url_length(lpUrlComponents, &dwLen))
3646 3647 3648 3649
        return FALSE;

    if (!lpszUrl || *lpdwUrlLength < dwLen)
    {
3650
        *lpdwUrlLength = (dwLen + 1) * sizeof(WCHAR);
3651
        INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
3652 3653 3654 3655 3656 3657
        return FALSE;
    }

    *lpdwUrlLength = dwLen;
    lpszUrl[0] = 0x00;

3658 3659
    dwLen = 0;

3660
    if (lpUrlComponents->lpszScheme)
3661 3662 3663 3664
    {
        dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Scheme);
        memcpy(lpszUrl, lpUrlComponents->lpszScheme, dwLen * sizeof(WCHAR));
        lpszUrl += dwLen;
3665 3666

        nScheme = GetInternetSchemeW(lpUrlComponents->lpszScheme, dwLen);
3667
    }
3668 3669
    else
    {
3670 3671 3672 3673 3674 3675 3676
        LPCWSTR scheme;
        nScheme = lpUrlComponents->nScheme;

        if (nScheme == INTERNET_SCHEME_DEFAULT)
            nScheme = INTERNET_SCHEME_HTTP;

        scheme = INTERNET_GetSchemeString(nScheme);
3677 3678 3679 3680
        dwLen = strlenW(scheme);
        memcpy(lpszUrl, scheme, dwLen * sizeof(WCHAR));
        lpszUrl += dwLen;
    }
3681

3682 3683 3684 3685 3686 3687 3688 3689 3690
    /* all schemes are followed by at least a colon */
    *lpszUrl = ':';
    lpszUrl++;

    if (!scheme_is_opaque(nScheme) || lpUrlComponents->lpszHostName)
    {
        memcpy(lpszUrl, slashSlashW, sizeof(slashSlashW));
        lpszUrl += sizeof(slashSlashW)/sizeof(slashSlashW[0]);
    }
3691 3692 3693

    if (lpUrlComponents->lpszUserName)
    {
3694 3695 3696
        dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, UserName);
        memcpy(lpszUrl, lpUrlComponents->lpszUserName, dwLen * sizeof(WCHAR));
        lpszUrl += dwLen;
3697 3698 3699

        if (lpUrlComponents->lpszPassword)
        {
3700 3701
            *lpszUrl = ':';
            lpszUrl++;
3702

3703 3704 3705
            dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Password);
            memcpy(lpszUrl, lpUrlComponents->lpszPassword, dwLen * sizeof(WCHAR));
            lpszUrl += dwLen;
3706 3707
        }

3708 3709
        *lpszUrl = '@';
        lpszUrl++;
3710 3711
    }

3712 3713 3714 3715 3716
    if (lpUrlComponents->lpszHostName)
    {
        dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, HostName);
        memcpy(lpszUrl, lpUrlComponents->lpszHostName, dwLen * sizeof(WCHAR));
        lpszUrl += dwLen;
3717

3718 3719
        if (!url_uses_default_port(nScheme, lpUrlComponents->nPort))
        {
3720
            WCHAR szPort[MAX_WORD_DIGITS+1];
3721 3722 3723 3724 3725 3726 3727 3728 3729

            sprintfW(szPort, percentD, lpUrlComponents->nPort);
            *lpszUrl = ':';
            lpszUrl++;
            dwLen = strlenW(szPort);
            memcpy(lpszUrl, szPort, dwLen * sizeof(WCHAR));
            lpszUrl += dwLen;
        }

3730 3731 3732 3733 3734 3735
        /* add slash between hostname and path if necessary */
        if (lpUrlComponents->lpszUrlPath && *lpUrlComponents->lpszUrlPath != '/')
        {
            *lpszUrl = '/';
            lpszUrl++;
        }
3736
    }
3737 3738


3739 3740 3741 3742
    if (lpUrlComponents->lpszUrlPath)
    {
        dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, UrlPath);
        memcpy(lpszUrl, lpUrlComponents->lpszUrlPath, dwLen * sizeof(WCHAR));
3743
        lpszUrl += dwLen;
3744 3745
    }

3746
    *lpszUrl = '\0';
3747 3748

    return TRUE;
3749 3750
}

3751 3752 3753 3754
/***********************************************************************
 *      InternetConfirmZoneCrossingA (WININET.@)
 *
 */
3755 3756 3757 3758 3759 3760
DWORD WINAPI InternetConfirmZoneCrossingA( HWND hWnd, LPSTR szUrlPrev, LPSTR szUrlNew, BOOL bPost )
{
    FIXME("(%p, %s, %s, %x) stub\n", hWnd, debugstr_a(szUrlPrev), debugstr_a(szUrlNew), bPost);
    return ERROR_SUCCESS;
}

3761 3762 3763 3764
/***********************************************************************
 *      InternetConfirmZoneCrossingW (WININET.@)
 *
 */
3765 3766 3767 3768 3769 3770 3771
DWORD WINAPI InternetConfirmZoneCrossingW( HWND hWnd, LPWSTR szUrlPrev, LPWSTR szUrlNew, BOOL bPost )
{
    FIXME("(%p, %s, %s, %x) stub\n", hWnd, debugstr_w(szUrlPrev), debugstr_w(szUrlNew), bPost);
    return ERROR_SUCCESS;
}

DWORD WINAPI InternetDialA( HWND hwndParent, LPSTR lpszConnectoid, DWORD dwFlags,
3772
                            DWORD_PTR* lpdwConnection, DWORD dwReserved )
3773
{
3774
    FIXME("(%p, %p, 0x%08x, %p, 0x%08x) stub\n", hwndParent, lpszConnectoid, dwFlags,
3775 3776 3777 3778 3779
          lpdwConnection, dwReserved);
    return ERROR_SUCCESS;
}

DWORD WINAPI InternetDialW( HWND hwndParent, LPWSTR lpszConnectoid, DWORD dwFlags,
3780
                            DWORD_PTR* lpdwConnection, DWORD dwReserved )
3781
{
3782
    FIXME("(%p, %p, 0x%08x, %p, 0x%08x) stub\n", hwndParent, lpszConnectoid, dwFlags,
3783 3784 3785 3786 3787 3788
          lpdwConnection, dwReserved);
    return ERROR_SUCCESS;
}

BOOL WINAPI InternetGoOnlineA( LPSTR lpszURL, HWND hwndParent, DWORD dwReserved )
{
3789
    FIXME("(%s, %p, 0x%08x) stub\n", debugstr_a(lpszURL), hwndParent, dwReserved);
3790 3791 3792 3793 3794
    return TRUE;
}

BOOL WINAPI InternetGoOnlineW( LPWSTR lpszURL, HWND hwndParent, DWORD dwReserved )
{
3795
    FIXME("(%s, %p, 0x%08x) stub\n", debugstr_w(lpszURL), hwndParent, dwReserved);
3796 3797 3798
    return TRUE;
}

3799
DWORD WINAPI InternetHangUp( DWORD_PTR dwConnection, DWORD dwReserved )
3800
{
3801
    FIXME("(0x%08lx, 0x%08x) stub\n", dwConnection, dwReserved);
3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814
    return ERROR_SUCCESS;
}

BOOL WINAPI CreateMD5SSOHash( PWSTR pszChallengeInfo, PWSTR pwszRealm, PWSTR pwszTarget,
                              PBYTE pbHexHash )
{
    FIXME("(%s, %s, %s, %p) stub\n", debugstr_w(pszChallengeInfo), debugstr_w(pwszRealm),
          debugstr_w(pwszTarget), pbHexHash);
    return FALSE;
}

BOOL WINAPI ResumeSuspendedDownload( HINTERNET hInternet, DWORD dwError )
{
3815
    FIXME("(%p, 0x%08x) stub\n", hInternet, dwError);
3816 3817
    return FALSE;
}
3818

3819
BOOL WINAPI InternetQueryFortezzaStatus(DWORD *a, DWORD_PTR b)
3820
{
3821
    FIXME("(%p, %08lx) stub\n", a, b);
3822 3823
    return 0;
}