ftp.c 85.5 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 8 9
 *
 * Ulrich Czekalla
 * Noureddine Jemmali
10 11
 *
 * Copyright 2000 Andreas Mohr
12
 * Copyright 2002 Jaco Greeff
13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
26
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 28
 */

29
#include "config.h"
30
#include "wine/port.h"
31

32
#include <errno.h>
33
#include <stdarg.h>
34 35 36
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Gerald Pfeifer's avatar
Gerald Pfeifer committed
37
#include <sys/types.h>
38 39 40
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
41 42 43
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
44
#include <time.h>
45
#include <assert.h>
46

47
#include "windef.h"
48 49 50
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
51
#include "wininet.h"
52
#include "winnls.h"
53
#include "winerror.h"
54
#include "winreg.h"
55
#include "winternl.h"
56
#include "shlwapi.h"
57

58
#include "wine/debug.h"
59 60
#include "internet.h"

61
WINE_DEFAULT_DEBUG_CHANNEL(wininet);
62 63 64 65 66 67 68

#define DATA_PACKET_SIZE 	0x2000
#define szCRLF 			"\r\n"
#define MAX_BACKLOG 		5

typedef enum {
  /* FTP commands with arguments. */
69 70 71 72 73 74 75 76 77 78 79 80 81
  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,
82
  FTP_CMD_SIZE,
83 84 85 86 87

  /* FTP commands without arguments. */
  FTP_CMD_ABOR,
  FTP_CMD_LIST,
  FTP_CMD_NLST,
88
  FTP_CMD_PASV,
89
  FTP_CMD_PWD,
90
  FTP_CMD_QUIT,
91
} FTP_COMMAND;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

static const CHAR *szFtpCommands[] = {
  "ACCT",
  "CWD",
  "DELE",
  "MKD",
  "PASS",
  "PORT",
  "RETR",
  "RMD",
  "RNFR",
  "RNTO",
  "STOR",
  "TYPE",
  "USER",
107
  "SIZE",
108 109 110
  "ABOR",
  "LIST",
  "NLST",
111
  "PASV",
112 113 114 115 116
  "PWD",
  "QUIT",
};

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

119 120 121
static void FTP_CloseFileTransferHandle(LPWININETHANDLEHEADER hdr);
static void FTP_CloseSessionHandle(LPWININETHANDLEHEADER hdr);
static void FTP_CloseFindNextHandle(LPWININETHANDLEHEADER hdr);
122
static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
123
	INTERNET_STATUS_CALLBACK lpfnStatusCB, LPWININETHANDLEHEADER hdr, DWORD dwContext);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
static BOOL FTP_SendStore(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType);
static BOOL FTP_GetDataSocket(LPWININETFTPSESSIONW lpwfs, LPINT nDataSocket);
static BOOL FTP_SendData(LPWININETFTPSESSIONW lpwfs, INT nDataSocket, HANDLE hFile);
static INT FTP_ReceiveResponse(LPWININETFTPSESSIONW lpwfs, DWORD dwContext);
static DWORD FTP_SendRetrieve(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType);
static BOOL FTP_RetrieveFileData(LPWININETFTPSESSIONW lpwfs, INT nDataSocket, DWORD nBytes, HANDLE hFile);
static BOOL FTP_InitListenSocket(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_ConnectToHost(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_SendPassword(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_SendAccount(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_SendType(LPWININETFTPSESSIONW lpwfs, DWORD dwType);
static BOOL FTP_GetFileSize(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, DWORD *dwSize);
static BOOL FTP_SendPort(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_DoPassive(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_SendPortOrPasv(LPWININETFTPSESSIONW lpwfs);
static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp);
static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW fileprop);
static BOOL FTP_ParseDirectory(LPWININETFTPSESSIONW lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
142
	LPFILEPROPERTIESW *lpafp, LPDWORD dwfp);
143
static HINTERNET FTP_ReceiveFileList(LPWININETFTPSESSIONW lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
144
	LPWIN32_FIND_DATAW lpFindFileData, DWORD dwContext);
145
static DWORD FTP_SetResponseError(DWORD dwResponse);
146

147 148 149 150 151 152 153 154 155 156 157 158
/***********************************************************************
 *           FtpPutFileA (WININET.@)
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpPutFileA(HINTERNET hConnect, LPCSTR lpszLocalFile,
    LPCSTR lpszNewRemoteFile, DWORD dwFlags, DWORD dwContext)
159
{
160 161 162 163 164 165 166 167
    LPWSTR lpwzLocalFile;
    LPWSTR lpwzNewRemoteFile;
    BOOL ret;
    
    lpwzLocalFile = lpszLocalFile?WININET_strdup_AtoW(lpszLocalFile):NULL;
    lpwzNewRemoteFile = lpszNewRemoteFile?WININET_strdup_AtoW(lpszNewRemoteFile):NULL;
    ret = FtpPutFileW(hConnect, lpwzLocalFile, lpwzNewRemoteFile,
                      dwFlags, dwContext);
168 169
    HeapFree(GetProcessHeap(), 0, lpwzLocalFile);
    HeapFree(GetProcessHeap(), 0, lpwzNewRemoteFile);
170 171 172
    return ret;
}

173
/***********************************************************************
174
 *           FtpPutFileW (WININET.@)
175 176 177 178 179 180 181 182
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
183 184
BOOL WINAPI FtpPutFileW(HINTERNET hConnect, LPCWSTR lpszLocalFile,
    LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD dwContext)
185
{
186
    LPWININETFTPSESSIONW lpwfs;
187
    LPWININETAPPINFOW hIC = NULL;
188
    BOOL r = FALSE;
189

190
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hConnect );
191 192 193
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
194
        goto lend;
195 196
    }

197
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
198 199 200
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
201
        struct WORKREQ_FTPPUTFILEW *req = &workRequest.u.FtpPutFileW;
202

203
        workRequest.asyncall = FTPPUTFILEW;
204
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
205 206
        req->lpszLocalFile = WININET_strdupW(lpszLocalFile);
        req->lpszNewRemoteFile = WININET_strdupW(lpszNewRemoteFile);
207 208
	req->dwFlags = dwFlags;
	req->dwContext = dwContext;
209

210
	r = INTERNET_AsyncCall(&workRequest);
211 212 213
    }
    else
    {
214
        r = FTP_FtpPutFileW(lpwfs, lpszLocalFile,
215
	    lpszNewRemoteFile, dwFlags, dwContext);
216
    }
217 218 219 220 221 222

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

    return r;
223 224 225
}

/***********************************************************************
226
 *           FTP_FtpPutFileW (Internal)
227 228 229 230 231 232 233 234
 *
 * Uploads a file to the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
235
BOOL WINAPI FTP_FtpPutFileW(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszLocalFile,
236
    LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD dwContext)
237
{
238
    HANDLE hFile = NULL;
239
    BOOL bSuccess = FALSE;
240
    LPWININETAPPINFOW hIC = NULL;
241
    INT nResCode;
242

243 244 245 246 247 248 249
    TRACE(" lpszLocalFile(%s) lpszNewRemoteFile(%s)\n", debugstr_w(lpszLocalFile), debugstr_w(lpszNewRemoteFile));

    if (!lpszLocalFile || !lpszNewRemoteFile)
    {
        INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
250

251
    assert( WH_HFTPSESSION == lpwfs->hdr.htype);
252 253 254

    /* Clear any error information */
    INTERNET_SetLastError(0);
255
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
256 257

    /* Open file to be uploaded */
258
    if (INVALID_HANDLE_VALUE ==
259
        (hFile = CreateFileW(lpszLocalFile, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0)))
260 261 262 263 264
    {
        INTERNET_SetLastError(ERROR_FILE_NOT_FOUND);
        goto lend;
    }

265
    SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
266 267 268 269 270

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

271
        /* Get data socket to server */
272
        if (FTP_GetDataSocket(lpwfs, &nDataSocket))
273 274
        {
            FTP_SendData(lpwfs, nDataSocket, hFile);
275
            closesocket(nDataSocket);
276
	    nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
277 278 279 280 281 282 283
	    if (nResCode)
	    {
	        if (nResCode == 226)
		    bSuccess = TRUE;
		else
		    FTP_SetResponseError(nResCode);
	    }
284 285 286 287
        }
    }

lend:
288
    if (lpwfs->lstnSocket != -1)
289
        closesocket(lpwfs->lstnSocket);
290

291
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
292 293
    {
        INTERNET_ASYNC_RESULT iar;
294

295 296
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
297
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
298 299 300 301 302 303 304 305 306 307 308
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    if (hFile)
        CloseHandle(hFile);

    return bSuccess;
}


/***********************************************************************
309
 *           FtpSetCurrentDirectoryA (WININET.@)
310 311 312 313 314 315 316 317
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
318
BOOL WINAPI FtpSetCurrentDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
319
{
320 321 322 323 324
    LPWSTR lpwzDirectory;
    BOOL ret;
    
    lpwzDirectory = lpszDirectory?WININET_strdup_AtoW(lpszDirectory):NULL;
    ret = FtpSetCurrentDirectoryW(hConnect, lpwzDirectory);
325
    HeapFree(GetProcessHeap(), 0, lpwzDirectory);
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    return ret;
}


/***********************************************************************
 *           FtpSetCurrentDirectoryW (WININET.@)
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpSetCurrentDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
{
342
    LPWININETFTPSESSIONW lpwfs = NULL;
343
    LPWININETAPPINFOW hIC = NULL;
344
    BOOL r = FALSE;
345

346 347 348 349 350 351
    if (!lpszDirectory)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }

352
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hConnect );
353 354 355
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
356
        goto lend;
357 358
    }

359
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
360

361
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
362 363 364
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
365
        struct WORKREQ_FTPSETCURRENTDIRECTORYW *req;
366

367
        workRequest.asyncall = FTPSETCURRENTDIRECTORYW;
368
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
369 370
        req = &workRequest.u.FtpSetCurrentDirectoryW;
        req->lpszDirectory = WININET_strdupW(lpszDirectory);
371

372
	r = INTERNET_AsyncCall(&workRequest);
373 374 375
    }
    else
    {
376
        r = FTP_FtpSetCurrentDirectoryW(lpwfs, lpszDirectory);
377
    }
378 379 380 381 382 383

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

    return r;
384 385 386
}


387
/***********************************************************************
388
 *           FTP_FtpSetCurrentDirectoryW (Internal)
389 390 391 392 393 394 395 396
 *
 * Change the working directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
397
BOOL WINAPI FTP_FtpSetCurrentDirectoryW(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszDirectory)
398 399
{
    INT nResCode;
400
    LPWININETAPPINFOW hIC = NULL;
401 402
    DWORD bSuccess = FALSE;

403
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
404 405 406 407 408 409 410 411 412 413

    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
        return FALSE;
    }

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

414
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
415
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_CWD, lpszDirectory,
416
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
417 418
        goto lend;

419
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
420 421 422 423 424 425 426 427 428 429

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

lend:
430
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
431 432
    {
        INTERNET_ASYNC_RESULT iar;
433

434 435
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
436
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
437 438 439 440 441 442 443
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }
    return bSuccess;
}


/***********************************************************************
444
 *           FtpCreateDirectoryA (WININET.@)
445 446 447 448 449 450 451 452
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
453
BOOL WINAPI FtpCreateDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
454
{
455 456 457 458 459
    LPWSTR lpwzDirectory;
    BOOL ret;
    
    lpwzDirectory = lpszDirectory?WININET_strdup_AtoW(lpszDirectory):NULL;
    ret = FtpCreateDirectoryW(hConnect, lpwzDirectory);
460
    HeapFree(GetProcessHeap(), 0, lpwzDirectory);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    return ret;
}


/***********************************************************************
 *           FtpCreateDirectoryW (WININET.@)
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpCreateDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
{
    LPWININETFTPSESSIONW lpwfs;
478
    LPWININETAPPINFOW hIC = NULL;
479
    BOOL r = FALSE;
480

481
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hConnect );
482 483 484
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
485
        goto lend;
486 487
    }

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

494
        workRequest.asyncall = FTPCREATEDIRECTORYW;
495
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
496 497
        req = &workRequest.u.FtpCreateDirectoryW;
        req->lpszDirectory = WININET_strdupW(lpszDirectory);
498

499
	r = INTERNET_AsyncCall(&workRequest);
500 501 502
    }
    else
    {
503
        r = FTP_FtpCreateDirectoryW(lpwfs, lpszDirectory);
504
    }
505 506 507 508 509
lend:
    if( lpwfs )
        WININET_Release( &lpwfs->hdr );

    return r;
510 511 512
}


513
/***********************************************************************
514
 *           FTP_FtpCreateDirectoryW (Internal)
515 516 517 518 519 520 521 522
 *
 * Create new directory on the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
523
BOOL WINAPI FTP_FtpCreateDirectoryW(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszDirectory)
524 525 526
{
    INT nResCode;
    BOOL bSuccess = FALSE;
527
    LPWININETAPPINFOW hIC = NULL;
528

529
    TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
530

531 532 533 534 535 536 537 538 539 540 541 542
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
        return FALSE;
    }

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

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

543
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
544 545 546 547 548 549 550 551 552
    if (nResCode)
    {
        if (nResCode == 257)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
553
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
554
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
555 556
    {
        INTERNET_ASYNC_RESULT iar;
557

558 559
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
560
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
561 562 563 564 565 566 567
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

/***********************************************************************
568
 *           FtpFindFirstFileA (WININET.@)
569 570 571 572 573 574 575 576
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
577
HINTERNET WINAPI FtpFindFirstFileA(HINTERNET hConnect,
578 579
    LPCSTR lpszSearchFile, LPWIN32_FIND_DATAA lpFindFileData, DWORD dwFlags, DWORD dwContext)
{
580 581 582 583 584 585 586 587
    LPWSTR lpwzSearchFile;
    WIN32_FIND_DATAW wfd;
    LPWIN32_FIND_DATAW lpFindFileDataW;
    HINTERNET ret;
    
    lpwzSearchFile = lpszSearchFile?WININET_strdup_AtoW(lpszSearchFile):NULL;
    lpFindFileDataW = lpFindFileData?&wfd:NULL;
    ret = FtpFindFirstFileW(hConnect, lpwzSearchFile, lpFindFileDataW, dwFlags, dwContext);
588
    HeapFree(GetProcessHeap(), 0, lpwzSearchFile);
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    
    if(lpFindFileData) {
        WININET_find_data_WtoA(lpFindFileDataW, lpFindFileData);
    }
    return ret;
}


/***********************************************************************
 *           FtpFindFirstFileW (WININET.@)
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
HINTERNET WINAPI FtpFindFirstFileW(HINTERNET hConnect,
    LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD dwContext)
{
    LPWININETFTPSESSIONW lpwfs;
611
    LPWININETAPPINFOW hIC = NULL;
612
    HINTERNET r = NULL;
613

614
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hConnect );
615 616 617
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
618
        goto lend;
619 620
    }

621
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
622 623 624
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
625
        struct WORKREQ_FTPFINDFIRSTFILEW *req;
626

627
        workRequest.asyncall = FTPFINDFIRSTFILEW;
628
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
629
        req = &workRequest.u.FtpFindFirstFileW;
630
        req->lpszSearchFile = (lpszSearchFile == NULL) ? NULL : WININET_strdupW(lpszSearchFile);
631 632 633
	req->lpFindFileData = lpFindFileData;
	req->dwFlags = dwFlags;
	req->dwContext= dwContext;
634 635

	INTERNET_AsyncCall(&workRequest);
636
	r = NULL;
637 638 639
    }
    else
    {
640
        r = FTP_FtpFindFirstFileW(lpwfs, lpszSearchFile, lpFindFileData,
641
            dwFlags, dwContext);
642
    }
643 644 645 646 647
lend:
    if( lpwfs )
        WININET_Release( &lpwfs->hdr );

    return r;
648 649 650
}


651
/***********************************************************************
652
 *           FTP_FtpFindFirstFileW (Internal)
653 654 655 656 657 658 659 660
 *
 * Search the specified directory
 *
 * RETURNS
 *    HINTERNET on success
 *    NULL on failure
 *
 */
661
HINTERNET WINAPI FTP_FtpFindFirstFileW(LPWININETFTPSESSIONW lpwfs,
662
    LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD dwContext)
663 664
{
    INT nResCode;
665
    LPWININETAPPINFOW hIC = NULL;
666
    HINTERNET hFindNext = NULL;
667 668 669

    TRACE("\n");

670
    assert(WH_HFTPSESSION == lpwfs->hdr.htype);
671 672 673 674 675 676 677 678 679 680

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

    if (!FTP_InitListenSocket(lpwfs))
        goto lend;

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

681
    if (!FTP_SendPortOrPasv(lpwfs))
682 683
        goto lend;

684
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
685
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_LIST, NULL,
686
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
687 688
        goto lend;

689
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
690 691 692 693 694 695
    if (nResCode)
    {
        if (nResCode == 125 || nResCode == 150)
        {
            INT nDataSocket;

696 697
            /* Get data socket to server */
            if (FTP_GetDataSocket(lpwfs, &nDataSocket))
698
            {
699
                hFindNext = FTP_ReceiveFileList(lpwfs, nDataSocket, lpszSearchFile, lpFindFileData, dwContext);
700
                closesocket(nDataSocket);
701
                nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
702 703 704 705 706 707 708 709 710
                if (nResCode != 226 && nResCode != 250)
                    INTERNET_SetLastError(ERROR_NO_MORE_FILES);
            }
        }
        else
            FTP_SetResponseError(nResCode);
    }

lend:
711
    if (lpwfs->lstnSocket != -1)
712
        closesocket(lpwfs->lstnSocket);
713

714
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
715 716 717 718 719 720 721
    {
        INTERNET_ASYNC_RESULT iar;

        if (hFindNext)
	{
            iar.dwResult = (DWORD)hFindNext;
            iar.dwError = ERROR_SUCCESS;
722
            SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
723 724 725 726 727
                &iar, sizeof(INTERNET_ASYNC_RESULT));
	}

        iar.dwResult = (DWORD)hFindNext;
        iar.dwError = hFindNext ? ERROR_SUCCESS : INTERNET_GetLastError();
728
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
729 730 731
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

732
    return hFindNext;
733 734 735 736
}


/***********************************************************************
737
 *           FtpGetCurrentDirectoryA (WININET.@)
738 739 740 741 742 743 744 745
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
746
BOOL WINAPI FtpGetCurrentDirectoryA(HINTERNET hFtpSession, LPSTR lpszCurrentDirectory,
747
    LPDWORD lpdwCurrentDirectory)
748
{
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    WCHAR dir[MAX_PATH];
    DWORD len;
    BOOL ret;

    if(lpdwCurrentDirectory) len = *lpdwCurrentDirectory;
    ret = FtpGetCurrentDirectoryW(hFtpSession, lpszCurrentDirectory?dir:NULL, lpdwCurrentDirectory?&len:NULL);
    if(lpdwCurrentDirectory) {
        *lpdwCurrentDirectory = len;
        if(lpszCurrentDirectory)
            WideCharToMultiByte(CP_ACP, 0, dir, len, lpszCurrentDirectory, *lpdwCurrentDirectory, NULL, NULL);
    }
    return ret;
}


/***********************************************************************
 *           FtpGetCurrentDirectoryW (WININET.@)
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpGetCurrentDirectoryW(HINTERNET hFtpSession, LPWSTR lpszCurrentDirectory,
    LPDWORD lpdwCurrentDirectory)
{
    LPWININETFTPSESSIONW lpwfs;
778
    LPWININETAPPINFOW hIC = NULL;
779
    BOOL r = FALSE;
780 781 782

    TRACE("len(%ld)\n", *lpdwCurrentDirectory);

783
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hFtpSession );
784 785 786
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
787
        goto lend;
788 789
    }

790
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
791 792 793
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
794
        struct WORKREQ_FTPGETCURRENTDIRECTORYW *req;
795

796
        workRequest.asyncall =  FTPGETCURRENTDIRECTORYW;
797
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
798
        req = &workRequest.u.FtpGetCurrentDirectoryW;
799 800
	req->lpszDirectory = lpszCurrentDirectory;
	req->lpdwDirectory = lpdwCurrentDirectory;
801

802
	r = INTERNET_AsyncCall(&workRequest);
803 804 805
    }
    else
    {
806
        r = FTP_FtpGetCurrentDirectoryW(lpwfs, lpszCurrentDirectory,
807
            lpdwCurrentDirectory);
808
    }
809 810 811 812 813 814

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

    return r;
815 816 817 818 819 820 821 822 823 824 825 826 827
}


/***********************************************************************
 *           FTP_FtpGetCurrentDirectoryA (Internal)
 *
 * Retrieves the current directory
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
828
BOOL WINAPI FTP_FtpGetCurrentDirectoryW(LPWININETFTPSESSIONW lpwfs, LPWSTR lpszCurrentDirectory,
829 830 831
	LPDWORD lpdwCurrentDirectory)
{
    INT nResCode;
832
    LPWININETAPPINFOW hIC = NULL;
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    DWORD bSuccess = FALSE;

    TRACE("len(%ld)\n", *lpdwCurrentDirectory);

    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
        return FALSE;
    }

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

    ZeroMemory(lpszCurrentDirectory, *lpdwCurrentDirectory);

848
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
849
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PWD, NULL,
850
        lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
851 852
        goto lend;

853
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
854 855 856 857
    if (nResCode)
    {
        if (nResCode == 257) /* Extract directory name */
        {
858
            DWORD firstpos, lastpos, len;
859
	    LPWSTR lpszResponseBuffer = WININET_strdup_AtoW(INTERNET_GetResponseBuffer());
860 861 862 863 864 865 866 867 868 869 870 871 872

            for (firstpos = 0, lastpos = 0; lpszResponseBuffer[lastpos]; lastpos++)
            {
                if ('"' == lpszResponseBuffer[lastpos])
                {
                    if (!firstpos)
                        firstpos = lastpos;
                    else
                        break;
		}
            }

            len = lastpos - firstpos - 1;
873
            lstrcpynW(lpszCurrentDirectory, &lpszResponseBuffer[firstpos+1], *lpdwCurrentDirectory);
874
            HeapFree(GetProcessHeap(), 0, lpszResponseBuffer);
875 876 877 878 879 880 881 882
            *lpdwCurrentDirectory = len;
            bSuccess = TRUE;
        }
        else
            FTP_SetResponseError(nResCode);
    }

lend:
883
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
884 885
    {
        INTERNET_ASYNC_RESULT iar;
886

887 888
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
889
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
890 891 892 893 894 895 896
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return (DWORD) bSuccess;
}

/***********************************************************************
897
 *           FtpOpenFileA (WININET.@)
898 899 900 901 902 903 904 905
 *
 * Open a remote file for writing or reading
 *
 * RETURNS
 *    HINTERNET handle on success
 *    NULL on failure
 *
 */
906
HINTERNET WINAPI FtpOpenFileA(HINTERNET hFtpSession,
907 908
    LPCSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
    DWORD dwContext)
909
{
910 911 912 913 914
    LPWSTR lpwzFileName;
    HINTERNET ret;
    
    lpwzFileName = lpszFileName?WININET_strdup_AtoW(lpszFileName):NULL;
    ret = FtpOpenFileW(hFtpSession, lpwzFileName, fdwAccess, dwFlags, dwContext);
915
    HeapFree(GetProcessHeap(), 0, lpwzFileName);
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    return ret;
}


/***********************************************************************
 *           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 dwContext)
{
    LPWININETFTPSESSIONW lpwfs;
935
    LPWININETAPPINFOW hIC = NULL;
936
    HINTERNET r = NULL;
937 938 939
    
    TRACE("(%p,%s,0x%08lx,0x%08lx,0x%08lx)\n", hFtpSession,
        debugstr_w(lpszFileName), fdwAccess, dwFlags, dwContext);
940

941
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hFtpSession );
942 943 944
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
945
        goto lend;
946 947
    }

948 949
    if (lpwfs->download_in_progress != NULL) {
	INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
950
	goto lend;
951
    }
952
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
953 954 955
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
956
        struct WORKREQ_FTPOPENFILEW *req;
957

958
        workRequest.asyncall = FTPOPENFILEW;
959
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
960 961
        req = &workRequest.u.FtpOpenFileW;
	req->lpszFilename = WININET_strdupW(lpszFileName);
962 963 964
	req->dwAccess = fdwAccess;
	req->dwFlags = dwFlags;
	req->dwContext = dwContext;
965 966

	INTERNET_AsyncCall(&workRequest);
967
	r = NULL;
968 969 970
    }
    else
    {
971
	r = FTP_FtpOpenFileW(lpwfs, lpszFileName, fdwAccess, dwFlags, dwContext);
972
    }
973 974 975 976 977 978

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

    return r;
979 980 981
}


982
/***********************************************************************
983
 *           FTP_FtpOpenFileW (Internal)
984 985 986 987 988 989 990 991
 *
 * Open a remote file for writing or reading
 *
 * RETURNS
 *    HINTERNET handle on success
 *    NULL on failure
 *
 */
992
HINTERNET FTP_FtpOpenFileW(LPWININETFTPSESSIONW lpwfs,
993
	LPCWSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
994 995 996 997
	DWORD dwContext)
{
    INT nDataSocket;
    BOOL bSuccess = FALSE;
998
    LPWININETFILE lpwh = NULL;
999
    LPWININETAPPINFOW hIC = NULL;
1000
    HINTERNET handle = NULL;
1001 1002 1003

    TRACE("\n");

1004
    assert (WH_HFTPSESSION == lpwfs->hdr.htype);
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

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

1020 1021
    /* Get data socket to server */
    if (bSuccess && FTP_GetDataSocket(lpwfs, &nDataSocket))
1022
    {
1023 1024 1025 1026
        lpwh = HeapAlloc(GetProcessHeap(), 0, sizeof(WININETFILE));
        lpwh->hdr.htype = WH_HFILE;
        lpwh->hdr.dwFlags = dwFlags;
        lpwh->hdr.dwContext = dwContext;
1027 1028 1029
        lpwh->hdr.lpwhparent = WININET_AddRef( &lpwfs->hdr );
        lpwh->hdr.dwRefCount = 1;
        lpwh->hdr.destroy = FTP_CloseFileTransferHandle;
1030
        lpwh->hdr.lpfnStatusCB = lpwfs->hdr.lpfnStatusCB;
1031 1032
        lpwh->nDataSocket = nDataSocket;
	lpwh->session_deleted = FALSE;
1033
	
1034 1035 1036 1037
        handle = WININET_AllocHandle( &lpwh->hdr );
        if( !handle )
            goto lend;

1038
	/* Indicate that a download is currently in progress */
1039
	lpwfs->download_in_progress = lpwh;
1040 1041
    }

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

1045
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1046
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1047 1048
    {
        INTERNET_ASYNC_RESULT iar;
1049

1050
	if (lpwh)
1051
	{
1052
            iar.dwResult = (DWORD)handle;
1053
            iar.dwError = ERROR_SUCCESS;
1054
            SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
1055 1056
                &iar, sizeof(INTERNET_ASYNC_RESULT));
	}
1057

1058 1059
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1060
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1061 1062 1063
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

1064 1065 1066 1067
lend:
    if( lpwh )
        WININET_Release( &lpwh->hdr );

1068
    return handle;
1069 1070 1071 1072
}


/***********************************************************************
1073
 *           FtpGetFileA (WININET.@)
1074 1075 1076 1077 1078 1079 1080 1081
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1082
BOOL WINAPI FtpGetFileA(HINTERNET hInternet, LPCSTR lpszRemoteFile, LPCSTR lpszNewFile,
1083 1084
    BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
    DWORD dwContext)
1085
{
1086 1087 1088 1089 1090 1091 1092 1093
    LPWSTR lpwzRemoteFile;
    LPWSTR lpwzNewFile;
    BOOL ret;
    
    lpwzRemoteFile = lpszRemoteFile?WININET_strdup_AtoW(lpszRemoteFile):NULL;
    lpwzNewFile = lpszNewFile?WININET_strdup_AtoW(lpszNewFile):NULL;
    ret = FtpGetFileW(hInternet, lpwzRemoteFile, lpwzNewFile, fFailIfExists,
        dwLocalFlagsAttribute, dwInternetFlags, dwContext);
1094 1095
    HeapFree(GetProcessHeap(), 0, lpwzRemoteFile);
    HeapFree(GetProcessHeap(), 0, lpwzNewFile);
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    return ret;
}


/***********************************************************************
 *           FtpGetFileW (WININET.@)
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpGetFileW(HINTERNET hInternet, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
    BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
    DWORD dwContext)
{
    LPWININETFTPSESSIONW lpwfs;
1115
    LPWININETAPPINFOW hIC = NULL;
1116
    BOOL r = FALSE;
1117

1118
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hInternet );
1119 1120 1121
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1122
        goto lend;
1123 1124
    }

1125 1126
    if (lpwfs->download_in_progress != NULL) {
	INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1127
        goto lend;
1128 1129
    }
    
1130
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1131 1132 1133
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1134
        struct WORKREQ_FTPGETFILEW *req;
1135

1136
        workRequest.asyncall = FTPGETFILEW;
1137
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1138 1139 1140
        req = &workRequest.u.FtpGetFileW;
        req->lpszRemoteFile = WININET_strdupW(lpszRemoteFile);
        req->lpszNewFile = WININET_strdupW(lpszNewFile);
1141 1142 1143 1144
	req->dwLocalFlagsAttribute = dwLocalFlagsAttribute;
	req->fFailIfExists = fFailIfExists;
	req->dwFlags = dwInternetFlags;
	req->dwContext = dwContext;
1145

1146
	r = INTERNET_AsyncCall(&workRequest);
1147 1148 1149
    }
    else
    {
1150
        r = FTP_FtpGetFileW(lpwfs, lpszRemoteFile, lpszNewFile,
1151 1152
           fFailIfExists, dwLocalFlagsAttribute, dwInternetFlags, dwContext);
    }
1153 1154 1155 1156 1157 1158

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

    return r;
1159 1160 1161
}


1162
/***********************************************************************
1163
 *           FTP_FtpGetFileW (Internal)
1164 1165 1166 1167 1168 1169 1170 1171
 *
 * Retrieve file from the FTP server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1172
BOOL WINAPI FTP_FtpGetFileW(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
1173 1174 1175 1176 1177 1178
	BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
	DWORD dwContext)
{
    DWORD nBytes;
    BOOL bSuccess = FALSE;
    HANDLE hFile;
1179
    LPWININETAPPINFOW hIC = NULL;
1180

1181
    TRACE("lpszRemoteFile(%s) lpszNewFile(%s)\n", debugstr_w(lpszRemoteFile), debugstr_w(lpszNewFile));
1182

1183
    assert (WH_HFTPSESSION == lpwfs->hdr.htype);
1184 1185 1186 1187 1188

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

    /* Ensure we can write to lpszNewfile by opening it */
1189
    hFile = CreateFileW(lpszNewFile, GENERIC_WRITE, 0, 0, fFailIfExists ?
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        CREATE_NEW : CREATE_ALWAYS, dwLocalFlagsAttribute, 0);
    if (INVALID_HANDLE_VALUE == hFile)
        goto lend;

    /* Set up socket to retrieve data */
    nBytes = FTP_SendRetrieve(lpwfs, lpszRemoteFile, dwInternetFlags);

    if (nBytes > 0)
    {
        INT nDataSocket;

1201 1202
        /* Get data socket to server */
        if (FTP_GetDataSocket(lpwfs, &nDataSocket))
1203 1204 1205 1206 1207
        {
            INT nResCode;

            /* Receive data */
            FTP_RetrieveFileData(lpwfs, nDataSocket, nBytes, hFile);
1208
            nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
1209 1210 1211 1212 1213 1214 1215
            if (nResCode)
            {
                if (nResCode == 226)
                    bSuccess = TRUE;
		else
                    FTP_SetResponseError(nResCode);
            }
1216
	    closesocket(nDataSocket);
1217 1218 1219 1220
        }
    }

lend:
1221
    if (lpwfs->lstnSocket != -1)
1222
        closesocket(lpwfs->lstnSocket);
1223

1224 1225 1226
    if (hFile)
        CloseHandle(hFile);

1227
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1228
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1229 1230
    {
        INTERNET_ASYNC_RESULT iar;
1231

1232 1233
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1234
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1235 1236 1237 1238 1239 1240
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

1241 1242 1243
/***********************************************************************
 *           FtpGetFileSize  (WININET.@)
 */
1244 1245 1246 1247 1248 1249 1250 1251 1252
DWORD WINAPI FtpGetFileSize( HINTERNET hFile, LPDWORD lpdwFileSizeHigh )
{
    FIXME("(%p, %p)\n", hFile, lpdwFileSizeHigh);

    if (lpdwFileSizeHigh)
        *lpdwFileSizeHigh = 0;

    return 0;
}
1253 1254

/***********************************************************************
1255
 *           FtpDeleteFileA  (WININET.@)
1256 1257 1258 1259 1260 1261 1262 1263
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1264
BOOL WINAPI FtpDeleteFileA(HINTERNET hFtpSession, LPCSTR lpszFileName)
1265
{
1266 1267 1268 1269 1270
    LPWSTR lpwzFileName;
    BOOL ret;
    
    lpwzFileName = lpszFileName?WININET_strdup_AtoW(lpszFileName):NULL;
    ret = FtpDeleteFileW(hFtpSession, lpwzFileName);
1271
    HeapFree(GetProcessHeap(), 0, lpwzFileName);
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    return ret;
}

/***********************************************************************
 *           FtpDeleteFileW  (WININET.@)
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpDeleteFileW(HINTERNET hFtpSession, LPCWSTR lpszFileName)
{
    LPWININETFTPSESSIONW lpwfs;
1288
    LPWININETAPPINFOW hIC = NULL;
1289
    BOOL r = FALSE;
1290

1291
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hFtpSession );
1292 1293 1294
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1295
        goto lend;
1296 1297
    }

1298
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1299 1300 1301
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1302
        struct WORKREQ_FTPDELETEFILEW *req;
1303

1304
        workRequest.asyncall = FTPDELETEFILEW;
1305
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1306 1307
        req = &workRequest.u.FtpDeleteFileW;
        req->lpszFilename = WININET_strdupW(lpszFileName);
1308

1309
	r = INTERNET_AsyncCall(&workRequest);
1310 1311 1312
    }
    else
    {
1313
        r = FTP_FtpDeleteFileW(hFtpSession, lpszFileName);
1314
    }
1315 1316 1317 1318 1319 1320

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

    return r;
1321 1322 1323
}

/***********************************************************************
1324
 *           FTP_FtpDeleteFileW  (Internal)
1325 1326 1327 1328 1329 1330 1331 1332
 *
 * Delete a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1333
BOOL FTP_FtpDeleteFileW(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszFileName)
1334 1335 1336
{
    INT nResCode;
    BOOL bSuccess = FALSE;
1337
    LPWININETAPPINFOW hIC = NULL;
1338

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

1341
    assert (WH_HFTPSESSION == lpwfs->hdr.htype);
1342 1343 1344 1345 1346 1347 1348

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

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

1349
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1350 1351 1352 1353 1354 1355 1356 1357
    if (nResCode)
    {
        if (nResCode == 250)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }
lend:
1358
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1359
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1360 1361
    {
        INTERNET_ASYNC_RESULT iar;
1362

1363 1364
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1365
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1366 1367 1368 1369 1370 1371 1372 1373
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}


/***********************************************************************
1374
 *           FtpRemoveDirectoryA  (WININET.@)
1375 1376 1377 1378 1379 1380 1381 1382
 *
 * Remove a directory on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1383
BOOL WINAPI FtpRemoveDirectoryA(HINTERNET hFtpSession, LPCSTR lpszDirectory)
1384
{
1385 1386 1387 1388 1389
    LPWSTR lpwzDirectory;
    BOOL ret;
    
    lpwzDirectory = lpszDirectory?WININET_strdup_AtoW(lpszDirectory):NULL;
    ret = FtpRemoveDirectoryW(hFtpSession, lpwzDirectory);
1390
    HeapFree(GetProcessHeap(), 0, lpwzDirectory);
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    return ret;
}

/***********************************************************************
 *           FtpRemoveDirectoryW  (WININET.@)
 *
 * Remove a directory on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpRemoveDirectoryW(HINTERNET hFtpSession, LPCWSTR lpszDirectory)
{
    LPWININETFTPSESSIONW lpwfs;
1407
    LPWININETAPPINFOW hIC = NULL;
1408
    BOOL r = FALSE;
1409

1410
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hFtpSession );
1411 1412 1413
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1414
        goto lend;
1415 1416
    }

1417
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1418 1419 1420
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1421
        struct WORKREQ_FTPREMOVEDIRECTORYW *req;
1422

1423
        workRequest.asyncall = FTPREMOVEDIRECTORYW;
1424
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1425 1426
        req = &workRequest.u.FtpRemoveDirectoryW;
        req->lpszDirectory = WININET_strdupW(lpszDirectory);
1427

1428
	r = INTERNET_AsyncCall(&workRequest);
1429 1430 1431
    }
    else
    {
1432
        r = FTP_FtpRemoveDirectoryW(lpwfs, lpszDirectory);
1433
    }
1434 1435 1436 1437 1438 1439

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

    return r;
1440 1441 1442
}

/***********************************************************************
1443
 *           FTP_FtpRemoveDirectoryW  (Internal)
1444 1445 1446 1447 1448 1449 1450 1451
 *
 * Remove a directory on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1452
BOOL FTP_FtpRemoveDirectoryW(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszDirectory)
1453 1454 1455
{
    INT nResCode;
    BOOL bSuccess = FALSE;
1456
    LPWININETAPPINFOW hIC = NULL;
1457 1458

    TRACE("\n");
1459

1460
    assert (WH_HFTPSESSION == lpwfs->hdr.htype);
1461 1462 1463 1464 1465 1466 1467

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

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

1468
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1469 1470 1471 1472 1473 1474 1475 1476 1477
    if (nResCode)
    {
        if (nResCode == 250)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
1478
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1479
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1480 1481
    {
        INTERNET_ASYNC_RESULT iar;
1482

1483 1484
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1485
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1486 1487 1488 1489 1490 1491 1492 1493
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}


/***********************************************************************
1494
 *           FtpRenameFileA  (WININET.@)
1495 1496 1497 1498 1499 1500 1501 1502
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1503
BOOL WINAPI FtpRenameFileA(HINTERNET hFtpSession, LPCSTR lpszSrc, LPCSTR lpszDest)
1504
{
1505 1506 1507 1508 1509 1510 1511
    LPWSTR lpwzSrc;
    LPWSTR lpwzDest;
    BOOL ret;
    
    lpwzSrc = lpszSrc?WININET_strdup_AtoW(lpszSrc):NULL;
    lpwzDest = lpszDest?WININET_strdup_AtoW(lpszDest):NULL;
    ret = FtpRenameFileW(hFtpSession, lpwzSrc, lpwzDest);
1512 1513
    HeapFree(GetProcessHeap(), 0, lpwzSrc);
    HeapFree(GetProcessHeap(), 0, lpwzDest);
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    return ret;
}

/***********************************************************************
 *           FtpRenameFileW  (WININET.@)
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
BOOL WINAPI FtpRenameFileW(HINTERNET hFtpSession, LPCWSTR lpszSrc, LPCWSTR lpszDest)
{
    LPWININETFTPSESSIONW lpwfs;
1530
    LPWININETAPPINFOW hIC = NULL;
1531
    BOOL r = FALSE;
1532

1533
    lpwfs = (LPWININETFTPSESSIONW) WININET_GetObject( hFtpSession );
1534 1535 1536
    if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
    {
        INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1537
        goto lend;
1538 1539
    }

1540
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1541 1542 1543
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
1544
        struct WORKREQ_FTPRENAMEFILEW *req;
1545

1546
        workRequest.asyncall = FTPRENAMEFILEW;
1547
	workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1548 1549 1550
        req = &workRequest.u.FtpRenameFileW;
        req->lpszSrcFile = WININET_strdupW(lpszSrc);
        req->lpszDestFile = WININET_strdupW(lpszDest);
1551

1552
	r = INTERNET_AsyncCall(&workRequest);
1553 1554 1555
    }
    else
    {
1556
        r = FTP_FtpRenameFileW(hFtpSession, lpszSrc, lpszDest);
1557
    }
1558 1559 1560 1561 1562 1563

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

    return r;
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
}

/***********************************************************************
 *           FTP_FtpRenameFileA  (Internal)
 *
 * Rename a file on the ftp server
 *
 * RETURNS
 *    TRUE on success
 *    FALSE on failure
 *
 */
1576 1577
BOOL FTP_FtpRenameFileW( LPWININETFTPSESSIONW lpwfs,
                         LPCWSTR lpszSrc, LPCWSTR lpszDest)
1578 1579 1580
{
    INT nResCode;
    BOOL bSuccess = FALSE;
1581
    LPWININETAPPINFOW hIC = NULL;
1582 1583

    TRACE("\n");
1584

1585
    assert (WH_HFTPSESSION == lpwfs->hdr.htype);
1586 1587 1588 1589 1590 1591 1592

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

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

1593
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1594 1595 1596 1597 1598
    if (nResCode == 350)
    {
        if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNTO, lpszDest, 0, 0, 0))
            goto lend;

1599
        nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1600 1601 1602 1603 1604 1605 1606 1607
    }

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

lend:
1608
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1609
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1610 1611
    {
        INTERNET_ASYNC_RESULT iar;
1612

1613 1614
        iar.dwResult = (DWORD)bSuccess;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1615
        SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1616 1617 1618 1619 1620 1621
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

    return bSuccess;
}

1622 1623 1624
/***********************************************************************
 *           FtpCommandA  (WININET.@)
 */
1625 1626 1627 1628 1629 1630 1631 1632 1633
BOOL WINAPI FtpCommandA( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
                         LPCSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
{
    FIXME("%p %d 0x%08lx %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
          debugstr_a(lpszCommand), dwContext, phFtpCommand);

    return TRUE;
}

1634 1635 1636
/***********************************************************************
 *           FtpCommandW  (WININET.@)
 */
1637 1638 1639 1640 1641 1642 1643 1644
BOOL WINAPI FtpCommandW( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
                         LPCWSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
{
    FIXME("%p %d 0x%08lx %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
          debugstr_w(lpszCommand), dwContext, phFtpCommand);

    return TRUE;
}
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656

/***********************************************************************
 *           FTP_Connect (internal)
 *
 * Connect to a ftp server
 *
 * RETURNS
 *   HINTERNET a session handle on success
 *   NULL on failure
 *
 */

1657
HINTERNET FTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
1658
	INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
1659 1660
	LPCWSTR lpszPassword, DWORD dwFlags, DWORD dwContext,
	DWORD dwInternalFlags)
1661
{
1662 1663
    static const WCHAR szDefaultUsername[] = {'a','n','o','n','y','m','o','u','s','\0'};
    static const WCHAR szDefaultPassword[] = {'u','s','e','r','@','s','e','r','v','e','r','\0'};
1664
    struct sockaddr_in socketAddr;
1665 1666
    INT nsocket = -1;
    UINT sock_namelen;
1667
    BOOL bSuccess = FALSE;
1668
    LPWININETFTPSESSIONW lpwfs = NULL;
1669
    HINTERNET handle = NULL;
1670

1671 1672
    TRACE("%p  Server(%s) Port(%d) User(%s) Paswd(%s)\n",
	    hIC, debugstr_w(lpszServerName),
1673
	    nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword));
1674

1675
    assert( hIC->hdr.htype == WH_HINIT );
1676 1677 1678

    if (NULL == lpszUserName && NULL != lpszPassword)
    {
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
	INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
        goto lerror;
    }
    
    lpwfs = HeapAlloc(GetProcessHeap(), 0, sizeof(WININETFTPSESSIONW));
    if (NULL == lpwfs)
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        goto lerror;
    }

1690 1691 1692
    if (nServerPort == INTERNET_INVALID_PORT_NUMBER)
	nServerPort = INTERNET_DEFAULT_FTP_PORT;

1693
    lpwfs->hdr.htype = WH_HFTPSESSION;
1694
    lpwfs->hdr.lpwhparent = WININET_AddRef( &hIC->hdr );
1695 1696 1697
    lpwfs->hdr.dwFlags = dwFlags;
    lpwfs->hdr.dwContext = dwContext;
    lpwfs->hdr.dwInternalFlags = dwInternalFlags;
1698 1699
    lpwfs->hdr.dwRefCount = 1;
    lpwfs->hdr.destroy = FTP_CloseSessionHandle;
1700
    lpwfs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
1701
    lpwfs->download_in_progress = NULL;
1702 1703 1704 1705 1706 1707 1708 1709 1710

    handle = WININET_AllocHandle( &lpwfs->hdr );
    if( !handle )
    {
        ERR("Failed to alloc handle\n");
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        goto lerror;
    }

1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
    if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
        if(strchrW(hIC->lpszProxy, ' '))
            FIXME("Several proxies not implemented.\n");
        if(hIC->lpszProxyBypass)
            FIXME("Proxy bypass is ignored.\n");
    }
    if ( !lpszUserName) {
        lpwfs->lpszUserName = WININET_strdupW(szDefaultUsername);
        lpwfs->lpszPassword = WININET_strdupW(szDefaultPassword);
    }
    else {
        lpwfs->lpszUserName = WININET_strdupW(lpszUserName);
        lpwfs->lpszPassword = WININET_strdupW(lpszPassword);
    }
    
    /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
1727
    if (!(lpwfs->hdr.dwInternalFlags & INET_OPENURL))
1728 1729 1730 1731 1732 1733
    {
        INTERNET_ASYNC_RESULT iar;

        iar.dwResult = (DWORD)handle;
        iar.dwError = ERROR_SUCCESS;

1734
        SendAsyncCallback(&hIC->hdr, dwContext,
1735 1736 1737 1738
                      INTERNET_STATUS_HANDLE_CREATED, &iar,
                      sizeof(INTERNET_ASYNC_RESULT));
    }
        
1739
    SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_RESOLVING_NAME,
1740
        (LPWSTR) lpszServerName, strlenW(lpszServerName));
1741

1742
    if (!GetAddress(lpszServerName, nServerPort, &socketAddr))
1743 1744 1745 1746 1747
    {
	INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
        goto lerror;
    }

1748
    SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_NAME_RESOLVED,
1749
        (LPWSTR) lpszServerName, strlenW(lpszServerName));
1750

1751 1752
    nsocket = socket(AF_INET,SOCK_STREAM,0);
    if (nsocket == -1)
1753 1754 1755 1756 1757
    {
	INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
        goto lerror;
    }

1758
    SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTING_TO_SERVER,
1759
        &socketAddr, sizeof(struct sockaddr_in));
1760 1761 1762

    if (connect(nsocket, (struct sockaddr *)&socketAddr, sizeof(socketAddr)) < 0)
    {
1763
	ERR("Unable to connect (%s)\n", strerror(errno));
1764 1765 1766 1767
	INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
    }
    else
    {
1768
        TRACE("Connected to server\n");
1769
	lpwfs->sndSocket = nsocket;
1770
        SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTED_TO_SERVER,
1771
            &socketAddr, sizeof(struct sockaddr_in));
1772

1773
	sock_namelen = sizeof(lpwfs->socketAddress);
1774
	getsockname(nsocket, (struct sockaddr *) &lpwfs->socketAddress, &sock_namelen);
1775 1776 1777 1778 1779 1780 1781 1782 1783

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

lerror:
1784
    if (!bSuccess && nsocket == -1)
1785
        closesocket(nsocket);
1786 1787 1788 1789

    if (!bSuccess && lpwfs)
    {
        HeapFree(GetProcessHeap(), 0, lpwfs);
1790
        WININET_FreeHandle( handle );
1791 1792 1793
        lpwfs = NULL;
    }

1794
    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1795 1796
    {
        INTERNET_ASYNC_RESULT iar;
1797

1798 1799
        iar.dwResult = (DWORD)lpwfs;
        iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1800
        SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1801 1802 1803
            &iar, sizeof(INTERNET_ASYNC_RESULT));
    }

1804
    return handle;
1805 1806 1807 1808
}


/***********************************************************************
1809
 *           FTP_ConnectToHost (internal)
1810 1811 1812 1813 1814 1815 1816 1817
 *
 * Connect to a ftp server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
1818
static BOOL FTP_ConnectToHost(LPWININETFTPSESSIONW lpwfs)
1819 1820 1821 1822 1823
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
1824
    FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1825 1826 1827 1828

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

1829
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
    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;
}


/***********************************************************************
1852
 *           FTP_SendCommandA (internal)
1853 1854 1855 1856 1857 1858 1859 1860
 *
 * Send command to server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
Mike McCormack's avatar
Mike McCormack committed
1861
static BOOL FTP_SendCommandA(INT nSocket, FTP_COMMAND ftpCmd, LPCSTR lpszParam,
1862
	INTERNET_STATUS_CALLBACK lpfnStatusCB, LPWININETHANDLEHEADER hdr, DWORD dwContext)
1863 1864 1865 1866
{
    	DWORD len;
	CHAR *buf;
	DWORD nBytesSent = 0;
1867
	int nRC = 0;
1868
	DWORD dwParamLen;
1869 1870 1871 1872

	TRACE("%d: (%s) %d\n", ftpCmd, lpszParam, nSocket);

	if (lpfnStatusCB)
1873 1874 1875 1876 1877 1878 1879 1880
        {
             HINTERNET hHandle = WININET_FindHandle( hdr );
	     if( hHandle )
             {
                 lpfnStatusCB(hHandle, dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
                 WININET_Release( hdr );
             }
        }
1881

1882 1883
	dwParamLen = lpszParam?strlen(lpszParam)+1:0;
	len = dwParamLen + strlen(szFtpCommands[ftpCmd]) + strlen(szCRLF);
1884 1885 1886 1887 1888
	if (NULL == (buf = HeapAlloc(GetProcessHeap(), 0, len+1)))
	{
	    INTERNET_SetLastError(ERROR_OUTOFMEMORY);
	    return FALSE;
	}
1889 1890
	sprintf(buf, "%s%s%s%s", szFtpCommands[ftpCmd], dwParamLen ? " " : "",
		dwParamLen ? lpszParam : "", szCRLF);
1891 1892

	TRACE("Sending (%s) len(%ld)\n", buf, len);
1893
	while((nBytesSent < len) && (nRC != -1))
1894 1895 1896 1897 1898 1899 1900 1901
	{
		nRC = send(nSocket, buf+nBytesSent, len - nBytesSent, 0);
		nBytesSent += nRC;
	}

	HeapFree(GetProcessHeap(), 0, (LPVOID)buf);

	if (lpfnStatusCB)
1902 1903 1904 1905 1906 1907 1908 1909 1910
        {
             HINTERNET hHandle = WININET_FindHandle( hdr );
	     if( hHandle )
             {
                 lpfnStatusCB(hHandle, dwContext, INTERNET_STATUS_REQUEST_SENT,
                              &nBytesSent, sizeof(DWORD));
                 WININET_Release( hdr );
             }
        }
1911 1912

	TRACE("Sent %ld bytes\n", nBytesSent);
1913
	return (nRC != -1);
1914 1915
}

1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
/***********************************************************************
 *           FTP_SendCommand (internal)
 *
 * Send command to server
 *
 * RETURNS
 *   TRUE on success
 *   NULL on failure
 *
 */
1926
static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
1927
	INTERNET_STATUS_CALLBACK lpfnStatusCB, LPWININETHANDLEHEADER hdr, DWORD dwContext)
1928 1929 1930
{
    BOOL ret;
    LPSTR lpszParamA = lpszParam?WININET_strdup_WtoA(lpszParam):NULL;
1931
    ret = FTP_SendCommandA(nSocket, ftpCmd, lpszParamA, lpfnStatusCB, hdr, dwContext);
1932 1933 1934
    HeapFree(GetProcessHeap(), 0, lpszParamA);
    return ret;
}
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945

/***********************************************************************
 *           FTP_ReceiveResponse (internal)
 *
 * Receive response from server
 *
 * RETURNS
 *   Reply code on success
 *   0 on failure
 *
 */
1946
INT FTP_ReceiveResponse(LPWININETFTPSESSIONW lpwfs, DWORD dwContext)
1947
{
1948
    LPSTR lpszResponse = INTERNET_GetResponseBuffer();
1949 1950
    DWORD nRecv;
    INT rc = 0;
1951 1952
    char firstprefix[5];
    BOOL multiline = FALSE;
1953
    LPWININETAPPINFOW hIC = NULL;
1954

1955
    TRACE("socket(%d)\n", lpwfs->sndSocket);
1956

1957
    hIC = (LPWININETAPPINFOW) lpwfs->hdr.lpwhparent;
1958
    SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1959 1960 1961

    while(1)
    {
1962
	if (!INTERNET_GetNextLine(lpwfs->sndSocket, &nRecv))
1963 1964
	    goto lerror;

1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
        if (nRecv >= 3)
	{
	    if(!multiline)
	    {
	        if(lpszResponse[3] != '-')
		    break;
		else
		{  /* Start of multiline repsonse.  Loop until we get "nnn " */
		    multiline = TRUE;
		    memcpy(firstprefix, lpszResponse, 3);
		    firstprefix[3] = ' ';
		    firstprefix[4] = '\0';
		}
	    }
	    else
	    {
	        if(!memcmp(firstprefix, lpszResponse, 4))
		    break;
	    }
	}
1985
    }
1986

1987 1988 1989 1990
    if (nRecv >= 3)
    {
        rc = atoi(lpszResponse);

1991
        SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
		    &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
 *
 */
2011
static BOOL FTP_SendPassword(LPWININETFTPSESSIONW lpwfs)
2012 2013 2014 2015 2016 2017 2018
{
    INT nResCode;
    BOOL bSuccess = FALSE;

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

2020
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
    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)
 *
2044
 *
2045 2046 2047 2048 2049 2050
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2051
static BOOL FTP_SendAccount(LPWININETFTPSESSIONW lpwfs)
2052 2053 2054 2055 2056
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");
2057
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_ACCT, szNoAccount, 0, 0, 0))
2058 2059
        goto lend;

2060
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
    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
 *
 */
2081
static BOOL FTP_SendStore(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
{
    INT nResCode;
    BOOL bSuccess = FALSE;

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

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

2093
    if (!FTP_SendPortOrPasv(lpwfs))
2094 2095 2096 2097
        goto lend;

    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_STOR, lpszRemoteFile, 0, 0, 0))
	    goto lend;
2098
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2099 2100 2101 2102 2103 2104 2105 2106 2107
    if (nResCode)
    {
        if (nResCode == 150)
            bSuccess = TRUE;
	else
            FTP_SetResponseError(nResCode);
    }

lend:
2108
    if (!bSuccess && lpwfs->lstnSocket != -1)
2109
    {
2110
        closesocket(lpwfs->lstnSocket);
2111
        lpwfs->lstnSocket = -1;
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
    }

    return bSuccess;
}


/***********************************************************************
 *           FTP_InitListenSocket (internal)
 *
 * Create a socket to listen for server response
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2128
static BOOL FTP_InitListenSocket(LPWININETFTPSESSIONW lpwfs)
2129 2130
{
    BOOL bSuccess = FALSE;
2131
    size_t namelen = sizeof(struct sockaddr_in);
2132 2133 2134 2135

    TRACE("\n");

    lpwfs->lstnSocket = socket(PF_INET, SOCK_STREAM, 0);
2136
    if (lpwfs->lstnSocket == -1)
2137 2138 2139 2140 2141
    {
        TRACE("Unable to create listening socket\n");
            goto lend;
    }

2142 2143 2144 2145
    /* 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 */
2146
    lpwfs->lstnSocketAddress.sin_port = htons((u_short) 0);
2147

2148
    if (bind(lpwfs->lstnSocket,(struct sockaddr *) &lpwfs->lstnSocketAddress, sizeof(struct sockaddr_in)) == -1)
2149 2150 2151 2152 2153
    {
        TRACE("Unable to bind socket\n");
        goto lend;
    }

2154
    if (listen(lpwfs->lstnSocket, MAX_BACKLOG) == -1)
2155 2156 2157 2158 2159
    {
        TRACE("listen failed\n");
        goto lend;
    }

2160
    if (getsockname(lpwfs->lstnSocket, (struct sockaddr *) &lpwfs->lstnSocketAddress, &namelen) != -1)
2161 2162 2163
        bSuccess = TRUE;

lend:
2164
    if (!bSuccess && lpwfs->lstnSocket == -1)
2165
    {
2166
        closesocket(lpwfs->lstnSocket);
2167
        lpwfs->lstnSocket = -1;
2168 2169 2170 2171 2172 2173 2174 2175 2176
    }

    return bSuccess;
}


/***********************************************************************
 *           FTP_SendType (internal)
 *
2177
 * Tell server type of data being transferred
2178 2179 2180 2181 2182
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
2183 2184 2185
 * 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.
2186
 */
2187
static BOOL FTP_SendType(LPWININETFTPSESSIONW lpwfs, DWORD dwType)
2188 2189
{
    INT nResCode;
2190
    WCHAR type[] = { 'I','\0' };
2191 2192 2193 2194
    BOOL bSuccess = FALSE;

    TRACE("\n");
    if (dwType & INTERNET_FLAG_TRANSFER_ASCII)
2195
        type[0] = 'A';
2196 2197 2198 2199

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

2200
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext)/100;
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
    if (nResCode)
    {
        if (nResCode == 2)
            bSuccess = TRUE;
	else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}

2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
/***********************************************************************
 *           FTP_GetFileSize (internal)
 *
 * Retrieves from the server the size of the given file
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2223
static BOOL FTP_GetFileSize(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, DWORD *dwSize)
2224 2225 2226 2227 2228 2229 2230 2231 2232
{
    INT nResCode;
    BOOL bSuccess = FALSE;

    TRACE("\n");

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

2233
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
    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;
}

2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265

/***********************************************************************
 *           FTP_SendPort (internal)
 *
 * Tell server which port to use
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2266
static BOOL FTP_SendPort(LPWININETFTPSESSIONW lpwfs)
2267
{
2268
    static const WCHAR szIPFormat[] = {'%','d',',','%','d',',','%','d',',','%','d',',','%','d',',','%','d','\0'};
2269
    INT nResCode;
2270
    WCHAR szIPAddress[64];
2271 2272 2273
    BOOL bSuccess = FALSE;
    TRACE("\n");

2274
    sprintfW(szIPAddress, szIPFormat,
2275 2276 2277 2278
	 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,
2279 2280 2281 2282 2283 2284
        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;

2285
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
    if (nResCode)
    {
        if (nResCode == 200)
            bSuccess = TRUE;
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}


/***********************************************************************
2300 2301 2302 2303
 *           FTP_DoPassive (internal)
 *
 * Tell server that we want to do passive transfers
 * and connect data socket
2304
 *
2305 2306 2307 2308 2309
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2310
static BOOL FTP_DoPassive(LPWININETFTPSESSIONW lpwfs)
2311 2312 2313 2314 2315 2316 2317 2318
{
    INT nResCode;
    BOOL bSuccess = FALSE;

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

2319
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2320 2321 2322 2323 2324 2325 2326 2327 2328
    if (nResCode)
    {
        if (nResCode == 227)
	{
	    LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
	    LPSTR p;
	    int f[6];
	    int i;
	    char *pAddr, *pPort;
2329
	    INT nsocket = -1;
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
	    struct sockaddr_in dataSocketAddress;

	    p = lpszResponseBuffer+4; /* skip status code */

	    /* do a very strict check; we can improve that later. */

	    if (strncmp(p, "Entering Passive Mode", 21))
	    {
		ERR("unknown response '%.*s', aborting\n", 21, p);
		goto lend;
	    }
	    p += 21; /* skip string */
	    if ((*p++ != ' ') || (*p++ != '('))
	    {
		ERR("unknown response format, aborting\n");
		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];

2367 2368
            nsocket = socket(AF_INET,SOCK_STREAM,0);
            if (nsocket == -1)
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
                goto lend;

	    if (connect(nsocket, (struct sockaddr *)&dataSocketAddress, sizeof(dataSocketAddress)))
            {
	        ERR("can't connect passive FTP data port.\n");
	        goto lend;
            }
	    lpwfs->pasvSocket = nsocket;
            bSuccess = TRUE;
	}
        else
            FTP_SetResponseError(nResCode);
    }

lend:
    return bSuccess;
}


2388
static BOOL FTP_SendPortOrPasv(LPWININETFTPSESSIONW lpwfs)
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
{
    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.
2410
 *
2411 2412 2413 2414 2415 2416
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2417
static BOOL FTP_GetDataSocket(LPWININETFTPSESSIONW lpwfs, LPINT nDataSocket)
2418 2419
{
    struct sockaddr_in saddr;
2420
    size_t addrlen = sizeof(struct sockaddr);
2421 2422

    TRACE("\n");
2423 2424 2425 2426 2427 2428 2429
    if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
    {
	*nDataSocket = lpwfs->pasvSocket;
    }
    else
    {
        *nDataSocket = accept(lpwfs->lstnSocket, (struct sockaddr *) &saddr, &addrlen);
2430
        closesocket(lpwfs->lstnSocket);
2431
        lpwfs->lstnSocket = -1;
2432
    }
2433
    return *nDataSocket != -1;
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
}


/***********************************************************************
 *           FTP_SendData (internal)
 *
 * Send data to the server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2447
static BOOL FTP_SendData(LPWININETFTPSESSIONW lpwfs, INT nDataSocket, HANDLE hFile)
2448 2449 2450 2451 2452
{
    BY_HANDLE_FILE_INFORMATION fi;
    DWORD nBytesRead = 0;
    DWORD nBytesSent = 0;
    DWORD nTotalSent = 0;
2453 2454
    DWORD nBytesToSend, nLen;
    int nRC = 1;
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
    time_t s_long_time, e_long_time;
    LONG nSeconds;
    CHAR *lpszBuffer;

    TRACE("\n");
    lpszBuffer = HeapAlloc(GetProcessHeap(), 0, sizeof(CHAR)*DATA_PACKET_SIZE);
    memset(lpszBuffer, 0, sizeof(CHAR)*DATA_PACKET_SIZE);

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

2484
        nLen = DATA_PACKET_SIZE < nBytesToSend ?
2485 2486 2487
            DATA_PACKET_SIZE : nBytesToSend;
        nRC  = send(nDataSocket, lpszBuffer, nLen, 0);

2488
        if (nRC != -1)
2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
        {
            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 )
        {
2499
            TRACE( "%ld bytes of %ld bytes (%ld%%) in %ld min %ld sec estimated remaining time %ld sec\n",
2500
            nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds / 60,
2501 2502 2503 2504
            nSeconds % 60, (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent );
        }
        else
        {
2505
            TRACE( "%ld bytes of %ld bytes (%ld%%) in %ld sec estimated remaining time %ld sec\n",
2506 2507 2508
            nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds,
            (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent);
        }
2509
    } while (nRC != -1);
2510 2511 2512

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

2513
    HeapFree(GetProcessHeap(), 0, lpszBuffer);
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528

    return nTotalSent;
}


/***********************************************************************
 *           FTP_SendRetrieve (internal)
 *
 * Send request to retrieve a file
 *
 * RETURNS
 *   Number of bytes to be received on success
 *   0 on failure
 *
 */
2529
static DWORD FTP_SendRetrieve(LPWININETFTPSESSIONW lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
{
    INT nResCode;
    DWORD nResult = 0;

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

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

2541
    if (!FTP_SendPortOrPasv(lpwfs))
2542 2543
        goto lend;

2544 2545 2546 2547 2548
    if (!FTP_GetFileSize(lpwfs, lpszRemoteFile, &nResult))
	goto lend;

    TRACE("Waiting to receive %ld bytes\n", nResult);
    
2549 2550 2551
    if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RETR, lpszRemoteFile, 0, 0, 0))
        goto lend;

2552
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2553 2554 2555
    if ((nResCode != 125) && (nResCode != 150)) {
	/* That means that we got an error getting the file. */
	nResult = 0;
2556 2557 2558
    }

lend:
2559
    if (0 == nResult && lpwfs->lstnSocket != -1)
2560
    {
2561
        closesocket(lpwfs->lstnSocket);
2562
        lpwfs->lstnSocket = -1;
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
    }

    return nResult;
}


/***********************************************************************
 *           FTP_RetrieveData  (internal)
 *
 * Retrieve data from server
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2579
static BOOL FTP_RetrieveFileData(LPWININETFTPSESSIONW lpwfs, INT nDataSocket, DWORD nBytes, HANDLE hFile)
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
{
    DWORD nBytesWritten;
    DWORD nBytesReceived = 0;
    INT nRC = 0;
    CHAR *lpszBuffer;

    TRACE("\n");

    if (INVALID_HANDLE_VALUE == hFile)
        return FALSE;

    lpszBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CHAR)*DATA_PACKET_SIZE);
    if (NULL == lpszBuffer)
    {
        INTERNET_SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }

2598
    while (nBytesReceived < nBytes && nRC != -1)
2599 2600
    {
        nRC = recv(nDataSocket, lpszBuffer, DATA_PACKET_SIZE, 0);
2601
        if (nRC != -1)
2602 2603 2604 2605
        {
            /* other side closed socket. */
            if (nRC == 0)
                goto recv_end;
2606
            WriteFile(hFile, lpszBuffer, nRC, &nBytesWritten, NULL);
2607 2608 2609
            nBytesReceived += nRC;
        }

2610
        TRACE("%ld bytes of %ld (%ld%%)\r", nBytesReceived, nBytes,
2611 2612 2613 2614
           nBytesReceived * 100 / nBytes);
    }

    TRACE("Data transfer complete\n");
2615
    HeapFree(GetProcessHeap(), 0, lpszBuffer);
2616 2617

recv_end:
2618
    return  (nRC != -1);
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
}


/***********************************************************************
 *           FTP_CloseSessionHandle (internal)
 *
 * Deallocate session handle
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2632
static void FTP_CloseSessionHandle(LPWININETHANDLEHEADER hdr)
2633
{
2634 2635
    LPWININETFTPSESSIONW lpwfs = (LPWININETFTPSESSIONW) hdr;

2636
    TRACE("\n");
2637 2638 2639

    if (lpwfs->download_in_progress != NULL)
	lpwfs->download_in_progress->session_deleted = TRUE;
2640
    
2641
    if (lpwfs->sndSocket != -1)
2642
        closesocket(lpwfs->sndSocket);
2643

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

2647 2648
    HeapFree(GetProcessHeap(), 0, lpwfs->lpszPassword);
    HeapFree(GetProcessHeap(), 0, lpwfs->lpszUserName);
2649 2650 2651 2652 2653
    HeapFree(GetProcessHeap(), 0, lpwfs);
}


/***********************************************************************
2654
 *           FTP_CloseFindNextHandle (internal)
2655 2656 2657 2658 2659 2660 2661 2662
 *
 * Deallocate session handle
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2663
static void FTP_CloseFindNextHandle(LPWININETHANDLEHEADER hdr)
2664
{
2665
    LPWININETFINDNEXTW lpwfn = (LPWININETFINDNEXTW) hdr;
2666
    DWORD i;
2667 2668 2669 2670 2671

    TRACE("\n");

    for (i = 0; i < lpwfn->size; i++)
    {
2672
        HeapFree(GetProcessHeap(), 0, lpwfn->lpafp[i].lpszName);
2673 2674 2675 2676 2677 2678
    }

    HeapFree(GetProcessHeap(), 0, lpwfn->lpafp);
    HeapFree(GetProcessHeap(), 0, lpwfn);
}

2679
/***********************************************************************
2680
 *           FTP_CloseFileTransferHandle (internal)
2681 2682 2683 2684 2685
 *
 * Closes the file transfer handle. This also 'cleans' the data queue of
 * the 'transfer conplete' message (this is a bit of a hack though :-/ )
 *
 */
2686
static void FTP_CloseFileTransferHandle(LPWININETHANDLEHEADER hdr)
2687
{
2688
    LPWININETFILE lpwh = (LPWININETFILE) hdr;
2689
    LPWININETFTPSESSIONW lpwfs = (LPWININETFTPSESSIONW) lpwh->hdr.lpwhparent;
2690 2691
    INT nResCode;

2692
    TRACE("\n");
2693 2694 2695 2696 2697 2698 2699 2700 2701

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

    /* This just serves to flush the control socket of any spurrious lines written
       to it (like '226 Transfer complete.').

       Wonder what to do if the server sends us an error code though...
    */
2702
    nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2703 2704
    
    if (lpwh->nDataSocket != -1)
2705
        closesocket(lpwh->nDataSocket);
2706 2707 2708

    HeapFree(GetProcessHeap(), 0, lpwh);
}
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719

/***********************************************************************
 *           FTP_ReceiveFileList (internal)
 *
 * Read file list from server
 *
 * RETURNS
 *   Handle to file list on success
 *   NULL on failure
 *
 */
2720
static HINTERNET FTP_ReceiveFileList(LPWININETFTPSESSIONW lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
2721
	LPWIN32_FIND_DATAW lpFindFileData, DWORD dwContext)
2722 2723
{
    DWORD dwSize = 0;
2724 2725
    LPFILEPROPERTIESW lpafp = NULL;
    LPWININETFINDNEXTW lpwfn = NULL;
2726
    HINTERNET handle = 0;
2727

2728
    TRACE("(%p,%d,%s,%p,%ld)\n", lpwfs, nSocket, debugstr_w(lpszSearchFile), lpFindFileData, dwContext);
2729

2730
    if (FTP_ParseDirectory(lpwfs, nSocket, lpszSearchFile, &lpafp, &dwSize))
2731
    {
2732 2733
        if(lpFindFileData)
            FTP_ConvertFileProp(lpafp, lpFindFileData);
2734

2735
        lpwfn = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETFINDNEXTW));
2736
        if (lpwfn)
2737
        {
2738 2739 2740 2741 2742
            lpwfn->hdr.htype = WH_HFINDNEXT;
            lpwfn->hdr.lpwhparent = WININET_AddRef( &lpwfs->hdr );
            lpwfn->hdr.dwContext = dwContext;
            lpwfn->hdr.dwRefCount = 1;
            lpwfn->hdr.destroy = FTP_CloseFindNextHandle;
2743
            lpwfn->hdr.lpfnStatusCB = lpwfs->hdr.lpfnStatusCB;
2744 2745 2746 2747
            lpwfn->index = 1; /* Next index is 1 since we return index 0 */
            lpwfn->size = dwSize;
            lpwfn->lpafp = lpafp;

2748
            handle = WININET_AllocHandle( &lpwfn->hdr );
2749
        }
2750
    }
2751

2752 2753 2754
    if( lpwfn )
        WININET_Release( &lpwfn->hdr );

2755
    TRACE("Matched %ld files\n", dwSize);
2756
    return handle;
2757 2758 2759 2760 2761 2762
}


/***********************************************************************
 *           FTP_ConvertFileProp (internal)
 *
2763
 * Converts FILEPROPERTIESW struct to WIN32_FIND_DATAA
2764 2765 2766 2767 2768 2769
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 *
 */
2770
BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData)
2771 2772 2773
{
    BOOL bSuccess = FALSE;

2774
    ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAW));
2775 2776 2777

    if (lpafp)
    {
2778 2779 2780
	/* Convert 'Unix' time to Windows time */
	RtlSecondsSince1970ToTime(mktime(&lpafp->tmLastModified),
				  (LARGE_INTEGER *) &(lpFindFileData->ftLastAccessTime));
2781 2782
	lpFindFileData->ftLastWriteTime = lpFindFileData->ftLastAccessTime;
	lpFindFileData->ftCreationTime = lpFindFileData->ftLastAccessTime;
2783
	
2784
        /* Not all fields are filled in */
2785 2786
        lpFindFileData->nFileSizeHigh = 0; /* We do not handle files bigger than 0xFFFFFFFF bytes yet :-) */
        lpFindFileData->nFileSizeLow = lpafp->nSize;
2787 2788 2789 2790 2791

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

        if (lpafp->lpszName)
2792
            lstrcpynW(lpFindFileData->cFileName, lpafp->lpszName, MAX_PATH);
2793 2794 2795 2796 2797 2798 2799

	bSuccess = TRUE;
    }

    return bSuccess;
}

2800 2801 2802 2803 2804 2805 2806 2807 2808
/***********************************************************************
 *           FTP_ParseNextFile (internal)
 *
 * Parse the next line in file listing
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 */
2809
static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW lpfp)
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
{
    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);
            }
            
            lpfp->tmLastModified.tm_sec  = 0;
            lpfp->tmLastModified.tm_min  = 0;
            lpfp->tmLastModified.tm_hour = 0;
            lpfp->tmLastModified.tm_mday = 0;
            lpfp->tmLastModified.tm_mon  = 0;
            lpfp->tmLastModified.tm_year = 0;
            
            /* Determine month */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if(strlen(pszToken) >= 3) {
                pszToken[3] = 0;
                if((pszTmp = StrStrIA(szMonths, pszToken)))
                    lpfp->tmLastModified.tm_mon = ((pszTmp - szMonths) / 3)+1;
            }
            /* Determine day */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            lpfp->tmLastModified.tm_mday = atoi(pszToken);
            /* Determine time or year */
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            if((pszTmp = strchr(pszToken, ':'))) {
                struct tm* apTM;
                time_t aTime;
                *pszTmp = 0;
                pszTmp++;
                lpfp->tmLastModified.tm_min = atoi(pszTmp);
                lpfp->tmLastModified.tm_hour = atoi(pszToken);
                time(&aTime);
                apTM = localtime(&aTime);
                lpfp->tmLastModified.tm_year = apTM->tm_year;
            }
            else {
                lpfp->tmLastModified.tm_year = atoi(pszToken) - 1900;
                lpfp->tmLastModified.tm_hour = 12;
            }
            TRACE("Mod time: %02d:%02d:%02d  %02d/%02d/%02d\n",
                lpfp->tmLastModified.tm_hour, lpfp->tmLastModified.tm_min, lpfp->tmLastModified.tm_sec,
                (lpfp->tmLastModified.tm_year >= 100) ? lpfp->tmLastModified.tm_year - 100 : lpfp->tmLastModified.tm_year,
                lpfp->tmLastModified.tm_mon, lpfp->tmLastModified.tm_mday);

            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            lpfp->lpszName = WININET_strdup_AtoW(pszToken);
            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)) {
            lpfp->permissions = 0xFFFF; /* No idea, put full permission :-) */
            
            sscanf(pszToken, "%d-%d-%d",
                &lpfp->tmLastModified.tm_mon,
                &lpfp->tmLastModified.tm_mday,
                &lpfp->tmLastModified.tm_year);

            /* Hacky and bad Y2K protection :-) */
            if (lpfp->tmLastModified.tm_year < 70)
                lpfp->tmLastModified.tm_year += 100;
            
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            sscanf(pszToken, "%d:%d",
                &lpfp->tmLastModified.tm_hour,
                &lpfp->tmLastModified.tm_min);
            if((pszToken[5] == 'P') && (pszToken[6] == 'M')) {
                lpfp->tmLastModified.tm_hour += 12;
            }
            lpfp->tmLastModified.tm_sec = 0;

            TRACE("Mod time: %02d:%02d:%02d  %02d/%02d/%02d\n",
                lpfp->tmLastModified.tm_hour, lpfp->tmLastModified.tm_min, lpfp->tmLastModified.tm_sec,
                (lpfp->tmLastModified.tm_year >= 100) ? lpfp->tmLastModified.tm_year - 100 : lpfp->tmLastModified.tm_year,
                lpfp->tmLastModified.tm_mon, lpfp->tmLastModified.tm_mday);
            
            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);
                TRACE("Size: %ld\n", lpfp->nSize);
            }
            
            pszToken = strtok(NULL, szSpace);
            if(!pszToken) continue;
            lpfp->lpszName = WININET_strdup_AtoW(pszToken);
            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) {
2951 2952
            if((lpszSearchFile == NULL) ||
	       (PathMatchSpecW(lpfp->lpszName, lpszSearchFile))) {
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
                found = TRUE;
                TRACE("Matched: %s\n", debugstr_w(lpfp->lpszName));
            }
            else {
                HeapFree(GetProcessHeap(), 0, lpfp->lpszName);
                lpfp->lpszName = NULL;
            }
        }
    } while(!found);
    return TRUE;
}
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973

/***********************************************************************
 *           FTP_ParseDirectory (internal)
 *
 * Parse string of directory information
 *
 * RETURNS
 *   TRUE on success
 *   FALSE on failure
 */
2974
static BOOL FTP_ParseDirectory(LPWININETFTPSESSIONW lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
2975
    LPFILEPROPERTIESW *lpafp, LPDWORD dwfp)
2976 2977
{
    BOOL bSuccess = TRUE;
2978 2979
    INT sizeFilePropArray = 500;/*20; */
    INT indexFilePropArray = -1;
2980 2981 2982 2983

    TRACE("\n");

    /* Allocate intial file properties array */
2984 2985 2986
    *lpafp = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(FILEPROPERTIESW)*(sizeFilePropArray));
    if (!*lpafp)
        return FALSE;
2987

2988 2989
    do {
        if (indexFilePropArray+1 >= sizeFilePropArray)
2990
        {
2991 2992
            LPFILEPROPERTIESW tmpafp;
            
2993
            sizeFilePropArray *= 2;
2994
            tmpafp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *lpafp,
2995
                sizeof(FILEPROPERTIESW)*sizeFilePropArray);
2996 2997 2998
            if (NULL == tmpafp)
            {
                bSuccess = FALSE;
2999
                break;
3000 3001 3002 3003
            }

            *lpafp = tmpafp;
        }
3004 3005
        indexFilePropArray++;
    } while (FTP_ParseNextFile(nSocket, lpszSearchFile, &(*lpafp)[indexFilePropArray]));
3006 3007 3008 3009 3010

    if (bSuccess && indexFilePropArray)
    {
        if (indexFilePropArray < sizeFilePropArray - 1)
        {
3011
            LPFILEPROPERTIESW tmpafp;
3012

3013
            tmpafp = HeapReAlloc(GetProcessHeap(), 0, *lpafp,
3014
                sizeof(FILEPROPERTIESW)*indexFilePropArray);
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040
            if (NULL == tmpafp)
                *lpafp = tmpafp;
        }
        *dwfp = indexFilePropArray;
    }
    else
    {
        HeapFree(GetProcessHeap(), 0, *lpafp);
        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
 *
 */
3041
static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp)
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103
{
    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
 *
 */
3104
static DWORD FTP_SetResponseError(DWORD dwResponse)
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
{
    DWORD dwCode = 0;

    switch(dwResponse)
    {
	case 421: /* Service not available - Server may be shutting down. */
	    dwCode = ERROR_INTERNET_TIMEOUT;
	    break;

	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 500: /* Syntax error. Command unrecognized. */
	case 501: /* Syntax error. Error in parameters or arguments. */
	    dwCode = ERROR_INTERNET_INCORRECT_FORMAT;
	    break;

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

	case 550: /* File action not taken. File not found or no access. */
	    dwCode = ERROR_INTERNET_ITEM_NOT_FOUND;
	    break;

	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 502: /* Command not implemented. */
	case 503: /* Bad sequence of command. */
	case 504: /* Command not implemented for that parameter. */
	case 532: /* Need account for storing files */
	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_INTERNAL_ERROR;
	    break;
    }
3150

3151 3152 3153
    INTERNET_SetLastError(dwCode);
    return dwCode;
}