ftp.c 104 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 "config.h"
31
#include "wine/port.h"
32

33 34 35 36
#if defined(__MINGW32__) || defined (_MSC_VER)
#include <ws2tcpip.h>
#endif

37
#include <errno.h>
38
#include <stdarg.h>
39 40 41
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Gerald Pfeifer's avatar
Gerald Pfeifer committed
42
#include <sys/types.h>
43 44 45
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
46 47 48
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
49 50 51
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
52 53 54
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
55
#include <time.h>
56
#include <assert.h>
57

58
#include "windef.h"
59 60 61
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
62
#include "wininet.h"
63
#include "winnls.h"
64
#include "winerror.h"
65
#include "winreg.h"
66
#include "winternl.h"
67
#include "shlwapi.h"
68

69
#include "wine/debug.h"
70 71
#include "internet.h"

72
WINE_DEFAULT_DEBUG_CHANNEL(wininet);
73

74
typedef struct _ftp_session_t ftp_session_t;
75 76 77

typedef struct
{
78
    object_header_t hdr;
79
    ftp_session_t *lpFtpSession;
80 81
    BOOL session_deleted;
    int nDataSocket;
82 83
    WCHAR *cache_file;
    HANDLE cache_file_handle;
84
} ftp_file_t;
85

86
struct _ftp_session_t
87
{
88
    object_header_t hdr;
89
    appinfo_t *lpAppInfo;
90 91 92
    int sndSocket;
    int lstnSocket;
    int pasvSocket; /* data socket connected by us in case of passive FTP */
93
    ftp_file_t *download_in_progress;
94 95
    struct sockaddr_in socketAddress;
    struct sockaddr_in lstnSocketAddress;
96 97
    LPWSTR servername;
    INTERNET_PORT serverport;
98 99
    LPWSTR  lpszPassword;
    LPWSTR  lpszUserName;
100
};
101

102 103 104 105 106
typedef struct
{
    BOOL bIsDirectory;
    LPWSTR lpszName;
    DWORD nSize;
107
    SYSTEMTIME tmLastModified;
108 109 110 111 112
    unsigned short permissions;
} FILEPROPERTIESW, *LPFILEPROPERTIESW;

typedef struct
{
113
    object_header_t hdr;
114
    ftp_session_t *lpFtpSession;
115 116 117 118 119
    DWORD index;
    DWORD size;
    LPFILEPROPERTIESW lpafp;
} WININETFTPFINDNEXTW, *LPWININETFTPFINDNEXTW;

120 121 122 123
#define DATA_PACKET_SIZE 	0x2000
#define szCRLF 			"\r\n"
#define MAX_BACKLOG 		5

124 125 126 127 128
/* 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

129 130
typedef enum {
  /* FTP commands with arguments. */
131 132 133 134 135 136 137 138 139 140 141 142 143
  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,
144
  FTP_CMD_SIZE,
145 146 147 148 149

  /* FTP commands without arguments. */
  FTP_CMD_ABOR,
  FTP_CMD_LIST,
  FTP_CMD_NLST,
150
  FTP_CMD_PASV,
151
  FTP_CMD_PWD,
152
  FTP_CMD_QUIT,
153
} FTP_COMMAND;
154

155
static const CHAR *const szFtpCommands[] = {
156 157 158 159 160 161 162 163 164 165 166 167 168
  "ACCT",
  "CWD",
  "DELE",
  "MKD",
  "PASS",
  "PORT",
  "RETR",
  "RMD",
  "RNFR",
  "RNTO",
  "STOR",
  "TYPE",
  "USER",
169
  "SIZE",
170 171 172
  "ABOR",
  "LIST",
  "NLST",
173
  "PASV",
174 175 176 177 178
  "PWD",
  "QUIT",
};

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

181
static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
182
	INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext);
183 184 185 186 187 188 189 190 191 192 193 194 195 196
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*);
197 198
static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp);
static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW fileprop);
199
static BOOL FTP_ParseDirectory(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
200
        LPFILEPROPERTIESW *lpafp, LPDWORD dwfp);
201
static HINTERNET FTP_ReceiveFileList(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
202
        LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext);
203
static DWORD FTP_SetResponseError(DWORD dwResponse);
204
static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData);
205
static BOOL FTP_FtpPutFileW(ftp_session_t*, LPCWSTR lpszLocalFile,
206
        LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext);
207 208 209
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*,
210
        LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext);
211
static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t*, LPWSTR lpszCurrentDirectory,
212
        LPDWORD lpdwCurrentDirectory);
213 214 215 216
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,
217 218 219
        BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
        DWORD_PTR dwContext);

220 221 222 223 224 225 226
/* 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;
}
227

228 229 230 231 232 233 234 235 236 237 238
/***********************************************************************
 *           FtpPutFileA (WININET.@)
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpPutFileA(HINTERNET hConnect, LPCSTR lpszLocalFile,
239
    LPCSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
240
{
241 242 243 244
    LPWSTR lpwzLocalFile;
    LPWSTR lpwzNewRemoteFile;
    BOOL ret;
    
245 246
    lpwzLocalFile = heap_strdupAtoW(lpszLocalFile);
    lpwzNewRemoteFile = heap_strdupAtoW(lpszNewRemoteFile);
247 248
    ret = FtpPutFileW(hConnect, lpwzLocalFile, lpwzNewRemoteFile,
                      dwFlags, dwContext);
249 250
    heap_free(lpwzLocalFile);
    heap_free(lpwzNewRemoteFile);
251 252 253
    return ret;
}

254 255 256
static void AsyncFtpPutFileProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPPUTFILEW const *req = &workRequest->u.FtpPutFileW;
257
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
258 259 260 261 262 263

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

    FTP_FtpPutFileW(lpwfs, req->lpszLocalFile,
               req->lpszNewRemoteFile, req->dwFlags, req->dwContext);

264 265
    heap_free(req->lpszLocalFile);
    heap_free(req->lpszNewRemoteFile);
266 267
}

268 269 270 271 272 273 274 275 276 277
/***********************************************************************
 *           FtpPutFileW (WININET.@)
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
278
BOOL WINAPI FtpPutFileW(HINTERNET hConnect, LPCWSTR lpszLocalFile,
279
    LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
280
{
281
    ftp_session_t *lpwfs;
282
    appinfo_t *hIC = NULL;
283
    BOOL r = FALSE;
284

285 286 287 288 289 290
    if (!lpszLocalFile || !lpszNewRemoteFile)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

291
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
292 293 294 295 296 297 298
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
299 300
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
301
        goto lend;
302 303
    }

304 305 306 307 308 309
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

310 311 312 313 314 315
    if ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

316
    hIC = lpwfs->lpAppInfo;
317 318 319
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
320
        struct WORKREQ_FTPPUTFILEW *req = &workRequest.u.FtpPutFileW;
321

322 323
        workRequest.asyncproc = AsyncFtpPutFileProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
324 325
        req->lpszLocalFile = heap_strdupW(lpszLocalFile);
        req->lpszNewRemoteFile = heap_strdupW(lpszNewRemoteFile);
326 327
	req->dwFlags = dwFlags;
	req->dwContext = dwContext;
328

329
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
330 331 332
    }
    else
    {
333
        r = FTP_FtpPutFileW(lpwfs, lpszLocalFile,
334
	    lpszNewRemoteFile, dwFlags, dwContext);
335
    }
336 337

lend:
338
    WININET_Release( &lpwfs->hdr );
339 340

    return r;
341 342 343
}

/***********************************************************************
344
 *           FTP_FtpPutFileW (Internal)
345 346 347 348 349 350 351 352
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
353
static BOOL FTP_FtpPutFileW(ftp_session_t *lpwfs, LPCWSTR lpszLocalFile,
354
    LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
355
{
356
    HANDLE hFile;
357
    BOOL bSuccess = FALSE;
358
    appinfo_t *hIC = NULL;
359
    INT nResCode;
360

361 362
    TRACE(" lpszLocalFile(%s) lpszNewRemoteFile(%s)\n", debugstr_w(lpszLocalFile), debugstr_w(lpszNewRemoteFile));

363 364 365 366
    /* Clear any error information */
    INTERNET_SetLastError(0);

    /* Open file to be uploaded */
367
    if (INVALID_HANDLE_VALUE ==
368
        (hFile = CreateFileW(lpszLocalFile, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0)))
369
        /* Let CreateFile set the appropriate error */
370
        return FALSE;
371

372 373
    hIC = lpwfs->lpAppInfo;

374
    SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
375 376 377 378 379

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

380
        /* Get data socket to server */
381
        if (FTP_GetDataSocket(lpwfs, &nDataSocket))
382 383
        {
            FTP_SendData(lpwfs, nDataSocket, hFile);
384
            closesocket(nDataSocket);
385
	    nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
386 387 388 389 390 391 392
	    if (nResCode)
	    {
	        if (nResCode == 226)
		    bSuccess = TRUE;
		else
		    FTP_SetResponseError(nResCode);
	    }
393 394 395
        }
    }

396
    if (lpwfs->lstnSocket != -1)
397
    {
398
        closesocket(lpwfs->lstnSocket);
399 400
        lpwfs->lstnSocket = -1;
    }
401

402
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
403 404
    {
        INTERNET_ASYNC_RESULT iar;
405

406 407
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
408
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
409 410 411
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

412
    CloseHandle(hFile);
413 414 415 416 417 418

    return bSuccess;
}


/***********************************************************************
419
 *           FtpSetCurrentDirectoryA (WININET.@)
420 421 422 423 424 425 426 427
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
428
BOOL WINAPI FtpSetCurrentDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
429
{
430 431 432
    LPWSTR lpwzDirectory;
    BOOL ret;
    
433
    lpwzDirectory = heap_strdupAtoW(lpszDirectory);
434
    ret = FtpSetCurrentDirectoryW(hConnect, lpwzDirectory);
435
    heap_free(lpwzDirectory);
436 437 438 439
    return ret;
}


440 441 442
static void AsyncFtpSetCurrentDirectoryProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPSETCURRENTDIRECTORYW const *req = &workRequest->u.FtpSetCurrentDirectoryW;
443
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
444 445 446 447

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

    FTP_FtpSetCurrentDirectoryW(lpwfs, req->lpszDirectory);
448
    heap_free(req->lpszDirectory);
449 450
}

451 452 453 454 455 456 457 458 459 460
/***********************************************************************
 *           FtpSetCurrentDirectoryW (WININET.@)
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
461 462
BOOL WINAPI FtpSetCurrentDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
{
463
    ftp_session_t *lpwfs = NULL;
464
    appinfo_t *hIC = NULL;
465
    BOOL r = FALSE;
466

467 468
    if (!lpszDirectory)
    {
469
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
470 471 472
        goto lend;
    }

473
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
474 475 476
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
477
        goto lend;
478 479
    }

480 481 482 483 484 485
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

486
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
487

488
    hIC = lpwfs->lpAppInfo;
489 490 491
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
492
        struct WORKREQ_FTPSETCURRENTDIRECTORYW *req;
493

494 495
        workRequest.asyncproc = AsyncFtpSetCurrentDirectoryProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
496
        req = &workRequest.u.FtpSetCurrentDirectoryW;
497
        req->lpszDirectory = heap_strdupW(lpszDirectory);
498

499
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
500 501 502
    }
    else
    {
503
        r = FTP_FtpSetCurrentDirectoryW(lpwfs, lpszDirectory);
504
    }
505 506 507 508 509 510

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

    return r;
511 512 513
}


514
/***********************************************************************
515
 *           FTP_FtpSetCurrentDirectoryW (Internal)
516 517 518 519 520 521 522 523
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
524
static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
525 526
{
    INT nResCode;
527
    appinfo_t *hIC = NULL;
528 529
    DWORD bSuccess = FALSE;

530
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
531 532 533 534

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

535
    hIC = lpwfs->lpAppInfo;
536
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_CWD, lpszDirectory,
537
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
538 539
        goto lend;

540
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
541 542 543 544 545 546 547 548 549 550

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

lend:
551
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
552 553
    {
        INTERNET_ASYNC_RESULT iar;
554

555
        iar.dwResult = bSuccess;
556
        iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
557
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
558 559 560 561 562 563 564
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }
    return bSuccess;
}


/***********************************************************************
565
 *           FtpCreateDirectoryA (WININET.@)
566 567 568 569 570 571 572 573
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
574
BOOL WINAPI FtpCreateDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
575
{
576 577 578
    LPWSTR lpwzDirectory;
    BOOL ret;
    
579
    lpwzDirectory = heap_strdupAtoW(lpszDirectory);
580
    ret = FtpCreateDirectoryW(hConnect, lpwzDirectory);
581
    heap_free(lpwzDirectory);
582 583 584 585
    return ret;
}


586 587 588
static void AsyncFtpCreateDirectoryProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPCREATEDIRECTORYW const *req = &workRequest->u.FtpCreateDirectoryW;
589
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
590 591 592 593

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

    FTP_FtpCreateDirectoryW(lpwfs, req->lpszDirectory);
594
    heap_free(req->lpszDirectory);
595 596
}

597 598 599 600 601 602 603 604 605 606
/***********************************************************************
 *           FtpCreateDirectoryW (WININET.@)
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
607 608
BOOL WINAPI FtpCreateDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
{
609
    ftp_session_t *lpwfs;
610
    appinfo_t *hIC = NULL;
611
    BOOL r = FALSE;
612

613
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
614 615 616 617 618 619 620
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
621 622
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
623
        goto lend;
624 625
    }

626 627 628 629 630 631
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

632 633 634 635 636 637
    if (!lpszDirectory)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

638
    hIC = lpwfs->lpAppInfo;
639 640 641
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
642
        struct WORKREQ_FTPCREATEDIRECTORYW *req;
643

644 645
        workRequest.asyncproc = AsyncFtpCreateDirectoryProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
646
        req = &workRequest.u.FtpCreateDirectoryW;
647
        req->lpszDirectory = heap_strdupW(lpszDirectory);
648

649
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
650 651 652
    }
    else
    {
653
        r = FTP_FtpCreateDirectoryW(lpwfs, lpszDirectory);
654
    }
655
lend:
656
    WININET_Release( &lpwfs->hdr );
657 658

    return r;
659 660 661
}


662
/***********************************************************************
663
 *           FTP_FtpCreateDirectoryW (Internal)
664 665 666 667 668 669 670 671
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
672
static BOOL FTP_FtpCreateDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
673 674 675
{
    INT nResCode;
    BOOL bSuccess = FALSE;
676
    appinfo_t *hIC = NULL;
677

678
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
679

680 681 682 683 684 685
    /* Clear any error information */
    INTERNET_SetLastError(0);

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

686
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
687 688 689 690 691 692 693 694 695
    if (nResCode)
    {
        if (nResCode == 257)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
696
    hIC = lpwfs->lpAppInfo;
697
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
698 699
    {
        INTERNET_ASYNC_RESULT iar;
700

701 702
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
703
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
704 705 706 707 708 709 710
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

/***********************************************************************
711
 *           FtpFindFirstFileA (WININET.@)
712 713 714 715 716 717 718 719
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
720
HINTERNET WINAPI FtpFindFirstFileA(HINTERNET hConnect,
721
    LPCSTR lpszSearchFile, LPWIN32_FIND_DATAA lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
722
{
723 724 725 726 727
    LPWSTR lpwzSearchFile;
    WIN32_FIND_DATAW wfd;
    LPWIN32_FIND_DATAW lpFindFileDataW;
    HINTERNET ret;
    
728
    lpwzSearchFile = heap_strdupAtoW(lpszSearchFile);
729 730
    lpFindFileDataW = lpFindFileData?&wfd:NULL;
    ret = FtpFindFirstFileW(hConnect, lpwzSearchFile, lpFindFileDataW, dwFlags, dwContext);
731
    heap_free(lpwzSearchFile);
732
    
733
    if (ret && lpFindFileData)
734
        WININET_find_data_WtoA(lpFindFileDataW, lpFindFileData);
735

736 737 738 739
    return ret;
}


740 741 742
static void AsyncFtpFindFirstFileProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPFINDFIRSTFILEW const *req = &workRequest->u.FtpFindFirstFileW;
743
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
744 745 746 747 748

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

    FTP_FtpFindFirstFileW(lpwfs, req->lpszSearchFile,
       req->lpFindFileData, req->dwFlags, req->dwContext);
749
    heap_free(req->lpszSearchFile);
750 751
}

752 753 754 755 756 757 758 759 760 761
/***********************************************************************
 *           FtpFindFirstFileW (WININET.@)
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
762
HINTERNET WINAPI FtpFindFirstFileW(HINTERNET hConnect,
763
    LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
764
{
765
    ftp_session_t *lpwfs;
766
    appinfo_t *hIC = NULL;
767
    HINTERNET r = NULL;
768

769
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
770 771 772
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
773
        goto lend;
774 775
    }

776 777 778 779 780 781
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

782
    hIC = lpwfs->lpAppInfo;
783 784 785
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
786
        struct WORKREQ_FTPFINDFIRSTFILEW *req;
787

788 789
        workRequest.asyncproc = AsyncFtpFindFirstFileProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
790
        req = &workRequest.u.FtpFindFirstFileW;
791
        req->lpszSearchFile = (lpszSearchFile == NULL) ? NULL : heap_strdupW(lpszSearchFile);
792 793 794
	req->lpFindFileData = lpFindFileData;
	req->dwFlags = dwFlags;
	req->dwContext= dwContext;
795 796

	INTERNET_AsyncCall(&workRequest);
797
	r = NULL;
798 799 800
    }
    else
    {
801
        r = FTP_FtpFindFirstFileW(lpwfs, lpszSearchFile, lpFindFileData,
802
            dwFlags, dwContext);
803
    }
804 805 806 807 808
lend:
    if( lpwfs )
        WININET_Release( &lpwfs->hdr );

    return r;
809 810 811
}


812
/***********************************************************************
813
 *           FTP_FtpFindFirstFileW (Internal)
814 815 816 817 818 819 820 821
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
822
static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t *lpwfs,
823
    LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
824 825
{
    INT nResCode;
826
    appinfo_t *hIC = NULL;
827
    HINTERNET hFindNext = NULL;
828 829 830 831 832 833 834 835 836 837 838 839

    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;

840
    if (!FTP_SendPortOrPasv(lpwfs))
841 842
        goto lend;

843
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_LIST, NULL,
844
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
845 846
        goto lend;

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

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

lend:
869
    if (lpwfs->lstnSocket != -1)
870
    {
871
        closesocket(lpwfs->lstnSocket);
872 873
        lpwfs->lstnSocket = -1;
    }
874

875
    hIC = lpwfs->lpAppInfo;
876
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
877 878 879 880 881
    {
        INTERNET_ASYNC_RESULT iar;

        if (hFindNext)
	{
882
            iar.dwResult = (DWORD_PTR)hFindNext;
883
            iar.dwError = ERROR_SUCCESS;
884
            SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
885 886 887
                &iar, sizeof(INTERNET_ASYNC_RESULT));
	}

888
        iar.dwResult = (DWORD_PTR)hFindNext;
889
        iar.dwError = hFindNext ? ERROR_SUCCESS : INTERNET_GetLastError();
890
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
891 892 893
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

894
    return hFindNext;
895 896 897 898
}


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

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

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

    if (lpdwCurrentDirectory) *lpdwCurrentDirectory = len;
933
    heap_free(dir);
934 935 936 937
    return ret;
}


938 939 940
static void AsyncFtpGetCurrentDirectoryProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPGETCURRENTDIRECTORYW const *req = &workRequest->u.FtpGetCurrentDirectoryW;
941
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
942 943 944 945 946 947

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

    FTP_FtpGetCurrentDirectoryW(lpwfs, req->lpszDirectory, req->lpdwDirectory);
}

948 949 950 951 952 953 954 955 956 957
/***********************************************************************
 *           FtpGetCurrentDirectoryW (WININET.@)
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
958 959 960
BOOL WINAPI FtpGetCurrentDirectoryW(HINTERNET hFtpSession, LPWSTR lpszCurrentDirectory,
    LPDWORD lpdwCurrentDirectory)
{
961
    ftp_session_t *lpwfs;
962
    appinfo_t *hIC = NULL;
963
    BOOL r = FALSE;
964

965
    TRACE("%p %p %p\n", hFtpSession, lpszCurrentDirectory, lpdwCurrentDirectory);
966

967
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
968 969 970 971 972 973 974
    if (NULL == lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        goto lend;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
975 976
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
977
        goto lend;
978 979
    }

980 981 982 983 984 985 986 987 988 989 990 991
    if (!lpdwCurrentDirectory)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

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

992 993 994 995 996 997
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

998
    hIC = lpwfs->lpAppInfo;
999 1000 1001
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1002
        struct WORKREQ_FTPGETCURRENTDIRECTORYW *req;
1003

1004 1005
        workRequest.asyncproc = AsyncFtpGetCurrentDirectoryProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1006
        req = &workRequest.u.FtpGetCurrentDirectoryW;
1007 1008
	req->lpszDirectory = lpszCurrentDirectory;
	req->lpdwDirectory = lpdwCurrentDirectory;
1009

1010
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
1011 1012 1013
    }
    else
    {
1014
        r = FTP_FtpGetCurrentDirectoryW(lpwfs, lpszCurrentDirectory,
1015
            lpdwCurrentDirectory);
1016
    }
1017 1018 1019 1020 1021 1022

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

    return r;
1023 1024 1025 1026
}


/***********************************************************************
1027
 *           FTP_FtpGetCurrentDirectoryW (Internal)
1028 1029 1030 1031 1032 1033 1034 1035
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1036
static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t *lpwfs, LPWSTR lpszCurrentDirectory,
1037 1038 1039
	LPDWORD lpdwCurrentDirectory)
{
    INT nResCode;
1040
    appinfo_t *hIC = NULL;
1041 1042 1043 1044 1045
    DWORD bSuccess = FALSE;

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

1046
    hIC = lpwfs->lpAppInfo;
1047
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PWD, NULL,
1048
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
1049 1050
        goto lend;

1051
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1052 1053 1054 1055
    if (nResCode)
    {
        if (nResCode == 257) /* Extract directory name */
        {
1056
            DWORD firstpos, lastpos, len;
1057
            LPWSTR lpszResponseBuffer = heap_strdupAtoW(INTERNET_GetResponseBuffer());
1058 1059 1060 1061 1062 1063 1064 1065 1066

            for (firstpos = 0, lastpos = 0; lpszResponseBuffer[lastpos]; lastpos++)
            {
                if ('"' == lpszResponseBuffer[lastpos])
                {
                    if (!firstpos)
                        firstpos = lastpos;
                    else
                        break;
1067 1068 1069 1070 1071 1072 1073 1074 1075
                }
            }
            len = lastpos - firstpos;
            if (*lpdwCurrentDirectory >= len)
            {
                memcpy(lpszCurrentDirectory, &lpszResponseBuffer[firstpos + 1], len * sizeof(WCHAR));
                lpszCurrentDirectory[len - 1] = 0;
                *lpdwCurrentDirectory = len;
                bSuccess = TRUE;
1076
            }
1077
            else INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1078

1079
            heap_free(lpszResponseBuffer);
1080 1081 1082 1083 1084 1085
        }
        else
            FTP_SetResponseError(nResCode);
    }

lend:
1086
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1087 1088
    {
        INTERNET_ASYNC_RESULT iar;
1089

1090
        iar.dwResult = bSuccess;
1091
        iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
1092
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1093 1094 1095
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

1096
    return bSuccess;
1097 1098 1099
}


1100 1101 1102 1103 1104 1105 1106
/***********************************************************************
 *           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 :-/ )
 *
 */
1107
static void FTPFILE_Destroy(object_header_t *hdr)
1108
{
1109
    ftp_file_t *lpwh = (ftp_file_t*) hdr;
1110
    ftp_session_t *lpwfs = lpwh->lpFtpSession;
1111 1112 1113 1114
    INT nResCode;

    TRACE("\n");

1115 1116 1117
    if (lpwh->cache_file_handle != INVALID_HANDLE_VALUE)
        CloseHandle(lpwh->cache_file_handle);

1118
    heap_free(lpwh->cache_file);
1119

1120 1121 1122 1123 1124 1125 1126 1127 1128
    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");

1129
    WININET_Release(&lpwh->lpFtpSession->hdr);
1130 1131
}

1132
static DWORD FTPFILE_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
{
    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;
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    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;
1161

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
            *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;
        }
    }
    }
1177
    return INET_QueryOption(hdr, option, buffer, size, unicode);
1178 1179
}

1180
static DWORD FTPFILE_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
1181
{
1182
    ftp_file_t *file = (ftp_file_t*)hdr;
1183
    int res;
1184
    DWORD error;
1185 1186 1187 1188 1189 1190 1191 1192

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

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

1193 1194 1195 1196 1197 1198 1199 1200 1201
    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;
1202 1203
}

1204
static DWORD FTPFILE_ReadFileExA(object_header_t *hdr, INTERNET_BUFFERSA *buffers,
1205 1206 1207 1208 1209
    DWORD flags, DWORD_PTR context)
{
    return FTPFILE_ReadFile(hdr, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength);
}

1210
static DWORD FTPFILE_ReadFileExW(object_header_t *hdr, INTERNET_BUFFERSW *buffers,
1211 1212 1213 1214 1215
    DWORD flags, DWORD_PTR context)
{
    return FTPFILE_ReadFile(hdr, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength);
}

1216
static DWORD FTPFILE_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
1217
{
1218
    ftp_file_t *lpwh = (ftp_file_t*) hdr;
1219 1220 1221 1222 1223
    int res;

    res = send(lpwh->nDataSocket, buffer, size, 0);

    *written = res>0 ? res : 0;
1224
    return res >= 0 ? ERROR_SUCCESS : sock_get_error(errno);
1225 1226
}

1227
static void FTP_ReceiveRequestData(ftp_file_t *file, BOOL first_notif)
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
{
    INTERNET_ASYNC_RESULT iar;
    BYTE buffer[4096];
    int available;

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

    available = recv(file->nDataSocket, buffer, sizeof(buffer), MSG_PEEK);

    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));
}

static void FTPFILE_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
{
1251
    ftp_file_t *file = (ftp_file_t*)workRequest->hdr;
1252 1253 1254 1255

    FTP_ReceiveRequestData(file, FALSE);
}

1256
static DWORD FTPFILE_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1257
{
1258
    ftp_file_t *file = (ftp_file_t*) hdr;
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    int retval, unread = 0;

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

#ifdef FIONREAD
    retval = ioctlsocket(file->nDataSocket, FIONREAD, &unread);
    if (!retval)
        TRACE("%d bytes of queued, but unread data\n", unread);
#else
    FIXME("FIONREAD not available\n");
#endif

    *available = unread;

    if(!unread) {
        BYTE byte;

        *available = 0;

        retval = recv(file->nDataSocket, &byte, 1, MSG_PEEK);
        if(retval > 0) {
            WORKREQUEST workRequest;

            *available = 0;
            workRequest.asyncproc = FTPFILE_AsyncQueryDataAvailableProc;
            workRequest.hdr = WININET_AddRef( &file->hdr );

            INTERNET_AsyncCall(&workRequest);

            return ERROR_IO_PENDING;
        }
    }

    return ERROR_SUCCESS;
}


1296
static const object_vtbl_t FTPFILEVtbl = {
1297
    FTPFILE_Destroy,
1298
    NULL,
1299
    FTPFILE_QueryOption,
1300
    INET_SetOption,
1301
    FTPFILE_ReadFile,
1302 1303
    FTPFILE_ReadFileExA,
    FTPFILE_ReadFileExW,
1304
    FTPFILE_WriteFile,
1305
    FTPFILE_QueryDataAvailable,
1306
    NULL
1307 1308
};

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

    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);
    }

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

        WININET_AddRef( &lpwfs->hdr );
        lpwh->lpFtpSession = lpwfs;
1358
        list_add_head( &lpwfs->hdr.children, &lpwh->hdr.entry );
1359 1360
	
	/* Indicate that a download is currently in progress */
1361
	lpwfs->download_in_progress = lpwh;
1362 1363
    }

1364
    if (lpwfs->lstnSocket != -1)
1365
    {
1366
        closesocket(lpwfs->lstnSocket);
1367 1368
        lpwfs->lstnSocket = -1;
    }
1369

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    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)
        {
1386
            WCHAR *url = heap_alloc(len * sizeof(WCHAR));
1387 1388 1389 1390 1391 1392 1393 1394 1395

            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());
1396
                    heap_free(lpwh->cache_file);
1397 1398 1399
                    lpwh->cache_file = NULL;
                }
            }
1400
            heap_free(url);
1401
        }
1402
        heap_free(uc.lpszUrlPath);
1403 1404
    }

1405
    hIC = lpwfs->lpAppInfo;
1406
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1407 1408
    {
        INTERNET_ASYNC_RESULT iar;
1409

1410
	if (lpwh)
1411
	{
1412
            iar.dwResult = (DWORD_PTR)lpwh->hdr.hInternet;
1413
            iar.dwError = ERROR_SUCCESS;
1414
            SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
1415 1416
                &iar, sizeof(INTERNET_ASYNC_RESULT));
	}
1417

1418 1419 1420 1421 1422 1423 1424 1425
        if(bSuccess) {
            FTP_ReceiveRequestData(lpwh, TRUE);
        }else {
            iar.dwResult = 0;
            iar.dwError = INTERNET_GetLastError();
            SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
                    &iar, sizeof(INTERNET_ASYNC_RESULT));
        }
1426 1427
    }

1428
    if(!bSuccess)
1429
        return FALSE;
1430

1431
    return lpwh->hdr.hInternet;
1432 1433 1434
}


1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
/***********************************************************************
 *           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;

1452
    lpwzFileName = heap_strdupAtoW(lpszFileName);
1453
    ret = FtpOpenFileW(hFtpSession, lpwzFileName, fdwAccess, dwFlags, dwContext);
1454
    heap_free(lpwzFileName);
1455 1456 1457 1458 1459 1460 1461
    return ret;
}


static void AsyncFtpOpenFileProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPOPENFILEW const *req = &workRequest->u.FtpOpenFileW;
1462
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1463 1464 1465 1466 1467

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

    FTP_FtpOpenFileW(lpwfs, req->lpszFilename,
        req->dwAccess, req->dwFlags, req->dwContext);
1468
    heap_free(req->lpszFilename);
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
}

/***********************************************************************
 *           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)
{
1485
    ftp_session_t *lpwfs;
1486
    appinfo_t *hIC = NULL;
1487 1488 1489 1490 1491
    HINTERNET r = NULL;

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

1492
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1493 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 1523 1524 1525 1526 1527
    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)
    {
        WORKREQUEST workRequest;
        struct WORKREQ_FTPOPENFILEW *req;

        workRequest.asyncproc = AsyncFtpOpenFileProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
        req = &workRequest.u.FtpOpenFileW;
1528
	req->lpszFilename = heap_strdupW(lpszFileName);
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	req->dwAccess = fdwAccess;
	req->dwFlags = dwFlags;
	req->dwContext = dwContext;

	INTERNET_AsyncCall(&workRequest);
	r = NULL;
    }
    else
    {
	r = FTP_FtpOpenFileW(lpwfs, lpszFileName, fdwAccess, dwFlags, dwContext);
    }

lend:
    WININET_Release( &lpwfs->hdr );

    return r;
}


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


1576 1577 1578
static void AsyncFtpGetFileProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPGETFILEW const *req = &workRequest->u.FtpGetFileW;
1579
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1580 1581 1582 1583 1584 1585

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

    FTP_FtpGetFileW(lpwfs, req->lpszRemoteFile,
             req->lpszNewFile, req->fFailIfExists,
             req->dwLocalFlagsAttribute, req->dwFlags, req->dwContext);
1586 1587
    heap_free(req->lpszRemoteFile);
    heap_free(req->lpszNewFile);
1588 1589
}

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600

/***********************************************************************
 *           FtpGetFileW (WININET.@)
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1601 1602
BOOL WINAPI FtpGetFileW(HINTERNET hInternet, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
    BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1603
    DWORD_PTR dwContext)
1604
{
1605
    ftp_session_t *lpwfs;
1606
    appinfo_t *hIC = NULL;
1607
    BOOL r = FALSE;
1608

1609 1610 1611 1612 1613 1614
    if (!lpszRemoteFile || !lpszNewFile)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

1615
    lpwfs = (ftp_session_t*) get_handle_object( hInternet );
1616 1617 1618 1619 1620 1621 1622
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
1623 1624
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1625
        goto lend;
1626 1627
    }

1628 1629 1630 1631 1632 1633
    if ((dwInternetFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

1634 1635 1636
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1637
        goto lend;
1638 1639
    }
    
1640
    hIC = lpwfs->lpAppInfo;
1641 1642 1643
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1644
        struct WORKREQ_FTPGETFILEW *req;
1645

1646 1647
        workRequest.asyncproc = AsyncFtpGetFileProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1648
        req = &workRequest.u.FtpGetFileW;
1649 1650
        req->lpszRemoteFile = heap_strdupW(lpszRemoteFile);
        req->lpszNewFile = heap_strdupW(lpszNewFile);
1651 1652 1653 1654
	req->dwLocalFlagsAttribute = dwLocalFlagsAttribute;
	req->fFailIfExists = fFailIfExists;
	req->dwFlags = dwInternetFlags;
	req->dwContext = dwContext;
1655

1656
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
1657 1658 1659
    }
    else
    {
1660
        r = FTP_FtpGetFileW(lpwfs, lpszRemoteFile, lpszNewFile,
1661 1662
           fFailIfExists, dwLocalFlagsAttribute, dwInternetFlags, dwContext);
    }
1663 1664

lend:
1665
    WININET_Release( &lpwfs->hdr );
1666 1667

    return r;
1668 1669 1670
}


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

1689
    TRACE("lpszRemoteFile(%s) lpszNewFile(%s)\n", debugstr_w(lpszRemoteFile), debugstr_w(lpszNewFile));
1690

1691 1692 1693 1694
    /* Clear any error information */
    INTERNET_SetLastError(0);

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

    /* Set up socket to retrieve data */
1701
    if (FTP_SendRetrieve(lpwfs, lpszRemoteFile, dwInternetFlags))
1702 1703 1704
    {
        INT nDataSocket;

1705 1706
        /* Get data socket to server */
        if (FTP_GetDataSocket(lpwfs, &nDataSocket))
1707 1708 1709 1710
        {
            INT nResCode;

            /* Receive data */
1711
            FTP_RetrieveFileData(lpwfs, nDataSocket, hFile);
1712 1713
            closesocket(nDataSocket);

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

1725
    if (lpwfs->lstnSocket != -1)
1726
    {
1727
        closesocket(lpwfs->lstnSocket);
1728 1729
        lpwfs->lstnSocket = -1;
    }
1730

1731
    CloseHandle(hFile);
1732

1733
    hIC = lpwfs->lpAppInfo;
1734
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1735 1736
    {
        INTERNET_ASYNC_RESULT iar;
1737

1738 1739
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1740
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1741 1742 1743
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

1744
    if (!bSuccess) DeleteFileW(lpszNewFile);
1745 1746 1747
    return bSuccess;
}

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

    if (lpdwFileSizeHigh)
        *lpdwFileSizeHigh = 0;

    return 0;
}
1760 1761

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

1782 1783 1784
static void AsyncFtpDeleteFileProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPDELETEFILEW const *req = &workRequest->u.FtpDeleteFileW;
1785
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1786 1787 1788 1789

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

    FTP_FtpDeleteFileW(lpwfs, req->lpszFilename);
1790
    heap_free(req->lpszFilename);
1791 1792
}

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
/***********************************************************************
 *           FtpDeleteFileW  (WININET.@)
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1803 1804
BOOL WINAPI FtpDeleteFileW(HINTERNET hFtpSession, LPCWSTR lpszFileName)
{
1805
    ftp_session_t *lpwfs;
1806
    appinfo_t *hIC = NULL;
1807
    BOOL r = FALSE;
1808

1809
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1810 1811 1812 1813 1814 1815 1816
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
1817 1818
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1819
        goto lend;
1820 1821
    }

1822 1823 1824 1825 1826 1827
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

1828 1829 1830 1831 1832 1833
    if (!lpszFileName)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

1834
    hIC = lpwfs->lpAppInfo;
1835 1836 1837
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1838
        struct WORKREQ_FTPDELETEFILEW *req;
1839

1840 1841
        workRequest.asyncproc = AsyncFtpDeleteFileProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1842
        req = &workRequest.u.FtpDeleteFileW;
1843
        req->lpszFilename = heap_strdupW(lpszFileName);
1844

1845
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
1846 1847 1848
    }
    else
    {
1849
        r = FTP_FtpDeleteFileW(lpwfs, lpszFileName);
1850
    }
1851 1852

lend:
1853
    WININET_Release( &lpwfs->hdr );
1854 1855

    return r;
1856 1857 1858
}

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

1874
    TRACE("%p\n", lpwfs);
1875

1876 1877 1878 1879 1880 1881
    /* Clear any error information */
    INTERNET_SetLastError(0);

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

1882
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1883 1884 1885 1886 1887 1888 1889 1890
    if (nResCode)
    {
        if (nResCode == 250)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }
lend:
1891
    hIC = lpwfs->lpAppInfo;
1892
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1893 1894
    {
        INTERNET_ASYNC_RESULT iar;
1895

1896 1897
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1898
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1899 1900 1901 1902 1903 1904 1905 1906
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}


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

1927 1928 1929
static void AsyncFtpRemoveDirectoryProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPREMOVEDIRECTORYW const *req = &workRequest->u.FtpRemoveDirectoryW;
1930
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1931 1932 1933 1934

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

    FTP_FtpRemoveDirectoryW(lpwfs, req->lpszDirectory);
1935
    heap_free(req->lpszDirectory);
1936 1937
}

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

1954
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1955 1956 1957 1958 1959 1960 1961
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
1962 1963
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1964
        goto lend;
1965 1966
    }

1967 1968 1969 1970 1971 1972
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

1973 1974 1975 1976 1977 1978
    if (!lpszDirectory)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

1979
    hIC = lpwfs->lpAppInfo;
1980 1981 1982
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1983
        struct WORKREQ_FTPREMOVEDIRECTORYW *req;
1984

1985 1986
        workRequest.asyncproc = AsyncFtpRemoveDirectoryProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1987
        req = &workRequest.u.FtpRemoveDirectoryW;
1988
        req->lpszDirectory = heap_strdupW(lpszDirectory);
1989

1990
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
1991 1992 1993
    }
    else
    {
1994
        r = FTP_FtpRemoveDirectoryW(lpwfs, lpszDirectory);
1995
    }
1996 1997

lend:
1998
    WININET_Release( &lpwfs->hdr );
1999 2000

    return r;
2001 2002 2003
}

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

    TRACE("\n");
2020

2021 2022 2023 2024 2025 2026
    /* Clear any error information */
    INTERNET_SetLastError(0);

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

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

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

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

    return bSuccess;
}


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

2076 2077 2078
static void AsyncFtpRenameFileProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_FTPRENAMEFILEW const *req = &workRequest->u.FtpRenameFileW;
2079
    ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
2080 2081 2082 2083

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

    FTP_FtpRenameFileW(lpwfs, req->lpszSrcFile, req->lpszDestFile);
2084 2085
    heap_free(req->lpszSrcFile);
    heap_free(req->lpszDestFile);
2086 2087
}

2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
/***********************************************************************
 *           FtpRenameFileW  (WININET.@)
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
2098 2099
BOOL WINAPI FtpRenameFileW(HINTERNET hFtpSession, LPCWSTR lpszSrc, LPCWSTR lpszDest)
{
2100
    ftp_session_t *lpwfs;
2101
    appinfo_t *hIC = NULL;
2102
    BOOL r = FALSE;
2103

2104
    lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
2105 2106 2107 2108 2109 2110 2111
    if (!lpwfs)
    {
        INTERNET_SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (WH_HFTPSESSION != lpwfs->hdr.htype)
2112 2113
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2114
        goto lend;
2115 2116
    }

2117 2118 2119 2120 2121 2122
    if (lpwfs->download_in_progress != NULL)
    {
        INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
        goto lend;
    }

2123 2124 2125 2126 2127 2128
    if (!lpszSrc || !lpszDest)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

2129
    hIC = lpwfs->lpAppInfo;
2130 2131 2132
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
2133
        struct WORKREQ_FTPRENAMEFILEW *req;
2134

2135 2136
        workRequest.asyncproc = AsyncFtpRenameFileProc;
        workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
2137
        req = &workRequest.u.FtpRenameFileW;
2138 2139
        req->lpszSrcFile = heap_strdupW(lpszSrc);
        req->lpszDestFile = heap_strdupW(lpszDest);
2140

2141
	r = res_to_le(INTERNET_AsyncCall(&workRequest));
2142 2143 2144
    }
    else
    {
2145
        r = FTP_FtpRenameFileW(lpwfs, lpszSrc, lpszDest);
2146
    }
2147 2148

lend:
2149
    WININET_Release( &lpwfs->hdr );
2150 2151

    return r;
2152 2153 2154
}

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

    TRACE("\n");
2171

2172 2173 2174 2175 2176 2177
    /* Clear any error information */
    INTERNET_SetLastError(0);

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

2178
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2179 2180 2181 2182 2183
    if (nResCode == 350)
    {
        if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNTO, lpszDest, 0, 0, 0))
            goto lend;

2184
        nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2185 2186 2187 2188 2189 2190 2191 2192
    }

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

lend:
2193
    hIC = lpwfs->lpAppInfo;
2194
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2195 2196
    {
        INTERNET_ASYNC_RESULT iar;
2197

2198 2199
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2200
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2201 2202 2203 2204 2205 2206
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

2207 2208 2209
/***********************************************************************
 *           FtpCommandA  (WININET.@)
 */
2210 2211 2212
BOOL WINAPI FtpCommandA( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
                         LPCSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
{
2213 2214 2215 2216
    BOOL r;
    WCHAR *cmdW;

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

2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
    if (fExpectResponse)
    {
        FIXME("data connection not supported\n");
        return FALSE;
    }

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

2231
    if (!(cmdW = heap_strdupAtoW(lpszCommand)))
2232 2233 2234 2235 2236 2237 2238
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }

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

2239
    heap_free(cmdW);
2240
    return r;
2241 2242
}

2243 2244 2245
/***********************************************************************
 *           FtpCommandW  (WININET.@)
 */
2246 2247 2248
BOOL WINAPI FtpCommandW( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
                         LPCWSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
{
2249
    BOOL r = FALSE;
2250
    ftp_session_t *lpwfs;
2251 2252 2253 2254 2255 2256
    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);
2257

2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    if (!lpszCommand || !lpszCommand[0])
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

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

2270
    lpwfs = (ftp_session_t*) get_handle_object( hConnect );
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
    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);
2290
    if ((cmd = heap_alloc(len)))
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
        WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, cmd, len, NULL, NULL);
    else
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        goto lend;
    }

    strcat(cmd, szCRLF);
    len--;

    TRACE("Sending (%s) len(%d)\n", cmd, len);
    while ((nBytesSent < len) && (nRC != -1))
    {
        nRC = send(lpwfs->sndSocket, cmd + nBytesSent, len - nBytesSent, 0);
        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 );
2323
    heap_free( cmd );
2324
    return r;
2325
}
2326

2327 2328 2329 2330 2331 2332

/***********************************************************************
 *           FTPSESSION_Destroy (internal)
 *
 * Deallocate session handle
 */
2333
static void FTPSESSION_Destroy(object_header_t *hdr)
2334
{
2335
    ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2336 2337 2338 2339 2340

    TRACE("\n");

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

2341 2342 2343
    heap_free(lpwfs->lpszPassword);
    heap_free(lpwfs->lpszUserName);
    heap_free(lpwfs->servername);
2344 2345
}

2346
static void FTPSESSION_CloseConnection(object_header_t *hdr)
2347
{
2348
    ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369

    TRACE("\n");

    SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
                      INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);

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

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

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

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

    SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
                      INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
}
2370

2371
static DWORD FTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
{
    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;
    }

2385
    return INET_QueryOption(hdr, option, buffer, size, unicode);
2386 2387
}

2388
static const object_vtbl_t FTPSESSIONVtbl = {
2389
    FTPSESSION_Destroy,
2390
    FTPSESSION_CloseConnection,
2391
    FTPSESSION_QueryOption,
2392
    INET_SetOption,
2393
    NULL,
2394
    NULL,
2395
    NULL,
2396
    NULL,
2397
    NULL
2398 2399 2400
};


2401 2402 2403 2404 2405 2406 2407 2408 2409
/***********************************************************************
 *           FTP_Connect (internal)
 *
 * Connect to a ftp server
 *
 * RETURNS
 *   HINTERNET a session handle on success
 *   NULL on failure
 *
2410 2411 2412 2413 2414 2415 2416 2417 2418
 * 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.
 *
2419 2420
 */

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

2441 2442
    TRACE("%p  Server(%s) Port(%d) User(%s) Paswd(%s)\n",
	    hIC, debugstr_w(lpszServerName),
2443
	    nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword));
2444

2445
    assert( hIC->hdr.htype == WH_HINIT );
2446

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

2460
    if (nServerPort == INTERNET_INVALID_PORT_NUMBER)
2461 2462 2463
        lpwfs->serverport = INTERNET_DEFAULT_FTP_PORT;
    else
        lpwfs->serverport = nServerPort;
2464

2465 2466 2467
    lpwfs->hdr.htype = WH_HFTPSESSION;
    lpwfs->hdr.dwFlags = dwFlags;
    lpwfs->hdr.dwContext = dwContext;
2468
    lpwfs->hdr.dwInternalFlags |= dwInternalFlags;
2469
    lpwfs->download_in_progress = NULL;
2470 2471 2472
    lpwfs->sndSocket = -1;
    lpwfs->lstnSocket = -1;
    lpwfs->pasvSocket = -1;
2473

2474 2475
    WININET_AddRef( &hIC->hdr );
    lpwfs->lpAppInfo = hIC;
2476
    list_add_head( &hIC->hdr.children, &lpwfs->hdr.entry );
2477

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

2489
        lpwfs->lpszUserName = heap_strdupW(szDefaultUsername);
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501

        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 */
                strcpyW(szPassword, szEmpty);
            }
        }
        RegCloseKey(key);

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

2515
        iar.dwResult = (DWORD_PTR)lpwfs->hdr.hInternet;
2516 2517
        iar.dwError = ERROR_SUCCESS;

2518
        SendAsyncCallback(&hIC->hdr, dwContext,
2519 2520 2521 2522
                      INTERNET_STATUS_HANDLE_CREATED, &iar,
                      sizeof(INTERNET_ASYNC_RESULT));
    }
        
2523
    SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_RESOLVING_NAME,
2524
        (LPWSTR) lpszServerName, (strlenW(lpszServerName)+1) * sizeof(WCHAR));
2525

2526
    sock_namelen = sizeof(socketAddr);
2527
    if (!GetAddress(lpszServerName, lpwfs->serverport, (struct sockaddr *)&socketAddr, &sock_namelen))
2528 2529 2530 2531 2532
    {
	INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
        goto lerror;
    }

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

    inet_ntop(socketAddr.sin_family, &socketAddr.sin_addr, szaddr, sizeof(szaddr));
    SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_NAME_RESOLVED,
                      szaddr, strlen(szaddr)+1);

2544 2545
    nsocket = socket(AF_INET,SOCK_STREAM,0);
    if (nsocket == -1)
2546 2547 2548 2549 2550
    {
	INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
        goto lerror;
    }

2551
    SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTING_TO_SERVER,
2552
                      szaddr, strlen(szaddr)+1);
2553

2554
    if (connect(nsocket, (struct sockaddr *)&socketAddr, sock_namelen) < 0)
2555
    {
2556
	ERR("Unable to connect (%s)\n", strerror(errno));
2557
	INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2558
	closesocket(nsocket);
2559 2560 2561
    }
    else
    {
2562
        TRACE("Connected to server\n");
2563
	lpwfs->sndSocket = nsocket;
2564
        SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTED_TO_SERVER,
2565
                          szaddr, strlen(szaddr)+1);
2566

2567
	sock_namelen = sizeof(lpwfs->socketAddress);
2568
	getsockname(nsocket, (struct sockaddr *) &lpwfs->socketAddress, &sock_namelen);
2569 2570 2571 2572 2573 2574 2575 2576 2577

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

lerror:
2578
    if (!bSuccess)
2579
    {
2580 2581 2582
        if(lpwfs)
            WININET_Release( &lpwfs->hdr );
        return NULL;
2583 2584
    }

2585
    return lpwfs->hdr.hInternet;
2586 2587 2588 2589
}


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

    TRACE("\n");
2605
    FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2606 2607 2608 2609

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

2610
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
    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;
}


/***********************************************************************
2633
 *           FTP_SendCommandA (internal)
2634 2635 2636 2637 2638 2639 2640 2641
 *
 * Send command to server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
Mike McCormack's avatar
Mike McCormack committed
2642
static BOOL FTP_SendCommandA(INT nSocket, FTP_COMMAND ftpCmd, LPCSTR lpszParam,
2643
	INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2644 2645 2646 2647
{
    	DWORD len;
	CHAR *buf;
	DWORD nBytesSent = 0;
2648
	int nRC = 0;
2649
	DWORD dwParamLen;
2650

2651
	TRACE("%d: (%s) %d\n", ftpCmd, debugstr_a(lpszParam), nSocket);
2652 2653

	if (lpfnStatusCB)
2654
        {
2655
            lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2656
        }
2657

2658 2659
	dwParamLen = lpszParam?strlen(lpszParam)+1:0;
	len = dwParamLen + strlen(szFtpCommands[ftpCmd]) + strlen(szCRLF);
2660
	if (NULL == (buf = heap_alloc(len+1)))
2661 2662 2663 2664
	{
	    INTERNET_SetLastError(ERROR_OUTOFMEMORY);
	    return FALSE;
	}
2665 2666
	sprintf(buf, "%s%s%s%s", szFtpCommands[ftpCmd], dwParamLen ? " " : "",
		dwParamLen ? lpszParam : "", szCRLF);
2667

2668
	TRACE("Sending (%s) len(%d)\n", buf, len);
2669
	while((nBytesSent < len) && (nRC != -1))
2670 2671 2672 2673
	{
		nRC = send(nSocket, buf+nBytesSent, len - nBytesSent, 0);
		nBytesSent += nRC;
	}
2674
    heap_free(buf);
2675 2676

	if (lpfnStatusCB)
2677
        {
2678 2679
            lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_REQUEST_SENT,
                         &nBytesSent, sizeof(DWORD));
2680
        }
2681

2682
	TRACE("Sent %d bytes\n", nBytesSent);
2683
	return (nRC != -1);
2684 2685
}

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
/***********************************************************************
 *           FTP_SendCommand (internal)
 *
 * Send command to server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
2696
static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
2697
	INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2698 2699
{
    BOOL ret;
2700
    LPSTR lpszParamA = heap_strdupWtoA(lpszParam);
2701
    ret = FTP_SendCommandA(nSocket, ftpCmd, lpszParamA, lpfnStatusCB, hdr, dwContext);
2702
    heap_free(lpszParamA);
2703 2704
    return ret;
}
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715

/***********************************************************************
 *           FTP_ReceiveResponse (internal)
 *
 * Receive response from server
 *
 * RETURNS
 *   Reply code on success
 *   0 on failure
 *
 */
2716
INT FTP_ReceiveResponse(ftp_session_t *lpwfs, DWORD_PTR dwContext)
2717
{
2718
    LPSTR lpszResponse = INTERNET_GetResponseBuffer();
2719 2720
    DWORD nRecv;
    INT rc = 0;
2721 2722 2723
    char firstprefix[5];
    BOOL multiline = FALSE;

2724
    TRACE("socket(%d)\n", lpwfs->sndSocket);
2725

2726
    SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2727 2728 2729

    while(1)
    {
2730
	if (!INTERNET_GetNextLine(lpwfs->sndSocket, &nRecv))
2731 2732
	    goto lerror;

2733 2734 2735 2736 2737 2738 2739
        if (nRecv >= 3)
	{
	    if(!multiline)
	    {
	        if(lpszResponse[3] != '-')
		    break;
		else
Austin English's avatar
Austin English committed
2740
		{  /* Start of multiline response.  Loop until we get "nnn " */
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
		    multiline = TRUE;
		    memcpy(firstprefix, lpszResponse, 3);
		    firstprefix[3] = ' ';
		    firstprefix[4] = '\0';
		}
	    }
	    else
	    {
	        if(!memcmp(firstprefix, lpszResponse, 4))
		    break;
	    }
	}
2753
    }
2754

2755 2756 2757 2758
    if (nRecv >= 3)
    {
        rc = atoi(lpszResponse);

2759
        SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
		    &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
 *
 */
2779
static BOOL FTP_SendPassword(ftp_session_t *lpwfs)
2780 2781 2782 2783 2784 2785 2786
{
    INT nResCode;
    BOOL bSuccess = FALSE;

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

2788
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
    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)
 *
2812
 *
2813 2814 2815 2816 2817 2818
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2819
static BOOL FTP_SendAccount(ftp_session_t *lpwfs)
2820 2821 2822 2823 2824
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
2825
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_ACCT, szNoAccount, 0, 0, 0))
2826 2827
        goto lend;

2828
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
    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
 *
 */
2849
static BOOL FTP_SendStore(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
{
    INT nResCode;
    BOOL bSuccess = FALSE;

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

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

2861
    if (!FTP_SendPortOrPasv(lpwfs))
2862 2863 2864 2865
        goto lend;

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_STOR, lpszRemoteFile, 0, 0, 0))
	    goto lend;
2866
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2867 2868
    if (nResCode)
    {
2869
        if (nResCode == 150 || nResCode == 125)
2870 2871 2872 2873 2874 2875
            bSuccess = TRUE;
	else
            FTP_SetResponseError(nResCode);
    }

lend:
2876
    if (!bSuccess && lpwfs->lstnSocket != -1)
2877
    {
2878
        closesocket(lpwfs->lstnSocket);
2879
        lpwfs->lstnSocket = -1;
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
    }

    return bSuccess;
}


/***********************************************************************
 *           FTP_InitListenSocket (internal)
 *
 * Create a socket to listen for server response
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2896
static BOOL FTP_InitListenSocket(ftp_session_t *lpwfs)
2897 2898
{
    BOOL bSuccess = FALSE;
2899
    socklen_t namelen = sizeof(lpwfs->lstnSocketAddress);
2900 2901 2902 2903

    TRACE("\n");

    lpwfs->lstnSocket = socket(PF_INET, SOCK_STREAM, 0);
2904
    if (lpwfs->lstnSocket == -1)
2905 2906 2907 2908 2909
    {
        TRACE("Unable to create listening socket\n");
            goto lend;
    }

2910 2911 2912 2913
    /* 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 */
2914
    lpwfs->lstnSocketAddress.sin_port = htons(0);
2915

2916
    if (bind(lpwfs->lstnSocket,(struct sockaddr *) &lpwfs->lstnSocketAddress, sizeof(lpwfs->lstnSocketAddress)) == -1)
2917 2918 2919 2920 2921
    {
        TRACE("Unable to bind socket\n");
        goto lend;
    }

2922
    if (listen(lpwfs->lstnSocket, MAX_BACKLOG) == -1)
2923 2924 2925 2926 2927
    {
        TRACE("listen failed\n");
        goto lend;
    }

2928
    if (getsockname(lpwfs->lstnSocket, (struct sockaddr *) &lpwfs->lstnSocketAddress, &namelen) != -1)
2929 2930 2931
        bSuccess = TRUE;

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

    return bSuccess;
}


/***********************************************************************
 *           FTP_SendType (internal)
 *
2945
 * Tell server type of data being transferred
2946 2947 2948 2949 2950
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
2951 2952 2953
 * 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.
2954
 */
2955
static BOOL FTP_SendType(ftp_session_t *lpwfs, DWORD dwType)
2956 2957
{
    INT nResCode;
2958
    WCHAR type[] = { 'I','\0' };
2959 2960 2961 2962
    BOOL bSuccess = FALSE;

    TRACE("\n");
    if (dwType & INTERNET_FLAG_TRANSFER_ASCII)
2963
        type[0] = 'A';
2964 2965 2966 2967

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

2968
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext)/100;
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
    if (nResCode)
    {
        if (nResCode == 2)
            bSuccess = TRUE;
	else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}

2981 2982

#if 0  /* FIXME: should probably be used for FtpGetFileSize */
2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
/***********************************************************************
 *           FTP_GetFileSize (internal)
 *
 * Retrieves from the server the size of the given file
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2993
static BOOL FTP_GetFileSize(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD *dwSize)
2994 2995 2996 2997 2998 2999 3000 3001 3002
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");

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

3003
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023
    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;
}
3024
#endif
3025

3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036

/***********************************************************************
 *           FTP_SendPort (internal)
 *
 * Tell server which port to use
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3037
static BOOL FTP_SendPort(ftp_session_t *lpwfs)
3038
{
3039
    static const WCHAR szIPFormat[] = {'%','d',',','%','d',',','%','d',',','%','d',',','%','d',',','%','d','\0'};
3040
    INT nResCode;
3041
    WCHAR szIPAddress[64];
3042 3043 3044
    BOOL bSuccess = FALSE;
    TRACE("\n");

3045
    sprintfW(szIPAddress, szIPFormat,
3046 3047 3048 3049
	 lpwfs->lstnSocketAddress.sin_addr.s_addr&0x000000FF,
        (lpwfs->lstnSocketAddress.sin_addr.s_addr&0x0000FF00)>>8,
        (lpwfs->lstnSocketAddress.sin_addr.s_addr&0x00FF0000)>>16,
        (lpwfs->lstnSocketAddress.sin_addr.s_addr&0xFF000000)>>24,
3050 3051 3052 3053 3054 3055
        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;

3056
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
    if (nResCode)
    {
        if (nResCode == 200)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}


/***********************************************************************
3071 3072 3073 3074
 *           FTP_DoPassive (internal)
 *
 * Tell server that we want to do passive transfers
 * and connect data socket
3075
 *
3076 3077 3078 3079 3080
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3081
static BOOL FTP_DoPassive(ftp_session_t *lpwfs)
3082 3083 3084 3085 3086 3087 3088 3089
{
    INT nResCode;
    BOOL bSuccess = FALSE;

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

3090
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3091 3092 3093 3094 3095 3096 3097 3098 3099
    if (nResCode)
    {
        if (nResCode == 227)
	{
	    LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
	    LPSTR p;
	    int f[6];
	    int i;
	    char *pAddr, *pPort;
3100
	    INT nsocket = -1;
3101 3102 3103
	    struct sockaddr_in dataSocketAddress;

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

3106
	    if (*p == '\0')
3107
	    {
3108
		ERR("no address found in response, aborting\n");
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130
		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;
	    pAddr = (char *)&(dataSocketAddress.sin_addr.s_addr);
	    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];

3131 3132
            nsocket = socket(AF_INET,SOCK_STREAM,0);
            if (nsocket == -1)
3133 3134 3135 3136 3137
                goto lend;

	    if (connect(nsocket, (struct sockaddr *)&dataSocketAddress, sizeof(dataSocketAddress)))
            {
	        ERR("can't connect passive FTP data port.\n");
3138
                closesocket(nsocket);
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
	        goto lend;
            }
	    lpwfs->pasvSocket = nsocket;
            bSuccess = TRUE;
	}
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}


3153
static BOOL FTP_SendPortOrPasv(ftp_session_t *lpwfs)
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
{
    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.
3175
 *
3176 3177 3178 3179 3180 3181
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3182
static BOOL FTP_GetDataSocket(ftp_session_t *lpwfs, LPINT nDataSocket)
3183 3184
{
    struct sockaddr_in saddr;
3185
    socklen_t addrlen = sizeof(struct sockaddr);
3186 3187

    TRACE("\n");
3188 3189 3190
    if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
    {
	*nDataSocket = lpwfs->pasvSocket;
3191
	lpwfs->pasvSocket = -1;
3192 3193 3194 3195
    }
    else
    {
        *nDataSocket = accept(lpwfs->lstnSocket, (struct sockaddr *) &saddr, &addrlen);
3196
        closesocket(lpwfs->lstnSocket);
3197
        lpwfs->lstnSocket = -1;
3198
    }
3199
    return *nDataSocket != -1;
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
}


/***********************************************************************
 *           FTP_SendData (internal)
 *
 * Send data to the server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3213
static BOOL FTP_SendData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3214 3215 3216 3217 3218
{
    BY_HANDLE_FILE_INFORMATION fi;
    DWORD nBytesRead = 0;
    DWORD nBytesSent = 0;
    DWORD nTotalSent = 0;
3219 3220
    DWORD nBytesToSend, nLen;
    int nRC = 1;
3221 3222 3223 3224 3225
    time_t s_long_time, e_long_time;
    LONG nSeconds;
    CHAR *lpszBuffer;

    TRACE("\n");
3226
    lpszBuffer = heap_alloc_zero(sizeof(CHAR)*DATA_PACKET_SIZE);
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248

    /* 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;
        }

3249
        nLen = DATA_PACKET_SIZE < nBytesToSend ?
3250 3251 3252
            DATA_PACKET_SIZE : nBytesToSend;
        nRC  = send(nDataSocket, lpszBuffer, nLen, 0);

3253
        if (nRC != -1)
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
        {
            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 )
        {
3264
            TRACE( "%d bytes of %d bytes (%d%%) in %d min %d sec estimated remaining time %d sec\n",
3265
            nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds / 60,
3266 3267 3268 3269
            nSeconds % 60, (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent );
        }
        else
        {
3270
            TRACE( "%d bytes of %d bytes (%d%%) in %d sec estimated remaining time %d sec\n",
3271 3272 3273
            nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds,
            (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent);
        }
3274
    } while (nRC != -1);
3275 3276 3277

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

3278
    heap_free(lpszBuffer);
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292
    return nTotalSent;
}


/***********************************************************************
 *           FTP_SendRetrieve (internal)
 *
 * Send request to retrieve a file
 *
 * RETURNS
 *   Number of bytes to be received on success
 *   0 on failure
 *
 */
3293
static BOOL FTP_SendRetrieve(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
3294 3295
{
    INT nResCode;
3296
    BOOL ret;
3297 3298

    TRACE("\n");
3299
    if (!(ret = FTP_InitListenSocket(lpwfs)))
3300 3301
        goto lend;

3302
    if (!(ret = FTP_SendType(lpwfs, dwType)))
3303 3304
        goto lend;

3305
    if (!(ret = FTP_SendPortOrPasv(lpwfs)))
3306 3307
        goto lend;

3308
    if (!(ret = FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RETR, lpszRemoteFile, 0, 0, 0)))
3309 3310
        goto lend;

3311
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3312 3313
    if ((nResCode != 125) && (nResCode != 150)) {
	/* That means that we got an error getting the file. */
3314 3315
        FTP_SetResponseError(nResCode);
	ret = FALSE;
3316 3317 3318
    }

lend:
3319
    if (!ret && lpwfs->lstnSocket != -1)
3320
    {
3321
        closesocket(lpwfs->lstnSocket);
3322
        lpwfs->lstnSocket = -1;
3323 3324
    }

3325
    return ret;
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
}


/***********************************************************************
 *           FTP_RetrieveData  (internal)
 *
 * Retrieve data from server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3339
static BOOL FTP_RetrieveFileData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3340 3341 3342 3343 3344 3345 3346
{
    DWORD nBytesWritten;
    INT nRC = 0;
    CHAR *lpszBuffer;

    TRACE("\n");

3347
    lpszBuffer = heap_alloc_zero(sizeof(CHAR)*DATA_PACKET_SIZE);
3348 3349 3350 3351 3352 3353
    if (NULL == lpszBuffer)
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }

3354
    while (nRC != -1)
3355 3356
    {
        nRC = recv(nDataSocket, lpszBuffer, DATA_PACKET_SIZE, 0);
3357
        if (nRC != -1)
3358 3359 3360 3361
        {
            /* other side closed socket. */
            if (nRC == 0)
                goto recv_end;
3362
            WriteFile(hFile, lpszBuffer, nRC, &nBytesWritten, NULL);
3363 3364 3365 3366 3367 3368
        }
    }

    TRACE("Data transfer complete\n");

recv_end:
3369 3370
    heap_free(lpszBuffer);
    return (nRC != -1);
3371 3372
}

3373
/***********************************************************************
3374
 *           FTPFINDNEXT_Destroy (internal)
3375
 *
3376
 * Deallocate session handle
3377
 */
3378
static void FTPFINDNEXT_Destroy(object_header_t *hdr)
3379
{
3380 3381
    LPWININETFTPFINDNEXTW lpwfn = (LPWININETFTPFINDNEXTW) hdr;
    DWORD i;
3382

3383
    TRACE("\n");
3384

3385
    WININET_Release(&lpwfn->lpFtpSession->hdr);
3386

3387
    for (i = 0; i < lpwfn->size; i++)
3388
    {
3389
        heap_free(lpwfn->lpafp[i].lpszName);
3390
    }
3391
    heap_free(lpwfn->lpafp);
3392
}
3393

3394
static DWORD FTPFINDNEXT_FindNextFileProc(WININETFTPFINDNEXTW *find, LPVOID data)
3395 3396 3397
{
    WIN32_FIND_DATAW *find_data = data;
    DWORD res = ERROR_SUCCESS;
3398

3399 3400 3401 3402 3403 3404 3405
    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++;
3406

3407 3408 3409 3410 3411 3412
        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)
3413 3414 3415
    {
        INTERNET_ASYNC_RESULT iar;

3416 3417
        iar.dwResult = (res == ERROR_SUCCESS);
        iar.dwError = res;
3418

3419
        INTERNET_SendCallback(&find->hdr, find->hdr.dwContext,
3420 3421 3422 3423
                              INTERNET_STATUS_REQUEST_COMPLETE, &iar,
                              sizeof(INTERNET_ASYNC_RESULT));
    }

3424
    return res;
3425 3426
}

3427
static void FTPFINDNEXT_AsyncFindNextFileProc(WORKREQUEST *workRequest)
3428
{
3429
    struct WORKREQ_FTPFINDNEXTW *req = &workRequest->u.FtpFindNextW;
3430

3431 3432
    FTPFINDNEXT_FindNextFileProc((WININETFTPFINDNEXTW*)workRequest->hdr, req->lpFindFileData);
}
3433

3434
static DWORD FTPFINDNEXT_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
{
    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;
    }

3448
    return INET_QueryOption(hdr, option, buffer, size, unicode);
3449 3450
}

3451
static DWORD FTPFINDNEXT_FindNextFileW(object_header_t *hdr, void *data)
3452 3453
{
    WININETFTPFINDNEXTW *find = (WININETFTPFINDNEXTW*)hdr;
3454

3455
    if (find->lpFtpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3456
    {
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
        WORKREQUEST workRequest;
        struct WORKREQ_FTPFINDNEXTW *req;

        workRequest.asyncproc = FTPFINDNEXT_AsyncFindNextFileProc;
        workRequest.hdr = WININET_AddRef( &find->hdr );
        req = &workRequest.u.FtpFindNextW;
        req->lpFindFileData = data;

	INTERNET_AsyncCall(&workRequest);

        return ERROR_SUCCESS;
3468 3469
    }

3470
    return FTPFINDNEXT_FindNextFileProc(find, data);
3471 3472
}

3473
static const object_vtbl_t FTPFINDNEXTVtbl = {
3474
    FTPFINDNEXT_Destroy,
3475
    NULL,
3476
    FTPFINDNEXT_QueryOption,
3477
    INET_SetOption,
3478
    NULL,
3479
    NULL,
3480
    NULL,
3481
    NULL,
3482
    NULL,
3483
    FTPFINDNEXT_FindNextFileW
3484
};
3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495

/***********************************************************************
 *           FTP_ReceiveFileList (internal)
 *
 * Read file list from server
 *
 * RETURNS
 *   Handle to file list on success
 *   NULL on failure
 *
 */
3496
static HINTERNET FTP_ReceiveFileList(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3497
	LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext)
3498 3499
{
    DWORD dwSize = 0;
3500
    LPFILEPROPERTIESW lpafp = NULL;
3501
    LPWININETFTPFINDNEXTW lpwfn = NULL;
3502

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

3505
    if (FTP_ParseDirectory(lpwfs, nSocket, lpszSearchFile, &lpafp, &dwSize))
3506
    {
3507 3508
        if(lpFindFileData)
            FTP_ConvertFileProp(lpafp, lpFindFileData);
3509

3510
        lpwfn = alloc_object(&lpwfs->hdr, &FTPFINDNEXTVtbl, sizeof(WININETFTPFINDNEXTW));
3511
        if (lpwfn)
3512
        {
3513
            lpwfn->hdr.htype = WH_HFTPFINDNEXT;
3514 3515 3516 3517 3518
            lpwfn->hdr.dwContext = dwContext;
            lpwfn->index = 1; /* Next index is 1 since we return index 0 */
            lpwfn->size = dwSize;
            lpwfn->lpafp = lpafp;

3519 3520
            WININET_AddRef( &lpwfs->hdr );
            lpwfn->lpFtpSession = lpwfs;
3521
            list_add_head( &lpwfs->hdr.children, &lpwfn->hdr.entry );
3522
        }
3523
    }
3524

3525
    TRACE("Matched %d files\n", dwSize);
3526
    return lpwfn ? lpwfn->hdr.hInternet : NULL;
3527 3528 3529 3530 3531 3532
}


/***********************************************************************
 *           FTP_ConvertFileProp (internal)
 *
3533
 * Converts FILEPROPERTIESW struct to WIN32_FIND_DATAA
3534 3535 3536 3537 3538 3539
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
3540
static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData)
3541 3542 3543
{
    BOOL bSuccess = FALSE;

3544
    ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAW));
3545 3546 3547

    if (lpafp)
    {
3548
        SystemTimeToFileTime( &lpafp->tmLastModified, &lpFindFileData->ftLastAccessTime );
3549 3550
	lpFindFileData->ftLastWriteTime = lpFindFileData->ftLastAccessTime;
	lpFindFileData->ftCreationTime = lpFindFileData->ftLastAccessTime;
3551
	
3552
        /* Not all fields are filled in */
3553 3554
        lpFindFileData->nFileSizeHigh = 0; /* We do not handle files bigger than 0xFFFFFFFF bytes yet :-) */
        lpFindFileData->nFileSizeLow = lpafp->nSize;
3555 3556 3557 3558 3559

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

        if (lpafp->lpszName)
3560
            lstrcpynW(lpFindFileData->cFileName, lpafp->lpszName, MAX_PATH);
3561 3562 3563 3564 3565 3566 3567

	bSuccess = TRUE;
    }

    return bSuccess;
}

3568 3569 3570 3571 3572 3573 3574 3575 3576
/***********************************************************************
 *           FTP_ParseNextFile (internal)
 *
 * Parse the next line in file listing
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 */
3577
static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW lpfp)
3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
{
    static const char szSpace[] = " \t";
    DWORD nBufLen;
    char *pszLine;
    char *pszToken;
    char *pszTmp;
    BOOL found = FALSE;
    int i;
    
    lpfp->lpszName = NULL;
    do {
        if(!(pszLine = INTERNET_GetNextLine(nSocket, &nBufLen)))
            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);
            }
            
3616 3617 3618 3619 3620 3621
            lpfp->tmLastModified.wSecond = 0;
            lpfp->tmLastModified.wMinute = 0;
            lpfp->tmLastModified.wHour   = 0;
            lpfp->tmLastModified.wDay    = 0;
            lpfp->tmLastModified.wMonth  = 0;
            lpfp->tmLastModified.wYear   = 0;
3622 3623 3624 3625 3626 3627 3628
            
            /* Determine month */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if(strlen(pszToken) >= 3) {
                pszToken[3] = 0;
                if((pszTmp = StrStrIA(szMonths, pszToken)))
3629
                    lpfp->tmLastModified.wMonth = ((pszTmp - szMonths) / 3)+1;
3630 3631 3632 3633
            }
            /* Determine day */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3634
            lpfp->tmLastModified.wDay = atoi(pszToken);
3635 3636 3637 3638
            /* Determine time or year */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if((pszTmp = strchr(pszToken, ':'))) {
3639
                SYSTEMTIME curr_time;
3640 3641
                *pszTmp = 0;
                pszTmp++;
3642 3643 3644 3645
                lpfp->tmLastModified.wMinute = atoi(pszTmp);
                lpfp->tmLastModified.wHour = atoi(pszToken);
                GetLocalTime( &curr_time );
                lpfp->tmLastModified.wYear = curr_time.wYear;
3646 3647
            }
            else {
3648 3649
                lpfp->tmLastModified.wYear = atoi(pszToken);
                lpfp->tmLastModified.wHour = 12;
3650
            }
3651 3652 3653
            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);
3654 3655 3656

            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3657
            lpfp->lpszName = heap_strdupAtoW(pszToken);
3658 3659 3660 3661 3662 3663 3664 3665
            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)) {
3666
            int mon, mday, year, hour, min;
3667 3668
            lpfp->permissions = 0xFFFF; /* No idea, put full permission :-) */
            
3669 3670 3671 3672
            sscanf(pszToken, "%d-%d-%d", &mon, &mday, &year);
            lpfp->tmLastModified.wDay   = mday;
            lpfp->tmLastModified.wMonth = mon;
            lpfp->tmLastModified.wYear  = year;
3673 3674

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

3677 3678
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3679 3680 3681
            sscanf(pszToken, "%d:%d", &hour, &min);
            lpfp->tmLastModified.wHour   = hour;
            lpfp->tmLastModified.wMinute = min;
3682
            if((pszToken[5] == 'P') && (pszToken[6] == 'M')) {
3683
                lpfp->tmLastModified.wHour += 12;
3684
            }
3685 3686 3687 3688 3689
            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);
3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700

            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if(!strcasecmp(pszToken, "<DIR>")) {
                lpfp->bIsDirectory = TRUE;
                lpfp->nSize = 0;
                TRACE("Is directory\n");
            }
            else {
                lpfp->bIsDirectory = FALSE;
                lpfp->nSize = atol(pszToken);
3701
                TRACE("Size: %d\n", lpfp->nSize);
3702 3703 3704 3705
            }
            
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
3706
            lpfp->lpszName = heap_strdupAtoW(pszToken);
3707 3708 3709 3710 3711 3712 3713 3714
            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) {
3715 3716
            if((lpszSearchFile == NULL) ||
	       (PathMatchSpecW(lpfp->lpszName, lpszSearchFile))) {
3717 3718 3719 3720
                found = TRUE;
                TRACE("Matched: %s\n", debugstr_w(lpfp->lpszName));
            }
            else {
3721
                heap_free(lpfp->lpszName);
3722 3723 3724 3725 3726 3727
                lpfp->lpszName = NULL;
            }
        }
    } while(!found);
    return TRUE;
}
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737

/***********************************************************************
 *           FTP_ParseDirectory (internal)
 *
 * Parse string of directory information
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 */
3738
static BOOL FTP_ParseDirectory(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3739
    LPFILEPROPERTIESW *lpafp, LPDWORD dwfp)
3740 3741
{
    BOOL bSuccess = TRUE;
3742 3743
    INT sizeFilePropArray = 500;/*20; */
    INT indexFilePropArray = -1;
3744 3745 3746

    TRACE("\n");

Austin English's avatar
Austin English committed
3747
    /* Allocate initial file properties array */
3748
    *lpafp = heap_alloc_zero(sizeof(FILEPROPERTIESW)*(sizeFilePropArray));
3749 3750
    if (!*lpafp)
        return FALSE;
3751

3752 3753
    do {
        if (indexFilePropArray+1 >= sizeFilePropArray)
3754
        {
3755 3756
            LPFILEPROPERTIESW tmpafp;
            
3757
            sizeFilePropArray *= 2;
3758
            tmpafp = heap_realloc_zero(*lpafp, sizeof(FILEPROPERTIESW)*sizeFilePropArray);
3759 3760 3761
            if (NULL == tmpafp)
            {
                bSuccess = FALSE;
3762
                break;
3763 3764 3765 3766
            }

            *lpafp = tmpafp;
        }
3767 3768
        indexFilePropArray++;
    } while (FTP_ParseNextFile(nSocket, lpszSearchFile, &(*lpafp)[indexFilePropArray]));
3769 3770 3771 3772 3773

    if (bSuccess && indexFilePropArray)
    {
        if (indexFilePropArray < sizeFilePropArray - 1)
        {
3774
            LPFILEPROPERTIESW tmpafp;
3775

3776
            tmpafp = heap_realloc(*lpafp, sizeof(FILEPROPERTIESW)*indexFilePropArray);
3777
            if (NULL != tmpafp)
3778 3779 3780 3781 3782 3783
                *lpafp = tmpafp;
        }
        *dwfp = indexFilePropArray;
    }
    else
    {
3784
        heap_free(*lpafp);
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802
        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
 *
 */
3803
static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp)
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
{
    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
 *
 */
3866
static DWORD FTP_SetResponseError(DWORD dwResponse)
3867 3868 3869 3870 3871
{
    DWORD dwCode = 0;

    switch(dwResponse)
    {
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
    case 425: /* Cannot open data connection. */
        dwCode = ERROR_INTERNET_CANNOT_CONNECT;
        break;

    case 426: /* Connection closed, transer aborted. */
        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;
3902
    }
3903

3904 3905 3906
    INTERNET_SetLastError(dwCode);
    return dwCode;
}