ftp.c 105 KB
Newer Older
1 2 3 4
/*
 * WININET - Ftp implementation
 *
 * Copyright 1999 Corel Corporation
5
 * Copyright 2004 Mike McCormack for CodeWeavers
6
 * Copyright 2004 Kevin Koltzau
7
 * Copyright 2007 Hans Leidekker
8 9 10
 *
 * Ulrich Czekalla
 * Noureddine Jemmali
11 12
 *
 * Copyright 2000 Andreas Mohr
13
 * Copyright 2002 Jaco Greeff
14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * 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
27
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28 29
 */

30
#include "ws2tcpip.h"
31

32
#include <stdarg.h>
33 34 35
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
36
#include <time.h>
37
#include <assert.h>
38

39
#include "windef.h"
40 41 42
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
43
#include "wininet.h"
44
#include "winnls.h"
45
#include "winerror.h"
46
#include "winreg.h"
47
#include "winternl.h"
48
#include "shlwapi.h"
49

50
#include "wine/debug.h"
51 52
#include "internet.h"

53
WINE_DEFAULT_DEBUG_CHANNEL(wininet);
54

55 56
#define RESPONSE_TIMEOUT        30

57
typedef struct _ftp_session_t ftp_session_t;
58 59 60

typedef struct
{
61
    object_header_t hdr;
62
    ftp_session_t *lpFtpSession;
63 64
    BOOL session_deleted;
    int nDataSocket;
65 66
    WCHAR *cache_file;
    HANDLE cache_file_handle;
67
} ftp_file_t;
68

69
struct _ftp_session_t
70
{
71
    object_header_t hdr;
72
    appinfo_t *lpAppInfo;
73 74 75
    int sndSocket;
    int lstnSocket;
    int pasvSocket; /* data socket connected by us in case of passive FTP */
76
    ftp_file_t *download_in_progress;
77 78
    struct sockaddr_in socketAddress;
    struct sockaddr_in lstnSocketAddress;
79 80
    LPWSTR servername;
    INTERNET_PORT serverport;
81 82
    LPWSTR  lpszPassword;
    LPWSTR  lpszUserName;
83
};
84

85 86 87 88 89
typedef struct
{
    BOOL bIsDirectory;
    LPWSTR lpszName;
    DWORD nSize;
90
    SYSTEMTIME tmLastModified;
91 92 93 94 95
    unsigned short permissions;
} FILEPROPERTIESW, *LPFILEPROPERTIESW;

typedef struct
{
96
    object_header_t hdr;
97
    ftp_session_t *lpFtpSession;
98 99 100 101 102
    DWORD index;
    DWORD size;
    LPFILEPROPERTIESW lpafp;
} WININETFTPFINDNEXTW, *LPWININETFTPFINDNEXTW;

103 104 105 106
#define DATA_PACKET_SIZE 	0x2000
#define szCRLF 			"\r\n"
#define MAX_BACKLOG 		5

107 108 109 110 111
/* Testing shows that Windows only accepts dwFlags where the last
 * 3 (yes 3) bits define FTP_TRANSFER_TYPE_UNKNOWN, FTP_TRANSFER_TYPE_ASCII or FTP_TRANSFER_TYPE_BINARY.
 */
#define FTP_CONDITION_MASK      0x0007

112 113
typedef enum {
  /* FTP commands with arguments. */
114 115 116 117 118 119 120 121 122 123 124 125 126
  FTP_CMD_ACCT,
  FTP_CMD_CWD,
  FTP_CMD_DELE,
  FTP_CMD_MKD,
  FTP_CMD_PASS,
  FTP_CMD_PORT,
  FTP_CMD_RETR,
  FTP_CMD_RMD,
  FTP_CMD_RNFR,
  FTP_CMD_RNTO,
  FTP_CMD_STOR,
  FTP_CMD_TYPE,
  FTP_CMD_USER,
127
  FTP_CMD_SIZE,
128 129 130 131 132

  /* FTP commands without arguments. */
  FTP_CMD_ABOR,
  FTP_CMD_LIST,
  FTP_CMD_NLST,
133
  FTP_CMD_PASV,
134
  FTP_CMD_PWD,
135
  FTP_CMD_QUIT,
136
} FTP_COMMAND;
137

138
static const CHAR *const szFtpCommands[] = {
139 140 141 142 143 144 145 146 147 148 149 150 151
  "ACCT",
  "CWD",
  "DELE",
  "MKD",
  "PASS",
  "PORT",
  "RETR",
  "RMD",
  "RNFR",
  "RNTO",
  "STOR",
  "TYPE",
  "USER",
152
  "SIZE",
153 154 155
  "ABOR",
  "LIST",
  "NLST",
156
  "PASV",
157 158 159 160 161
  "PWD",
  "QUIT",
};

static const CHAR szMonths[] = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
162
static const WCHAR szNoAccount[] = {'n','o','a','c','c','o','u','n','t','\0'};
163

164
static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
165
	INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext);
166 167 168 169 170 171 172 173 174 175 176 177 178 179
static BOOL FTP_SendStore(ftp_session_t*, LPCWSTR lpszRemoteFile, DWORD dwType);
static BOOL FTP_GetDataSocket(ftp_session_t*, LPINT nDataSocket);
static BOOL FTP_SendData(ftp_session_t*, INT nDataSocket, HANDLE hFile);
static INT FTP_ReceiveResponse(ftp_session_t*, DWORD_PTR dwContext);
static BOOL FTP_SendRetrieve(ftp_session_t*, LPCWSTR lpszRemoteFile, DWORD dwType);
static BOOL FTP_RetrieveFileData(ftp_session_t*, INT nDataSocket, HANDLE hFile);
static BOOL FTP_InitListenSocket(ftp_session_t*);
static BOOL FTP_ConnectToHost(ftp_session_t*);
static BOOL FTP_SendPassword(ftp_session_t*);
static BOOL FTP_SendAccount(ftp_session_t*);
static BOOL FTP_SendType(ftp_session_t*, DWORD dwType);
static BOOL FTP_SendPort(ftp_session_t*);
static BOOL FTP_DoPassive(ftp_session_t*);
static BOOL FTP_SendPortOrPasv(ftp_session_t*);
180 181
static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp);
static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW fileprop);
182
static BOOL FTP_ParseDirectory(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
183
        LPFILEPROPERTIESW *lpafp, LPDWORD dwfp);
184
static HINTERNET FTP_ReceiveFileList(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
185
        LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext);
186
static DWORD FTP_SetResponseError(DWORD dwResponse);
187
static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData);
188
static BOOL FTP_FtpPutFileW(ftp_session_t*, LPCWSTR lpszLocalFile,
189
        LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext);
190 191 192
static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
static BOOL FTP_FtpCreateDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t*,
193
        LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext);
194
static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t*, LPWSTR lpszCurrentDirectory,
195
        LPDWORD lpdwCurrentDirectory);
196 197 198 199
static BOOL FTP_FtpRenameFileW(ftp_session_t*, LPCWSTR lpszSrc, LPCWSTR lpszDest);
static BOOL FTP_FtpRemoveDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
static BOOL FTP_FtpDeleteFileW(ftp_session_t*, LPCWSTR lpszFileName);
static BOOL FTP_FtpGetFileW(ftp_session_t*, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
200 201 202
        BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
        DWORD_PTR dwContext);

203 204 205 206 207 208 209
/* A temporary helper until we get rid of INTERNET_GetLastError calls */
static BOOL res_to_le(DWORD res)
{
    if(res != ERROR_SUCCESS)
        INTERNET_SetLastError(res);
    return res == ERROR_SUCCESS;
}
210

211 212 213 214 215 216 217 218 219 220 221
/***********************************************************************
 *           FtpPutFileA (WININET.@)
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpPutFileA(HINTERNET hConnect, LPCSTR lpszLocalFile,
222
    LPCSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
223
{
224 225 226 227
    LPWSTR lpwzLocalFile;
    LPWSTR lpwzNewRemoteFile;
    BOOL ret;
    
228 229
    lpwzLocalFile = heap_strdupAtoW(lpszLocalFile);
    lpwzNewRemoteFile = heap_strdupAtoW(lpszNewRemoteFile);
230 231
    ret = FtpPutFileW(hConnect, lpwzLocalFile, lpwzNewRemoteFile,
                      dwFlags, dwContext);
232 233
    heap_free(lpwzLocalFile);
    heap_free(lpwzNewRemoteFile);
234 235 236
    return ret;
}

237 238 239 240 241 242 243 244 245
typedef struct {
    task_header_t hdr;
    WCHAR *local_file;
    WCHAR *remote_file;
    DWORD flags;
    DWORD_PTR context;
} put_file_task_t;

static void AsyncFtpPutFileProc(task_header_t *hdr)
246
{
247 248
    put_file_task_t *task = (put_file_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
249

250
    TRACE("%p\n", session);
251

252 253
    FTP_FtpPutFileW(session, task->local_file, task->remote_file,
               task->flags, task->context);
254

255 256
    heap_free(task->local_file);
    heap_free(task->remote_file);
257 258
}

259 260 261 262 263 264 265 266 267 268
/***********************************************************************
 *           FtpPutFileW (WININET.@)
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
269
BOOL WINAPI FtpPutFileW(HINTERNET hConnect, LPCWSTR lpszLocalFile,
270
    LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
271
{
272
    ftp_session_t *lpwfs;
273
    appinfo_t *hIC = NULL;
274
    BOOL r = FALSE;
275

276 277 278 279 280 281
    if (!lpszLocalFile || !lpszNewRemoteFile)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

282
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
283 284 285 286 287 288 289
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
290 291
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
292
        goto lend;
293 294
    }

295 296 297 298 299 300
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

301 302 303 304 305 306
    if ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

307
    hIC = lpwfs->lpAppInfo;
308 309
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
310
        put_file_task_t *task = alloc_async_task(&lpwfs->hdr, AsyncFtpPutFileProc, sizeof(*task));
311

312 313 314 315
        task->local_file = heap_strdupW(lpszLocalFile);
        task->remote_file = heap_strdupW(lpszNewRemoteFile);
        task->flags = dwFlags;
        task->context = dwContext;
316

317
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
318 319 320
    }
    else
    {
321
        r = FTP_FtpPutFileW(lpwfs, lpszLocalFile,
322
	    lpszNewRemoteFile, dwFlags, dwContext);
323
    }
324 325

lend:
326
    WININET_Release( &lpwfs->hdr );
327 328

    return r;
329 330 331
}

/***********************************************************************
332
 *           FTP_FtpPutFileW (Internal)
333 334 335 336 337 338 339 340
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
341
static BOOL FTP_FtpPutFileW(ftp_session_t *lpwfs, LPCWSTR lpszLocalFile,
342
    LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
343
{
344
    HANDLE hFile;
345
    BOOL bSuccess = FALSE;
346
    appinfo_t *hIC = NULL;
347
    INT nResCode;
348

349 350
    TRACE(" lpszLocalFile(%s) lpszNewRemoteFile(%s)\n", debugstr_w(lpszLocalFile), debugstr_w(lpszNewRemoteFile));

351 352 353 354
    /* Clear any error information */
    INTERNET_SetLastError(0);

    /* Open file to be uploaded */
355
    if (INVALID_HANDLE_VALUE ==
356
        (hFile = CreateFileW(lpszLocalFile, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0)))
357
        /* Let CreateFile set the appropriate error */
358
        return FALSE;
359

360 361
    hIC = lpwfs->lpAppInfo;

362
    INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
363 364 365 366 367

    if (FTP_SendStore(lpwfs, lpszNewRemoteFile, dwFlags))
    {
        INT nDataSocket;

368
        /* Get data socket to server */
369
        if (FTP_GetDataSocket(lpwfs, &nDataSocket))
370 371
        {
            FTP_SendData(lpwfs, nDataSocket, hFile);
372
            closesocket(nDataSocket);
373
	    nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
374 375 376 377 378 379 380
	    if (nResCode)
	    {
	        if (nResCode == 226)
		    bSuccess = TRUE;
		else
		    FTP_SetResponseError(nResCode);
	    }
381 382 383
        }
    }

384
    if (lpwfs->lstnSocket != -1)
385
    {
386
        closesocket(lpwfs->lstnSocket);
387 388
        lpwfs->lstnSocket = -1;
    }
389

390
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
391 392
    {
        INTERNET_ASYNC_RESULT iar;
393

394 395
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
396
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
397 398 399
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

400
    CloseHandle(hFile);
401 402 403 404 405 406

    return bSuccess;
}


/***********************************************************************
407
 *           FtpSetCurrentDirectoryA (WININET.@)
408 409 410 411 412 413 414 415
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
416
BOOL WINAPI FtpSetCurrentDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
417
{
418 419 420
    LPWSTR lpwzDirectory;
    BOOL ret;
    
421
    lpwzDirectory = heap_strdupAtoW(lpszDirectory);
422
    ret = FtpSetCurrentDirectoryW(hConnect, lpwzDirectory);
423
    heap_free(lpwzDirectory);
424 425 426
    return ret;
}

427 428 429 430
typedef struct {
    task_header_t hdr;
    WCHAR *directory;
} directory_task_t;
431

432
static void AsyncFtpSetCurrentDirectoryProc(task_header_t *hdr)
433
{
434 435
    directory_task_t *task = (directory_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
436

437
    TRACE("%p\n", session);
438

439 440
    FTP_FtpSetCurrentDirectoryW(session, task->directory);
    heap_free(task->directory);
441 442
}

443 444 445 446 447 448 449 450 451 452
/***********************************************************************
 *           FtpSetCurrentDirectoryW (WININET.@)
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
453 454
BOOL WINAPI FtpSetCurrentDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
{
455
    ftp_session_t *lpwfs = NULL;
456
    appinfo_t *hIC = NULL;
457
    BOOL r = FALSE;
458

459 460
    if (!lpszDirectory)
    {
461
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
462 463 464
        goto lend;
    }

465
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
466 467 468
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
469
        goto lend;
470 471
    }

472 473 474 475 476 477
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

478
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
479

480
    hIC = lpwfs->lpAppInfo;
481 482
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
483
        directory_task_t *task;
484

485
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpSetCurrentDirectoryProc, sizeof(*task));
486
        task->directory = heap_strdupW(lpszDirectory);
487

488
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
489 490 491
    }
    else
    {
492
        r = FTP_FtpSetCurrentDirectoryW(lpwfs, lpszDirectory);
493
    }
494 495 496 497 498 499

lend:
    if( lpwfs )
        WININET_Release( &lpwfs->hdr );

    return r;
500 501 502
}


503
/***********************************************************************
504
 *           FTP_FtpSetCurrentDirectoryW (Internal)
505 506 507 508 509 510 511 512
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
513
static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
514 515
{
    INT nResCode;
516
    appinfo_t *hIC = NULL;
517
    BOOL bSuccess = FALSE;
518

519
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
520 521 522 523

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

524
    hIC = lpwfs->lpAppInfo;
525
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_CWD, lpszDirectory,
526
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
527 528
        goto lend;

529
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
530 531 532 533 534 535 536 537 538 539

    if (nResCode)
    {
        if (nResCode == 250)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
540
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
541 542
    {
        INTERNET_ASYNC_RESULT iar;
543

544
        iar.dwResult = bSuccess;
545
        iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
546
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
547 548 549 550 551 552 553
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }
    return bSuccess;
}


/***********************************************************************
554
 *           FtpCreateDirectoryA (WININET.@)
555 556 557 558 559 560 561 562
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
563
BOOL WINAPI FtpCreateDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
564
{
565 566 567
    LPWSTR lpwzDirectory;
    BOOL ret;
    
568
    lpwzDirectory = heap_strdupAtoW(lpszDirectory);
569
    ret = FtpCreateDirectoryW(hConnect, lpwzDirectory);
570
    heap_free(lpwzDirectory);
571 572 573 574
    return ret;
}


575
static void AsyncFtpCreateDirectoryProc(task_header_t *hdr)
576
{
577 578
    directory_task_t *task = (directory_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
579

580
    TRACE(" %p\n", session);
581

582 583
    FTP_FtpCreateDirectoryW(session, task->directory);
    heap_free(task->directory);
584 585
}

586 587 588 589 590 591 592 593 594 595
/***********************************************************************
 *           FtpCreateDirectoryW (WININET.@)
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
596 597
BOOL WINAPI FtpCreateDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
{
598
    ftp_session_t *lpwfs;
599
    appinfo_t *hIC = NULL;
600
    BOOL r = FALSE;
601

602
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
603 604 605 606 607 608 609
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
610 611
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
612
        goto lend;
613 614
    }

615 616 617 618 619 620
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

621 622 623 624 625 626
    if (!lpszDirectory)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

627
    hIC = lpwfs->lpAppInfo;
628 629
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
630
        directory_task_t *task;
631

632
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpCreateDirectoryProc, sizeof(*task));
633
        task->directory = heap_strdupW(lpszDirectory);
634

635
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
636 637 638
    }
    else
    {
639
        r = FTP_FtpCreateDirectoryW(lpwfs, lpszDirectory);
640
    }
641
lend:
642
    WININET_Release( &lpwfs->hdr );
643 644

    return r;
645 646 647
}


648
/***********************************************************************
649
 *           FTP_FtpCreateDirectoryW (Internal)
650 651 652 653 654 655 656 657
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
658
static BOOL FTP_FtpCreateDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
659 660 661
{
    INT nResCode;
    BOOL bSuccess = FALSE;
662
    appinfo_t *hIC = NULL;
663

664
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
665

666 667 668 669 670 671
    /* Clear any error information */
    INTERNET_SetLastError(0);

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_MKD, lpszDirectory, 0, 0, 0))
        goto lend;

672
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
673 674 675 676 677 678 679 680 681
    if (nResCode)
    {
        if (nResCode == 257)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
682
    hIC = lpwfs->lpAppInfo;
683
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
684 685
    {
        INTERNET_ASYNC_RESULT iar;
686

687 688
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
689
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
690 691 692 693 694 695 696
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

/***********************************************************************
697
 *           FtpFindFirstFileA (WININET.@)
698 699 700 701 702 703 704 705
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
706
HINTERNET WINAPI FtpFindFirstFileA(HINTERNET hConnect,
707
    LPCSTR lpszSearchFile, LPWIN32_FIND_DATAA lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
708
{
709 710 711 712 713
    LPWSTR lpwzSearchFile;
    WIN32_FIND_DATAW wfd;
    LPWIN32_FIND_DATAW lpFindFileDataW;
    HINTERNET ret;
    
714
    lpwzSearchFile = heap_strdupAtoW(lpszSearchFile);
715 716
    lpFindFileDataW = lpFindFileData?&wfd:NULL;
    ret = FtpFindFirstFileW(hConnect, lpwzSearchFile, lpFindFileDataW, dwFlags, dwContext);
717
    heap_free(lpwzSearchFile);
718
    
719
    if (ret && lpFindFileData)
720
        WININET_find_data_WtoA(lpFindFileDataW, lpFindFileData);
721

722 723 724
    return ret;
}

725 726 727 728 729 730 731
typedef struct {
    task_header_t hdr;
    WCHAR *search_file;
    WIN32_FIND_DATAW *find_file_data;
    DWORD flags;
    DWORD_PTR context;
} find_first_file_task_t;
732

733
static void AsyncFtpFindFirstFileProc(task_header_t *hdr)
734
{
735 736
    find_first_file_task_t *task = (find_first_file_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
737

738
    TRACE("%p\n", session);
739

740 741
    FTP_FtpFindFirstFileW(session, task->search_file, task->find_file_data, task->flags, task->context);
    heap_free(task->search_file);
742 743
}

744 745 746 747 748 749 750 751 752 753
/***********************************************************************
 *           FtpFindFirstFileW (WININET.@)
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
754
HINTERNET WINAPI FtpFindFirstFileW(HINTERNET hConnect,
755
    LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
756
{
757
    ftp_session_t *lpwfs;
758
    appinfo_t *hIC = NULL;
759
    HINTERNET r = NULL;
760

761
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
762 763 764
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
765
        goto lend;
766 767
    }

768 769 770 771 772 773
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

774
    hIC = lpwfs->lpAppInfo;
775 776
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
777
        find_first_file_task_t *task;
778

779
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpFindFirstFileProc, sizeof(*task));
780 781 782 783 784 785 786
        task->search_file = heap_strdupW(lpszSearchFile);
        task->find_file_data = lpFindFileData;
        task->flags = dwFlags;
        task->context = dwContext;

        INTERNET_AsyncCall(&task->hdr);
        r = NULL;
787 788 789
    }
    else
    {
790
        r = FTP_FtpFindFirstFileW(lpwfs, lpszSearchFile, lpFindFileData,
791
            dwFlags, dwContext);
792
    }
793 794 795 796 797
lend:
    if( lpwfs )
        WININET_Release( &lpwfs->hdr );

    return r;
798 799 800
}


801
/***********************************************************************
802
 *           FTP_FtpFindFirstFileW (Internal)
803 804 805 806 807 808 809 810
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
811
static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t *lpwfs,
812
    LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
813 814
{
    INT nResCode;
815
    appinfo_t *hIC = NULL;
816
    HINTERNET hFindNext = NULL;
817
    LPWSTR lpszSearchPath = NULL;
818 819 820 821 822 823 824 825 826 827 828 829

    TRACE("\n");

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

    if (!FTP_InitListenSocket(lpwfs))
        goto lend;

    if (!FTP_SendType(lpwfs, INTERNET_FLAG_TRANSFER_ASCII))
        goto lend;

830
    if (!FTP_SendPortOrPasv(lpwfs))
831 832
        goto lend;

833 834 835 836
    /* split search path into file and path */
    if (lpszSearchFile)
    {
        LPCWSTR name = lpszSearchFile, p;
837 838
        if ((p = wcsrchr( name, '\\' ))) name = p + 1;
        if ((p = wcsrchr( name, '/' ))) name = p + 1;
839 840 841 842 843 844 845 846
        if (name != lpszSearchFile)
        {
            lpszSearchPath = heap_strndupW(lpszSearchFile, name - lpszSearchFile);
            lpszSearchFile = name;
        }
    }

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_LIST, lpszSearchPath,
847
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
848 849
        goto lend;

850
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
851 852 853 854 855 856
    if (nResCode)
    {
        if (nResCode == 125 || nResCode == 150)
        {
            INT nDataSocket;

857 858
            /* Get data socket to server */
            if (FTP_GetDataSocket(lpwfs, &nDataSocket))
859
            {
860
                hFindNext = FTP_ReceiveFileList(lpwfs, nDataSocket, lpszSearchFile, lpFindFileData, dwContext);
861
                closesocket(nDataSocket);
862
                nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
863 864 865 866 867 868 869 870 871
                if (nResCode != 226 && nResCode != 250)
                    INTERNET_SetLastError(ERROR_NO_MORE_FILES);
            }
        }
        else
            FTP_SetResponseError(nResCode);
    }

lend:
872 873
    heap_free(lpszSearchPath);

874
    if (lpwfs->lstnSocket != -1)
875
    {
876
        closesocket(lpwfs->lstnSocket);
877 878
        lpwfs->lstnSocket = -1;
    }
879

880
    hIC = lpwfs->lpAppInfo;
881
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
882 883 884 885 886
    {
        INTERNET_ASYNC_RESULT iar;

        if (hFindNext)
	{
887
            iar.dwResult = (DWORD_PTR)hFindNext;
888
            iar.dwError = ERROR_SUCCESS;
889
            INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
890 891 892
                &iar, sizeof(INTERNET_ASYNC_RESULT));
	}

893
        iar.dwResult = (DWORD_PTR)hFindNext;
894
        iar.dwError = hFindNext ? ERROR_SUCCESS : INTERNET_GetLastError();
895
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
896 897 898
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

899
    return hFindNext;
900 901 902 903
}


/***********************************************************************
904
 *           FtpGetCurrentDirectoryA (WININET.@)
905 906 907 908 909 910 911 912
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
913
BOOL WINAPI FtpGetCurrentDirectoryA(HINTERNET hFtpSession, LPSTR lpszCurrentDirectory,
914
    LPDWORD lpdwCurrentDirectory)
915
{
916
    WCHAR *dir = NULL;
917 918 919
    DWORD len;
    BOOL ret;

920 921 922 923
    if(lpdwCurrentDirectory) {
        len = *lpdwCurrentDirectory;
        if(lpszCurrentDirectory)
        {
924
            dir = heap_alloc(len * sizeof(WCHAR));
925 926 927 928 929 930 931
            if (NULL == dir)
            {
                INTERNET_SetLastError(ERROR_OUTOFMEMORY);
                return FALSE;
            }
        }
    }
932
    ret = FtpGetCurrentDirectoryW(hFtpSession, lpszCurrentDirectory?dir:NULL, lpdwCurrentDirectory?&len:NULL);
933 934 935 936 937

    if (ret && lpszCurrentDirectory)
        WideCharToMultiByte(CP_ACP, 0, dir, -1, lpszCurrentDirectory, len, NULL, NULL);

    if (lpdwCurrentDirectory) *lpdwCurrentDirectory = len;
938
    heap_free(dir);
939 940 941
    return ret;
}

942 943 944 945 946
typedef struct {
    task_header_t hdr;
    WCHAR *directory;
    DWORD *directory_len;
} get_current_dir_task_t;
947

948
static void AsyncFtpGetCurrentDirectoryProc(task_header_t *hdr)
949
{
950 951
    get_current_dir_task_t *task = (get_current_dir_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
952

953
    TRACE("%p\n", session);
954

955
    FTP_FtpGetCurrentDirectoryW(session, task->directory, task->directory_len);
956 957
}

958 959 960 961 962 963 964 965 966 967
/***********************************************************************
 *           FtpGetCurrentDirectoryW (WININET.@)
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
968 969 970
BOOL WINAPI FtpGetCurrentDirectoryW(HINTERNET hFtpSession, LPWSTR lpszCurrentDirectory,
    LPDWORD lpdwCurrentDirectory)
{
971
    ftp_session_t *lpwfs;
972
    appinfo_t *hIC = NULL;
973
    BOOL r = FALSE;
974

975
    TRACE("%p %p %p\n", hFtpSession, lpszCurrentDirectory, lpdwCurrentDirectory);
976

977
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
978 979 980 981 982 983 984
    if (NULL == lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        goto lend;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
985 986
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
987
        goto lend;
988 989
    }

990 991 992 993 994 995 996 997 998 999 1000 1001
    if (!lpdwCurrentDirectory)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

    if (lpszCurrentDirectory == NULL)
    {
        INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto lend;
    }

1002 1003 1004 1005 1006 1007
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

1008
    hIC = lpwfs->lpAppInfo;
1009 1010
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
1011
        get_current_dir_task_t *task;
1012

1013
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpGetCurrentDirectoryProc, sizeof(*task));
1014 1015
        task->directory = lpszCurrentDirectory;
        task->directory_len = lpdwCurrentDirectory;
1016

1017
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
1018 1019 1020
    }
    else
    {
1021
        r = FTP_FtpGetCurrentDirectoryW(lpwfs, lpszCurrentDirectory,
1022
            lpdwCurrentDirectory);
1023
    }
1024 1025 1026 1027 1028 1029

lend:
    if( lpwfs )
        WININET_Release( &lpwfs->hdr );

    return r;
1030 1031 1032 1033
}


/***********************************************************************
1034
 *           FTP_FtpGetCurrentDirectoryW (Internal)
1035 1036 1037 1038 1039 1040 1041 1042
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1043
static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t *lpwfs, LPWSTR lpszCurrentDirectory,
1044 1045 1046
	LPDWORD lpdwCurrentDirectory)
{
    INT nResCode;
1047
    appinfo_t *hIC = NULL;
1048
    BOOL bSuccess = FALSE;
1049 1050 1051 1052

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

1053
    hIC = lpwfs->lpAppInfo;
1054
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PWD, NULL,
1055
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
1056 1057
        goto lend;

1058
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1059 1060 1061 1062
    if (nResCode)
    {
        if (nResCode == 257) /* Extract directory name */
        {
1063
            DWORD firstpos, lastpos, len;
1064
            LPWSTR lpszResponseBuffer = heap_strdupAtoW(INTERNET_GetResponseBuffer());
1065 1066 1067 1068 1069 1070 1071 1072 1073

            for (firstpos = 0, lastpos = 0; lpszResponseBuffer[lastpos]; lastpos++)
            {
                if ('"' == lpszResponseBuffer[lastpos])
                {
                    if (!firstpos)
                        firstpos = lastpos;
                    else
                        break;
1074 1075 1076 1077 1078 1079 1080 1081 1082
                }
            }
            len = lastpos - firstpos;
            if (*lpdwCurrentDirectory >= len)
            {
                memcpy(lpszCurrentDirectory, &lpszResponseBuffer[firstpos + 1], len * sizeof(WCHAR));
                lpszCurrentDirectory[len - 1] = 0;
                *lpdwCurrentDirectory = len;
                bSuccess = TRUE;
1083
            }
1084
            else INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1085

1086
            heap_free(lpszResponseBuffer);
1087 1088 1089 1090 1091 1092
        }
        else
            FTP_SetResponseError(nResCode);
    }

lend:
1093
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1094 1095
    {
        INTERNET_ASYNC_RESULT iar;
1096

1097
        iar.dwResult = bSuccess;
1098
        iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
1099
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1100 1101 1102
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

1103
    return bSuccess;
1104 1105 1106
}


1107 1108 1109 1110 1111 1112 1113
/***********************************************************************
 *           FTPFILE_Destroy(internal)
 *
 * Closes the file transfer handle. This also 'cleans' the data queue of
 * the 'transfer complete' message (this is a bit of a hack though :-/ )
 *
 */
1114
static void FTPFILE_Destroy(object_header_t *hdr)
1115
{
1116
    ftp_file_t *lpwh = (ftp_file_t*) hdr;
1117
    ftp_session_t *lpwfs = lpwh->lpFtpSession;
1118 1119 1120 1121
    INT nResCode;

    TRACE("\n");

1122 1123 1124
    if (lpwh->cache_file_handle != INVALID_HANDLE_VALUE)
        CloseHandle(lpwh->cache_file_handle);

1125
    heap_free(lpwh->cache_file);
1126

1127 1128 1129 1130 1131 1132 1133 1134 1135
    if (!lpwh->session_deleted)
        lpwfs->download_in_progress = NULL;

    if (lpwh->nDataSocket != -1)
        closesocket(lpwh->nDataSocket);

    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
    if (nResCode > 0 && nResCode != 226) WARN("server reports failed transfer\n");

1136
    WININET_Release(&lpwh->lpFtpSession->hdr);
1137 1138
}

1139
static DWORD FTPFILE_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
{
    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_FTP_FILE;
        return ERROR_SUCCESS;
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    case INTERNET_OPTION_DATAFILE_NAME:
    {
        DWORD required;
        ftp_file_t *file = (ftp_file_t *)hdr;

        TRACE("INTERNET_OPTION_DATAFILE_NAME\n");

        if (!file->cache_file)
        {
            *size = 0;
            return ERROR_INTERNET_ITEM_NOT_FOUND;
        }
        if (unicode)
        {
            required = (lstrlenW(file->cache_file) + 1) * sizeof(WCHAR);
            if (*size < required)
                return ERROR_INSUFFICIENT_BUFFER;
1168

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
            *size = required;
            memcpy(buffer, file->cache_file, *size);
            return ERROR_SUCCESS;
        }
        else
        {
            required = WideCharToMultiByte(CP_ACP, 0, file->cache_file, -1, NULL, 0, NULL, NULL);
            if (required > *size)
                return ERROR_INSUFFICIENT_BUFFER;

            *size = WideCharToMultiByte(CP_ACP, 0, file->cache_file, -1, buffer, *size, NULL, NULL);
            return ERROR_SUCCESS;
        }
    }
    }
1184
    return INET_QueryOption(hdr, option, buffer, size, unicode);
1185 1186
}

1187 1188
static DWORD FTPFILE_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read,
    DWORD flags, DWORD_PTR context)
1189
{
1190
    ftp_file_t *file = (ftp_file_t*)hdr;
1191
    int res;
1192
    DWORD error;
1193 1194 1195 1196 1197

    if (file->nDataSocket == -1)
        return ERROR_INTERNET_DISCONNECTED;

    /* FIXME: FTP should use NETCON_ stuff */
1198
    res = sock_recv(file->nDataSocket, buffer, size, MSG_WAITALL);
1199 1200
    *read = res>0 ? res : 0;

1201 1202 1203 1204 1205 1206 1207 1208 1209
    error = res >= 0 ? ERROR_SUCCESS : INTERNET_ERROR_BASE; /* FIXME */
    if (error == ERROR_SUCCESS && file->cache_file)
    {
        DWORD bytes_written;

        if (!WriteFile(file->cache_file_handle, buffer, *read, &bytes_written, NULL))
            WARN("WriteFile failed: %u\n", GetLastError());
    }
    return error;
1210 1211
}

1212
static DWORD FTPFILE_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
1213
{
1214
    ftp_file_t *lpwh = (ftp_file_t*) hdr;
1215 1216
    int res;

1217
    res = sock_send(lpwh->nDataSocket, buffer, size, 0);
1218 1219

    *written = res>0 ? res : 0;
1220
    return res >= 0 ? ERROR_SUCCESS : WSAGetLastError();
1221 1222
}

1223
static void FTP_ReceiveRequestData(ftp_file_t *file, BOOL first_notif)
1224 1225 1226 1227 1228 1229 1230
{
    INTERNET_ASYNC_RESULT iar;
    BYTE buffer[4096];
    int available;

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

1231
    available = sock_recv(file->nDataSocket, buffer, sizeof(buffer), MSG_PEEK);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244

    if(available != -1) {
        iar.dwResult = (DWORD_PTR)file->hdr.hInternet;
        iar.dwError = first_notif ? 0 : available;
    }else {
        iar.dwResult = 0;
        iar.dwError = INTERNET_GetLastError();
    }

    INTERNET_SendCallback(&file->hdr, file->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
                          sizeof(INTERNET_ASYNC_RESULT));
}

1245
static void FTPFILE_AsyncQueryDataAvailableProc(task_header_t *task)
1246
{
1247
    ftp_file_t *file = (ftp_file_t*)task->hdr;
1248 1249 1250 1251

    FTP_ReceiveRequestData(file, FALSE);
}

1252
static DWORD FTPFILE_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1253
{
1254
    ftp_file_t *file = (ftp_file_t*) hdr;
1255 1256
    ULONG unread = 0;
    int retval;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270

    TRACE("(%p %p %x %lx)\n", file, available, flags, ctx);

    retval = ioctlsocket(file->nDataSocket, FIONREAD, &unread);
    if (!retval)
        TRACE("%d bytes of queued, but unread data\n", unread);

    *available = unread;

    if(!unread) {
        BYTE byte;

        *available = 0;

1271
        retval = sock_recv(file->nDataSocket, &byte, 1, MSG_PEEK);
1272
        if(retval > 0) {
1273
            task_header_t *task;
1274

1275 1276
            task = alloc_async_task(&file->hdr, FTPFILE_AsyncQueryDataAvailableProc, sizeof(*task));
            INTERNET_AsyncCall(task);
1277 1278 1279 1280 1281 1282 1283 1284

            return ERROR_IO_PENDING;
        }
    }

    return ERROR_SUCCESS;
}

1285 1286 1287 1288 1289 1290
static DWORD FTPFILE_LockRequestFile(object_header_t *hdr, req_file_t **ret)
{
    ftp_file_t *file = (ftp_file_t*)hdr;
    FIXME("%p\n", file);
    return ERROR_NOT_SUPPORTED;
}
1291

1292
static const object_vtbl_t FTPFILEVtbl = {
1293
    FTPFILE_Destroy,
1294
    NULL,
1295
    FTPFILE_QueryOption,
1296
    INET_SetOption,
1297
    FTPFILE_ReadFile,
1298
    FTPFILE_WriteFile,
1299
    FTPFILE_QueryDataAvailable,
1300 1301
    NULL,
    FTPFILE_LockRequestFile
1302 1303
};

1304
/***********************************************************************
1305
 *           FTP_FtpOpenFileW (Internal)
1306 1307 1308 1309 1310 1311 1312 1313
 *
 * Open a remote file for writing or reading
 *
 * RETURNS
 *    HINTERNET handle on success
 *    NULL on failure
 *
 */
1314
static HINTERNET FTP_FtpOpenFileW(ftp_session_t *lpwfs,
1315
	LPCWSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
1316
	DWORD_PTR dwContext)
1317 1318 1319
{
    INT nDataSocket;
    BOOL bSuccess = FALSE;
1320
    ftp_file_t *lpwh = NULL;
1321
    appinfo_t *hIC = NULL;
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338

    TRACE("\n");

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

    if (GENERIC_READ == fdwAccess)
    {
        /* Set up socket to retrieve data */
        bSuccess = FTP_SendRetrieve(lpwfs, lpszFileName, dwFlags);
    }
    else if (GENERIC_WRITE == fdwAccess)
    {
        /* Set up socket to send data */
        bSuccess = FTP_SendStore(lpwfs, lpszFileName, dwFlags);
    }

1339 1340
    /* Get data socket to server */
    if (bSuccess && FTP_GetDataSocket(lpwfs, &nDataSocket))
1341
    {
1342
        lpwh = alloc_object(&lpwfs->hdr, &FTPFILEVtbl, sizeof(ftp_file_t));
1343 1344 1345 1346
        lpwh->hdr.htype = WH_HFILE;
        lpwh->hdr.dwFlags = dwFlags;
        lpwh->hdr.dwContext = dwContext;
        lpwh->nDataSocket = nDataSocket;
1347 1348 1349
        lpwh->cache_file = NULL;
        lpwh->cache_file_handle = INVALID_HANDLE_VALUE;
        lpwh->session_deleted = FALSE;
1350 1351 1352

        WININET_AddRef( &lpwfs->hdr );
        lpwh->lpFtpSession = lpwfs;
1353
        list_add_head( &lpwfs->hdr.children, &lpwh->hdr.entry );
1354 1355
	
	/* Indicate that a download is currently in progress */
1356
	lpwfs->download_in_progress = lpwh;
1357 1358
    }

1359
    if (lpwfs->lstnSocket != -1)
1360
    {
1361
        closesocket(lpwfs->lstnSocket);
1362 1363
        lpwfs->lstnSocket = -1;
    }
1364

1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    if (bSuccess && fdwAccess == GENERIC_READ)
    {
        WCHAR filename[MAX_PATH + 1];
        URL_COMPONENTSW uc;
        DWORD len;

        memset(&uc, 0, sizeof(uc));
        uc.dwStructSize = sizeof(uc);
        uc.nScheme      = INTERNET_SCHEME_FTP;
        uc.lpszHostName = lpwfs->servername;
        uc.nPort        = lpwfs->serverport;
        uc.lpszUserName = lpwfs->lpszUserName;
        uc.lpszUrlPath  = heap_strdupW(lpszFileName);

        if (!InternetCreateUrlW(&uc, 0, NULL, &len) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
1381
            WCHAR *url = heap_alloc(len * sizeof(WCHAR));
1382 1383 1384 1385 1386 1387 1388 1389 1390

            if (url && InternetCreateUrlW(&uc, 0, url, &len) && CreateUrlCacheEntryW(url, 0, NULL, filename, 0))
            {
                lpwh->cache_file = heap_strdupW(filename);
                lpwh->cache_file_handle = CreateFileW(filename, GENERIC_WRITE, FILE_SHARE_READ,
                                                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
                if (lpwh->cache_file_handle == INVALID_HANDLE_VALUE)
                {
                    WARN("Could not create cache file: %u\n", GetLastError());
1391
                    heap_free(lpwh->cache_file);
1392 1393 1394
                    lpwh->cache_file = NULL;
                }
            }
1395
            heap_free(url);
1396
        }
1397
        heap_free(uc.lpszUrlPath);
1398 1399
    }

1400
    hIC = lpwfs->lpAppInfo;
1401
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1402 1403
    {
        INTERNET_ASYNC_RESULT iar;
1404

1405
	if (lpwh)
1406
	{
1407
            iar.dwResult = (DWORD_PTR)lpwh->hdr.hInternet;
1408
            iar.dwError = ERROR_SUCCESS;
1409
            INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
1410 1411
                &iar, sizeof(INTERNET_ASYNC_RESULT));
	}
1412

1413 1414 1415 1416 1417
        if(bSuccess) {
            FTP_ReceiveRequestData(lpwh, TRUE);
        }else {
            iar.dwResult = 0;
            iar.dwError = INTERNET_GetLastError();
1418
            INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1419 1420
                    &iar, sizeof(INTERNET_ASYNC_RESULT));
        }
1421 1422
    }

1423
    if(!bSuccess)
1424
        return FALSE;
1425

1426
    return lpwh->hdr.hInternet;
1427 1428 1429
}


1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
/***********************************************************************
 *           FtpOpenFileA (WININET.@)
 *
 * Open a remote file for writing or reading
 *
 * RETURNS
 *    HINTERNET handle on success
 *    NULL on failure
 *
 */
HINTERNET WINAPI FtpOpenFileA(HINTERNET hFtpSession,
    LPCSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
    DWORD_PTR dwContext)
{
    LPWSTR lpwzFileName;
    HINTERNET ret;

1447
    lpwzFileName = heap_strdupAtoW(lpszFileName);
1448
    ret = FtpOpenFileW(hFtpSession, lpwzFileName, fdwAccess, dwFlags, dwContext);
1449
    heap_free(lpwzFileName);
1450 1451 1452
    return ret;
}

1453 1454 1455 1456 1457 1458 1459
typedef struct {
    task_header_t hdr;
    WCHAR *file_name;
    DWORD access;
    DWORD flags;
    DWORD_PTR context;
} open_file_task_t;
1460

1461
static void AsyncFtpOpenFileProc(task_header_t *hdr)
1462
{
1463 1464
    open_file_task_t *task = (open_file_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
1465

1466
    TRACE("%p\n", session);
1467

1468 1469
    FTP_FtpOpenFileW(session, task->file_name, task->access, task->flags, task->context);
    heap_free(task->file_name);
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
}

/***********************************************************************
 *           FtpOpenFileW (WININET.@)
 *
 * Open a remote file for writing or reading
 *
 * RETURNS
 *    HINTERNET handle on success
 *    NULL on failure
 *
 */
HINTERNET WINAPI FtpOpenFileW(HINTERNET hFtpSession,
    LPCWSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
    DWORD_PTR dwContext)
{
1486
    ftp_session_t *lpwfs;
1487
    appinfo_t *hIC = NULL;
1488 1489 1490 1491 1492
    HINTERNET r = NULL;

    TRACE("(%p,%s,0x%08x,0x%08x,0x%08lx)\n", hFtpSession,
        debugstr_w(lpszFileName), fdwAccess, dwFlags, dwContext);

1493
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
        goto lend;
    }

    if ((!lpszFileName) ||
        ((fdwAccess != GENERIC_READ) && (fdwAccess != GENERIC_WRITE)) ||
        ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY))
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

    hIC = lpwfs->lpAppInfo;
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
1523
        open_file_task_t *task;
1524

1525
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpOpenFileProc, sizeof(*task));
1526 1527 1528 1529 1530 1531 1532
        task->file_name = heap_strdupW(lpszFileName);
        task->access = fdwAccess;
        task->flags = dwFlags;
        task->context = dwContext;

        INTERNET_AsyncCall(&task->hdr);
        r = NULL;
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    }
    else
    {
	r = FTP_FtpOpenFileW(lpwfs, lpszFileName, fdwAccess, dwFlags, dwContext);
    }

lend:
    WININET_Release( &lpwfs->hdr );

    return r;
}


1546
/***********************************************************************
1547
 *           FtpGetFileA (WININET.@)
1548 1549 1550 1551 1552 1553 1554 1555
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1556
BOOL WINAPI FtpGetFileA(HINTERNET hInternet, LPCSTR lpszRemoteFile, LPCSTR lpszNewFile,
1557
    BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1558
    DWORD_PTR dwContext)
1559
{
1560 1561 1562 1563
    LPWSTR lpwzRemoteFile;
    LPWSTR lpwzNewFile;
    BOOL ret;
    
1564 1565
    lpwzRemoteFile = heap_strdupAtoW(lpszRemoteFile);
    lpwzNewFile = heap_strdupAtoW(lpszNewFile);
1566 1567
    ret = FtpGetFileW(hInternet, lpwzRemoteFile, lpwzNewFile, fFailIfExists,
        dwLocalFlagsAttribute, dwInternetFlags, dwContext);
1568 1569
    heap_free(lpwzRemoteFile);
    heap_free(lpwzNewFile);
1570 1571 1572
    return ret;
}

1573 1574 1575 1576 1577 1578 1579 1580 1581
typedef struct {
    task_header_t hdr;
    WCHAR *remote_file;
    WCHAR *new_file;
    BOOL fail_if_exists;
    DWORD local_attr;
    DWORD flags;
    DWORD_PTR context;
} get_file_task_t;
1582

1583
static void AsyncFtpGetFileProc(task_header_t *hdr)
1584
{
1585 1586
    get_file_task_t *task = (get_file_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
1587

1588
    TRACE("%p\n", session);
1589

1590 1591 1592 1593
    FTP_FtpGetFileW(session, task->remote_file, task->new_file, task->fail_if_exists,
             task->local_attr, task->flags, task->context);
    heap_free(task->remote_file);
    heap_free(task->new_file);
1594 1595
}

1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

/***********************************************************************
 *           FtpGetFileW (WININET.@)
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1607 1608
BOOL WINAPI FtpGetFileW(HINTERNET hInternet, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
    BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1609
    DWORD_PTR dwContext)
1610
{
1611
    ftp_session_t *lpwfs;
1612
    appinfo_t *hIC = NULL;
1613
    BOOL r = FALSE;
1614

1615 1616 1617 1618 1619 1620
    if (!lpszRemoteFile || !lpszNewFile)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

1621
    lpwfs = (ftp_session_t*) get_handle_object( hInternet );
1622 1623 1624 1625 1626 1627 1628
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
1629 1630
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1631
        goto lend;
1632 1633
    }

1634 1635 1636 1637 1638 1639
    if ((dwInternetFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

1640 1641 1642
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1643
        goto lend;
1644 1645
    }
    
1646
    hIC = lpwfs->lpAppInfo;
1647 1648
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
1649
        get_file_task_t *task;
1650

1651
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpGetFileProc, sizeof(*task));
1652 1653 1654 1655 1656 1657
        task->remote_file = heap_strdupW(lpszRemoteFile);
        task->new_file = heap_strdupW(lpszNewFile);
        task->local_attr = dwLocalFlagsAttribute;
        task->fail_if_exists = fFailIfExists;
        task->flags = dwInternetFlags;
        task->context = dwContext;
1658

1659
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
1660 1661 1662
    }
    else
    {
1663
        r = FTP_FtpGetFileW(lpwfs, lpszRemoteFile, lpszNewFile,
1664 1665
           fFailIfExists, dwLocalFlagsAttribute, dwInternetFlags, dwContext);
    }
1666 1667

lend:
1668
    WININET_Release( &lpwfs->hdr );
1669 1670

    return r;
1671 1672 1673
}


1674
/***********************************************************************
1675
 *           FTP_FtpGetFileW (Internal)
1676 1677 1678 1679 1680 1681 1682 1683
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1684
static BOOL FTP_FtpGetFileW(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
1685
	BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1686
	DWORD_PTR dwContext)
1687 1688 1689
{
    BOOL bSuccess = FALSE;
    HANDLE hFile;
1690
    appinfo_t *hIC = NULL;
1691

1692
    TRACE("lpszRemoteFile(%s) lpszNewFile(%s)\n", debugstr_w(lpszRemoteFile), debugstr_w(lpszNewFile));
1693

1694 1695 1696 1697
    /* Clear any error information */
    INTERNET_SetLastError(0);

    /* Ensure we can write to lpszNewfile by opening it */
1698
    hFile = CreateFileW(lpszNewFile, GENERIC_WRITE, 0, 0, fFailIfExists ?
1699 1700
        CREATE_NEW : CREATE_ALWAYS, dwLocalFlagsAttribute, 0);
    if (INVALID_HANDLE_VALUE == hFile)
1701
        return FALSE;
1702 1703

    /* Set up socket to retrieve data */
1704
    if (FTP_SendRetrieve(lpwfs, lpszRemoteFile, dwInternetFlags))
1705 1706 1707
    {
        INT nDataSocket;

1708 1709
        /* Get data socket to server */
        if (FTP_GetDataSocket(lpwfs, &nDataSocket))
1710 1711 1712 1713
        {
            INT nResCode;

            /* Receive data */
1714
            FTP_RetrieveFileData(lpwfs, nDataSocket, hFile);
1715 1716
            closesocket(nDataSocket);

1717
            nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
1718 1719 1720 1721
            if (nResCode)
            {
                if (nResCode == 226)
                    bSuccess = TRUE;
1722
                else
1723 1724 1725 1726 1727
                    FTP_SetResponseError(nResCode);
            }
        }
    }

1728
    if (lpwfs->lstnSocket != -1)
1729
    {
1730
        closesocket(lpwfs->lstnSocket);
1731 1732
        lpwfs->lstnSocket = -1;
    }
1733

1734
    CloseHandle(hFile);
1735

1736
    hIC = lpwfs->lpAppInfo;
1737
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1738 1739
    {
        INTERNET_ASYNC_RESULT iar;
1740

1741 1742
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1743
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1744 1745 1746
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

1747
    if (!bSuccess) DeleteFileW(lpszNewFile);
1748 1749 1750
    return bSuccess;
}

1751 1752 1753
/***********************************************************************
 *           FtpGetFileSize  (WININET.@)
 */
1754 1755 1756 1757 1758 1759 1760 1761 1762
DWORD WINAPI FtpGetFileSize( HINTERNET hFile, LPDWORD lpdwFileSizeHigh )
{
    FIXME("(%p, %p)\n", hFile, lpdwFileSizeHigh);

    if (lpdwFileSizeHigh)
        *lpdwFileSizeHigh = 0;

    return 0;
}
1763 1764

/***********************************************************************
1765
 *           FtpDeleteFileA  (WININET.@)
1766 1767 1768 1769 1770 1771 1772 1773
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1774
BOOL WINAPI FtpDeleteFileA(HINTERNET hFtpSession, LPCSTR lpszFileName)
1775
{
1776 1777 1778
    LPWSTR lpwzFileName;
    BOOL ret;
    
1779
    lpwzFileName = heap_strdupAtoW(lpszFileName);
1780
    ret = FtpDeleteFileW(hFtpSession, lpwzFileName);
1781
    heap_free(lpwzFileName);
1782 1783 1784
    return ret;
}

1785 1786 1787 1788 1789 1790
typedef struct {
    task_header_t hdr;
    WCHAR *file_name;
} delete_file_task_t;

static void AsyncFtpDeleteFileProc(task_header_t *hdr)
1791
{
1792 1793
    delete_file_task_t *task = (delete_file_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
1794

1795
    TRACE("%p\n", session);
1796

1797 1798
    FTP_FtpDeleteFileW(session, task->file_name);
    heap_free(task->file_name);
1799 1800
}

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
/***********************************************************************
 *           FtpDeleteFileW  (WININET.@)
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1811 1812
BOOL WINAPI FtpDeleteFileW(HINTERNET hFtpSession, LPCWSTR lpszFileName)
{
1813
    ftp_session_t *lpwfs;
1814
    appinfo_t *hIC = NULL;
1815
    BOOL r = FALSE;
1816

1817
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1818 1819 1820 1821 1822 1823 1824
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
1825 1826
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1827
        goto lend;
1828 1829
    }

1830 1831 1832 1833 1834 1835
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

1836 1837 1838 1839 1840 1841
    if (!lpszFileName)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

1842
    hIC = lpwfs->lpAppInfo;
1843 1844
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
1845
        delete_file_task_t *task;
1846

1847
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpDeleteFileProc, sizeof(*task));
1848
        task->file_name = heap_strdupW(lpszFileName);
1849

1850
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
1851 1852 1853
    }
    else
    {
1854
        r = FTP_FtpDeleteFileW(lpwfs, lpszFileName);
1855
    }
1856 1857

lend:
1858
    WININET_Release( &lpwfs->hdr );
1859 1860

    return r;
1861 1862 1863
}

/***********************************************************************
1864
 *           FTP_FtpDeleteFileW  (Internal)
1865 1866 1867 1868 1869 1870 1871 1872
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1873
BOOL FTP_FtpDeleteFileW(ftp_session_t *lpwfs, LPCWSTR lpszFileName)
1874 1875 1876
{
    INT nResCode;
    BOOL bSuccess = FALSE;
1877
    appinfo_t *hIC = NULL;
1878

1879
    TRACE("%p\n", lpwfs);
1880

1881 1882 1883 1884 1885 1886
    /* Clear any error information */
    INTERNET_SetLastError(0);

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_DELE, lpszFileName, 0, 0, 0))
        goto lend;

1887
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1888 1889 1890 1891 1892 1893 1894 1895
    if (nResCode)
    {
        if (nResCode == 250)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }
lend:
1896
    hIC = lpwfs->lpAppInfo;
1897
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1898 1899
    {
        INTERNET_ASYNC_RESULT iar;
1900

1901 1902
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1903
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1904 1905 1906 1907 1908 1909 1910 1911
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}


/***********************************************************************
1912
 *           FtpRemoveDirectoryA  (WININET.@)
1913 1914 1915 1916 1917 1918 1919 1920
 *
 * Remove a directory on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1921
BOOL WINAPI FtpRemoveDirectoryA(HINTERNET hFtpSession, LPCSTR lpszDirectory)
1922
{
1923 1924 1925
    LPWSTR lpwzDirectory;
    BOOL ret;
    
1926
    lpwzDirectory = heap_strdupAtoW(lpszDirectory);
1927
    ret = FtpRemoveDirectoryW(hFtpSession, lpwzDirectory);
1928
    heap_free(lpwzDirectory);
1929 1930 1931
    return ret;
}

1932
static void AsyncFtpRemoveDirectoryProc(task_header_t *hdr)
1933
{
1934 1935
    directory_task_t *task = (directory_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
1936

1937
    TRACE("%p\n", session);
1938

1939 1940
    FTP_FtpRemoveDirectoryW(session, task->directory);
    heap_free(task->directory);
1941 1942
}

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
/***********************************************************************
 *           FtpRemoveDirectoryW  (WININET.@)
 *
 * Remove a directory on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1953 1954
BOOL WINAPI FtpRemoveDirectoryW(HINTERNET hFtpSession, LPCWSTR lpszDirectory)
{
1955
    ftp_session_t *lpwfs;
1956
    appinfo_t *hIC = NULL;
1957
    BOOL r = FALSE;
1958

1959
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1960 1961 1962 1963 1964 1965 1966
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
1967 1968
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1969
        goto lend;
1970 1971
    }

1972 1973 1974 1975 1976 1977
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

1978 1979 1980 1981 1982 1983
    if (!lpszDirectory)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

1984
    hIC = lpwfs->lpAppInfo;
1985 1986
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
1987
        directory_task_t *task;
1988

1989
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpRemoveDirectoryProc, sizeof(*task));
1990
        task->directory = heap_strdupW(lpszDirectory);
1991

1992
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
1993 1994 1995
    }
    else
    {
1996
        r = FTP_FtpRemoveDirectoryW(lpwfs, lpszDirectory);
1997
    }
1998 1999

lend:
2000
    WININET_Release( &lpwfs->hdr );
2001 2002

    return r;
2003 2004 2005
}

/***********************************************************************
2006
 *           FTP_FtpRemoveDirectoryW  (Internal)
2007 2008 2009 2010 2011 2012 2013 2014
 *
 * Remove a directory on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
2015
BOOL FTP_FtpRemoveDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
2016 2017 2018
{
    INT nResCode;
    BOOL bSuccess = FALSE;
2019
    appinfo_t *hIC = NULL;
2020 2021

    TRACE("\n");
2022

2023 2024 2025 2026 2027 2028
    /* Clear any error information */
    INTERNET_SetLastError(0);

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RMD, lpszDirectory, 0, 0, 0))
        goto lend;

2029
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2030 2031 2032 2033 2034 2035 2036 2037 2038
    if (nResCode)
    {
        if (nResCode == 250)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
2039
    hIC = lpwfs->lpAppInfo;
2040
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2041 2042
    {
        INTERNET_ASYNC_RESULT iar;
2043

2044 2045
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2046
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2047 2048 2049 2050 2051 2052 2053 2054
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}


/***********************************************************************
2055
 *           FtpRenameFileA  (WININET.@)
2056 2057 2058 2059 2060 2061 2062 2063
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
2064
BOOL WINAPI FtpRenameFileA(HINTERNET hFtpSession, LPCSTR lpszSrc, LPCSTR lpszDest)
2065
{
2066 2067 2068 2069
    LPWSTR lpwzSrc;
    LPWSTR lpwzDest;
    BOOL ret;
    
2070 2071
    lpwzSrc = heap_strdupAtoW(lpszSrc);
    lpwzDest = heap_strdupAtoW(lpszDest);
2072
    ret = FtpRenameFileW(hFtpSession, lpwzSrc, lpwzDest);
2073 2074
    heap_free(lpwzSrc);
    heap_free(lpwzDest);
2075 2076 2077
    return ret;
}

2078 2079 2080 2081 2082 2083 2084
typedef struct {
    task_header_t hdr;
    WCHAR *src_file;
    WCHAR *dst_file;
} rename_file_task_t;

static void AsyncFtpRenameFileProc(task_header_t *hdr)
2085
{
2086 2087
    rename_file_task_t *task = (rename_file_task_t*)hdr;
    ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
2088

2089
    TRACE("%p\n", session);
2090

2091 2092 2093
    FTP_FtpRenameFileW(session, task->src_file, task->dst_file);
    heap_free(task->src_file);
    heap_free(task->dst_file);
2094 2095
}

2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
/***********************************************************************
 *           FtpRenameFileW  (WININET.@)
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
2106 2107
BOOL WINAPI FtpRenameFileW(HINTERNET hFtpSession, LPCWSTR lpszSrc, LPCWSTR lpszDest)
{
2108
    ftp_session_t *lpwfs;
2109
    appinfo_t *hIC = NULL;
2110
    BOOL r = FALSE;
2111

2112
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
2113 2114 2115 2116 2117 2118 2119
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
2120 2121
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2122
        goto lend;
2123 2124
    }

2125 2126 2127 2128 2129 2130
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

2131 2132 2133 2134 2135 2136
    if (!lpszSrc || !lpszDest)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

2137
    hIC = lpwfs->lpAppInfo;
2138 2139
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
2140
        rename_file_task_t *task;
2141

2142
        task = alloc_async_task(&lpwfs->hdr, AsyncFtpRenameFileProc, sizeof(*task));
2143 2144
        task->src_file = heap_strdupW(lpszSrc);
        task->dst_file = heap_strdupW(lpszDest);
2145

2146
        r = res_to_le(INTERNET_AsyncCall(&task->hdr));
2147 2148 2149
    }
    else
    {
2150
        r = FTP_FtpRenameFileW(lpwfs, lpszSrc, lpszDest);
2151
    }
2152 2153

lend:
2154
    WININET_Release( &lpwfs->hdr );
2155 2156

    return r;
2157 2158 2159
}

/***********************************************************************
2160
 *           FTP_FtpRenameFileW  (Internal)
2161 2162 2163 2164 2165 2166 2167 2168
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
2169
BOOL FTP_FtpRenameFileW(ftp_session_t *lpwfs, LPCWSTR lpszSrc, LPCWSTR lpszDest)
2170 2171 2172
{
    INT nResCode;
    BOOL bSuccess = FALSE;
2173
    appinfo_t *hIC = NULL;
2174 2175

    TRACE("\n");
2176

2177 2178 2179 2180 2181 2182
    /* Clear any error information */
    INTERNET_SetLastError(0);

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNFR, lpszSrc, 0, 0, 0))
        goto lend;

2183
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2184 2185 2186 2187 2188
    if (nResCode == 350)
    {
        if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNTO, lpszDest, 0, 0, 0))
            goto lend;

2189
        nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2190 2191 2192 2193 2194 2195 2196 2197
    }

    if (nResCode == 250)
        bSuccess = TRUE;
    else
        FTP_SetResponseError(nResCode);

lend:
2198
    hIC = lpwfs->lpAppInfo;
2199
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2200 2201
    {
        INTERNET_ASYNC_RESULT iar;
2202

2203 2204
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2205
        INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2206 2207 2208 2209 2210 2211
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

2212 2213 2214
/***********************************************************************
 *           FtpCommandA  (WININET.@)
 */
2215 2216 2217
BOOL WINAPI FtpCommandA( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
                         LPCSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
{
2218 2219 2220 2221
    BOOL r;
    WCHAR *cmdW;

    TRACE("%p %d 0x%08x %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
2222 2223
          debugstr_a(lpszCommand), dwContext, phFtpCommand);

2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
    if (fExpectResponse)
    {
        FIXME("data connection not supported\n");
        return FALSE;
    }

    if (!lpszCommand || !lpszCommand[0])
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

2236
    if (!(cmdW = heap_strdupAtoW(lpszCommand)))
2237 2238 2239 2240 2241 2242 2243
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }

    r = FtpCommandW(hConnect, fExpectResponse, dwFlags, cmdW, dwContext, phFtpCommand);

2244
    heap_free(cmdW);
2245
    return r;
2246 2247
}

2248 2249 2250
/***********************************************************************
 *           FtpCommandW  (WININET.@)
 */
2251 2252 2253
BOOL WINAPI FtpCommandW( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
                         LPCWSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
{
2254
    BOOL r = FALSE;
2255
    ftp_session_t *lpwfs;
2256 2257 2258 2259 2260 2261
    LPSTR cmd = NULL;
    DWORD len, nBytesSent= 0;
    INT nResCode, nRC = 0;

    TRACE("%p %d 0x%08x %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
           debugstr_w(lpszCommand), dwContext, phFtpCommand);
2262

2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
    if (!lpszCommand || !lpszCommand[0])
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (fExpectResponse)
    {
        FIXME("data connection not supported\n");
        return FALSE;
    }

2275
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
        goto lend;
    }

    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

    len = WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, NULL, 0, NULL, NULL) + strlen(szCRLF);
2295
    if ((cmd = heap_alloc(len)))
2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
        WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, cmd, len, NULL, NULL);
    else
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        goto lend;
    }

    strcat(cmd, szCRLF);
    len--;

2306
    TRACE("Sending (%s) len(%d)\n", debugstr_a(cmd), len);
2307 2308
    while ((nBytesSent < len) && (nRC != -1))
    {
2309
        nRC = sock_send(lpwfs->sndSocket, cmd + nBytesSent, len - nBytesSent, 0);
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
        if (nRC != -1)
        {
            nBytesSent += nRC;
            TRACE("Sent %d bytes\n", nRC);
        }
    }

    if (nBytesSent)
    {
        nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
        if (nResCode > 0 && nResCode < 400)
            r = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    WININET_Release( &lpwfs->hdr );
2328
    heap_free( cmd );
2329
    return r;
2330
}
2331

2332 2333 2334 2335 2336 2337

/***********************************************************************
 *           FTPSESSION_Destroy (internal)
 *
 * Deallocate session handle
 */
2338
static void FTPSESSION_Destroy(object_header_t *hdr)
2339
{
2340
    ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2341 2342 2343 2344 2345

    TRACE("\n");

    WININET_Release(&lpwfs->lpAppInfo->hdr);

2346 2347 2348
    heap_free(lpwfs->lpszPassword);
    heap_free(lpwfs->lpszUserName);
    heap_free(lpwfs->servername);
2349 2350
}

2351
static void FTPSESSION_CloseConnection(object_header_t *hdr)
2352
{
2353
    ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2354 2355 2356

    TRACE("\n");

2357
    INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
2358 2359 2360 2361 2362
                      INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);

    if (lpwfs->download_in_progress != NULL)
        lpwfs->download_in_progress->session_deleted = TRUE;

2363 2364
    if (lpwfs->sndSocket != -1)
        closesocket(lpwfs->sndSocket);
2365

2366 2367
    if (lpwfs->lstnSocket != -1)
        closesocket(lpwfs->lstnSocket);
2368 2369 2370 2371

    if (lpwfs->pasvSocket != -1)
        closesocket(lpwfs->pasvSocket);

2372
    INTERNET_SendCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
2373 2374
                      INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
}
2375

2376
static DWORD FTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
{
    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_CONNECT_FTP;
        return ERROR_SUCCESS;
    }

2390
    return INET_QueryOption(hdr, option, buffer, size, unicode);
2391 2392
}

2393
static const object_vtbl_t FTPSESSIONVtbl = {
2394
    FTPSESSION_Destroy,
2395
    FTPSESSION_CloseConnection,
2396
    FTPSESSION_QueryOption,
2397
    INET_SetOption,
2398
    NULL,
2399
    NULL,
2400
    NULL,
2401
    NULL
2402 2403 2404
};


2405 2406 2407 2408 2409 2410 2411 2412 2413
/***********************************************************************
 *           FTP_Connect (internal)
 *
 * Connect to a ftp server
 *
 * RETURNS
 *   HINTERNET a session handle on success
 *   NULL on failure
 *
2414 2415 2416 2417 2418 2419 2420 2421 2422
 * NOTES:
 *
 * Windows uses 'anonymous' as the username, when given a NULL username
 * and a NULL password. The password is first looked up in:
 *
 * HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\EmailName
 *
 * If this entry is not present it uses the current username as the password.
 *
2423 2424
 */

2425
HINTERNET FTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
2426
	INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2427
	LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
2428
	DWORD dwInternalFlags)
2429
{
2430 2431 2432 2433 2434 2435
    static const WCHAR szKey[] = {'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};
    static const WCHAR szValue[] = {'E','m','a','i','l','N','a','m','e',0};
2436
    static const WCHAR szDefaultUsername[] = {'a','n','o','n','y','m','o','u','s','\0'};
2437
    static const WCHAR szEmpty[] = {'\0'};
2438
    struct sockaddr_in socketAddr;
2439
    INT nsocket = -1;
2440
    socklen_t sock_namelen;
2441
    BOOL bSuccess = FALSE;
2442
    ftp_session_t *lpwfs = NULL;
2443
    char szaddr[INET6_ADDRSTRLEN];
2444

2445 2446
    TRACE("%p  Server(%s) Port(%d) User(%s) Paswd(%s)\n",
	    hIC, debugstr_w(lpszServerName),
2447
	    nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword));
2448

2449
    assert( hIC->hdr.htype == WH_HINIT );
2450

2451
    if ((!lpszUserName || !*lpszUserName) && lpszPassword && *lpszPassword)
2452
    {
2453
	INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2454
        return NULL;
2455 2456
    }
    
2457
    lpwfs = alloc_object(&hIC->hdr, &FTPSESSIONVtbl, sizeof(ftp_session_t));
2458 2459 2460
    if (NULL == lpwfs)
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2461
        return NULL;
2462 2463
    }

2464
    if (nServerPort == INTERNET_INVALID_PORT_NUMBER)
2465 2466 2467
        lpwfs->serverport = INTERNET_DEFAULT_FTP_PORT;
    else
        lpwfs->serverport = nServerPort;
2468

2469 2470 2471
    lpwfs->hdr.htype = WH_HFTPSESSION;
    lpwfs->hdr.dwFlags = dwFlags;
    lpwfs->hdr.dwContext = dwContext;
2472
    lpwfs->hdr.dwInternalFlags |= dwInternalFlags;
2473
    lpwfs->download_in_progress = NULL;
2474 2475 2476
    lpwfs->sndSocket = -1;
    lpwfs->lstnSocket = -1;
    lpwfs->pasvSocket = -1;
2477

2478 2479
    WININET_AddRef( &hIC->hdr );
    lpwfs->lpAppInfo = hIC;
2480
    list_add_head( &hIC->hdr.children, &lpwfs->hdr.entry );
2481

2482
    if(hIC->proxy && hIC->accessType == INTERNET_OPEN_TYPE_PROXY) {
2483
        if(wcschr(hIC->proxy, ' '))
2484
            FIXME("Several proxies not implemented.\n");
2485
        if(hIC->proxyBypass)
2486 2487
            FIXME("Proxy bypass is ignored.\n");
    }
2488
    if (!lpszUserName || !lpszUserName[0]) {
2489 2490 2491 2492
        HKEY key;
        WCHAR szPassword[MAX_PATH];
        DWORD len = sizeof(szPassword);

2493
        lpwfs->lpszUserName = heap_strdupW(szDefaultUsername);
2494 2495 2496 2497 2498 2499

        RegOpenKeyW(HKEY_CURRENT_USER, szKey, &key);
        if (RegQueryValueExW(key, szValue, NULL, NULL, (LPBYTE)szPassword, &len)) {
            /* Nothing in the registry, get the username and use that as the password */
            if (!GetUserNameW(szPassword, &len)) {
                /* Should never get here, but use an empty password as failsafe */
2500
                lstrcpyW(szPassword, szEmpty);
2501 2502 2503 2504 2505
            }
        }
        RegCloseKey(key);

        TRACE("Password used for anonymous ftp : (%s)\n", debugstr_w(szPassword));
2506
        lpwfs->lpszPassword = heap_strdupW(szPassword);
2507 2508
    }
    else {
2509 2510
        lpwfs->lpszUserName = heap_strdupW(lpszUserName);
        lpwfs->lpszPassword = heap_strdupW(lpszPassword ? lpszPassword : szEmpty);
2511
    }
2512
    lpwfs->servername = heap_strdupW(lpszServerName);
2513 2514
    
    /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2515
    if (!(lpwfs->hdr.dwInternalFlags & INET_OPENURL))
2516 2517 2518
    {
        INTERNET_ASYNC_RESULT iar;

2519
        iar.dwResult = (DWORD_PTR)lpwfs->hdr.hInternet;
2520 2521
        iar.dwError = ERROR_SUCCESS;

2522
        INTERNET_SendCallback(&hIC->hdr, dwContext,
2523 2524 2525 2526
                      INTERNET_STATUS_HANDLE_CREATED, &iar,
                      sizeof(INTERNET_ASYNC_RESULT));
    }
        
2527
    INTERNET_SendCallback(&hIC->hdr, dwContext, INTERNET_STATUS_RESOLVING_NAME,
2528
        (LPWSTR) lpszServerName, (lstrlenW(lpszServerName)+1) * sizeof(WCHAR));
2529

2530
    sock_namelen = sizeof(socketAddr);
2531
    if (!GetAddress(lpszServerName, lpwfs->serverport, (struct sockaddr *)&socketAddr, &sock_namelen, szaddr))
2532 2533 2534 2535 2536
    {
	INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
        goto lerror;
    }

2537 2538 2539 2540 2541 2542
    if (socketAddr.sin_family != AF_INET)
    {
        WARN("unsupported address family %d\n", socketAddr.sin_family);
        INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
        goto lerror;
    }
2543

2544
    INTERNET_SendCallback(&hIC->hdr, dwContext, INTERNET_STATUS_NAME_RESOLVED,
2545 2546
                      szaddr, strlen(szaddr)+1);

2547
    init_winsock();
2548 2549
    nsocket = socket(AF_INET,SOCK_STREAM,0);
    if (nsocket == -1)
2550 2551 2552 2553 2554
    {
	INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
        goto lerror;
    }

2555
    INTERNET_SendCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTING_TO_SERVER,
2556
                      szaddr, strlen(szaddr)+1);
2557

2558
    if (connect(nsocket, (struct sockaddr *)&socketAddr, sock_namelen) < 0)
2559
    {
2560
	ERR("Unable to connect (%d)\n", WSAGetLastError());
2561
	INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2562
	closesocket(nsocket);
2563 2564 2565
    }
    else
    {
2566
        TRACE("Connected to server\n");
2567
	lpwfs->sndSocket = nsocket;
2568
        INTERNET_SendCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTED_TO_SERVER,
2569
                          szaddr, strlen(szaddr)+1);
2570

2571
	sock_namelen = sizeof(lpwfs->socketAddress);
2572
	getsockname(nsocket, (struct sockaddr *) &lpwfs->socketAddress, &sock_namelen);
2573 2574 2575 2576 2577 2578 2579 2580 2581

        if (FTP_ConnectToHost(lpwfs))
        {
            TRACE("Successfully logged into server\n");
            bSuccess = TRUE;
        }
    }

lerror:
2582
    if (!bSuccess)
2583
    {
2584
        WININET_Release(&lpwfs->hdr);
2585
        return NULL;
2586 2587
    }

2588
    return lpwfs->hdr.hInternet;
2589 2590 2591 2592
}


/***********************************************************************
2593
 *           FTP_ConnectToHost (internal)
2594 2595 2596 2597 2598 2599 2600 2601
 *
 * Connect to a ftp server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
2602
static BOOL FTP_ConnectToHost(ftp_session_t *lpwfs)
2603 2604 2605 2606 2607
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
2608
    FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2609 2610 2611 2612

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_USER, lpwfs->lpszUserName, 0, 0, 0))
        goto lend;

2613
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
    if (nResCode)
    {
        /* Login successful... */
        if (nResCode == 230)
            bSuccess = TRUE;
        /* User name okay, need password... */
        else if (nResCode == 331)
            bSuccess = FTP_SendPassword(lpwfs);
        /* Need account for login... */
        else if (nResCode == 332)
            bSuccess = FTP_SendAccount(lpwfs);
        else
            FTP_SetResponseError(nResCode);
    }

    TRACE("Returning %d\n", bSuccess);
lend:
    return bSuccess;
}

2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
/***********************************************************************
 *           FTP_GetNextLine  (internal)
 *
 * Parse next line in directory string listing
 *
 * RETURNS
 *   Pointer to beginning of next line
 *   NULL on failure
 *
 */

static LPSTR FTP_GetNextLine(INT nSocket, LPDWORD dwLen)
{
2647 2648
    struct timeval tv = {RESPONSE_TIMEOUT,0};
    FD_SET set;
2649 2650 2651 2652 2653
    INT nRecv = 0;
    LPSTR lpszBuffer = INTERNET_GetResponseBuffer();

    TRACE("\n");

2654 2655
    FD_ZERO(&set);
    FD_SET(nSocket, &set);
2656 2657 2658

    while (nRecv < MAX_REPLY_LEN)
    {
2659
        if (select(nSocket+1, &set, NULL, NULL, &tv) > 0)
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
        {
            if (sock_recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
            {
                INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
                return NULL;
            }

            if (lpszBuffer[nRecv] == '\n')
            {
                lpszBuffer[nRecv] = '\0';
                *dwLen = nRecv - 1;
                TRACE(":%d %s\n", nRecv, lpszBuffer);
                return lpszBuffer;
            }
            if (lpszBuffer[nRecv] != '\r')
                nRecv++;
        }
	else
	{
            INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
            return NULL;
        }
    }

    return NULL;
}
2686 2687

/***********************************************************************
2688
 *           FTP_SendCommandA (internal)
2689 2690 2691 2692 2693 2694 2695 2696
 *
 * Send command to server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
Mike McCormack's avatar
Mike McCormack committed
2697
static BOOL FTP_SendCommandA(INT nSocket, FTP_COMMAND ftpCmd, LPCSTR lpszParam,
2698
	INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2699 2700 2701 2702
{
    	DWORD len;
	CHAR *buf;
	DWORD nBytesSent = 0;
2703
	int nRC = 0;
2704
	DWORD dwParamLen;
2705

2706
	TRACE("%d: (%s) %d\n", ftpCmd, debugstr_a(lpszParam), nSocket);
2707 2708

	if (lpfnStatusCB)
2709
        {
2710
            lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2711
        }
2712

2713 2714
	dwParamLen = lpszParam?strlen(lpszParam)+1:0;
	len = dwParamLen + strlen(szFtpCommands[ftpCmd]) + strlen(szCRLF);
2715
	if (NULL == (buf = heap_alloc(len+1)))
2716 2717 2718 2719
	{
	    INTERNET_SetLastError(ERROR_OUTOFMEMORY);
	    return FALSE;
	}
2720 2721
	sprintf(buf, "%s%s%s%s", szFtpCommands[ftpCmd], dwParamLen ? " " : "",
		dwParamLen ? lpszParam : "", szCRLF);
2722

2723
	TRACE("Sending (%s) len(%d)\n", debugstr_a(buf), len);
2724
	while((nBytesSent < len) && (nRC != -1))
2725
	{
2726
		nRC = sock_send(nSocket, buf+nBytesSent, len - nBytesSent, 0);
2727 2728
		nBytesSent += nRC;
	}
2729
    heap_free(buf);
2730 2731

	if (lpfnStatusCB)
2732
        {
2733 2734
            lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_REQUEST_SENT,
                         &nBytesSent, sizeof(DWORD));
2735
        }
2736

2737
	TRACE("Sent %d bytes\n", nBytesSent);
2738
	return (nRC != -1);
2739 2740
}

2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
/***********************************************************************
 *           FTP_SendCommand (internal)
 *
 * Send command to server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
2751
static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
2752
	INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2753 2754
{
    BOOL ret;
2755
    LPSTR lpszParamA = heap_strdupWtoA(lpszParam);
2756
    ret = FTP_SendCommandA(nSocket, ftpCmd, lpszParamA, lpfnStatusCB, hdr, dwContext);
2757
    heap_free(lpszParamA);
2758 2759
    return ret;
}
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770

/***********************************************************************
 *           FTP_ReceiveResponse (internal)
 *
 * Receive response from server
 *
 * RETURNS
 *   Reply code on success
 *   0 on failure
 *
 */
2771
INT FTP_ReceiveResponse(ftp_session_t *lpwfs, DWORD_PTR dwContext)
2772
{
2773
    LPSTR lpszResponse = INTERNET_GetResponseBuffer();
2774 2775
    DWORD nRecv;
    INT rc = 0;
2776 2777 2778
    char firstprefix[5];
    BOOL multiline = FALSE;

2779
    TRACE("socket(%d)\n", lpwfs->sndSocket);
2780

2781
    INTERNET_SendCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2782 2783 2784

    while(1)
    {
2785
	if (!FTP_GetNextLine(lpwfs->sndSocket, &nRecv))
2786 2787
	    goto lerror;

2788 2789 2790 2791 2792 2793 2794
        if (nRecv >= 3)
	{
	    if(!multiline)
	    {
	        if(lpszResponse[3] != '-')
		    break;
		else
Austin English's avatar
Austin English committed
2795
		{  /* Start of multiline response.  Loop until we get "nnn " */
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807
		    multiline = TRUE;
		    memcpy(firstprefix, lpszResponse, 3);
		    firstprefix[3] = ' ';
		    firstprefix[4] = '\0';
		}
	    }
	    else
	    {
	        if(!memcmp(firstprefix, lpszResponse, 4))
		    break;
	    }
	}
2808
    }
2809

2810 2811 2812 2813
    if (nRecv >= 3)
    {
        rc = atoi(lpszResponse);

2814
        INTERNET_SendCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
		    &nRecv, sizeof(DWORD));
    }

lerror:
    TRACE("return %d\n", rc);
    return rc;
}


/***********************************************************************
 *           FTP_SendPassword (internal)
 *
 * Send password to ftp server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
2834
static BOOL FTP_SendPassword(ftp_session_t *lpwfs)
2835 2836 2837 2838 2839 2840 2841
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PASS, lpwfs->lpszPassword, 0, 0, 0))
        goto lend;
2842

2843
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
    if (nResCode)
    {
        TRACE("Received reply code %d\n", nResCode);
        /* Login successful... */
        if (nResCode == 230)
            bSuccess = TRUE;
        /* Command not implemented, superfluous at the server site... */
        /* Need account for login... */
        else if (nResCode == 332)
            bSuccess = FTP_SendAccount(lpwfs);
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    TRACE("Returning %d\n", bSuccess);
    return bSuccess;
}


/***********************************************************************
 *           FTP_SendAccount (internal)
 *
2867
 *
2868 2869 2870 2871 2872 2873
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2874
static BOOL FTP_SendAccount(ftp_session_t *lpwfs)
2875 2876 2877 2878 2879
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
2880
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_ACCT, szNoAccount, 0, 0, 0))
2881 2882
        goto lend;

2883
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
    if (nResCode)
        bSuccess = TRUE;
    else
        FTP_SetResponseError(nResCode);

lend:
    return bSuccess;
}


/***********************************************************************
 *           FTP_SendStore (internal)
 *
 * Send request to upload file to ftp server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2904
static BOOL FTP_SendStore(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
    if (!FTP_InitListenSocket(lpwfs))
        goto lend;

    if (!FTP_SendType(lpwfs, dwType))
        goto lend;

2916
    if (!FTP_SendPortOrPasv(lpwfs))
2917 2918 2919 2920
        goto lend;

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_STOR, lpszRemoteFile, 0, 0, 0))
	    goto lend;
2921
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2922 2923
    if (nResCode)
    {
2924
        if (nResCode == 150 || nResCode == 125)
2925 2926 2927 2928 2929 2930
            bSuccess = TRUE;
	else
            FTP_SetResponseError(nResCode);
    }

lend:
2931
    if (!bSuccess && lpwfs->lstnSocket != -1)
2932
    {
2933
        closesocket(lpwfs->lstnSocket);
2934
        lpwfs->lstnSocket = -1;
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
    }

    return bSuccess;
}


/***********************************************************************
 *           FTP_InitListenSocket (internal)
 *
 * Create a socket to listen for server response
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2951
static BOOL FTP_InitListenSocket(ftp_session_t *lpwfs)
2952 2953
{
    BOOL bSuccess = FALSE;
2954
    socklen_t namelen = sizeof(lpwfs->lstnSocketAddress);
2955 2956 2957

    TRACE("\n");

2958
    init_winsock();
2959
    lpwfs->lstnSocket = socket(AF_INET, SOCK_STREAM, 0);
2960
    if (lpwfs->lstnSocket == -1)
2961 2962 2963 2964 2965
    {
        TRACE("Unable to create listening socket\n");
            goto lend;
    }

2966 2967 2968 2969
    /* We obtain our ip addr from the name of the command channel socket */
    lpwfs->lstnSocketAddress = lpwfs->socketAddress;

    /* and get the system to assign us a port */
2970
    lpwfs->lstnSocketAddress.sin_port = htons(0);
2971

2972
    if (bind(lpwfs->lstnSocket,(struct sockaddr *) &lpwfs->lstnSocketAddress, sizeof(lpwfs->lstnSocketAddress)) == -1)
2973 2974 2975 2976 2977
    {
        TRACE("Unable to bind socket\n");
        goto lend;
    }

2978
    if (listen(lpwfs->lstnSocket, MAX_BACKLOG) == -1)
2979 2980 2981 2982 2983
    {
        TRACE("listen failed\n");
        goto lend;
    }

2984
    if (getsockname(lpwfs->lstnSocket, (struct sockaddr *) &lpwfs->lstnSocketAddress, &namelen) != -1)
2985 2986 2987
        bSuccess = TRUE;

lend:
2988
    if (!bSuccess && lpwfs->lstnSocket != -1)
2989
    {
2990
        closesocket(lpwfs->lstnSocket);
2991
        lpwfs->lstnSocket = -1;
2992 2993 2994 2995 2996 2997 2998 2999 3000
    }

    return bSuccess;
}


/***********************************************************************
 *           FTP_SendType (internal)
 *
3001
 * Tell server type of data being transferred
3002 3003 3004 3005 3006
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
3007 3008 3009
 * W98SE doesn't cache the type that's currently set
 * (i.e. it sends it always),
 * so we probably don't want to do that either.
3010
 */
3011
static BOOL FTP_SendType(ftp_session_t *lpwfs, DWORD dwType)
3012 3013
{
    INT nResCode;
3014
    WCHAR type[] = { 'I','\0' };
3015 3016 3017 3018
    BOOL bSuccess = FALSE;

    TRACE("\n");
    if (dwType & INTERNET_FLAG_TRANSFER_ASCII)
3019
        type[0] = 'A';
3020 3021 3022 3023

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_TYPE, type, 0, 0, 0))
        goto lend;

3024
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext)/100;
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
    if (nResCode)
    {
        if (nResCode == 2)
            bSuccess = TRUE;
	else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}

3037 3038

#if 0  /* FIXME: should probably be used for FtpGetFileSize */
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
/***********************************************************************
 *           FTP_GetFileSize (internal)
 *
 * Retrieves from the server the size of the given file
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3049
static BOOL FTP_GetFileSize(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD *dwSize)
3050 3051 3052 3053 3054 3055 3056 3057 3058
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_SIZE, lpszRemoteFile, 0, 0, 0))
        goto lend;

3059
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
    if (nResCode)
    {
        if (nResCode == 213) {
	    /* Now parses the output to get the actual file size */
	    int i;
	    LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();

	    for (i = 0; (lpszResponseBuffer[i] != ' ') && (lpszResponseBuffer[i] != '\0'); i++) ;
	    if (lpszResponseBuffer[i] == '\0') return FALSE;
	    *dwSize = atol(&(lpszResponseBuffer[i + 1]));
	    
            bSuccess = TRUE;
	} else {
            FTP_SetResponseError(nResCode);
	}
    }

lend:
    return bSuccess;
}
3080
#endif
3081

3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092

/***********************************************************************
 *           FTP_SendPort (internal)
 *
 * Tell server which port to use
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3093
static BOOL FTP_SendPort(ftp_session_t *lpwfs)
3094
{
3095
    static const WCHAR szIPFormat[] = {'%','d',',','%','d',',','%','d',',','%','d',',','%','d',',','%','d','\0'};
3096
    INT nResCode;
3097
    WCHAR szIPAddress[64];
3098 3099 3100
    BOOL bSuccess = FALSE;
    TRACE("\n");

3101
    swprintf(szIPAddress, ARRAY_SIZE(szIPAddress), szIPFormat,
3102 3103 3104 3105
	 lpwfs->lstnSocketAddress.sin_addr.S_un.S_addr&0x000000FF,
        (lpwfs->lstnSocketAddress.sin_addr.S_un.S_addr&0x0000FF00)>>8,
        (lpwfs->lstnSocketAddress.sin_addr.S_un.S_addr&0x00FF0000)>>16,
        (lpwfs->lstnSocketAddress.sin_addr.S_un.S_addr&0xFF000000)>>24,
3106 3107 3108 3109 3110 3111
        lpwfs->lstnSocketAddress.sin_port & 0xFF,
        (lpwfs->lstnSocketAddress.sin_port & 0xFF00)>>8);

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PORT, szIPAddress, 0, 0, 0))
        goto lend;

3112
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
    if (nResCode)
    {
        if (nResCode == 200)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}


/***********************************************************************
3127 3128 3129 3130
 *           FTP_DoPassive (internal)
 *
 * Tell server that we want to do passive transfers
 * and connect data socket
3131
 *
3132 3133 3134 3135 3136
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3137
static BOOL FTP_DoPassive(ftp_session_t *lpwfs)
3138 3139 3140 3141 3142 3143 3144 3145
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PASV, NULL, 0, 0, 0))
        goto lend;

3146
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3147 3148 3149 3150 3151 3152 3153 3154 3155
    if (nResCode)
    {
        if (nResCode == 227)
	{
	    LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
	    LPSTR p;
	    int f[6];
	    int i;
	    char *pAddr, *pPort;
3156
	    INT nsocket = -1;
3157 3158 3159
	    struct sockaddr_in dataSocketAddress;

	    p = lpszResponseBuffer+4; /* skip status code */
3160
	    while (*p != '\0' && (*p < '0' || *p > '9')) p++;
3161

3162
	    if (*p == '\0')
3163
	    {
3164
		ERR("no address found in response, aborting\n");
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
		goto lend;
	    }

	    if (sscanf(p, "%d,%d,%d,%d,%d,%d",  &f[0], &f[1], &f[2], &f[3],
				    		&f[4], &f[5]) != 6)
	    {
		ERR("unknown response address format '%s', aborting\n", p);
		goto lend;
	    }
	    for (i=0; i < 6; i++)
		f[i] = f[i] & 0xff;

	    dataSocketAddress = lpwfs->socketAddress;
3178
	    pAddr = (char *)&(dataSocketAddress.sin_addr.S_un.S_addr);
3179 3180 3181 3182 3183 3184 3185 3186
	    pPort = (char *)&(dataSocketAddress.sin_port);
            pAddr[0] = f[0];
            pAddr[1] = f[1];
            pAddr[2] = f[2];
            pAddr[3] = f[3];
	    pPort[0] = f[4];
	    pPort[1] = f[5];

3187 3188
            nsocket = socket(AF_INET,SOCK_STREAM,0);
            if (nsocket == -1)
3189 3190 3191 3192 3193
                goto lend;

	    if (connect(nsocket, (struct sockaddr *)&dataSocketAddress, sizeof(dataSocketAddress)))
            {
	        ERR("can't connect passive FTP data port.\n");
3194
                closesocket(nsocket);
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
	        goto lend;
            }
	    lpwfs->pasvSocket = nsocket;
            bSuccess = TRUE;
	}
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}


3209
static BOOL FTP_SendPortOrPasv(ftp_session_t *lpwfs)
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
{
    if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
    {
        if (!FTP_DoPassive(lpwfs))
            return FALSE;
    }
    else
    {
	if (!FTP_SendPort(lpwfs))
            return FALSE;
    }
    return TRUE;
}


/***********************************************************************
 *           FTP_GetDataSocket (internal)
 *
 * Either accepts an incoming data socket connection from the server
 * or just returns the already opened socket after a PASV command
 * in case of passive FTP.
3231
 *
3232 3233 3234 3235 3236 3237
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3238
static BOOL FTP_GetDataSocket(ftp_session_t *lpwfs, LPINT nDataSocket)
3239 3240
{
    struct sockaddr_in saddr;
3241
    socklen_t addrlen = sizeof(saddr);
3242 3243

    TRACE("\n");
3244 3245 3246
    if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
    {
	*nDataSocket = lpwfs->pasvSocket;
3247
	lpwfs->pasvSocket = -1;
3248 3249 3250 3251
    }
    else
    {
        *nDataSocket = accept(lpwfs->lstnSocket, (struct sockaddr *) &saddr, &addrlen);
3252
        closesocket(lpwfs->lstnSocket);
3253
        lpwfs->lstnSocket = -1;
3254
    }
3255
    return *nDataSocket != -1;
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
}


/***********************************************************************
 *           FTP_SendData (internal)
 *
 * Send data to the server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3269
static BOOL FTP_SendData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3270 3271 3272 3273 3274
{
    BY_HANDLE_FILE_INFORMATION fi;
    DWORD nBytesRead = 0;
    DWORD nBytesSent = 0;
    DWORD nTotalSent = 0;
3275 3276
    DWORD nBytesToSend, nLen;
    int nRC = 1;
3277 3278 3279 3280 3281
    time_t s_long_time, e_long_time;
    LONG nSeconds;
    CHAR *lpszBuffer;

    TRACE("\n");
3282
    lpszBuffer = heap_alloc_zero(sizeof(CHAR)*DATA_PACKET_SIZE);
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304

    /* Get the size of the file. */
    GetFileInformationByHandle(hFile, &fi);
    time(&s_long_time);

    do
    {
        nBytesToSend = nBytesRead - nBytesSent;

        if (nBytesToSend <= 0)
        {
            /* Read data from file. */
            nBytesSent = 0;
            if (!ReadFile(hFile, lpszBuffer, DATA_PACKET_SIZE, &nBytesRead, 0))
            ERR("Failed reading from file\n");

            if (nBytesRead > 0)
                nBytesToSend = nBytesRead;
            else
                break;
        }

3305
        nLen = DATA_PACKET_SIZE < nBytesToSend ?
3306
            DATA_PACKET_SIZE : nBytesToSend;
3307
        nRC  = sock_send(nDataSocket, lpszBuffer, nLen, 0);
3308

3309
        if (nRC != -1)
3310 3311 3312 3313 3314 3315 3316 3317 3318 3319
        {
            nBytesSent += nRC;
            nTotalSent += nRC;
        }

        /* Do some computation to display the status. */
        time(&e_long_time);
        nSeconds = e_long_time - s_long_time;
        if( nSeconds / 60 > 0 )
        {
3320
            TRACE( "%d bytes of %d bytes (%d%%) in %d min %d sec estimated remaining time %d sec\n",
3321
            nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds / 60,
3322 3323 3324 3325
            nSeconds % 60, (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent );
        }
        else
        {
3326
            TRACE( "%d bytes of %d bytes (%d%%) in %d sec estimated remaining time %d sec\n",
3327 3328 3329
            nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds,
            (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent);
        }
3330
    } while (nRC != -1);
3331 3332 3333

    TRACE("file transfer complete!\n");

3334
    heap_free(lpszBuffer);
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
    return nTotalSent;
}


/***********************************************************************
 *           FTP_SendRetrieve (internal)
 *
 * Send request to retrieve a file
 *
 * RETURNS
 *   Number of bytes to be received on success
 *   0 on failure
 *
 */
3349
static BOOL FTP_SendRetrieve(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
3350 3351
{
    INT nResCode;
3352
    BOOL ret;
3353 3354

    TRACE("\n");
3355
    if (!(ret = FTP_InitListenSocket(lpwfs)))
3356 3357
        goto lend;

3358
    if (!(ret = FTP_SendType(lpwfs, dwType)))
3359 3360
        goto lend;

3361
    if (!(ret = FTP_SendPortOrPasv(lpwfs)))
3362 3363
        goto lend;

3364
    if (!(ret = FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RETR, lpszRemoteFile, 0, 0, 0)))
3365 3366
        goto lend;

3367
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3368 3369
    if ((nResCode != 125) && (nResCode != 150)) {
	/* That means that we got an error getting the file. */
3370 3371
        FTP_SetResponseError(nResCode);
	ret = FALSE;
3372 3373 3374
    }

lend:
3375
    if (!ret && lpwfs->lstnSocket != -1)
3376
    {
3377
        closesocket(lpwfs->lstnSocket);
3378
        lpwfs->lstnSocket = -1;
3379 3380
    }

3381
    return ret;
3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
}


/***********************************************************************
 *           FTP_RetrieveData  (internal)
 *
 * Retrieve data from server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3395
static BOOL FTP_RetrieveFileData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3396 3397 3398 3399 3400 3401 3402
{
    DWORD nBytesWritten;
    INT nRC = 0;
    CHAR *lpszBuffer;

    TRACE("\n");

3403
    lpszBuffer = heap_alloc_zero(sizeof(CHAR)*DATA_PACKET_SIZE);
3404 3405 3406 3407 3408 3409
    if (NULL == lpszBuffer)
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }

3410
    while (nRC != -1)
3411
    {
3412
        nRC = sock_recv(nDataSocket, lpszBuffer, DATA_PACKET_SIZE, 0);
3413
        if (nRC != -1)
3414 3415 3416 3417
        {
            /* other side closed socket. */
            if (nRC == 0)
                goto recv_end;
3418
            WriteFile(hFile, lpszBuffer, nRC, &nBytesWritten, NULL);
3419 3420 3421 3422 3423 3424
        }
    }

    TRACE("Data transfer complete\n");

recv_end:
3425 3426
    heap_free(lpszBuffer);
    return (nRC != -1);
3427 3428
}

3429
/***********************************************************************
3430
 *           FTPFINDNEXT_Destroy (internal)
3431
 *
3432
 * Deallocate session handle
3433
 */
3434
static void FTPFINDNEXT_Destroy(object_header_t *hdr)
3435
{
3436 3437
    LPWININETFTPFINDNEXTW lpwfn = (LPWININETFTPFINDNEXTW) hdr;
    DWORD i;
3438

3439
    TRACE("\n");
3440

3441
    WININET_Release(&lpwfn->lpFtpSession->hdr);
3442

3443
    for (i = 0; i < lpwfn->size; i++)
3444
    {
3445
        heap_free(lpwfn->lpafp[i].lpszName);
3446
    }
3447
    heap_free(lpwfn->lpafp);
3448
}
3449

3450
static DWORD FTPFINDNEXT_FindNextFileProc(WININETFTPFINDNEXTW *find, LPVOID data)
3451 3452 3453
{
    WIN32_FIND_DATAW *find_data = data;
    DWORD res = ERROR_SUCCESS;
3454

3455 3456 3457 3458 3459 3460 3461
    TRACE("index(%d) size(%d)\n", find->index, find->size);

    ZeroMemory(find_data, sizeof(WIN32_FIND_DATAW));

    if (find->index < find->size) {
        FTP_ConvertFileProp(&find->lpafp[find->index], find_data);
        find->index++;
3462

3463 3464 3465 3466 3467 3468
        TRACE("Name: %s\nSize: %d\n", debugstr_w(find_data->cFileName), find_data->nFileSizeLow);
    }else {
        res = ERROR_NO_MORE_FILES;
    }

    if (find->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3469 3470 3471
    {
        INTERNET_ASYNC_RESULT iar;

3472 3473
        iar.dwResult = (res == ERROR_SUCCESS);
        iar.dwError = res;
3474

3475
        INTERNET_SendCallback(&find->hdr, find->hdr.dwContext,
3476 3477 3478 3479
                              INTERNET_STATUS_REQUEST_COMPLETE, &iar,
                              sizeof(INTERNET_ASYNC_RESULT));
    }

3480
    return res;
3481 3482
}

3483 3484 3485 3486 3487 3488
typedef struct {
    task_header_t hdr;
    WIN32_FIND_DATAW *find_data;
} find_next_task_t;

static void FTPFINDNEXT_AsyncFindNextFileProc(task_header_t *hdr)
3489
{
3490
    find_next_task_t *task = (find_next_task_t*)hdr;
3491

3492
    FTPFINDNEXT_FindNextFileProc((WININETFTPFINDNEXTW*)task->hdr.hdr, task->find_data);
3493
}
3494

3495
static DWORD FTPFINDNEXT_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508
{
    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_FTP_FIND;
        return ERROR_SUCCESS;
    }

3509
    return INET_QueryOption(hdr, option, buffer, size, unicode);
3510 3511
}

3512
static DWORD FTPFINDNEXT_FindNextFileW(object_header_t *hdr, void *data)
3513 3514
{
    WININETFTPFINDNEXTW *find = (WININETFTPFINDNEXTW*)hdr;
3515

3516
    if (find->lpFtpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3517
    {
3518
        find_next_task_t *task;
3519

3520
        task = alloc_async_task(&find->hdr, FTPFINDNEXT_AsyncFindNextFileProc, sizeof(*task));
3521
        task->find_data = data;
3522

3523
        INTERNET_AsyncCall(&task->hdr);
3524
        return ERROR_SUCCESS;
3525 3526
    }

3527
    return FTPFINDNEXT_FindNextFileProc(find, data);
3528 3529
}

3530
static const object_vtbl_t FTPFINDNEXTVtbl = {
3531
    FTPFINDNEXT_Destroy,
3532
    NULL,
3533
    FTPFINDNEXT_QueryOption,
3534
    INET_SetOption,
3535
    NULL,
3536
    NULL,
3537
    NULL,
3538
    FTPFINDNEXT_FindNextFileW
3539
};
3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550

/***********************************************************************
 *           FTP_ReceiveFileList (internal)
 *
 * Read file list from server
 *
 * RETURNS
 *   Handle to file list on success
 *   NULL on failure
 *
 */
3551
static HINTERNET FTP_ReceiveFileList(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3552
	LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext)
3553 3554
{
    DWORD dwSize = 0;
3555
    LPFILEPROPERTIESW lpafp = NULL;
3556
    LPWININETFTPFINDNEXTW lpwfn = NULL;
3557

3558
    TRACE("(%p,%d,%s,%p,%08lx)\n", lpwfs, nSocket, debugstr_w(lpszSearchFile), lpFindFileData, dwContext);
3559

3560
    if (FTP_ParseDirectory(lpwfs, nSocket, lpszSearchFile, &lpafp, &dwSize))
3561
    {
3562 3563
        if(lpFindFileData)
            FTP_ConvertFileProp(lpafp, lpFindFileData);
3564

3565
        lpwfn = alloc_object(&lpwfs->hdr, &FTPFINDNEXTVtbl, sizeof(WININETFTPFINDNEXTW));
3566
        if (lpwfn)
3567
        {
3568
            lpwfn->hdr.htype = WH_HFTPFINDNEXT;
3569 3570 3571 3572 3573
            lpwfn->hdr.dwContext = dwContext;
            lpwfn->index = 1; /* Next index is 1 since we return index 0 */
            lpwfn->size = dwSize;
            lpwfn->lpafp = lpafp;

3574 3575
            WININET_AddRef( &lpwfs->hdr );
            lpwfn->lpFtpSession = lpwfs;
3576
            list_add_head( &lpwfs->hdr.children, &lpwfn->hdr.entry );
3577
        }
3578
    }
3579

3580
    TRACE("Matched %d files\n", dwSize);
3581
    return lpwfn ? lpwfn->hdr.hInternet : NULL;
3582 3583 3584 3585 3586 3587
}


/***********************************************************************
 *           FTP_ConvertFileProp (internal)
 *
3588
 * Converts FILEPROPERTIESW struct to WIN32_FIND_DATAA
3589 3590 3591 3592 3593 3594
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3595
static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData)
3596 3597 3598
{
    BOOL bSuccess = FALSE;

3599
    ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAW));
3600 3601 3602

    if (lpafp)
    {
3603
        SystemTimeToFileTime( &lpafp->tmLastModified, &lpFindFileData->ftLastAccessTime );
3604 3605
	lpFindFileData->ftLastWriteTime = lpFindFileData->ftLastAccessTime;
	lpFindFileData->ftCreationTime = lpFindFileData->ftLastAccessTime;
3606
	
3607
        /* Not all fields are filled in */
3608 3609
        lpFindFileData->nFileSizeHigh = 0; /* We do not handle files bigger than 0xFFFFFFFF bytes yet :-) */
        lpFindFileData->nFileSizeLow = lpafp->nSize;
3610 3611 3612 3613 3614

	if (lpafp->bIsDirectory)
	    lpFindFileData->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;

        if (lpafp->lpszName)
3615
            lstrcpynW(lpFindFileData->cFileName, lpafp->lpszName, MAX_PATH);
3616 3617 3618 3619 3620 3621 3622

	bSuccess = TRUE;
    }

    return bSuccess;
}

3623 3624 3625 3626 3627 3628 3629 3630 3631
/***********************************************************************
 *           FTP_ParseNextFile (internal)
 *
 * Parse the next line in file listing
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 */
3632
static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW lpfp)
3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
{
    static const char szSpace[] = " \t";
    DWORD nBufLen;
    char *pszLine;
    char *pszToken;
    char *pszTmp;
    BOOL found = FALSE;
    int i;
    
    lpfp->lpszName = NULL;
    do {
3644
        if(!(pszLine = FTP_GetNextLine(nSocket, &nBufLen)))
3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
            return FALSE;
    
        pszToken = strtok(pszLine, szSpace);
        /* ls format
         * <Permissions> <NoLinks> <owner>   <group> <size> <date>  <time or year> <filename>
         *
         * For instance:
         * drwx--s---     2         pcarrier  ens     512    Sep 28  1995           pcarrier
         */
        if(!isdigit(pszToken[0]) && 10 == strlen(pszToken)) {
            if(!FTP_ParsePermission(pszToken, lpfp))
                lpfp->bIsDirectory = FALSE;
            for(i=0; i<=3; i++) {
              if(!(pszToken = strtok(NULL, szSpace)))
                  break;
            }
            if(!pszToken) continue;
            if(lpfp->bIsDirectory) {
                TRACE("Is directory\n");
                lpfp->nSize = 0;
            }
            else {
                TRACE("Size: %s\n", pszToken);
                lpfp->nSize = atol(pszToken);
            }
            
3671 3672 3673 3674 3675 3676
            lpfp->tmLastModified.wSecond = 0;
            lpfp->tmLastModified.wMinute = 0;
            lpfp->tmLastModified.wHour   = 0;
            lpfp->tmLastModified.wDay    = 0;
            lpfp->tmLastModified.wMonth  = 0;
            lpfp->tmLastModified.wYear   = 0;
3677 3678 3679 3680 3681 3682 3683
            
            /* Determine month */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if(strlen(pszToken) >= 3) {
                pszToken[3] = 0;
                if((pszTmp = StrStrIA(szMonths, pszToken)))
3684
                    lpfp->tmLastModified.wMonth = ((pszTmp - szMonths) / 3)+1;
3685 3686 3687 3688
            }
            /* Determine day */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3689
            lpfp->tmLastModified.wDay = atoi(pszToken);
3690 3691 3692 3693
            /* Determine time or year */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if((pszTmp = strchr(pszToken, ':'))) {
3694
                SYSTEMTIME curr_time;
3695 3696
                *pszTmp = 0;
                pszTmp++;
3697 3698 3699 3700
                lpfp->tmLastModified.wMinute = atoi(pszTmp);
                lpfp->tmLastModified.wHour = atoi(pszToken);
                GetLocalTime( &curr_time );
                lpfp->tmLastModified.wYear = curr_time.wYear;
3701 3702
            }
            else {
3703 3704
                lpfp->tmLastModified.wYear = atoi(pszToken);
                lpfp->tmLastModified.wHour = 12;
3705
            }
3706 3707 3708
            TRACE("Mod time: %02d:%02d:%02d  %04d/%02d/%02d\n",
                  lpfp->tmLastModified.wHour, lpfp->tmLastModified.wMinute, lpfp->tmLastModified.wSecond,
                  lpfp->tmLastModified.wYear, lpfp->tmLastModified.wMonth, lpfp->tmLastModified.wDay);
3709 3710 3711

            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3712
            lpfp->lpszName = heap_strdupAtoW(pszToken);
3713 3714 3715 3716 3717 3718 3719 3720
            TRACE("File: %s\n", debugstr_w(lpfp->lpszName));
        }
        /* NT way of parsing ... :
            
                07-13-03  08:55PM       <DIR>          sakpatch
                05-09-03  06:02PM             12656686 2003-04-21bgm_cmd_e.rgz
        */
        else if(isdigit(pszToken[0]) && 8 == strlen(pszToken)) {
3721
            int mon, mday, year, hour, min;
3722 3723
            lpfp->permissions = 0xFFFF; /* No idea, put full permission :-) */
            
3724 3725 3726 3727
            sscanf(pszToken, "%d-%d-%d", &mon, &mday, &year);
            lpfp->tmLastModified.wDay   = mday;
            lpfp->tmLastModified.wMonth = mon;
            lpfp->tmLastModified.wYear  = year;
3728 3729

            /* Hacky and bad Y2K protection :-) */
3730 3731
            if (lpfp->tmLastModified.wYear < 70) lpfp->tmLastModified.wYear += 2000;

3732 3733
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3734 3735 3736
            sscanf(pszToken, "%d:%d", &hour, &min);
            lpfp->tmLastModified.wHour   = hour;
            lpfp->tmLastModified.wMinute = min;
3737
            if((pszToken[5] == 'P') && (pszToken[6] == 'M')) {
3738
                lpfp->tmLastModified.wHour += 12;
3739
            }
3740 3741 3742 3743 3744
            lpfp->tmLastModified.wSecond = 0;

            TRACE("Mod time: %02d:%02d:%02d  %04d/%02d/%02d\n",
                  lpfp->tmLastModified.wHour, lpfp->tmLastModified.wMinute, lpfp->tmLastModified.wSecond,
                  lpfp->tmLastModified.wYear, lpfp->tmLastModified.wMonth, lpfp->tmLastModified.wDay);
3745 3746 3747

            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3748
            if(!stricmp(pszToken, "<DIR>")) {
3749 3750 3751 3752 3753 3754 3755
                lpfp->bIsDirectory = TRUE;
                lpfp->nSize = 0;
                TRACE("Is directory\n");
            }
            else {
                lpfp->bIsDirectory = FALSE;
                lpfp->nSize = atol(pszToken);
3756
                TRACE("Size: %d\n", lpfp->nSize);
3757 3758 3759 3760
            }
            
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3761
            lpfp->lpszName = heap_strdupAtoW(pszToken);
3762 3763 3764 3765 3766 3767 3768 3769
            TRACE("Name: %s\n", debugstr_w(lpfp->lpszName));
        }
        /* EPLF format - http://cr.yp.to/ftp/list/eplf.html */
        else if(pszToken[0] == '+') {
            FIXME("EPLF Format not implemented\n");
        }
        
        if(lpfp->lpszName) {
3770 3771
            if((lpszSearchFile == NULL) ||
	       (PathMatchSpecW(lpfp->lpszName, lpszSearchFile))) {
3772 3773 3774 3775
                found = TRUE;
                TRACE("Matched: %s\n", debugstr_w(lpfp->lpszName));
            }
            else {
3776
                heap_free(lpfp->lpszName);
3777 3778 3779 3780 3781 3782
                lpfp->lpszName = NULL;
            }
        }
    } while(!found);
    return TRUE;
}
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792

/***********************************************************************
 *           FTP_ParseDirectory (internal)
 *
 * Parse string of directory information
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 */
3793
static BOOL FTP_ParseDirectory(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3794
    LPFILEPROPERTIESW *lpafp, LPDWORD dwfp)
3795 3796
{
    BOOL bSuccess = TRUE;
3797 3798
    INT sizeFilePropArray = 500;/*20; */
    INT indexFilePropArray = -1;
3799 3800 3801

    TRACE("\n");

Austin English's avatar
Austin English committed
3802
    /* Allocate initial file properties array */
3803
    *lpafp = heap_alloc_zero(sizeof(FILEPROPERTIESW)*(sizeFilePropArray));
3804 3805
    if (!*lpafp)
        return FALSE;
3806

3807 3808
    do {
        if (indexFilePropArray+1 >= sizeFilePropArray)
3809
        {
3810 3811
            LPFILEPROPERTIESW tmpafp;
            
3812
            sizeFilePropArray *= 2;
3813
            tmpafp = heap_realloc_zero(*lpafp, sizeof(FILEPROPERTIESW)*sizeFilePropArray);
3814 3815 3816
            if (NULL == tmpafp)
            {
                bSuccess = FALSE;
3817
                break;
3818 3819 3820 3821
            }

            *lpafp = tmpafp;
        }
3822 3823
        indexFilePropArray++;
    } while (FTP_ParseNextFile(nSocket, lpszSearchFile, &(*lpafp)[indexFilePropArray]));
3824 3825 3826 3827 3828

    if (bSuccess && indexFilePropArray)
    {
        if (indexFilePropArray < sizeFilePropArray - 1)
        {
3829
            LPFILEPROPERTIESW tmpafp;
3830

3831
            tmpafp = heap_realloc(*lpafp, sizeof(FILEPROPERTIESW)*indexFilePropArray);
3832
            if (NULL != tmpafp)
3833 3834 3835 3836 3837 3838
                *lpafp = tmpafp;
        }
        *dwfp = indexFilePropArray;
    }
    else
    {
3839
        heap_free(*lpafp);
3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
        INTERNET_SetLastError(ERROR_NO_MORE_FILES);
        bSuccess = FALSE;
    }

    return bSuccess;
}


/***********************************************************************
 *           FTP_ParsePermission (internal)
 *
 * Parse permission string of directory information
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3858
static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp)
3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920
{
    BOOL bSuccess = TRUE;
    unsigned short nPermission = 0;
    INT nPos = 1;
    INT nLast  = 9;

    TRACE("\n");
    if ((*lpszPermission != 'd') && (*lpszPermission != '-') && (*lpszPermission != 'l'))
    {
        bSuccess = FALSE;
        return bSuccess;
    }

    lpfp->bIsDirectory = (*lpszPermission == 'd');
    do
    {
        switch (nPos)
        {
            case 1:
                nPermission |= (*(lpszPermission+1) == 'r' ? 1 : 0) << 8;
                break;
            case 2:
                nPermission |= (*(lpszPermission+2) == 'w' ? 1 : 0) << 7;
                break;
            case 3:
                nPermission |= (*(lpszPermission+3) == 'x' ? 1 : 0) << 6;
                break;
            case 4:
                nPermission |= (*(lpszPermission+4) == 'r' ? 1 : 0) << 5;
                break;
            case 5:
                nPermission |= (*(lpszPermission+5) == 'w' ? 1 : 0) << 4;
                break;
            case 6:
                nPermission |= (*(lpszPermission+6) == 'x' ? 1 : 0) << 3;
                break;
            case 7:
                nPermission |= (*(lpszPermission+7) == 'r' ? 1 : 0) << 2;
                break;
            case 8:
                nPermission |= (*(lpszPermission+8) == 'w' ? 1 : 0) << 1;
                break;
            case 9:
                nPermission |= (*(lpszPermission+9) == 'x' ? 1 : 0);
                break;
        }
        nPos++;
    }while (nPos <= nLast);

    lpfp->permissions = nPermission;
    return bSuccess;
}


/***********************************************************************
 *           FTP_SetResponseError (internal)
 *
 * Set the appropriate error code for a given response from the server
 *
 * RETURNS
 *
 */
3921
static DWORD FTP_SetResponseError(DWORD dwResponse)
3922 3923 3924 3925 3926
{
    DWORD dwCode = 0;

    switch(dwResponse)
    {
3927 3928 3929 3930
    case 425: /* Cannot open data connection. */
        dwCode = ERROR_INTERNET_CANNOT_CONNECT;
        break;

3931
    case 426: /* Connection closed, transfer aborted. */
3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956
        dwCode = ERROR_INTERNET_CONNECTION_ABORTED;
        break;

    case 530: /* Not logged in. Login incorrect. */
        dwCode = ERROR_INTERNET_LOGIN_FAILURE;
        break;

    case 421: /* Service not available - Server may be shutting down. */
    case 450: /* File action not taken. File may be busy. */
    case 451: /* Action aborted. Server error. */
    case 452: /* Action not taken. Insufficient storage space on server. */
    case 500: /* Syntax error. Command unrecognized. */
    case 501: /* Syntax error. Error in parameters or arguments. */
    case 502: /* Command not implemented. */
    case 503: /* Bad sequence of commands. */
    case 504: /* Command not implemented for that parameter. */
    case 532: /* Need account for storing files */
    case 550: /* File action not taken. File not found or no access. */
    case 551: /* Requested action aborted. Page type unknown */
    case 552: /* Action aborted. Exceeded storage allocation */
    case 553: /* Action not taken. File name not allowed. */

    default:
        dwCode = ERROR_INTERNET_EXTENDED_ERROR;
        break;
3957
    }
3958

3959 3960 3961
    INTERNET_SetLastError(dwCode);
    return dwCode;
}