]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ftp.cc
hno/squid-2.3.STABLE1.idns_config-2.patch [with adaptions to current release]
[thirdparty/squid.git] / src / ftp.cc
CommitLineData
be335c22 1
30a4f2a8 2/*
3b3a620c 3 * $Id: ftp.cc,v 1.291 2000/05/02 20:25:33 hno Exp $
30a4f2a8 4 *
5 * DEBUG: section 9 File Transfer Protocol (FTP)
6 * AUTHOR: Harvest Derived
7 *
42c04c16 8 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
e25c139f 9 * ----------------------------------------------------------
30a4f2a8 10 *
11 * Squid is the result of efforts by numerous individuals from the
12 * Internet community. Development is led by Duane Wessels of the
e25c139f 13 * National Laboratory for Applied Network Research and funded by the
14 * National Science Foundation. Squid is Copyrighted (C) 1998 by
efd900cb 15 * the Regents of the University of California. Please see the
16 * COPYRIGHT file for full details. Squid incorporates software
17 * developed and/or copyrighted by other sources. Please see the
18 * CREDITS file for full details.
30a4f2a8 19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
cbdec147 32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 33 *
30a4f2a8 34 */
019dd986 35
44a47c6e 36#include "squid.h"
090089c4 37
3fdadc70 38static const char *const crlf = "\r\n";
39static char cbuf[1024];
40
41typedef enum {
42 BEGIN,
43 SENT_USER,
44 SENT_PASS,
45 SENT_TYPE,
46 SENT_MDTM,
47 SENT_SIZE,
48 SENT_PORT,
49 SENT_PASV,
50 SENT_CWD,
51 SENT_LIST,
52 SENT_NLST,
53 SENT_REST,
54 SENT_RETR,
54220df8 55 SENT_STOR,
3fdadc70 56 SENT_QUIT,
54220df8 57 READING_DATA,
58 WRITING_DATA,
59 SENT_MKDIR
3fdadc70 60} ftp_state_t;
090089c4 61
e55f0142 62struct _ftp_flags {
1ecaa0a0 63 unsigned int isdir:1;
64 unsigned int pasv_supported:1;
65 unsigned int skip_whitespace:1;
66 unsigned int rest_supported:1;
67 unsigned int pasv_only:1;
68 unsigned int authenticated:1;
69 unsigned int http_header_sent:1;
70 unsigned int tried_nlst:1;
71 unsigned int use_base:1;
72 unsigned int root_dir:1;
73 unsigned int no_dotdot:1;
74 unsigned int html_header_sent:1;
75 unsigned int binary:1;
76 unsigned int try_slash_hack:1;
77 unsigned int put:1;
78 unsigned int put_mkdir:1;
79 unsigned int listformat_unknown:1;
80 unsigned int datachannel_hack:1;
e55f0142 81};
82
090089c4 83typedef struct _Ftpdata {
84 StoreEntry *entry;
983061ed 85 request_t *request;
77a30ebb 86 char user[MAX_URL];
87 char password[MAX_URL];
9bc73deb 88 int password_url;
f0afe435 89 char *reply_hdr;
f0afe435 90 int reply_hdr_state;
3fdadc70 91 char *title_url;
9bc73deb 92 char *base_href;
3fdadc70 93 int conn_att;
94 int login_att;
95 ftp_state_t state;
3fdadc70 96 time_t mdtm;
97 int size;
3fdadc70 98 wordlist *pathcomps;
99 char *filepath;
100 int restart_offset;
cfbf5373 101 int restarted_offset;
3fdadc70 102 int rest_att;
103 char *proxy_host;
104 size_t list_width;
105 wordlist *cwd_message;
969c39b9 106 char *old_request;
107 char *old_reply;
0f169992 108 char *old_filepath;
9e242e02 109 char typecode;
3fdadc70 110 struct {
111 int fd;
112 char *buf;
113 size_t size;
114 off_t offset;
115 FREE *freefunc;
116 wordlist *message;
b9916917 117 char *last_command;
118 char *last_reply;
3fdadc70 119 int replycode;
120 } ctrl;
121 struct {
122 int fd;
123 char *buf;
124 size_t size;
125 off_t offset;
126 FREE *freefunc;
9b312a19 127 char *host;
128 u_short port;
3fdadc70 129 } data;
e55f0142 130 struct _ftp_flags flags;
db1cd23c 131 FwdState *fwd;
e5f6c5c2 132} FtpStateData;
090089c4 133
3fdadc70 134typedef struct {
135 char type;
136 int size;
137 char *date;
138 char *name;
139 char *showname;
140 char *link;
141} ftpListParts;
142
ea3a2a69 143typedef void (FTPSM) (FtpStateData *);
0a0bf5db 144
c68e9c6b 145#define FTP_LOGIN_ESCAPED 1
146#define FTP_LOGIN_NOT_ESCAPED 0
147
983061ed 148/* Local functions */
3fdadc70 149static CNCB ftpPasvCallback;
dbfed404 150static PF ftpDataRead;
9e4ad609 151static PF ftpStateFree;
b6a2f15e 152static PF ftpPumpClosedData;
5c5783a2 153static PF ftpTimeout;
3fdadc70 154static PF ftpReadControlReply;
155static CWCB ftpWriteCommandCallback;
c68e9c6b 156static void ftpLoginParser(const char *, FtpStateData *, int escaped);
4f310655 157static wordlist *ftpParseControlReply(char *, size_t, int *, int *);
cfbf5373 158static int ftpRestartable(FtpStateData * ftpState);
f5b8bbc4 159static void ftpAppendSuccessHeader(FtpStateData * ftpState);
ee1679df 160static void ftpAuthRequired(HttpReply * reply, request_t * request, const char *realm);
969c39b9 161static void ftpHackShortcut(FtpStateData * ftpState, FTPSM * nextState);
54220df8 162static void ftpPutStart(FtpStateData *);
163static CWCB ftpPutTransferDone;
0f169992 164static void ftpUnhack(FtpStateData * ftpState);
05491dc4 165static void ftpScheduleReadControlReply(FtpStateData *, int);
4f310655 166static void ftpHandleControlReply(FtpStateData *);
ee16d4ab 167static char *ftpHtmlifyListEntry(char *line, FtpStateData * ftpState);
7e3ce7b9 168static void ftpFailed(FtpStateData *, err_type);
169static void ftpFailedErrorMessage(FtpStateData *, err_type);
983061ed 170
7e3ce7b9 171/*
172 * State machine functions
969c39b9 173 * send == state transition
174 * read == wait for response, and select next state transition
dbfed404 175 * other == Transition logic
969c39b9 176 */
3fdadc70 177static FTPSM ftpReadWelcome;
969c39b9 178static FTPSM ftpSendUser;
3fdadc70 179static FTPSM ftpReadUser;
969c39b9 180static FTPSM ftpSendPass;
3fdadc70 181static FTPSM ftpReadPass;
969c39b9 182static FTPSM ftpSendType;
3fdadc70 183static FTPSM ftpReadType;
969c39b9 184static FTPSM ftpSendMdtm;
3fdadc70 185static FTPSM ftpReadMdtm;
969c39b9 186static FTPSM ftpSendSize;
3fdadc70 187static FTPSM ftpReadSize;
969c39b9 188static FTPSM ftpSendPort;
3fdadc70 189static FTPSM ftpReadPort;
969c39b9 190static FTPSM ftpSendPasv;
3fdadc70 191static FTPSM ftpReadPasv;
dbfed404 192static FTPSM ftpTraverseDirectory;
193static FTPSM ftpListDir;
194static FTPSM ftpGetFile;
969c39b9 195static FTPSM ftpSendCwd;
3fdadc70 196static FTPSM ftpReadCwd;
969c39b9 197static FTPSM ftpSendList;
198static FTPSM ftpSendNlst;
3fdadc70 199static FTPSM ftpReadList;
969c39b9 200static FTPSM ftpSendRest;
3fdadc70 201static FTPSM ftpReadRest;
969c39b9 202static FTPSM ftpSendRetr;
3fdadc70 203static FTPSM ftpReadRetr;
204static FTPSM ftpReadTransferDone;
969c39b9 205static FTPSM ftpSendQuit;
206static FTPSM ftpReadQuit;
207static FTPSM ftpFail;
dbfed404 208static FTPSM ftpDataTransferDone;
209static FTPSM ftpRestOrList;
54220df8 210static FTPSM ftpSendStor;
211static FTPSM ftpReadStor;
212static FTPSM ftpSendReply;
213static FTPSM ftpTryMkdir;
214static FTPSM ftpReadMkdir;
dbfed404 215/************************************************
216** State Machine Description (excluding hacks) **
217*************************************************
218From To
219---------------------------------------
220Welcome User
221User Pass
222Pass Type
223Type TraverseDirectory / GetFile
224TraverseDirectory Cwd / GetFile / ListDir
225Cwd TraverseDirectory
226GetFile Mdtm
227Mdtm Size
228Size Pasv
229ListDir Pasv
230Pasv RestOrList
231RestOrList Rest / Retr / Nlst / List
232Rest Retr
233Retr / Nlst / List (ftpDataRead on datachannel)
234(ftpDataRead) ReadTransferDone
235ReadTransferDone DataTransferDone
236DataTransferDone Quit
237Quit -
238************************************************/
3fdadc70 239
240FTPSM *FTP_SM_FUNCS[] =
241{
9bc73deb 242 ftpReadWelcome, /* BEGIN */
243 ftpReadUser, /* SENT_USER */
244 ftpReadPass, /* SENT_PASS */
245 ftpReadType, /* SENT_TYPE */
246 ftpReadMdtm, /* SENT_MDTM */
247 ftpReadSize, /* SENT_SIZE */
248 ftpReadPort, /* SENT_PORT */
249 ftpReadPasv, /* SENT_PASV */
250 ftpReadCwd, /* SENT_CWD */
3fdadc70 251 ftpReadList, /* SENT_LIST */
252 ftpReadList, /* SENT_NLST */
9bc73deb 253 ftpReadRest, /* SENT_REST */
254 ftpReadRetr, /* SENT_RETR */
255 ftpReadStor, /* SENT_STOR */
256 ftpReadQuit, /* SENT_QUIT */
257 ftpReadTransferDone, /* READING_DATA (RETR,LIST,NLST) */
258 ftpSendReply, /* WRITING_DATA (STOR) */
259 ftpReadMkdir /* SENT_MKDIR */
3fdadc70 260};
e381a13d 261
582b6456 262static void
79d39a72 263ftpStateFree(int fdnotused, void *data)
ba718c8f 264{
582b6456 265 FtpStateData *ftpState = data;
51fa90db 266 if (ftpState == NULL)
582b6456 267 return;
c3b838d4 268 debug(9, 3) ("ftpStateFree: %s\n", storeUrl(ftpState->entry));
bfcaf585 269 storeUnregisterAbort(ftpState->entry);
f88211e8 270 storeUnlockObject(ftpState->entry);
51fa90db 271 if (ftpState->reply_hdr) {
db1cd23c 272 memFree(ftpState->reply_hdr, MEM_8K_BUF);
1ecaa0a0 273 /* this seems unnecessary, but people report SEGV's
274 * when freeing memory in this function */
51fa90db 275 ftpState->reply_hdr = NULL;
f0afe435 276 }
30a4f2a8 277 requestUnlink(ftpState->request);
1ecaa0a0 278 if (ftpState->ctrl.buf) {
3fdadc70 279 ftpState->ctrl.freefunc(ftpState->ctrl.buf);
1ecaa0a0 280 /* this seems unnecessary, but people report SEGV's
281 * when freeing memory in this function */
282 ftpState->ctrl.buf = NULL;
283 }
284 if (ftpState->data.buf) {
3fdadc70 285 ftpState->data.freefunc(ftpState->data.buf);
1ecaa0a0 286 /* this seems unnecessary, but people report SEGV's
287 * when freeing memory in this function */
288 ftpState->data.buf = NULL;
289 }
3fdadc70 290 if (ftpState->pathcomps)
291 wordlistDestroy(&ftpState->pathcomps);
292 if (ftpState->ctrl.message)
293 wordlistDestroy(&ftpState->ctrl.message);
294 if (ftpState->cwd_message)
295 wordlistDestroy(&ftpState->cwd_message);
b9916917 296 safe_free(ftpState->ctrl.last_reply);
297 safe_free(ftpState->ctrl.last_command);
969c39b9 298 safe_free(ftpState->old_request);
299 safe_free(ftpState->old_reply);
0f169992 300 safe_free(ftpState->old_filepath);
b5639035 301 safe_free(ftpState->title_url);
9bc73deb 302 safe_free(ftpState->base_href);
b5639035 303 safe_free(ftpState->filepath);
9b312a19 304 safe_free(ftpState->data.host);
a0eff6be 305 if (ftpState->data.fd > -1) {
d05283d9 306 comm_close(ftpState->data.fd);
307 ftpState->data.fd = -1;
a0eff6be 308 }
7dd44885 309 cbdataFree(ftpState);
ba718c8f 310}
311
b8d8561b 312static void
c68e9c6b 313ftpLoginParser(const char *login, FtpStateData * ftpState, int escaped)
090089c4 314{
983061ed 315 char *s = NULL;
582b6456 316 xstrncpy(ftpState->user, login, MAX_URL);
317 if ((s = strchr(ftpState->user, ':'))) {
983061ed 318 *s = 0;
582b6456 319 xstrncpy(ftpState->password, s + 1, MAX_URL);
c68e9c6b 320 if (escaped)
321 rfc1738_unescape(ftpState->password);
9bc73deb 322 ftpState->password_url = 1;
983061ed 323 } else {
582b6456 324 xstrncpy(ftpState->password, null_string, MAX_URL);
983061ed 325 }
c68e9c6b 326 if (escaped)
327 rfc1738_unescape(ftpState->user);
582b6456 328 if (ftpState->user[0] || ftpState->password[0])
429fdbec 329 return;
582b6456 330 xstrncpy(ftpState->user, "anonymous", MAX_URL);
e34e0322 331 xstrncpy(ftpState->password, Config.Ftp.anon_user, MAX_URL);
090089c4 332}
333
24382924 334static void
5c5783a2 335ftpTimeout(int fd, void *data)
090089c4 336{
582b6456 337 FtpStateData *ftpState = data;
338 StoreEntry *entry = ftpState->entry;
9fb13bb6 339 debug(9, 4) ("ftpTimeout: FD %d: '%s'\n", fd, storeUrl(entry));
7e3ce7b9 340 if (SENT_PASV == ftpState->state && fd == ftpState->data.fd) {
341 /* stupid ftp.netscape.com */
342 ftpState->fwd->flags.dont_retry = 0;
343 ftpState->fwd->flags.ftp_pasv_failed = 1;
344 debug(9, 1) ("ftpTimeout: timeout in SENT_PASV state\n");
345 }
9bc73deb 346 ftpFailed(ftpState, ERR_READ_TIMEOUT);
347 /* ftpFailed closes ctrl.fd and frees ftpState */
090089c4 348}
349
3fdadc70 350static void
351ftpListingStart(FtpStateData * ftpState)
352{
353 StoreEntry *e = ftpState->entry;
354 wordlist *w;
ee16d4ab 355 char *dirup;
6e5ae4a4 356 int i, j, k;
438fc1e3 357 storeBuffer(e);
3fdadc70 358 storeAppendPrintf(e, "<!-- HTML listing generated by Squid %s -->\n",
359 version_string);
360 storeAppendPrintf(e, "<!-- %s -->\n", mkrfc1123(squid_curtime));
361 storeAppendPrintf(e, "<HTML><HEAD><TITLE>\n");
362 storeAppendPrintf(e, "FTP Directory: %s\n",
363 ftpState->title_url);
364 storeAppendPrintf(e, "</TITLE>\n");
e55f0142 365 if (ftpState->flags.use_base)
3fdadc70 366 storeAppendPrintf(e, "<BASE HREF=\"%s\">\n",
9bc73deb 367 ftpState->base_href);
3fdadc70 368 storeAppendPrintf(e, "</HEAD><BODY>\n");
369 if (ftpState->cwd_message) {
370 storeAppendPrintf(e, "<PRE>\n");
371 for (w = ftpState->cwd_message; w; w = w->next)
372 storeAppendPrintf(e, "%s\n", w->key);
373 storeAppendPrintf(e, "</PRE>\n");
374 storeAppendPrintf(e, "<HR>\n");
375 wordlistDestroy(&ftpState->cwd_message);
376 }
377 storeAppendPrintf(e, "<H2>\n");
6e5ae4a4 378 storeAppendPrintf(e, "FTP Directory: ");
379 /* "ftp://" == 6 characters */
380 assert(strlen(ftpState->title_url) >= 6);
381 for (i = 6, j = 0; ftpState->title_url[i]; j = i) {
382 storeAppendPrintf(e, "<A HREF=\"");
383 i += strcspn(&ftpState->title_url[i], "/");
384 if (ftpState->title_url[i] == '/')
385 i++;
386 for (k = 0; k < i; k++)
387 storeAppendPrintf(e, "%c", ftpState->title_url[k]);
388 storeAppendPrintf(e, "\">");
389 for (k = j; k < i - 1; k++)
390 storeAppendPrintf(e, "%c", ftpState->title_url[k]);
391 if (ftpState->title_url[k] != '/')
392 storeAppendPrintf(e, "%c", ftpState->title_url[k++]);
393 storeAppendPrintf(e, "</A>");
394 if (k < i)
395 storeAppendPrintf(e, "%c", ftpState->title_url[k++]);
396 if (i == j) {
397 /* Error guard, or "assert" */
398 storeAppendPrintf(e, "ERROR: Failed to parse URL: %s\n",
399 ftpState->title_url);
400 debug(9, 0) ("Failed to parse URL: %s\n", ftpState->title_url);
401 break;
402 }
403 }
3fdadc70 404 storeAppendPrintf(e, "</H2>\n");
405 storeAppendPrintf(e, "<PRE>\n");
ee16d4ab 406 dirup = ftpHtmlifyListEntry("<internal-dirup>", ftpState);
407 storeAppend(e, dirup, strlen(dirup));
438fc1e3 408 storeBufferFlush(e);
e55f0142 409 ftpState->flags.html_header_sent = 1;
3fdadc70 410}
411
412static void
413ftpListingFinish(FtpStateData * ftpState)
414{
415 StoreEntry *e = ftpState->entry;
438fc1e3 416 storeBuffer(e);
3fdadc70 417 storeAppendPrintf(e, "</PRE>\n");
e55f0142 418 if (ftpState->flags.listformat_unknown && !ftpState->flags.tried_nlst) {
dbfed404 419 storeAppendPrintf(e, "<A HREF=\"./;type=d\">[As plain directory]</A>\n");
0e473d70 420 } else if (ftpState->typecode == 'D') {
dbfed404 421 storeAppendPrintf(e, "<A HREF=\"./\">[As extended directory]</A>\n");
422 }
3fdadc70 423 storeAppendPrintf(e, "<HR>\n");
424 storeAppendPrintf(e, "<ADDRESS>\n");
a15705d0 425 storeAppendPrintf(e, "Generated %s by %s (<a href=\"http://squid.nlanr.net/Squid/\">%s</a>)\n",
3fdadc70 426 mkrfc1123(squid_curtime),
a15705d0 427 getMyHostname(),
428 full_appname_string,
429 version_string);
3fdadc70 430 storeAppendPrintf(e, "</ADDRESS></BODY></HTML>\n");
438fc1e3 431 storeBufferFlush(e);
3fdadc70 432}
433
434static const char *Month[] =
435{
436 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
437 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
438};
439
440static int
441is_month(const char *buf)
442{
443 int i;
444 for (i = 0; i < 12; i++)
445 if (!strcasecmp(buf, Month[i]))
446 return 1;
447 return 0;
448}
449
450
451static void
452ftpListPartsFree(ftpListParts ** parts)
453{
454 safe_free((*parts)->date);
455 safe_free((*parts)->name);
456 safe_free((*parts)->showname);
457 safe_free((*parts)->link);
458 safe_free(*parts);
459}
460
461#define MAX_TOKENS 64
462
75e5a32e 463#define SCAN_FTP1 "%[0123456789]"
464#define SCAN_FTP2 "%[0123456789:]"
465#define SCAN_FTP3 "%[0123456789]-%[0123456789]-%[0123456789]"
466#define SCAN_FTP4 "%[0123456789]:%[0123456789]%[AaPp]%[Mm]"
467
3fdadc70 468static ftpListParts *
e55f0142 469ftpListParseParts(const char *buf, struct _ftp_flags flags)
3fdadc70 470{
471 ftpListParts *p = NULL;
472 char *t = NULL;
473 const char *ct = NULL;
474 char *tokens[MAX_TOKENS];
475 int i;
476 int n_tokens;
477 static char sbuf[128];
478 char *xbuf = NULL;
479 if (buf == NULL)
480 return NULL;
481 if (*buf == '\0')
482 return NULL;
483 p = xcalloc(1, sizeof(ftpListParts));
484 n_tokens = 0;
485 for (i = 0; i < MAX_TOKENS; i++)
486 tokens[i] = (char *) NULL;
487 xbuf = xstrdup(buf);
e55f0142 488 if (flags.tried_nlst) {
dbfed404 489 /* Machine readable format, one name per line */
0e473d70 490 p->name = xbuf;
491 p->type = '\0';
dbfed404 492 return p;
493 }
3fdadc70 494 for (t = strtok(xbuf, w_space); t && n_tokens < MAX_TOKENS; t = strtok(NULL, w_space))
495 tokens[n_tokens++] = xstrdup(t);
496 xfree(xbuf);
497 /* locate the Month field */
b6a2f15e 498 for (i = 3; i < n_tokens - 2; i++) {
3fdadc70 499 if (!is_month(tokens[i])) /* Month */
500 continue;
75e5a32e 501 if (!sscanf(tokens[i - 1], SCAN_FTP1, sbuf)) /* Size */
3fdadc70 502 continue;
75e5a32e 503 if (!sscanf(tokens[i + 1], SCAN_FTP1, sbuf)) /* Day */
3fdadc70 504 continue;
75e5a32e 505 if (!sscanf(tokens[i + 2], SCAN_FTP2, sbuf)) /* Yr | hh:mm */
3fdadc70 506 continue;
507 p->type = *tokens[0];
508 p->size = atoi(tokens[i - 1]);
042461c3 509 snprintf(sbuf, 128, "%s %2s %5s",
3fdadc70 510 tokens[i], tokens[i + 1], tokens[i + 2]);
511 if (!strstr(buf, sbuf))
042461c3 512 snprintf(sbuf, 128, "%s %2s %-5s",
3fdadc70 513 tokens[i], tokens[i + 1], tokens[i + 2]);
514 if ((t = strstr(buf, sbuf))) {
515 p->date = xstrdup(sbuf);
e55f0142 516 if (flags.skip_whitespace) {
3fdadc70 517 t += strlen(sbuf);
518 while (strchr(w_space, *t))
519 t++;
520 } else {
521 /* XXX assumes a single space between date and filename
522 * suggested by: Nathan.Bailey@cc.monash.edu.au and
523 * Mike Battersby <mike@starbug.bofh.asn.au> */
524 t += strlen(sbuf) + 1;
525 }
526 p->name = xstrdup(t);
527 if ((t = strstr(p->name, " -> "))) {
528 *t = '\0';
529 p->link = xstrdup(t + 4);
530 }
531 }
532 break;
533 }
534 /* try it as a DOS listing */
535 if (n_tokens > 3 && p->name == NULL &&
75e5a32e 536 sscanf(tokens[0], SCAN_FTP3, sbuf, sbuf, sbuf) == 3 &&
3fdadc70 537 /* 04-05-70 */
75e5a32e 538 sscanf(tokens[1], SCAN_FTP4, sbuf, sbuf, sbuf, sbuf) == 4) {
3fdadc70 539 /* 09:33PM */
540 if (!strcasecmp(tokens[2], "<dir>")) {
541 p->type = 'd';
542 } else {
543 p->type = '-';
544 p->size = atoi(tokens[2]);
545 }
042461c3 546 snprintf(sbuf, 128, "%s %s", tokens[0], tokens[1]);
3fdadc70 547 p->date = xstrdup(sbuf);
20f88067 548 if (p->type == 'd') {
549 /* Directory.. name begins with first printable after <dir> */
550 ct = strstr(buf, tokens[2]);
551 ct += strlen(tokens[2]);
b6a2f15e 552 while (xisspace(*ct))
20f88067 553 ct++;
c079f69d 554 if (!*ct)
20f88067 555 ct = NULL;
556 } else {
557 /* A file. Name begins after size, with a space in between */
558 snprintf(sbuf, 128, " %s %s", tokens[2], tokens[3]);
559 ct = strstr(buf, sbuf);
560 if (ct) {
561 ct += strlen(tokens[2]) + 2;
562 }
563 }
564 p->name = xstrdup(ct ? ct : tokens[3]);
3fdadc70 565 }
566 /* Try EPLF format; carson@lehman.com */
567 if (p->name == NULL && buf[0] == '+') {
568 ct = buf + 1;
569 p->type = 0;
570 while (ct && *ct) {
efd900cb 571 long lt;
572 time_t t;
3fdadc70 573 switch (*ct) {
574 case '\t':
575 sscanf(ct + 1, "%[^,]", sbuf);
576 p->name = xstrdup(sbuf);
577 break;
578 case 's':
579 sscanf(ct + 1, "%d", &(p->size));
580 break;
581 case 'm':
efd900cb 582 if (1 != sscanf(ct + 1, "%ld", &lt))
583 break;
584 t = lt;
585 p->date = xstrdup(ctime(&t));
3fdadc70 586 *(strstr(p->date, "\n")) = '\0';
587 break;
588 case '/':
589 p->type = 'd';
590 break;
591 case 'r':
592 p->type = '-';
593 break;
594 case 'i':
595 break;
596 default:
597 break;
598 }
599 ct = strstr(ct, ",");
600 if (ct) {
601 ct++;
602 }
603 }
604 if (p->type == 0) {
605 p->type = '-';
606 }
607 }
608 for (i = 0; i < n_tokens; i++)
609 xfree(tokens[i]);
b5639035 610 if (p->name == NULL)
611 ftpListPartsFree(&p);
3fdadc70 612 return p;
613}
614
615static const char *
616dots_fill(size_t len)
617{
618 static char buf[256];
619 int i = 0;
620 if (len > Config.Ftp.list_width) {
621 memset(buf, ' ', 256);
622 buf[0] = '\n';
623 buf[Config.Ftp.list_width + 4] = '\0';
624 return buf;
625 }
626 for (i = (int) len; i < Config.Ftp.list_width; i++)
627 buf[i - len] = (i % 2) ? '.' : ' ';
628 buf[i - len] = '\0';
629 return buf;
630}
631
632static char *
dbfed404 633ftpHtmlifyListEntry(char *line, FtpStateData * ftpState)
3fdadc70 634{
3fdadc70 635 LOCAL_ARRAY(char, icon, 2048);
2a1ca944 636 LOCAL_ARRAY(char, href, 2048 + 40);
637 LOCAL_ARRAY(char, text, 2048);
638 LOCAL_ARRAY(char, size, 2048);
639 LOCAL_ARRAY(char, chdir, 2048 + 40);
640 LOCAL_ARRAY(char, view, 2048 + 40);
641 LOCAL_ARRAY(char, download, 2048 + 40);
642 LOCAL_ARRAY(char, link, 2048 + 40);
3fdadc70 643 LOCAL_ARRAY(char, html, 8192);
3fdadc70 644 size_t width = Config.Ftp.list_width;
645 ftpListParts *parts;
0cdcddb9 646 *icon = *href = *text = *size = *chdir = *view = *download = *link = *html = '\0';
69e81830 647 if ((int) strlen(line) > 1024) {
042461c3 648 snprintf(html, 8192, "%s\n", line);
3fdadc70 649 return html;
650 }
ee16d4ab 651 /* Handle builtin <dirup> */
652 if (!strcmp(line, "<internal-dirup>")) {
2a1ca944 653 /* <A HREF="{href}">{icon}</A> <A HREF="{href}">{text}</A> {link} */
4162ee3b 654 snprintf(icon, 2048, "<IMG BORDER=0 SRC=\"%s\" ALT=\"%-6s\">",
655 mimeGetIconURL("internal-dirup"),
656 "[DIRUP]");
e55f0142 657 if (!ftpState->flags.no_dotdot && !ftpState->flags.root_dir) {
13e80e5b 658 /* Normal directory */
2a1ca944 659 strcpy(href, "../");
660 strcpy(text, "Parent Directory");
e55f0142 661 } else if (!ftpState->flags.no_dotdot && ftpState->flags.root_dir) {
13e80e5b 662 /* "Top level" directory */
2a1ca944 663 strcpy(href, "%2e%2e/");
664 strcpy(text, "Parent Directory");
665 snprintf(link, 2048, "(<A HREF=\"%s\">%s</A>)",
13e80e5b 666 "%2f/",
667 "Root Directory");
e55f0142 668 } else if (ftpState->flags.no_dotdot && !ftpState->flags.root_dir) {
13e80e5b 669 /* Normal directory where last component is / or .. */
2a1ca944 670 strcpy(href, "%2e%2e/");
671 strcpy(text, "Parent Directory");
672 snprintf(link, 2048, "(<A HREF=\"%s\">%s</A>)",
13e80e5b 673 "../",
2a1ca944 674 "Back");
13e80e5b 675 } else { /* NO_DOTDOT && ROOT_DIR */
676 /* "UNIX Root" directory */
2a1ca944 677 strcpy(href, "../");
678 strcpy(text, "Home Directory");
13e80e5b 679 }
2a1ca944 680 snprintf(html, 8192, "<A HREF=\"%s\">%s</A> <A HREF=\"%s\">%s</A> %s\n",
0cdcddb9 681 href, icon, href, text, link);
ee16d4ab 682 return html;
683 }
684 if ((parts = ftpListParseParts(line, ftpState->flags)) == NULL) {
685 char *p;
686 snprintf(html, 8192, "%s\n", line);
b6a2f15e 687 for (p = line; *p && xisspace(*p); p++);
688 if (*p && !xisspace(*p))
ee16d4ab 689 ftpState->flags.listformat_unknown = 1;
13e80e5b 690 return html;
691 }
3fdadc70 692 if (!strcmp(parts->name, ".") || !strcmp(parts->name, "..")) {
693 *html = '\0';
b5639035 694 ftpListPartsFree(&parts);
3fdadc70 695 return html;
696 }
697 parts->size += 1023;
698 parts->size >>= 10;
699 parts->showname = xstrdup(parts->name);
700 if (!Config.Ftp.list_wrap) {
701 if (strlen(parts->showname) > width - 1) {
702 *(parts->showname + width - 1) = '>';
703 *(parts->showname + width - 0) = '\0';
704 }
705 }
2a1ca944 706 /* {icon} {text} . . . {date}{size}{chdir}{view}{download}{link}\n */
9bc73deb 707 xstrncpy(href, rfc1738_escape_part(parts->name), 2048);
2a1ca944 708 xstrncpy(text, parts->showname, 2048);
3fdadc70 709 switch (parts->type) {
710 case 'd':
2a1ca944 711 snprintf(icon, 2048, "<IMG BORDER=0 SRC=\"%s\" ALT=\"%-6s\">",
4162ee3b 712 mimeGetIconURL("internal-dir"),
3fdadc70 713 "[DIR]");
2a1ca944 714 strncat(href, "/", 2048);
3fdadc70 715 break;
716 case 'l':
2a1ca944 717 snprintf(icon, 2048, "<IMG BORDER=0 SRC=\"%s\" ALT=\"%-6s\">",
4162ee3b 718 mimeGetIconURL("internal-link"),
3fdadc70 719 "[LINK]");
7b63416b 720 /* sometimes there is an 'l' flag, but no "->" link */
721 if (parts->link)
2a1ca944 722 snprintf(link, 2048, " -> <A HREF=\"%s\">%s</A>",
7b63416b 723 rfc1738_escape(parts->link),
724 parts->link);
3fdadc70 725 break;
dbfed404 726 case '\0':
2a1ca944 727 snprintf(icon, 2048, "<IMG BORDER=0 SRC=\"%s\" ALT=\"%-6s\">",
4162ee3b 728 mimeGetIconURL(parts->name),
dbfed404 729 "[UNKNOWN]");
2a1ca944 730 snprintf(chdir, 2048, " <A HREF=\"%s/;type=d\"><IMG BORDER=0 SRC=\"%s\" "
0cdcddb9 731 "ALT=\"[DIR]\"></A>",
dbfed404 732 rfc1738_escape(parts->name),
2a1ca944 733 mimeGetIconURL("internal-dir"));
dbfed404 734 break;
3fdadc70 735 case '-':
736 default:
2a1ca944 737 snprintf(icon, 2048, "<IMG BORDER=0 SRC=\"%s\" ALT=\"%-6s\">",
4162ee3b 738 mimeGetIconURL(parts->name),
3fdadc70 739 "[FILE]");
2a1ca944 740 snprintf(size, 2048, " %6dk", parts->size);
3fdadc70 741 break;
742 }
2a1ca944 743 if (parts->type != 'd') {
744 if (mimeGetViewOption(parts->name)) {
745 snprintf(view, 2048, " <A HREF=\"%s;type=a\"><IMG BORDER=0 SRC=\"%s\" "
0cdcddb9 746 "ALT=\"[VIEW]\"></A>",
2a1ca944 747 href, mimeGetIconURL("internal-view"));
748 }
749 if (mimeGetDownloadOption(parts->name)) {
750 snprintf(download, 2048, " <A HREF=\"%s;type=i\"><IMG BORDER=0 SRC=\"%s\" "
0cdcddb9 751 "ALT=\"[DOWNLOAD]\"></A>",
2a1ca944 752 href, mimeGetIconURL("internal-download"));
753 }
754 }
755 /* <A HREF="{href}">{icon}</A> <A HREF="{href}">{text}</A> . . . {date}{size}{chdir}{view}{download}{link}\n */
756 if (parts->type != '\0') {
757 snprintf(html, 8192, "<A HREF=\"%s\">%s</A> <A HREF=\"%s\">%s</A>%s "
0cdcddb9 758 "%s%8s%s%s%s%s\n",
2a1ca944 759 href, icon, href, text, dots_fill(strlen(text)),
760 parts->date, size, chdir, view, download, link);
761 } else {
762 /* Plain listing. {icon} {text} ... {chdir}{view}{download} */
763 snprintf(html, 8192, "<A HREF=\"%s\">%s</A> <A HREF=\"%s\">%s</A>%s "
0cdcddb9 764 "%s%s%s%s\n",
2a1ca944 765 href, icon, href, text, dots_fill(strlen(text)),
766 chdir, view, download, link);
767 }
3fdadc70 768 ftpListPartsFree(&parts);
3fdadc70 769 return html;
770}
771
772static void
4f310655 773ftpParseListing(FtpStateData * ftpState)
3fdadc70 774{
775 char *buf = ftpState->data.buf;
7131112f 776 char *sbuf; /* NULL-terminated copy of buf */
b5639035 777 char *end;
778 char *line;
3fdadc70 779 char *s;
780 char *t;
781 size_t linelen;
b5639035 782 size_t usable;
3fdadc70 783 StoreEntry *e = ftpState->entry;
4f310655 784 int len = ftpState->data.offset;
7131112f 785 /*
786 * We need a NULL-terminated buffer for scanning, ick
787 */
788 sbuf = xmalloc(len + 1);
789 xstrncpy(sbuf, buf, len + 1);
790 end = sbuf + len - 1;
791 while (*end != '\r' && *end != '\n' && end > sbuf)
3fdadc70 792 end--;
7131112f 793 usable = end - sbuf;
5999b776 794 debug(9, 3) ("ftpParseListing: usable = %d\n", usable);
b5639035 795 if (usable == 0) {
9fb13bb6 796 debug(9, 3) ("ftpParseListing: didn't find end for %s\n", storeUrl(e));
7131112f 797 xfree(sbuf);
3fdadc70 798 return;
799 }
7131112f 800 debug(9, 3) ("ftpParseListing: %d bytes to play with\n", len);
7021844c 801 line = memAllocate(MEM_4K_BUF);
3fdadc70 802 end++;
438fc1e3 803 storeBuffer(e);
362be274 804 s = sbuf;
805 s += strspn(s, crlf);
806 for (; s < end; s += strcspn(s, crlf), s += strspn(s, crlf)) {
7131112f 807 debug(9, 3) ("ftpParseListing: s = {%s}\n", s);
3fdadc70 808 linelen = strcspn(s, crlf) + 1;
fc09761c 809 if (linelen < 2)
810 break;
3fdadc70 811 if (linelen > 4096)
812 linelen = 4096;
813 xstrncpy(line, s, linelen);
7131112f 814 debug(9, 7) ("ftpParseListing: {%s}\n", line);
3fdadc70 815 if (!strncmp(line, "total", 5))
816 continue;
dbfed404 817 t = ftpHtmlifyListEntry(line, ftpState);
3fdadc70 818 assert(t != NULL);
819 storeAppend(e, t, strlen(t));
820 }
438fc1e3 821 storeBufferFlush(e);
b5639035 822 assert(usable <= len);
823 if (usable < len) {
824 /* must copy partial line to beginning of buf */
e29f7586 825 linelen = len - usable;
b5639035 826 if (linelen > 4096)
827 linelen = 4096;
828 xstrncpy(line, end, linelen);
829 xstrncpy(ftpState->data.buf, line, ftpState->data.size);
830 ftpState->data.offset = strlen(ftpState->data.buf);
831 }
db1cd23c 832 memFree(line, MEM_4K_BUF);
4a2635aa 833 xfree(sbuf);
3fdadc70 834}
090089c4 835
79a15e0a 836static void
837ftpReadComplete(FtpStateData * ftpState)
838{
4cca8b93 839 debug(9, 3) ("ftpReadComplete\n");
79a15e0a 840 /* Connection closed; retrieval done. */
9bc73deb 841 if (ftpState->data.fd > -1) {
842 /*
843 * close data socket so it does not occupy resources while
844 * we wait
845 */
846 comm_close(ftpState->data.fd);
847 ftpState->data.fd = -1;
54220df8 848 }
79a15e0a 849 /* expect the "transfer complete" message on the control socket */
05491dc4 850 ftpScheduleReadControlReply(ftpState, 1);
79a15e0a 851}
852
582b6456 853static void
dbfed404 854ftpDataRead(int fd, void *data)
090089c4 855{
582b6456 856 FtpStateData *ftpState = data;
090089c4 857 int len;
a57512fa 858 int j;
30a4f2a8 859 int bin;
bfcaf585 860 StoreEntry *entry = ftpState->entry;
79a15e0a 861 MemObject *mem = entry->mem_obj;
447e176b 862 size_t read_sz;
863#if DELAY_POOLS
864 delay_id delay_id = delayMostBytesAllowed(mem);
865#endif
3fdadc70 866 assert(fd == ftpState->data.fd);
e92e4e44 867 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
08ce47ab 868 comm_close(ftpState->ctrl.fd);
b8890359 869 return;
e92e4e44 870 }
1a6e21ac 871 errno = 0;
447e176b 872 read_sz = ftpState->data.size - ftpState->data.offset;
873#if DELAY_POOLS
56e64999 874 read_sz = delayBytesWanted(delay_id, 1, read_sz);
447e176b 875#endif
876 memset(ftpState->data.buf + ftpState->data.offset, '\0', read_sz);
886f2785 877 Counter.syscalls.sock.reads++;
447e176b 878 len = read(fd, ftpState->data.buf + ftpState->data.offset, read_sz);
ee1679df 879 if (len > 0) {
880 fd_bytes(fd, len, FD_READ);
447e176b 881#if DELAY_POOLS
882 delayBytesIn(delay_id, len);
883#endif
a0f32775 884 kb_incr(&Counter.server.all.kbytes_in, len);
885 kb_incr(&Counter.server.ftp.kbytes_in, len);
4f310655 886 ftpState->data.offset += len;
ee1679df 887 }
dbfed404 888 debug(9, 5) ("ftpDataRead: FD %d, Read %d bytes\n", fd, len);
30a4f2a8 889 if (len > 0) {
4a63c85f 890 IOStats.Ftp.reads++;
a57512fa 891 for (j = len - 1, bin = 0; j; bin++)
892 j >>= 1;
30a4f2a8 893 IOStats.Ftp.read_hist[bin]++;
894 }
ee16d4ab 895 if (ftpState->flags.isdir && !ftpState->flags.html_header_sent && len >= 0) {
896 ftpListingStart(ftpState);
897 }
ba718c8f 898 if (len < 0) {
3b3a620c 899 debug(50, ignoreErrno(errno) ? 3 : 1) ("ftpDataRead: read error: %s\n", xstrerror());
b224ea98 900 if (ignoreErrno(errno)) {
a57512fa 901 commSetSelect(fd,
902 COMM_SELECT_READ,
dbfed404 903 ftpDataRead,
a57512fa 904 data,
905 Config.Timeout.read);
6fe6313d 906 } else {
9bc73deb 907 ftpFailed(ftpState, ERR_READ_ERROR);
908 /* ftpFailed closes ctrl.fd and frees ftpState */
909 return;
6fe6313d 910 }
090089c4 911 } else if (len == 0) {
79a15e0a 912 ftpReadComplete(ftpState);
090089c4 913 } else {
e55f0142 914 if (ftpState->flags.isdir) {
4f310655 915 ftpParseListing(ftpState);
b5639035 916 } else {
b5639035 917 storeAppend(entry, ftpState->data.buf, len);
4f310655 918 ftpState->data.offset = 0;
b5639035 919 }
48451fb1 920 if (ftpState->size > 0 && mem->inmem_hi >= ftpState->size + mem->reply->hdr_sz)
79a15e0a 921 ftpReadComplete(ftpState);
922 else
923 commSetSelect(fd,
924 COMM_SELECT_READ,
dbfed404 925 ftpDataRead,
79a15e0a 926 data,
927 Config.Timeout.read);
090089c4 928 }
090089c4 929}
930
429fdbec 931/*
932 * ftpCheckAuth
933 *
934 * Return 1 if we have everything needed to complete this request.
935 * Return 0 if something is missing.
936 */
937static int
5999b776 938ftpCheckAuth(FtpStateData * ftpState, const HttpHeader * req_hdr)
429fdbec 939{
940 char *orig_user;
63259c34 941 const char *auth;
c68e9c6b 942 ftpLoginParser(ftpState->request->login, ftpState, FTP_LOGIN_ESCAPED);
9bc73deb 943 if (!ftpState->user[0])
944 return 1; /* no name */
945 if (ftpState->password_url || ftpState->password[0])
946 return 1; /* passwd provided in URL */
429fdbec 947 /* URL has name, but no passwd */
99edd1c3 948 if (!(auth = httpHeaderGetAuth(req_hdr, HDR_AUTHORIZATION, "Basic")))
429fdbec 949 return 0; /* need auth header */
c68e9c6b 950 ftpState->flags.authenticated = 1;
429fdbec 951 orig_user = xstrdup(ftpState->user);
c68e9c6b 952 ftpLoginParser(auth, ftpState, FTP_LOGIN_NOT_ESCAPED);
429fdbec 953 if (!strcmp(orig_user, ftpState->user)) {
954 xfree(orig_user);
955 return 1; /* same username */
956 }
957 strcpy(ftpState->user, orig_user);
958 xfree(orig_user);
959 return 0; /* different username */
960}
961
13e80e5b 962static void
963ftpCheckUrlpath(FtpStateData * ftpState)
964{
965 request_t *request = ftpState->request;
966 int l;
02922e76 967 const char *t;
968 if ((t = strRChr(request->urlpath, ';')) != NULL) {
dbfed404 969 if (strncasecmp(t + 1, "type=", 5) == 0) {
970 ftpState->typecode = (char) toupper((int) *(t + 6));
4d62b0af 971 strCutPtr(request->urlpath, t);
dbfed404 972 }
973 }
02922e76 974 l = strLen(request->urlpath);
e55f0142 975 ftpState->flags.use_base = 1;
13e80e5b 976 /* check for null path */
02922e76 977 if (!l) {
e55f0142 978 ftpState->flags.isdir = 1;
979 ftpState->flags.root_dir = 1;
02922e76 980 } else if (!strCmp(request->urlpath, "/%2f/")) {
aac53724 981 /* UNIX root directory */
982 ftpState->flags.use_base = 0;
e55f0142 983 ftpState->flags.isdir = 1;
984 ftpState->flags.root_dir = 1;
02922e76 985 } else if ((l >= 1) && (*(strBuf(request->urlpath) + l - 1) == '/')) {
aac53724 986 /* Directory URL, ending in / */
e55f0142 987 ftpState->flags.isdir = 1;
988 ftpState->flags.use_base = 0;
13e80e5b 989 if (l == 1)
e55f0142 990 ftpState->flags.root_dir = 1;
13e80e5b 991 }
992}
993
3fdadc70 994static void
995ftpBuildTitleUrl(FtpStateData * ftpState)
996{
997 request_t *request = ftpState->request;
998 size_t len;
999 char *t;
1000 len = 64
1001 + strlen(ftpState->user)
1002 + strlen(ftpState->password)
1003 + strlen(request->host)
02922e76 1004 + strLen(request->urlpath);
3fdadc70 1005 t = ftpState->title_url = xcalloc(len, 1);
1006 strcat(t, "ftp://");
1007 if (strcmp(ftpState->user, "anonymous")) {
1008 strcat(t, ftpState->user);
1009 strcat(t, "@");
1010 }
1011 strcat(t, request->host);
1012 if (request->port != urlDefaultPort(PROTO_FTP))
56878878 1013 snprintf(&t[strlen(t)], len - strlen(t), ":%d", request->port);
02922e76 1014 strcat(t, strBuf(request->urlpath));
9bc73deb 1015 t = ftpState->base_href = xcalloc(len, 1);
1016 strcat(t, "ftp://");
1017 if (strcmp(ftpState->user, "anonymous")) {
1018 strcat(t, rfc1738_escape_part(ftpState->user));
1019 if (ftpState->password_url) {
1020 strcat(t, ":");
1021 strcat(t, rfc1738_escape_part(ftpState->password));
1022 }
1023 strcat(t, "@");
1024 }
1025 strcat(t, request->host);
1026 if (request->port != urlDefaultPort(PROTO_FTP))
1027 snprintf(&t[strlen(t)], len - strlen(t), ":%d", request->port);
1028 strcat(t, strBuf(request->urlpath));
1029 strcat(t, "/");
3fdadc70 1030}
1031
770f051d 1032void
db1cd23c 1033ftpStart(FwdState * fwd)
0a0bf5db 1034{
db1cd23c 1035 request_t *request = fwd->request;
1036 StoreEntry *entry = fwd->entry;
1037 int fd = fwd->server_fd;
0a0bf5db 1038 LOCAL_ARRAY(char, realm, 8192);
9fb13bb6 1039 const char *url = storeUrl(entry);
5c5783a2 1040 FtpStateData *ftpState = xcalloc(1, sizeof(FtpStateData));
a0f32775 1041 HttpReply *reply;
c68e9c6b 1042 StoreEntry *pe = NULL;
1043 const cache_key *key = NULL;
db1cd23c 1044 cbdataAdd(ftpState, cbdataXfree, 0);
5fb59f68 1045 debug(9, 3) ("ftpStart: '%s'\n", url);
a0f32775 1046 Counter.server.all.requests++;
1047 Counter.server.ftp.requests++;
770f051d 1048 storeLockObject(entry);
5c5783a2 1049 ftpState->entry = entry;
5c5783a2 1050 ftpState->request = requestLink(request);
41462d93 1051 ftpState->ctrl.fd = fd;
3fdadc70 1052 ftpState->data.fd = -1;
a533dc81 1053 ftpState->size = -1;
6b8e7481 1054 ftpState->mdtm = -1;
9bc73deb 1055 ftpState->flags.pasv_supported = !fwd->flags.ftp_pasv_failed;
e55f0142 1056 ftpState->flags.rest_supported = 1;
db1cd23c 1057 ftpState->fwd = fwd;
54768eba 1058 comm_add_close_handler(fd, ftpStateFree, ftpState);
54220df8 1059 if (ftpState->request->method == METHOD_PUT)
e55f0142 1060 ftpState->flags.put = 1;
99edd1c3 1061 if (!ftpCheckAuth(ftpState, &request->header)) {
429fdbec 1062 /* This request is not fully authenticated */
1063 if (request->port == 21) {
56878878 1064 snprintf(realm, 8192, "ftp %s", ftpState->user);
429fdbec 1065 } else {
56878878 1066 snprintf(realm, 8192, "ftp %s port %d",
5c5783a2 1067 ftpState->user, request->port);
e381a13d 1068 }
c68e9c6b 1069 /* eject any old cached object */
1070 key = storeKeyPublic(entry->mem_obj->url, entry->mem_obj->method);
1071 if ((pe = storeGet(key)) != NULL)
1072 storeRelease(pe);
63259c34 1073 /* create reply */
a0f32775 1074 reply = entry->mem_obj->reply;
1075 assert(reply != NULL);
1076 /* create appropriate reply */
1077 ftpAuthRequired(reply, request, realm);
1078 httpReplySwapOut(reply, entry);
db1cd23c 1079 fwdComplete(ftpState->fwd);
54768eba 1080 comm_close(fd);
429fdbec 1081 return;
e381a13d 1082 }
13e80e5b 1083 ftpCheckUrlpath(ftpState);
3fdadc70 1084 ftpBuildTitleUrl(ftpState);
5fb59f68 1085 debug(9, 5) ("ftpStart: host=%s, path=%s, user=%s, passwd=%s\n",
02922e76 1086 ftpState->request->host, strBuf(ftpState->request->urlpath),
5c5783a2 1087 ftpState->user, ftpState->password);
41462d93 1088 ftpState->state = BEGIN;
54768eba 1089 ftpState->ctrl.last_command = xstrdup("Connect to server");
41462d93 1090 ftpState->ctrl.buf = memAllocate(MEM_4K_BUF);
1091 ftpState->ctrl.freefunc = memFree4K;
1092 ftpState->ctrl.size = 4096;
1093 ftpState->ctrl.offset = 0;
1094 ftpState->data.buf = xmalloc(SQUID_TCP_SO_RCVBUF);
1095 ftpState->data.size = SQUID_TCP_SO_RCVBUF;
1096 ftpState->data.freefunc = xfree;
05491dc4 1097 ftpScheduleReadControlReply(ftpState, 0);
090089c4 1098}
1099
3fdadc70 1100/* ====================================================================== */
1101
b8d8561b 1102static void
3fdadc70 1103ftpWriteCommand(const char *buf, FtpStateData * ftpState)
234967c9 1104{
a3d5953d 1105 debug(9, 5) ("ftpWriteCommand: %s\n", buf);
b9916917 1106 safe_free(ftpState->ctrl.last_command);
9bc73deb 1107 safe_free(ftpState->ctrl.last_reply);
b9916917 1108 ftpState->ctrl.last_command = xstrdup(buf);
3fdadc70 1109 comm_write(ftpState->ctrl.fd,
1110 xstrdup(buf),
1111 strlen(buf),
1112 ftpWriteCommandCallback,
1113 ftpState,
1114 xfree);
05491dc4 1115 ftpScheduleReadControlReply(ftpState, 0);
3fdadc70 1116}
1117
1118static void
79a15e0a 1119ftpWriteCommandCallback(int fd, char *bufnotused, size_t size, int errflag, void *data)
3fdadc70 1120{
1121 FtpStateData *ftpState = data;
a3d5953d 1122 debug(9, 7) ("ftpWriteCommandCallback: wrote %d bytes\n", size);
ee1679df 1123 if (size > 0) {
1124 fd_bytes(fd, size, FD_WRITE);
a0f32775 1125 kb_incr(&Counter.server.all.kbytes_out, size);
399e85ea 1126 kb_incr(&Counter.server.ftp.kbytes_out, size);
ee1679df 1127 }
96f1be5d 1128 if (errflag == COMM_ERR_CLOSING)
1129 return;
3fdadc70 1130 if (errflag) {
270b86af 1131 debug(50, 1) ("ftpWriteCommandCallback: FD %d: %s\n", fd, xstrerror());
9bc73deb 1132 ftpFailed(ftpState, ERR_WRITE_ERROR);
1133 /* ftpFailed closes ctrl.fd and frees ftpState */
1134 return;
3fdadc70 1135 }
1136}
1137
1138static wordlist *
4f310655 1139ftpParseControlReply(char *buf, size_t len, int *codep, int *used)
3fdadc70 1140{
1141 char *s;
4f310655 1142 char *sbuf;
1143 char *end;
1144 int usable;
3fdadc70 1145 int complete = 0;
51eeadc6 1146 wordlist *head = NULL;
3fdadc70 1147 wordlist *list;
1148 wordlist **tail = &head;
1149 off_t offset;
1150 size_t linelen;
b5639035 1151 int code = -1;
a3d5953d 1152 debug(9, 5) ("ftpParseControlReply\n");
4f310655 1153 /*
1154 * We need a NULL-terminated buffer for scanning, ick
1155 */
1156 sbuf = xmalloc(len + 1);
1157 xstrncpy(sbuf, buf, len + 1);
1158 end = sbuf + len - 1;
1159 while (*end != '\r' && *end != '\n' && end > sbuf)
1b28db46 1160 end--;
4f310655 1161 usable = end - sbuf;
1162 debug(9, 3) ("ftpParseControlReply: usable = %d\n", usable);
1163 if (usable == 0) {
1b28db46 1164 debug(9, 3) ("ftpParseControlReply: didn't find end of line\n");
5fff72e3 1165 safe_free(sbuf);
1b28db46 1166 return NULL;
4f310655 1167 }
1168 debug(9, 3) ("ftpParseControlReply: %d bytes to play with\n", len);
1169 end++;
1170 s = sbuf;
1171 s += strspn(s, crlf);
1172 for (; s < end; s += strcspn(s, crlf), s += strspn(s, crlf)) {
1173 if (complete)
1174 break;
1b28db46 1175 debug(9, 3) ("ftpParseControlReply: s = {%s}\n", s);
3fdadc70 1176 linelen = strcspn(s, crlf) + 1;
fc09761c 1177 if (linelen < 2)
1178 break;
3fdadc70 1179 if (linelen > 3)
1180 complete = (*s >= '0' && *s <= '9' && *(s + 3) == ' ');
1181 if (complete)
1182 code = atoi(s);
1183 offset = 0;
1184 if (linelen > 3)
1185 if (*s >= '0' && *s <= '9' && (*(s + 3) == '-' || *(s + 3) == ' '))
1186 offset = 4;
c68e9c6b 1187 list = memAllocate(MEM_WORDLIST);
3fdadc70 1188 list->key = xmalloc(linelen - offset);
1189 xstrncpy(list->key, s + offset, linelen - offset);
4939c5da 1190 debug(9, 7) ("%d %s\n", code, list->key);
3fdadc70 1191 *tail = list;
1192 tail = &list->next;
1193 }
4f310655 1194 *used = (int) (s - sbuf);
1c34d125 1195 safe_free(sbuf);
3fdadc70 1196 if (!complete)
1197 wordlistDestroy(&head);
1198 if (codep)
1199 *codep = code;
1200 return head;
1201}
1202
4f310655 1203static void
1b28db46 1204ftpScheduleReadControlReply(FtpStateData * ftpState, int buffered_ok)
4f310655 1205{
1b28db46 1206 debug(9, 3) ("ftpScheduleReadControlReply: FD %d\n", ftpState->ctrl.fd);
05491dc4 1207 if (buffered_ok && ftpState->ctrl.offset > 0) {
4f310655 1208 /* We've already read some reply data */
1209 ftpHandleControlReply(ftpState);
1210 } else {
1b28db46 1211 commSetSelect(ftpState->ctrl.fd,
4f310655 1212 COMM_SELECT_READ,
1213 ftpReadControlReply,
1214 ftpState,
1215 Config.Timeout.read);
7e3ce7b9 1216 /*
1217 * Cancel the timeout on the Data socket (if any) and
1218 * establish one on the control socket.
1219 */
1220 if (ftpState->data.fd > -1)
1221 commSetTimeout(ftpState->data.fd, -1, NULL, NULL);
1222 commSetTimeout(ftpState->ctrl.fd, Config.Timeout.read, ftpTimeout,
1223 ftpState);
4f310655 1224 }
1225}
1226
3fdadc70 1227static void
1228ftpReadControlReply(int fd, void *data)
1229{
1230 FtpStateData *ftpState = data;
1231 StoreEntry *entry = ftpState->entry;
3fdadc70 1232 int len;
a3d5953d 1233 debug(9, 5) ("ftpReadControlReply\n");
9bc73deb 1234 if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1235 comm_close(ftpState->ctrl.fd);
1236 return;
1237 }
3fdadc70 1238 assert(ftpState->ctrl.offset < ftpState->ctrl.size);
886f2785 1239 Counter.syscalls.sock.reads++;
3fdadc70 1240 len = read(fd,
1241 ftpState->ctrl.buf + ftpState->ctrl.offset,
1242 ftpState->ctrl.size - ftpState->ctrl.offset);
ee1679df 1243 if (len > 0) {
1244 fd_bytes(fd, len, FD_READ);
a0f32775 1245 kb_incr(&Counter.server.all.kbytes_in, len);
399e85ea 1246 kb_incr(&Counter.server.ftp.kbytes_in, len);
ee1679df 1247 }
a3d5953d 1248 debug(9, 5) ("ftpReadControlReply: FD %d, Read %d bytes\n", fd, len);
3fdadc70 1249 if (len < 0) {
3b3a620c 1250 debug(50, ignoreErrno(errno) ? 3 : 1) ("ftpReadControlReply: read error: %s\n", xstrerror());
b224ea98 1251 if (ignoreErrno(errno)) {
05491dc4 1252 ftpScheduleReadControlReply(ftpState, 0);
3fdadc70 1253 } else {
9bc73deb 1254 ftpFailed(ftpState, ERR_READ_ERROR);
1255 /* ftpFailed closes ctrl.fd and frees ftpState */
1256 return;
3fdadc70 1257 }
1258 return;
1259 }
1260 if (len == 0) {
cc11e161 1261 if (entry->store_status == STORE_PENDING) {
9bc73deb 1262 ftpFailed(ftpState, ERR_FTP_FAILURE);
1263 /* ftpFailed closes ctrl.fd and frees ftpState */
1264 return;
9b312a19 1265 }
ff008d84 1266 comm_close(ftpState->ctrl.fd);
3fdadc70 1267 return;
1268 }
b5639035 1269 len += ftpState->ctrl.offset;
1270 ftpState->ctrl.offset = len;
3fdadc70 1271 assert(len <= ftpState->ctrl.size);
4f310655 1272 ftpHandleControlReply(ftpState);
1273}
1274
1275static void
1276ftpHandleControlReply(FtpStateData * ftpState)
1277{
1278 char *oldbuf;
ec603b25 1279 wordlist **W;
4f310655 1280 int bytes_used = 0;
3fdadc70 1281 wordlistDestroy(&ftpState->ctrl.message);
4f310655 1282 ftpState->ctrl.message = ftpParseControlReply(ftpState->ctrl.buf,
1283 ftpState->ctrl.offset, &ftpState->ctrl.replycode, &bytes_used);
05491dc4 1284 if (ftpState->ctrl.message == NULL) {
4f310655 1285 /* didn't get complete reply yet */
4f310655 1286 if (ftpState->ctrl.offset == ftpState->ctrl.size) {
3fdadc70 1287 oldbuf = ftpState->ctrl.buf;
1288 ftpState->ctrl.buf = xcalloc(ftpState->ctrl.size << 1, 1);
1289 xmemcpy(ftpState->ctrl.buf, oldbuf, ftpState->ctrl.size);
1290 ftpState->ctrl.size <<= 1;
1291 ftpState->ctrl.freefunc(oldbuf);
1292 ftpState->ctrl.freefunc = xfree;
1293 }
05491dc4 1294 ftpScheduleReadControlReply(ftpState, 0);
3fdadc70 1295 return;
05491dc4 1296 } else if (ftpState->ctrl.offset == bytes_used) {
1297 /* used it all up */
1298 ftpState->ctrl.offset = 0;
4f310655 1299 } else {
1300 /* Got some data past the complete reply */
1301 assert(bytes_used < ftpState->ctrl.offset);
1302 ftpState->ctrl.offset -= bytes_used;
1303 xmemmove(ftpState->ctrl.buf, ftpState->ctrl.buf + bytes_used,
1304 ftpState->ctrl.offset);
3fdadc70 1305 }
ec603b25 1306 /* Find the last line of the reply message */
1307 for (W = &ftpState->ctrl.message; (*W)->next; W = &(*W)->next);
b9916917 1308 safe_free(ftpState->ctrl.last_reply);
1309 ftpState->ctrl.last_reply = (*W)->key;
3fdadc70 1310 safe_free(*W);
4fc773f7 1311 debug(9, 8) ("ftpHandleControlReply: state=%d, code=%d\n", ftpState->state,
4f310655 1312 ftpState->ctrl.replycode);
3fdadc70 1313 FTP_SM_FUNCS[ftpState->state] (ftpState);
234967c9 1314}
1315
3fdadc70 1316/* ====================================================================== */
1317
1318static void
1319ftpReadWelcome(FtpStateData * ftpState)
1320{
1321 int code = ftpState->ctrl.replycode;
a3d5953d 1322 debug(9, 3) ("ftpReadWelcome\n");
e55f0142 1323 if (ftpState->flags.pasv_only)
3fdadc70 1324 ftpState->login_att++;
9bc73deb 1325 /* Dont retry if the FTP server accepted the connection */
1326 ftpState->fwd->flags.dont_retry = 1;
3fdadc70 1327 if (code == 220) {
4d62b0af 1328 if (ftpState->ctrl.message) {
3fdadc70 1329 if (strstr(ftpState->ctrl.message->key, "NetWare"))
e55f0142 1330 ftpState->flags.skip_whitespace = 1;
4d62b0af 1331 if (ftpState->cwd_message)
1332 wordlistDestroy(&ftpState->cwd_message);
1333 ftpState->cwd_message = ftpState->ctrl.message;
1334 ftpState->ctrl.message = NULL;
1335 }
969c39b9 1336 ftpSendUser(ftpState);
cdc33f35 1337 } else if (code == 120) {
c3b838d4 1338 if (NULL != ftpState->ctrl.message)
1339 debug(9, 3) ("FTP server is busy: %s\n",
1340 ftpState->ctrl.message->key);
cdc33f35 1341 return;
3fdadc70 1342 } else {
1343 ftpFail(ftpState);
1344 }
1345}
1346
969c39b9 1347static void
1348ftpSendUser(FtpStateData * ftpState)
1349{
1350 if (ftpState->proxy_host != NULL)
1351 snprintf(cbuf, 1024, "USER %s@%s\r\n",
1352 ftpState->user,
1353 ftpState->request->host);
1354 else
1355 snprintf(cbuf, 1024, "USER %s\r\n", ftpState->user);
1356 ftpWriteCommand(cbuf, ftpState);
1357 ftpState->state = SENT_USER;
1358}
1359
3fdadc70 1360static void
1361ftpReadUser(FtpStateData * ftpState)
234967c9 1362{
3fdadc70 1363 int code = ftpState->ctrl.replycode;
a3d5953d 1364 debug(9, 3) ("ftpReadUser\n");
3fdadc70 1365 if (code == 230) {
1366 ftpReadPass(ftpState);
1367 } else if (code == 331) {
969c39b9 1368 ftpSendPass(ftpState);
3fdadc70 1369 } else {
1370 ftpFail(ftpState);
1371 }
1372}
1373
969c39b9 1374static void
1375ftpSendPass(FtpStateData * ftpState)
1376{
1377 snprintf(cbuf, 1024, "PASS %s\r\n", ftpState->password);
1378 ftpWriteCommand(cbuf, ftpState);
1379 ftpState->state = SENT_PASS;
1380}
1381
3fdadc70 1382static void
1383ftpReadPass(FtpStateData * ftpState)
1384{
1385 int code = ftpState->ctrl.replycode;
a3d5953d 1386 debug(9, 3) ("ftpReadPass\n");
3fdadc70 1387 if (code == 230) {
4fc773f7 1388 if (ftpState->ctrl.message) {
1389 if (ftpState->cwd_message)
1390 wordlistDestroy(&ftpState->cwd_message);
1391 ftpState->cwd_message = ftpState->ctrl.message;
1392 ftpState->ctrl.message = NULL;
1393 }
969c39b9 1394 ftpSendType(ftpState);
3fdadc70 1395 } else {
1396 ftpFail(ftpState);
1397 }
1398}
1399
969c39b9 1400static void
1401ftpSendType(FtpStateData * ftpState)
1402{
02922e76 1403 const char *t;
1404 const char *filename;
969c39b9 1405 char mode;
9e242e02 1406 /*
1407 * Ref section 3.2.2 of RFC 1738
1408 */
1409 switch (mode = ftpState->typecode) {
1410 case 'D':
1411 mode = 'A';
1412 break;
1413 case 'A':
1414 case 'I':
1415 break;
1416 default:
e55f0142 1417 if (ftpState->flags.isdir) {
dbfed404 1418 mode = 'A';
1419 } else {
02922e76 1420 t = strRChr(ftpState->request->urlpath, '/');
1421 filename = t ? t + 1 : strBuf(ftpState->request->urlpath);
dbfed404 1422 mode = mimeGetTransferMode(filename);
1423 }
9e242e02 1424 break;
1425 }
969c39b9 1426 if (mode == 'I')
e55f0142 1427 ftpState->flags.binary = 1;
cfbf5373 1428 else
1429 ftpState->flags.binary = 0;
969c39b9 1430 snprintf(cbuf, 1024, "TYPE %c\r\n", mode);
1431 ftpWriteCommand(cbuf, ftpState);
1432 ftpState->state = SENT_TYPE;
1433}
1434
3fdadc70 1435static void
1436ftpReadType(FtpStateData * ftpState)
1437{
1438 int code = ftpState->ctrl.replycode;
3fdadc70 1439 char *path;
6e5ae4a4 1440 char *d, *p;
a3d5953d 1441 debug(9, 3) ("This is ftpReadType\n");
3fdadc70 1442 if (code == 200) {
4c75f031 1443 p = path = xstrdup(strBuf(ftpState->request->urlpath));
1444 if (*p == '/')
1445 p++;
1446 while (*p) {
1447 d = p;
6e5ae4a4 1448 p += strcspn(p, "/");
1449 if (*p)
1450 *p++ = '\0';
13e80e5b 1451 rfc1738_unescape(d);
c68e9c6b 1452 wordlistAdd(&ftpState->pathcomps, d);
3fdadc70 1453 }
13e80e5b 1454 xfree(path);
969c39b9 1455 if (ftpState->pathcomps)
1456 ftpTraverseDirectory(ftpState);
1457 else
dbfed404 1458 ftpListDir(ftpState);
3fdadc70 1459 } else {
1460 ftpFail(ftpState);
1461 }
1462}
1463
1464static void
969c39b9 1465ftpTraverseDirectory(FtpStateData * ftpState)
3fdadc70 1466{
1467 wordlist *w;
0f169992 1468 debug(9, 4) ("ftpTraverseDirectory %s\n",
1469 ftpState->filepath ? ftpState->filepath : "<NULL>");
969c39b9 1470
1471 safe_free(ftpState->filepath);
1472 /* Done? */
1473 if (ftpState->pathcomps == NULL) {
a3d5953d 1474 debug(9, 3) ("the final component was a directory\n");
dbfed404 1475 ftpListDir(ftpState);
234967c9 1476 return;
3fdadc70 1477 }
969c39b9 1478 /* Go to next path component */
1479 w = ftpState->pathcomps;
1480 ftpState->filepath = w->key;
1481 ftpState->pathcomps = w->next;
1482 xfree(w);
1483 /* Check if we are to CWD or RETR */
e55f0142 1484 if (ftpState->pathcomps != NULL || ftpState->flags.isdir) {
969c39b9 1485 ftpSendCwd(ftpState);
1486 } else {
1487 debug(9, 3) ("final component is probably a file\n");
dbfed404 1488 ftpGetFile(ftpState);
969c39b9 1489 return;
1490 }
1491}
1492
1493static void
1494ftpSendCwd(FtpStateData * ftpState)
1495{
1496 char *path = ftpState->filepath;
1497 debug(9, 3) ("ftpSendCwd\n");
1498 if (!strcmp(path, "..") || !strcmp(path, "/")) {
e55f0142 1499 ftpState->flags.no_dotdot = 1;
13e80e5b 1500 } else {
e55f0142 1501 ftpState->flags.no_dotdot = 0;
13e80e5b 1502 }
6e5ae4a4 1503 if (*path)
1504 snprintf(cbuf, 1024, "CWD %s\r\n", path);
1505 else
1506 snprintf(cbuf, 1024, "CWD\r\n");
969c39b9 1507 ftpWriteCommand(cbuf, ftpState);
1508 ftpState->state = SENT_CWD;
3fdadc70 1509}
77a30ebb 1510
3fdadc70 1511static void
1512ftpReadCwd(FtpStateData * ftpState)
1513{
1514 int code = ftpState->ctrl.replycode;
a3d5953d 1515 debug(9, 3) ("This is ftpReadCwd\n");
3fdadc70 1516 if (code >= 200 && code < 300) {
969c39b9 1517 /* CWD OK */
0f169992 1518 ftpUnhack(ftpState);
3fdadc70 1519 if (ftpState->cwd_message)
1520 wordlistDestroy(&ftpState->cwd_message);
1521 ftpState->cwd_message = ftpState->ctrl.message;
1522 ftpState->ctrl.message = NULL;
969c39b9 1523 /* Continue to traverse the path */
1524 ftpTraverseDirectory(ftpState);
3fdadc70 1525 } else {
1526 /* CWD FAILED */
e55f0142 1527 if (!ftpState->flags.put)
4162ee3b 1528 ftpFail(ftpState);
54220df8 1529 else
4162ee3b 1530 ftpTryMkdir(ftpState);
c021888f 1531 }
3fdadc70 1532}
1533
54220df8 1534static void
4162ee3b 1535ftpTryMkdir(FtpStateData * ftpState)
54220df8 1536{
4162ee3b 1537 char *path = ftpState->filepath;
1538 debug(9, 3) ("ftpTryMkdir: with path=%s\n", path);
1539 snprintf(cbuf, 1024, "MKD %s\r\n", path);
1540 ftpWriteCommand(cbuf, ftpState);
1541 ftpState->state = SENT_MKDIR;
54220df8 1542}
1543
1544static void
4162ee3b 1545ftpReadMkdir(FtpStateData * ftpState)
1546{
1547 char *path = ftpState->filepath;
1548 int code = ftpState->ctrl.replycode;
1549
c3b838d4 1550 debug(9, 3) ("ftpReadMkdir: path %s, code %d\n", path, code);
4162ee3b 1551 if (code == 257) { /* success */
1552 ftpSendCwd(ftpState);
1553 } else if (code == 550) { /* dir exists */
e55f0142 1554 if (ftpState->flags.put_mkdir) {
1555 ftpState->flags.put_mkdir = 1;
4162ee3b 1556 ftpSendCwd(ftpState);
1557 } else
1558 ftpSendReply(ftpState);
1559 } else
1560 ftpSendReply(ftpState);
54220df8 1561}
1562
dbfed404 1563static void
1564ftpGetFile(FtpStateData * ftpState)
1565{
1566 assert(*ftpState->filepath != '\0');
e55f0142 1567 ftpState->flags.isdir = 0;
dbfed404 1568 ftpSendMdtm(ftpState);
1569}
1570
1571static void
1572ftpListDir(FtpStateData * ftpState)
1573{
e55f0142 1574 if (!ftpState->flags.isdir) {
dbfed404 1575 debug(9, 3) ("Directory path did not end in /\n");
1576 strcat(ftpState->title_url, "/");
e55f0142 1577 ftpState->flags.isdir = 1;
1578 ftpState->flags.use_base = 1;
dbfed404 1579 }
1580 ftpSendPasv(ftpState);
1581}
1582
969c39b9 1583static void
1584ftpSendMdtm(FtpStateData * ftpState)
1585{
1586 assert(*ftpState->filepath != '\0');
1587 snprintf(cbuf, 1024, "MDTM %s\r\n", ftpState->filepath);
1588 ftpWriteCommand(cbuf, ftpState);
1589 ftpState->state = SENT_MDTM;
1590}
1591
3fdadc70 1592static void
1593ftpReadMdtm(FtpStateData * ftpState)
1594{
1595 int code = ftpState->ctrl.replycode;
a3d5953d 1596 debug(9, 3) ("This is ftpReadMdtm\n");
3fdadc70 1597 if (code == 213) {
b9916917 1598 ftpState->mdtm = parse_iso3307_time(ftpState->ctrl.last_reply);
0f169992 1599 ftpUnhack(ftpState);
3fdadc70 1600 } else if (code < 0) {
1601 ftpFail(ftpState);
77a30ebb 1602 }
969c39b9 1603 ftpSendSize(ftpState);
1604}
1605
1606static void
1607ftpSendSize(FtpStateData * ftpState)
1608{
1609 /* Only send SIZE for binary transfers. The returned size
1610 * is useless on ASCII transfers */
e55f0142 1611 if (ftpState->flags.binary) {
969c39b9 1612 assert(ftpState->filepath != NULL);
1613 assert(*ftpState->filepath != '\0');
1614 snprintf(cbuf, 1024, "SIZE %s\r\n", ftpState->filepath);
1615 ftpWriteCommand(cbuf, ftpState);
1616 ftpState->state = SENT_SIZE;
1617 } else
1618 /* Skip to next state no non-binary transfers */
1619 ftpSendPasv(ftpState);
3fdadc70 1620}
1621
1622static void
1623ftpReadSize(FtpStateData * ftpState)
1624{
1625 int code = ftpState->ctrl.replycode;
a3d5953d 1626 debug(9, 3) ("This is ftpReadSize\n");
3fdadc70 1627 if (code == 213) {
0f169992 1628 ftpUnhack(ftpState);
b9916917 1629 ftpState->size = atoi(ftpState->ctrl.last_reply);
bc2f604d 1630 if (ftpState->size == 0) {
1631 debug(9, 2) ("ftpReadSize: SIZE reported %s on %s\n",
1632 ftpState->ctrl.last_reply,
1633 ftpState->title_url);
1634 ftpState->size = -1;
1635 }
3fdadc70 1636 } else if (code < 0) {
1637 ftpFail(ftpState);
1638 }
4939c5da 1639 ftpSendPasv(ftpState);
3fdadc70 1640}
1641
1642static void
1643ftpSendPasv(FtpStateData * ftpState)
1644{
1645 int fd;
cdc33f35 1646 struct sockaddr_in addr;
6637e3a5 1647 socklen_t addr_len;
7497ceef 1648 if (ftpState->request->method == METHOD_HEAD) {
1649 /* Terminate here for HEAD requests */
1650 ftpAppendSuccessHeader(ftpState);
1651 storeTimestampsSet(ftpState->entry);
1652 fwdComplete(ftpState->fwd);
1653 ftpSendQuit(ftpState);
1654 return;
1655 }
a57512fa 1656 if (ftpState->data.fd >= 0) {
e55f0142 1657 if (!ftpState->flags.datachannel_hack) {
0f169992 1658 /* We are already connected, reuse this connection. */
1659 ftpRestOrList(ftpState);
1660 return;
1661 } else {
1662 /* Close old connection */
1663 comm_close(ftpState->data.fd);
1664 ftpState->data.fd = -1;
1665 }
a57512fa 1666 }
e55f0142 1667 if (!ftpState->flags.pasv_supported) {
3fdadc70 1668 ftpSendPort(ftpState);
1669 return;
30a4f2a8 1670 }
cdc33f35 1671 addr_len = sizeof(addr);
1672 if (getsockname(ftpState->ctrl.fd, (struct sockaddr *) &addr, &addr_len)) {
1673 debug(9, 0) ("ftpSendPasv: getsockname(%d,..): %s\n",
1674 ftpState->ctrl.fd, xstrerror());
1675 addr.sin_addr = Config.Addrs.tcp_outgoing;
1676 }
1677 /* Open data channel with the same local address as control channel */
3fdadc70 1678 fd = comm_open(SOCK_STREAM,
16b204c4 1679 0,
cdc33f35 1680 addr.sin_addr,
30a4f2a8 1681 0,
3fdadc70 1682 COMM_NONBLOCKING,
9fb13bb6 1683 storeUrl(ftpState->entry));
05e11a8c 1684 debug(9, 3) ("ftpSendPasv: Unconnected data socket created on FD %d\n", fd);
3fdadc70 1685 if (fd < 0) {
1686 ftpFail(ftpState);
1687 return;
1688 }
ff008d84 1689 /*
1690 * No comm_add_close_handler() here. If we have both ctrl and
1691 * data FD's call ftpStateFree() upon close, then we have
1692 * to delete the close handler which did NOT get called
1693 * to prevent ftpStateFree() getting called twice.
1694 * Instead we'll always call comm_close() on the ctrl FD.
1695 */
3fdadc70 1696 ftpState->data.fd = fd;
042461c3 1697 snprintf(cbuf, 1024, "PASV\r\n");
3fdadc70 1698 ftpWriteCommand(cbuf, ftpState);
1699 ftpState->state = SENT_PASV;
7e3ce7b9 1700 /*
1701 * ugly hack for ftp servers like ftp.netscape.com that sometimes
1702 * dont acknowledge PORT commands.
1703 */
1704 commSetTimeout(ftpState->data.fd, 15, ftpTimeout, ftpState);
3fdadc70 1705}
1706
1707static void
1708ftpReadPasv(FtpStateData * ftpState)
1709{
1710 int code = ftpState->ctrl.replycode;
1711 int h1, h2, h3, h4;
1712 int p1, p2;
1713 int n;
1714 u_short port;
1715 int fd = ftpState->data.fd;
b9916917 1716 char *buf = ftpState->ctrl.last_reply;
3fdadc70 1717 LOCAL_ARRAY(char, junk, 1024);
a3d5953d 1718 debug(9, 3) ("This is ftpReadPasv\n");
3fdadc70 1719 if (code != 227) {
a3d5953d 1720 debug(9, 3) ("PASV not supported by remote end\n");
3fdadc70 1721 ftpSendPort(ftpState);
1722 return;
1723 }
69e81830 1724 if ((int) strlen(buf) > 1024) {
2a1bc30a 1725 debug(9, 1) ("ftpReadPasv: Avoiding potential buffer overflow\n");
3fdadc70 1726 ftpSendPort(ftpState);
1727 return;
1728 }
1729 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1730 /* ANSI sez [^0-9] is undefined, it breaks on Watcom cc */
a3d5953d 1731 debug(9, 5) ("scanning: %s\n", buf);
3fdadc70 1732 n = sscanf(buf, "%[^0123456789]%d,%d,%d,%d,%d,%d",
1733 junk, &h1, &h2, &h3, &h4, &p1, &p2);
1734 if (n != 7 || p1 < 0 || p2 < 0 || p1 > 255 || p2 > 255) {
a3d5953d 1735 debug(9, 3) ("Bad 227 reply\n");
1736 debug(9, 3) ("n=%d, p1=%d, p2=%d\n", n, p1, p2);
3fdadc70 1737 ftpSendPort(ftpState);
1738 return;
1739 }
56878878 1740 snprintf(junk, 1024, "%d.%d.%d.%d", h1, h2, h3, h4);
3fdadc70 1741 if (!safe_inet_addr(junk, NULL)) {
a3d5953d 1742 debug(9, 1) ("unsafe address (%s)\n", junk);
3fdadc70 1743 ftpSendPort(ftpState);
1744 return;
1745 }
1746 port = ((p1 << 8) + p2);
7f74df3a 1747 if (0 == port) {
1afe05c5 1748 debug(9, 1) ("ftpReadPasv: Invalid PASV reply: %s\n", buf);
7f74df3a 1749 ftpSendPort(ftpState);
1750 return;
1751 }
a3d5953d 1752 debug(9, 5) ("ftpReadPasv: connecting to %s, port %d\n", junk, port);
9b312a19 1753 ftpState->data.port = port;
1754 ftpState->data.host = xstrdup(junk);
9bc73deb 1755 safe_free(ftpState->ctrl.last_command);
1756 safe_free(ftpState->ctrl.last_reply);
1757 ftpState->ctrl.last_command = xstrdup("Connect to server data port");
3fdadc70 1758 commConnectStart(fd, junk, port, ftpPasvCallback, ftpState);
1759}
1760
1761static void
1762ftpPasvCallback(int fd, int status, void *data)
1763{
1764 FtpStateData *ftpState = data;
a3d5953d 1765 debug(9, 3) ("ftpPasvCallback\n");
9b312a19 1766 if (status != COMM_OK) {
9bc73deb 1767 debug(9, 2) ("ftpPasvCallback: failed to connect. Retrying without PASV.\n");
1768 ftpState->fwd->flags.dont_retry = 0; /* this is a retryable error */
1769 ftpState->fwd->flags.ftp_pasv_failed = 1;
1770 ftpFailed(ftpState, ERR_NONE);
1771 /* ftpFailed closes ctrl.fd and frees ftpState */
3fdadc70 1772 return;
1773 }
1774 ftpRestOrList(ftpState);
1775}
1776
cdc33f35 1777static int
1778ftpOpenListenSocket(FtpStateData * ftpState, int fallback)
1779{
1780 int fd;
1781 struct sockaddr_in addr;
6637e3a5 1782 socklen_t addr_len;
cdc33f35 1783 int on = 1;
1784 u_short port = 0;
7e3ce7b9 1785 /*
1786 * * Tear down any old data connection if any. We are about to
1787 * * establish a new one.
1788 */
1789 if (ftpState->data.fd > 0) {
1790 comm_close(ftpState->data.fd);
1791 ftpState->data.fd = -1;
1792 }
4f310655 1793 /*
1794 * Set up a listen socket on the same local address as the
1795 * control connection.
1796 */
cdc33f35 1797 addr_len = sizeof(addr);
1798 if (getsockname(ftpState->ctrl.fd, (struct sockaddr *) &addr, &addr_len)) {
1799 debug(9, 0) ("ftpOpenListenSocket: getsockname(%d,..): %s\n",
1800 ftpState->ctrl.fd, xstrerror());
1801 return -1;
1802 }
4f310655 1803 /*
1804 * REUSEADDR is needed in fallback mode, since the same port is
1805 * used for both control and data.
cdc33f35 1806 */
1807 if (fallback) {
1808 setsockopt(ftpState->ctrl.fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));
1809 port = ntohs(addr.sin_port);
1810 }
1811 fd = comm_open(SOCK_STREAM,
1812 0,
1813 addr.sin_addr,
1814 port,
1815 COMM_NONBLOCKING | (fallback ? COMM_REUSEADDR : 0),
1816 storeUrl(ftpState->entry));
05e11a8c 1817 debug(9, 3) ("ftpOpenListenSocket: Unconnected data socket created on FD %d\n", fd);
cdc33f35 1818 if (fd < 0) {
1819 debug(9, 0) ("ftpOpenListenSocket: comm_open failed\n");
1820 return -1;
1821 }
1822 if (comm_listen(fd) < 0) {
1823 comm_close(fd);
1824 return -1;
1825 }
1826 ftpState->data.fd = fd;
1827 ftpState->data.port = comm_local_port(fd);;
1828 ftpState->data.host = NULL;
1829 return fd;
1830}
1831
3fdadc70 1832static void
1833ftpSendPort(FtpStateData * ftpState)
1834{
cdc33f35 1835 int fd;
1836 struct sockaddr_in addr;
6637e3a5 1837 socklen_t addr_len;
cdc33f35 1838 unsigned char *addrptr;
1839 unsigned char *portptr;
a3d5953d 1840 debug(9, 3) ("This is ftpSendPort\n");
e55f0142 1841 ftpState->flags.pasv_supported = 0;
cdc33f35 1842 fd = ftpOpenListenSocket(ftpState, 0);
1843 addr_len = sizeof(addr);
1844 if (getsockname(fd, (struct sockaddr *) &addr, &addr_len)) {
1845 debug(9, 0) ("ftpSendPort: getsockname(%d,..): %s\n", fd, xstrerror());
1846 /* XXX Need to set error message */
1847 ftpFail(ftpState);
1848 return;
1849 }
1850 addrptr = (unsigned char *) &addr.sin_addr.s_addr;
1851 portptr = (unsigned char *) &addr.sin_port;
1852 snprintf(cbuf, 1024, "PORT %d,%d,%d,%d,%d,%d\r\n",
1853 addrptr[0], addrptr[1], addrptr[2], addrptr[3],
1854 portptr[0], portptr[1]);
1855 ftpWriteCommand(cbuf, ftpState);
1856 ftpState->state = SENT_PORT;
3fdadc70 1857}
1858
1859static void
cdc33f35 1860ftpReadPort(FtpStateData * ftpState)
3fdadc70 1861{
cdc33f35 1862 int code = ftpState->ctrl.replycode;
a3d5953d 1863 debug(9, 3) ("This is ftpReadPort\n");
cdc33f35 1864 if (code != 200) {
1865 /* Fall back on using the same port as the control connection */
1866 debug(9, 3) ("PORT not supported by remote end\n");
cdc33f35 1867 ftpOpenListenSocket(ftpState, 1);
1868 }
1869 ftpRestOrList(ftpState);
1870}
1871
1872/* "read" handler to accept data connection */
1873static void
1874ftpAcceptDataConnection(int fd, void *data)
1875{
1876 FtpStateData *ftpState = data;
1877 struct sockaddr_in peer, me;
1878 debug(9, 3) ("ftpAcceptDataConnection\n");
1879
1880 fd = comm_accept(fd, &peer, &me);
1881 if (fd < 0) {
1882 debug(9, 1) ("ftpHandleDataAccept: comm_accept(%d): %s", fd, xstrerror());
1883 /* XXX Need to set error message */
1884 ftpFail(ftpState);
1885 return;
1886 }
c93a9f49 1887 /* Replace the Listen socket with the accepted data socket */
1888 comm_close(ftpState->data.fd);
05e11a8c 1889 debug(9, 3) ("ftpAcceptDataConnection: Connected data socket on FD %d\n", fd);
cdc33f35 1890 ftpState->data.fd = fd;
1891 ftpState->data.port = ntohs(peer.sin_port);
1892 ftpState->data.host = xstrdup(inet_ntoa(peer.sin_addr));
58226b89 1893 commSetTimeout(ftpState->ctrl.fd, -1, NULL, NULL);
05e11a8c 1894 commSetTimeout(ftpState->data.fd, Config.Timeout.read, ftpTimeout,
1895 ftpState);
cdc33f35 1896 /* XXX We should have a flag to track connect state...
1897 * host NULL -> not connected, port == local port
1898 * host set -> connected, port == remote port
1899 */
1900 /* Restart state (SENT_NLST/LIST/RETR) */
1901 FTP_SM_FUNCS[ftpState->state] (ftpState);
3fdadc70 1902}
1903
1904static void
1905ftpRestOrList(FtpStateData * ftpState)
1906{
a3d5953d 1907 debug(9, 3) ("This is ftpRestOrList\n");
e55f0142 1908 if (ftpState->flags.put) {
4162ee3b 1909 debug(9, 3) ("ftpRestOrList: Sending STOR request...\n");
54220df8 1910 ftpSendStor(ftpState);
1911 } else if (ftpState->typecode == 'D') {
dbfed404 1912 /* XXX This should NOT be here */
9e242e02 1913 ftpSendNlst(ftpState); /* sec 3.2.2 of RFC 1738 */
e55f0142 1914 ftpState->flags.isdir = 1;
1915 ftpState->flags.use_base = 1;
1916 } else if (ftpState->flags.isdir)
969c39b9 1917 ftpSendList(ftpState);
cfbf5373 1918 else if (ftpRestartable(ftpState))
969c39b9 1919 ftpSendRest(ftpState);
1920 else
1921 ftpSendRetr(ftpState);
1922}
1923
54220df8 1924static void
1925ftpSendStor(FtpStateData * ftpState)
1926{
9bc73deb 1927 if (ftpState->filepath != NULL) {
1928 /* Plain file upload */
1929 snprintf(cbuf, 1024, "STOR %s\r\n", ftpState->filepath);
1930 ftpWriteCommand(cbuf, ftpState);
1931 ftpState->state = SENT_STOR;
1932 } else if (httpHeaderGetInt(&ftpState->request->header, HDR_CONTENT_LENGTH) > 0) {
1933 /* File upload without a filename. use STOU to generate one */
1934 snprintf(cbuf, 1024, "STOU\r\n");
1935 ftpWriteCommand(cbuf, ftpState);
1936 ftpState->state = SENT_STOR;
1937 } else {
1938 /* No file to transfer. Only create directories if needed */
1939 ftpSendReply(ftpState);
1940 }
54220df8 1941}
1942
1943static void
1944ftpReadStor(FtpStateData * ftpState)
1945{
1946 int code = ftpState->ctrl.replycode;
1947 debug(9, 3) ("This is ftpReadStor\n");
9bc73deb 1948 if (code == 125 || (code == 150 && ftpState->data.host)) {
1949 /* Begin data transfer */
1950 debug(9, 3) ("ftpReadStor: starting data transfer\n");
acce49bf 1951 /*
1952 * Cancel the timeout on the Control socket, pumpStart will
1953 * establish one on the data socket.
1954 */
1955 commSetTimeout(ftpState->ctrl.fd, -1, NULL, NULL);
1956 ftpPutStart(ftpState);
1957 debug(9, 3) ("ftpReadStor: writing data channel\n");
1958 ftpState->state = WRITING_DATA;
9bc73deb 1959 } else if (code == 150) {
1960 /* Accept data channel */
1961 debug(9, 3) ("ftpReadStor: accepting data channel\n");
1962 commSetSelect(ftpState->data.fd,
1963 COMM_SELECT_READ,
1964 ftpAcceptDataConnection,
1965 ftpState,
1966 0);
54220df8 1967 } else {
9bc73deb 1968 debug(9, 3) ("ftpReadStor: Unexpected reply code %s\n", code);
1969 ftpFail(ftpState);
54220df8 1970 }
1971}
1972
969c39b9 1973static void
1974ftpSendRest(FtpStateData * ftpState)
1975{
1976 snprintf(cbuf, 1024, "REST %d\r\n", ftpState->restart_offset);
1977 ftpWriteCommand(cbuf, ftpState);
1978 ftpState->state = SENT_REST;
3fdadc70 1979}
1980
cfbf5373 1981static int
1982ftpRestartable(FtpStateData * ftpState)
1983{
1984 if (ftpState->restart_offset > 0)
1985 return 1;
1986 if (!ftpState->request->range)
1987 return 0;
1988 if (!ftpState->flags.binary)
1989 return 0;
1990 if (ftpState->size <= 0)
1991 return 0;
1992
1993 ftpState->restart_offset = httpHdrRangeLowestOffset(ftpState->request->range, (size_t) ftpState->size);
1994 if (ftpState->restart_offset <= 0)
1995 return 0;
1996 return 1;
1997}
1998
3fdadc70 1999static void
2000ftpReadRest(FtpStateData * ftpState)
2001{
2002 int code = ftpState->ctrl.replycode;
a3d5953d 2003 debug(9, 3) ("This is ftpReadRest\n");
3fdadc70 2004 assert(ftpState->restart_offset > 0);
2005 if (code == 350) {
cfbf5373 2006 ftpState->restarted_offset = ftpState->restart_offset;
969c39b9 2007 ftpSendRetr(ftpState);
3fdadc70 2008 } else if (code > 0) {
a3d5953d 2009 debug(9, 3) ("ftpReadRest: REST not supported\n");
e55f0142 2010 ftpState->flags.rest_supported = 0;
c7e0305b 2011 ftpSendRetr(ftpState);
3fdadc70 2012 } else {
2013 ftpFail(ftpState);
2014 }
2015}
2016
969c39b9 2017static void
2018ftpSendList(FtpStateData * ftpState)
2019{
dbfed404 2020 if (ftpState->filepath) {
e55f0142 2021 ftpState->flags.use_base = 1;
dbfed404 2022 snprintf(cbuf, 1024, "LIST %s\r\n", ftpState->filepath);
2023 } else {
2024 snprintf(cbuf, 1024, "LIST\r\n");
2025 }
969c39b9 2026 ftpWriteCommand(cbuf, ftpState);
2027 ftpState->state = SENT_LIST;
2028}
2029
dbfed404 2030static void
2031ftpSendNlst(FtpStateData * ftpState)
2032{
e55f0142 2033 ftpState->flags.tried_nlst = 1;
dbfed404 2034 if (ftpState->filepath) {
e55f0142 2035 ftpState->flags.use_base = 1;
dbfed404 2036 snprintf(cbuf, 1024, "NLST %s\r\n", ftpState->filepath);
2037 } else {
2038 snprintf(cbuf, 1024, "NLST\r\n");
2039 }
2040 ftpWriteCommand(cbuf, ftpState);
2041 ftpState->state = SENT_NLST;
2042}
2043
3fdadc70 2044static void
2045ftpReadList(FtpStateData * ftpState)
2046{
2047 int code = ftpState->ctrl.replycode;
a3d5953d 2048 debug(9, 3) ("This is ftpReadList\n");
cdc33f35 2049 if (code == 125 || (code == 150 && ftpState->data.host)) {
2050 /* Begin data transfer */
3fdadc70 2051 ftpAppendSuccessHeader(ftpState);
2052 commSetSelect(ftpState->data.fd,
30a4f2a8 2053 COMM_SELECT_READ,
dbfed404 2054 ftpDataRead,
3fdadc70 2055 ftpState,
2acf4be6 2056 Config.Timeout.read);
41462d93 2057 commSetDefer(ftpState->data.fd, fwdCheckDeferRead, ftpState->entry);
3fdadc70 2058 ftpState->state = READING_DATA;
05e11a8c 2059 /*
2060 * Cancel the timeout on the Control socket and establish one
2061 * on the data socket
2062 */
a0eff6be 2063 commSetTimeout(ftpState->ctrl.fd, -1, NULL, NULL);
2064 commSetTimeout(ftpState->data.fd, Config.Timeout.read, ftpTimeout, ftpState);
3fdadc70 2065 return;
cdc33f35 2066 } else if (code == 150) {
2067 /* Accept data channel */
2068 commSetSelect(ftpState->data.fd,
2069 COMM_SELECT_READ,
2070 ftpAcceptDataConnection,
2071 ftpState,
05e11a8c 2072 0);
2073 /*
2074 * Cancel the timeout on the Control socket and establish one
2075 * on the data socket
2076 */
2077 commSetTimeout(ftpState->ctrl.fd, -1, NULL, NULL);
2078 commSetTimeout(ftpState->data.fd, Config.Timeout.read, ftpTimeout, ftpState);
cdc33f35 2079 return;
e55f0142 2080 } else if (!ftpState->flags.tried_nlst && code > 300) {
969c39b9 2081 ftpSendNlst(ftpState);
3fdadc70 2082 } else {
2083 ftpFail(ftpState);
2084 return;
2085 }
2086}
2087
969c39b9 2088static void
2089ftpSendRetr(FtpStateData * ftpState)
2090{
2091 assert(ftpState->filepath != NULL);
2092 snprintf(cbuf, 1024, "RETR %s\r\n", ftpState->filepath);
2093 ftpWriteCommand(cbuf, ftpState);
2094 ftpState->state = SENT_RETR;
2095}
2096
3fdadc70 2097static void
2098ftpReadRetr(FtpStateData * ftpState)
2099{
2100 int code = ftpState->ctrl.replycode;
a3d5953d 2101 debug(9, 3) ("This is ftpReadRetr\n");
cdc33f35 2102 if (code == 125 || (code == 150 && ftpState->data.host)) {
2103 /* Begin data transfer */
a57512fa 2104 debug(9, 3) ("ftpReadRetr: reading data channel\n");
3fdadc70 2105 ftpAppendSuccessHeader(ftpState);
2106 commSetSelect(ftpState->data.fd,
2107 COMM_SELECT_READ,
dbfed404 2108 ftpDataRead,
3fdadc70 2109 ftpState,
2acf4be6 2110 Config.Timeout.read);
41462d93 2111 commSetDefer(ftpState->data.fd, fwdCheckDeferRead, ftpState->entry);
3fdadc70 2112 ftpState->state = READING_DATA;
bd200c90 2113 /*
2114 * Cancel the timeout on the Control socket and establish one
2115 * on the data socket
2116 */
2acf4be6 2117 commSetTimeout(ftpState->ctrl.fd, -1, NULL, NULL);
bd200c90 2118 commSetTimeout(ftpState->data.fd, Config.Timeout.read, ftpTimeout,
2119 ftpState);
cdc33f35 2120 } else if (code == 150) {
2121 /* Accept data channel */
2122 commSetSelect(ftpState->data.fd,
2123 COMM_SELECT_READ,
2124 ftpAcceptDataConnection,
2125 ftpState,
05e11a8c 2126 0);
bd200c90 2127 /*
2128 * Cancel the timeout on the Control socket and establish one
2129 * on the data socket
2130 */
2131 commSetTimeout(ftpState->ctrl.fd, -1, NULL, NULL);
2132 commSetTimeout(ftpState->data.fd, Config.Timeout.read, ftpTimeout,
2133 ftpState);
cdc33f35 2134 } else if (code >= 300) {
e55f0142 2135 if (!ftpState->flags.try_slash_hack) {
969c39b9 2136 /* Try this as a directory missing trailing slash... */
2137 ftpHackShortcut(ftpState, ftpSendCwd);
2138 } else {
2139 ftpFail(ftpState);
2140 }
cdc33f35 2141 } else {
2142 ftpFail(ftpState);
3fdadc70 2143 }
2144}
2145
2146static void
2147ftpReadTransferDone(FtpStateData * ftpState)
2148{
2149 int code = ftpState->ctrl.replycode;
a3d5953d 2150 debug(9, 3) ("This is ftpReadTransferDone\n");
9bc73deb 2151 if (code == 226) {
2152 /* Connection closed; retrieval done. */
2153 if (ftpState->flags.html_header_sent)
2154 ftpListingFinish(ftpState);
2155 if (!ftpState->flags.put) {
2156 storeTimestampsSet(ftpState->entry);
2157 fwdComplete(ftpState->fwd);
2158 }
2159 ftpDataTransferDone(ftpState);
2160 } else { /* != 226 */
c3b838d4 2161 debug(9, 1) ("ftpReadTransferDone: Got code %d after reading data\n",
2162 code);
9bc73deb 2163 ftpFailed(ftpState, ERR_FTP_FAILURE);
2164 /* ftpFailed closes ctrl.fd and frees ftpState */
2165 return;
3fdadc70 2166 }
2167}
2168
2169static void
2170ftpDataTransferDone(FtpStateData * ftpState)
2171{
a3d5953d 2172 debug(9, 3) ("This is ftpDataTransferDone\n");
033fa114 2173 if (ftpState->data.fd > -1) {
a3d5953d 2174 comm_close(ftpState->data.fd);
2175 ftpState->data.fd = -1;
033fa114 2176 }
969c39b9 2177 ftpSendQuit(ftpState);
2178}
2179
2180static void
2181ftpSendQuit(FtpStateData * ftpState)
2182{
033fa114 2183 assert(ftpState->ctrl.fd > -1);
56878878 2184 snprintf(cbuf, 1024, "QUIT\r\n");
3fdadc70 2185 ftpWriteCommand(cbuf, ftpState);
2186 ftpState->state = SENT_QUIT;
2187}
2188
2189static void
2190ftpReadQuit(FtpStateData * ftpState)
2191{
2192 comm_close(ftpState->ctrl.fd);
2193}
2194
969c39b9 2195static void
2196ftpTrySlashHack(FtpStateData * ftpState)
2197{
2198 char *path;
e55f0142 2199 ftpState->flags.try_slash_hack = 1;
969c39b9 2200 /* Free old paths */
2201 if (ftpState->pathcomps)
2202 wordlistDestroy(&ftpState->pathcomps);
2203 safe_free(ftpState->filepath);
2204 /* Build the new path (urlpath begins with /) */
02922e76 2205 path = xstrdup(strBuf(ftpState->request->urlpath));
969c39b9 2206 rfc1738_unescape(path);
2207 ftpState->filepath = path;
2208 /* And off we go */
dbfed404 2209 ftpGetFile(ftpState);
969c39b9 2210}
2211
0f169992 2212static void
2213ftpTryDatachannelHack(FtpStateData * ftpState)
2214{
e55f0142 2215 ftpState->flags.datachannel_hack = 1;
0f169992 2216 /* we have to undo some of the slash hack... */
2217 if (ftpState->old_filepath != NULL) {
e55f0142 2218 ftpState->flags.try_slash_hack = 0;
0f169992 2219 safe_free(ftpState->filepath);
2220 ftpState->filepath = ftpState->old_filepath;
2221 ftpState->old_filepath = NULL;
2222 }
e55f0142 2223 ftpState->flags.tried_nlst = 0;
0f169992 2224 /* And off we go */
e55f0142 2225 if (ftpState->flags.isdir) {
0f169992 2226 ftpListDir(ftpState);
2227 } else {
2228 ftpGetFile(ftpState);
2229 }
2230 return;
2231}
2232
2233/* Forget hack status. Next error is shown to the user */
2234static void
2235ftpUnhack(FtpStateData * ftpState)
2236{
2237 if (ftpState->old_request != NULL) {
2238 safe_free(ftpState->old_request);
2239 safe_free(ftpState->old_reply);
2240 }
2241}
2242
969c39b9 2243static void
2244ftpHackShortcut(FtpStateData * ftpState, FTPSM * nextState)
2245{
c7e0305b 2246 /* Clear some unwanted state */
2247 ftpState->restarted_offset = 0;
2248 ftpState->restart_offset = 0;
0f169992 2249 /* Save old error message & some state info */
2250 if (ftpState->old_request == NULL) {
2251 ftpState->old_request = ftpState->ctrl.last_command;
2252 ftpState->ctrl.last_command = NULL;
2253 ftpState->old_reply = ftpState->ctrl.last_reply;
2254 ftpState->ctrl.last_reply = NULL;
2255 if (ftpState->pathcomps == NULL && ftpState->filepath != NULL)
2256 ftpState->old_filepath = xstrdup(ftpState->filepath);
2257 }
969c39b9 2258 /* Jump to the "hack" state */
2259 nextState(ftpState);
2260}
2261
3fdadc70 2262static void
2263ftpFail(FtpStateData * ftpState)
2264{
a3d5953d 2265 debug(9, 3) ("ftpFail\n");
dbfed404 2266 /* Try the / hack to support "Netscape" FTP URL's for retreiving files */
0cdcddb9 2267 if (!ftpState->flags.isdir && /* Not a directory */
2268 !ftpState->flags.try_slash_hack && /* Not in slash hack */
2a1ca944 2269 ftpState->mdtm <= 0 && ftpState->size < 0 && /* Not known as a file */
c7e0305b 2270 strNCaseCmp(ftpState->request->urlpath, "/%2f", 4) != 0) { /* No slash encoded */
969c39b9 2271 switch (ftpState->state) {
2272 case SENT_CWD:
2273 case SENT_RETR:
2274 /* Try the / hack */
2275 ftpHackShortcut(ftpState, ftpTrySlashHack);
2276 return;
2277 default:
2278 break;
2279 }
2280 }
0f169992 2281 /* Try to reopen datachannel */
e55f0142 2282 if (!ftpState->flags.datachannel_hack &&
0f169992 2283 ftpState->pathcomps == NULL) {
2284 switch (ftpState->state) {
2285 case SENT_RETR:
2286 case SENT_LIST:
2287 case SENT_NLST:
2288 /* Try to reopen datachannel */
2289 ftpHackShortcut(ftpState, ftpTryDatachannelHack);
2290 return;
2291 default:
2292 break;
2293 }
2294 }
9bc73deb 2295 ftpFailed(ftpState, ERR_NONE);
2296 /* ftpFailed closes ctrl.fd and frees ftpState */
2297}
2298
2299static void
2300ftpFailed(FtpStateData * ftpState, err_type error)
2301{
2302 StoreEntry *entry = ftpState->entry;
2303 if (entry->mem_obj->inmem_hi == 0)
2304 ftpFailedErrorMessage(ftpState, error);
2305 if (ftpState->data.fd > -1) {
2306 comm_close(ftpState->data.fd);
2307 ftpState->data.fd = -1;
2308 }
2309 comm_close(ftpState->ctrl.fd);
2310}
2311
2312static void
2313ftpFailedErrorMessage(FtpStateData * ftpState, err_type error)
2314{
2315 ErrorState *err;
2316 char *command, *reply;
b6a2f15e 2317 /* Translate FTP errors into HTTP errors */
2318 err = NULL;
9bc73deb 2319 switch (error) {
2320 case ERR_NONE:
2321 switch (ftpState->state) {
2322 case SENT_USER:
2323 case SENT_PASS:
2324 if (ftpState->ctrl.replycode > 500)
2325 err = errorCon(ERR_FTP_FORBIDDEN, HTTP_FORBIDDEN);
2326 else if (ftpState->ctrl.replycode == 421)
2327 err = errorCon(ERR_FTP_UNAVAILABLE, HTTP_SERVICE_UNAVAILABLE);
2328 break;
2329 case SENT_CWD:
2330 case SENT_RETR:
2331 if (ftpState->ctrl.replycode == 550)
2332 err = errorCon(ERR_FTP_NOT_FOUND, HTTP_NOT_FOUND);
2333 break;
2334 default:
2335 break;
2336 }
b6a2f15e 2337 break;
9bc73deb 2338 case ERR_READ_TIMEOUT:
2339 err = errorCon(error, HTTP_GATEWAY_TIMEOUT);
b6a2f15e 2340 break;
2341 default:
9bc73deb 2342 err = errorCon(error, HTTP_BAD_GATEWAY);
b6a2f15e 2343 break;
2344 }
2345 if (err == NULL)
2346 err = errorCon(ERR_FTP_FAILURE, HTTP_BAD_GATEWAY);
9bc73deb 2347 err->xerrno = errno;
b9916917 2348 err->request = requestLink(ftpState->request);
9bc73deb 2349 err->ftp.server_msg = ftpState->ctrl.message;
2350 ftpState->ctrl.message = NULL;
969c39b9 2351 if (ftpState->old_request)
9bc73deb 2352 command = ftpState->old_request;
969c39b9 2353 else
9bc73deb 2354 command = ftpState->ctrl.last_command;
2355 if (command && strncmp(command, "PASS", 4) == 0)
2356 command = "PASS <yourpassword>";
969c39b9 2357 if (ftpState->old_reply)
9bc73deb 2358 reply = ftpState->old_reply;
969c39b9 2359 else
9bc73deb 2360 reply = ftpState->ctrl.last_reply;
2361 if (command)
2362 err->ftp.request = xstrdup(command);
2363 if (reply)
2364 err->ftp.reply = xstrdup(reply);
2365 fwdFail(ftpState->fwd, err);
3fdadc70 2366}
2367
9bc73deb 2368static void
b6a2f15e 2369ftpPumpClosedData(int data_fd, void *data)
2370{
2371 FtpStateData *ftpState = data;
2372 assert(data_fd == ftpState->data.fd);
2373 /*
2374 * Ugly pump module closed our server-side. Deal with it.
2375 * The data FD is already closed, so just set it to -1.
2376 */
2377 ftpState->data.fd = -1;
2378 /*
2379 * Currently, thats all we have to do. Because the upload failed,
2380 * storeAbort() will be called on the reply entry. That will
2381 * call fwdAbort, which closes ftpState->ctrl.fd and then
2382 * ftpStateFree gets called.
2383 */
2384}
2385
54220df8 2386static void
2387ftpPutStart(FtpStateData * ftpState)
2388{
2389 debug(9, 3) ("ftpPutStart\n");
b6a2f15e 2390 /*
2391 * sigh, we need this gross hack to detect when ugly pump module
2392 * aborts and wants to close the server-side.
2393 */
2394 comm_add_close_handler(ftpState->data.fd, ftpPumpClosedData, ftpState);
789f4e81 2395 pumpStart(ftpState->data.fd, ftpState->fwd, ftpPutTransferDone, ftpState);
54220df8 2396}
2397
4162ee3b 2398static void
54220df8 2399ftpPutTransferDone(int fd, char *bufnotused, size_t size, int errflag, void *data)
2400{
e449e190 2401 FtpStateData *ftpState = data;
54220df8 2402 if (ftpState->data.fd >= 0) {
b6a2f15e 2403 comm_remove_close_handler(fd, ftpPumpClosedData, ftpState);
4162ee3b 2404 comm_close(ftpState->data.fd);
2405 ftpState->data.fd = -1;
54220df8 2406 }
2407 ftpReadComplete(ftpState);
2408}
2409
2410static void
2411ftpSendReply(FtpStateData * ftpState)
2412{
2413 ErrorState *err;
acce49bf 2414 int code = ftpState->ctrl.replycode;
728da2ee 2415 http_status http_code;
2416 err_type err_code = ERR_NONE;
c3b838d4 2417 debug(9, 5) ("ftpSendReply: %s, code %d\n",
2418 storeUrl(ftpState->entry), code);
54220df8 2419 if (cbdataValid(ftpState))
acce49bf 2420 debug(9, 5) ("ftpSendReply: ftpState (%p) is valid!\n", ftpState);
2421 if (code == 226) {
2422 err_code = (ftpState->mdtm > 0) ? ERR_FTP_PUT_MODIFIED : ERR_FTP_PUT_CREATED;
2423 http_code = (ftpState->mdtm > 0) ? HTTP_ACCEPTED : HTTP_CREATED;
9bc73deb 2424 } else if (code == 227) {
2425 err_code = ERR_FTP_PUT_CREATED;
2426 http_code = HTTP_CREATED;
54220df8 2427 } else {
2428 err_code = ERR_FTP_PUT_ERROR;
acce49bf 2429 http_code = HTTP_INTERNAL_SERVER_ERROR;
54220df8 2430 }
54220df8 2431 err = errorCon(err_code, http_code);
2432 err->request = requestLink(ftpState->request);
2433 if (ftpState->old_request)
9bc73deb 2434 err->ftp.request = xstrdup(ftpState->old_request);
54220df8 2435 else
9bc73deb 2436 err->ftp.request = xstrdup(ftpState->ctrl.last_command);
54220df8 2437 if (ftpState->old_reply)
9bc73deb 2438 err->ftp.reply = xstrdup(ftpState->old_reply);
54220df8 2439 else
9bc73deb 2440 err->ftp.reply = xstrdup(ftpState->ctrl.last_reply);
54220df8 2441 errorAppendEntry(ftpState->entry, err);
54220df8 2442 storeBufferFlush(ftpState->entry);
9bc73deb 2443 ftpSendQuit(ftpState);
54220df8 2444}
2445
3fdadc70 2446static void
2447ftpAppendSuccessHeader(FtpStateData * ftpState)
2448{
2449 char *mime_type = NULL;
2450 char *mime_enc = NULL;
02922e76 2451 String urlpath = ftpState->request->urlpath;
2452 const char *filename = NULL;
2453 const char *t = NULL;
3fdadc70 2454 StoreEntry *e = ftpState->entry;
c68e9c6b 2455 StoreEntry *pe = NULL;
9e975e4e 2456 http_reply *reply = e->mem_obj->reply;
e55f0142 2457 if (ftpState->flags.http_header_sent)
3fdadc70 2458 return;
e55f0142 2459 ftpState->flags.http_header_sent = 1;
8350fe9b 2460 assert(e->mem_obj->inmem_hi == 0);
2749ab78 2461 EBIT_CLR(e->flags, ENTRY_FWD_HDR_WAIT);
02922e76 2462 filename = (t = strRChr(urlpath, '/')) ? t + 1 : strBuf(urlpath);
e55f0142 2463 if (ftpState->flags.isdir) {
3fdadc70 2464 mime_type = "text/html";
2465 } else {
31b4984a 2466 switch (ftpState->typecode) {
2467 case 'I':
2468 mime_type = "application/octet-stream";
2469 mime_enc = mimeGetContentEncoding(filename);
2470 break;
2471 case 'A':
2472 mime_type = "text/plain";
2473 break;
2474 default:
2475 mime_type = mimeGetContentType(filename);
2476 mime_enc = mimeGetContentEncoding(filename);
2477 break;
2478 }
3fdadc70 2479 }
438fc1e3 2480 storeBuffer(e);
cb69b4c7 2481 httpReplyReset(reply);
2482 /* set standard stuff */
cfbf5373 2483 if (ftpState->restarted_offset) {
2484 /* Partial reply */
c2352aa2 2485 HttpHdrRangeSpec range_spec;
e3dd531e 2486 range_spec.offset = ftpState->restarted_offset;
c2352aa2 2487 range_spec.length = ftpState->size - ftpState->restarted_offset;
cfbf5373 2488 httpReplySetHeaders(reply, 1.0, HTTP_PARTIAL_CONTENT, "Gatewaying",
2489 mime_type, ftpState->size - ftpState->restarted_offset, ftpState->mdtm, -2);
2490 httpHeaderAddContRange(&reply->header, range_spec, ftpState->size);
2491 } else {
2492 /* Full reply */
2493 httpReplySetHeaders(reply, 1.0, HTTP_OK, "Gatewaying",
2494 mime_type, ftpState->size, ftpState->mdtm, -2);
2495 }
cb69b4c7 2496 /* additional info */
2497 if (mime_enc)
d8b249ef 2498 httpHeaderPutStr(&reply->header, HDR_CONTENT_ENCODING, mime_enc);
cb69b4c7 2499 httpReplySwapOut(reply, e);
438fc1e3 2500 storeBufferFlush(e);
2acf4be6 2501 reply->hdr_sz = e->mem_obj->inmem_hi;
e6b02cfc 2502 storeTimestampsSet(e);
c68e9c6b 2503 if (ftpState->flags.authenticated) {
2504 /*
2505 * Authenticated requests can't be cached. Eject any old cached
2506 * object
2507 */
2508 pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method);
2509 if (pe)
2510 storeRelease(pe);
2511 storeRelease(e);
cfbf5373 2512 } else if (EBIT_TEST(e->flags, ENTRY_CACHABLE) && !ftpState->restarted_offset) {
40ced4c0 2513 storeSetPublicKey(e);
c68e9c6b 2514 } else {
2515 storeRelease(e);
2516 }
77a30ebb 2517}
bfcaf585 2518
cb69b4c7 2519static void
ee1679df 2520ftpAuthRequired(HttpReply * old_reply, request_t * request, const char *realm)
cb69b4c7 2521{
2522 ErrorState *err = errorCon(ERR_ACCESS_DENIED, HTTP_UNAUTHORIZED);
2523 HttpReply *rep;
2524 err->request = requestLink(request);
2525 rep = errorBuildReply(err);
cb69b4c7 2526 errorStateFree(err);
63259c34 2527 /* add Authenticate header */
d8b249ef 2528 httpHeaderPutAuth(&rep->header, "Basic", realm);
63259c34 2529 /* move new reply to the old one */
2530 httpReplyAbsorb(old_reply, rep);
cb69b4c7 2531}
8f872bb6 2532
2533char *
2534ftpUrlWith2f(const request_t * request)
2535{
2536 LOCAL_ARRAY(char, buf, MAX_URL);
2537 LOCAL_ARRAY(char, loginbuf, MAX_LOGIN_SZ + 1);
2538 LOCAL_ARRAY(char, portbuf, 32);
2539 char *t;
2540 portbuf[0] = '\0';
23d92c64 2541 if (request->protocol != PROTO_FTP)
2542 return NULL;
8f872bb6 2543 if (request->port != urlDefaultPort(request->protocol))
2544 snprintf(portbuf, 32, ":%d", request->port);
2545 loginbuf[0] = '\0';
69e81830 2546 if ((int) strlen(request->login) > 0) {
8f872bb6 2547 strcpy(loginbuf, request->login);
2548 if ((t = strchr(loginbuf, ':')))
2549 *t = '\0';
2550 strcat(loginbuf, "@");
2551 }
2552 snprintf(buf, MAX_URL, "%s://%s%s%s%s%s",
2553 ProtocolStr[request->protocol],
2554 loginbuf,
2555 request->host,
2556 portbuf,
2557 "/%2f",
02922e76 2558 strBuf(request->urlpath));
8f872bb6 2559 if ((t = strchr(buf, '?')))
2560 *t = '\0';
2561 return buf;
2562}