2 * DEBUG: section 09 File Transfer Protocol (FTP)
3 * AUTHOR: Harvest Derived
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
34 #include "acl/FilledChecklist.h"
35 #include "clients/forward.h"
36 #include "clients/FtpClient.h"
38 #include "comm/ConnOpener.h"
39 #include "comm/Read.h"
40 #include "comm/TcpAcceptor.h"
41 #include "CommCalls.h"
42 #include "compat/strtoll.h"
43 #include "errorpage.h"
47 #include "html_quote.h"
48 #include "HttpHdrContRange.h"
49 #include "HttpHeader.h"
50 #include "HttpHeaderRange.h"
51 #include "HttpReply.h"
52 #include "HttpRequest.h"
59 #include "SquidConfig.h"
60 #include "SquidString.h"
61 #include "SquidTime.h"
62 #include "StatCounters.h"
69 #include "DelayPools.h"
70 #include "MemObject.h"
81 bool pasv_supported
; ///< PASV command is allowed
82 bool epsv_all_sent
; ///< EPSV ALL has been used. Must abort on failures.
84 bool pasv_failed
; // was FwdState::flags.ftp_pasv_failed
87 bool authenticated
; ///< authentication success
88 bool tried_auth_anonymous
; ///< auth has tried to use anonymous credentials already.
89 bool tried_auth_nopass
; ///< auth tried username with no password already.
95 bool http_header_sent
;
105 bool listformat_unknown
;
107 bool completed_forwarding
;
111 typedef void (StateMethod
)(Ftp::Gateway
*);
113 /// FTP Gateway: An FTP client that takes an HTTP request with an ftp:// URI,
114 /// converts it into one or more FTP commands, and then
115 /// converts one or more FTP responses into the final HTTP response.
116 class Gateway
: public Ftp::Client
122 char password
[MAX_URL
];
136 int64_t restart_offset
;
142 MemBuf listing
; ///< FTP directory listing in HTML format.
147 // these should all be private
148 virtual void start();
149 virtual Http::StatusCode
failedHttpStatus(err_type
&error
);
150 void loginParser(const char *, int escaped
);
152 void appendSuccessHeader();
153 void hackShortcut(StateMethod
*nextState
);
157 MemBuf
*htmlifyListEntry(const char *line
);
158 void completedListing(void);
160 /// create a data channel acceptor and start listening.
161 void listenForDataChannel(const Comm::ConnectionPointer
&conn
);
163 int checkAuth(const HttpHeader
* req_hdr
);
165 void buildTitleUrl();
166 void writeReplyBody(const char *, size_t len
);
167 void printfReplyBody(const char *fmt
, ...);
168 virtual void completeForwarding();
169 void processHeadResponse();
170 void processReplyBody();
171 void setCurrentOffset(int64_t offset
) { currentOffset
= offset
; }
172 int64_t getCurrentOffset() const { return currentOffset
; }
174 virtual void dataChannelConnected(const CommConnectCbParams
&io
);
175 static PF ftpDataWrite
;
176 virtual void timeout(const CommTimeoutCbParams
&io
);
177 void ftpAcceptDataConnection(const CommAcceptCbParams
&io
);
179 static HttpReply
*ftpAuthRequired(HttpRequest
* request
, const char *realm
);
180 const char *ftpRealm(void);
181 void loginFailed(void);
183 virtual void haveParsedReplyHeaders();
185 virtual bool haveControlChannel(const char *caller_name
) const;
188 virtual void handleControlReply();
189 virtual void dataClosed(const CommCloseCbParams
&io
);
192 virtual bool mayReadVirginReplyBody() const;
193 // BodyConsumer for HTTP: consume request body.
194 virtual void handleRequestBodyProducerAborted();
196 CBDATA_CLASS2(Gateway
);
201 typedef Ftp::StateMethod FTPSM
; // to avoid lots of non-changes
203 CBDATA_NAMESPACED_CLASS_INIT(Ftp
, Gateway
);
214 #define FTP_LOGIN_ESCAPED 1
216 #define FTP_LOGIN_NOT_ESCAPED 0
218 #define CTRL_BUFLEN 1024
219 static char cbuf
[CTRL_BUFLEN
];
222 * State machine functions
223 * send == state transition
224 * read == wait for response, and select next state transition
225 * other == Transition logic
227 static FTPSM ftpReadWelcome
;
228 static FTPSM ftpSendUser
;
229 static FTPSM ftpReadUser
;
230 static FTPSM ftpSendPass
;
231 static FTPSM ftpReadPass
;
232 static FTPSM ftpSendType
;
233 static FTPSM ftpReadType
;
234 static FTPSM ftpSendMdtm
;
235 static FTPSM ftpReadMdtm
;
236 static FTPSM ftpSendSize
;
237 static FTPSM ftpReadSize
;
238 static FTPSM ftpSendEPRT
;
239 static FTPSM ftpReadEPRT
;
240 static FTPSM ftpSendPORT
;
241 static FTPSM ftpReadPORT
;
242 static FTPSM ftpSendPassive
;
243 static FTPSM ftpReadEPSV
;
244 static FTPSM ftpReadPasv
;
245 static FTPSM ftpTraverseDirectory
;
246 static FTPSM ftpListDir
;
247 static FTPSM ftpGetFile
;
248 static FTPSM ftpSendCwd
;
249 static FTPSM ftpReadCwd
;
250 static FTPSM ftpRestOrList
;
251 static FTPSM ftpSendList
;
252 static FTPSM ftpSendNlst
;
253 static FTPSM ftpReadList
;
254 static FTPSM ftpSendRest
;
255 static FTPSM ftpReadRest
;
256 static FTPSM ftpSendRetr
;
257 static FTPSM ftpReadRetr
;
258 static FTPSM ftpReadTransferDone
;
259 static FTPSM ftpSendStor
;
260 static FTPSM ftpReadStor
;
261 static FTPSM ftpWriteTransferDone
;
262 static FTPSM ftpSendReply
;
263 static FTPSM ftpSendMkdir
;
264 static FTPSM ftpReadMkdir
;
265 static FTPSM ftpFail
;
266 static FTPSM ftpSendQuit
;
267 static FTPSM ftpReadQuit
;
269 /************************************************
270 ** Debugs Levels used here **
271 *************************************************
274 Protocol and Transmission failures.
275 2 FTP Protocol Chatter
280 ************************************************/
282 /************************************************
283 ** State Machine Description (excluding hacks) **
284 *************************************************
286 ---------------------------------------
290 Type TraverseDirectory / GetFile
291 TraverseDirectory Cwd / GetFile / ListDir
292 Cwd TraverseDirectory / Mkdir
298 FileOrList Rest / Retr / Nlst / List / Mkdir (PUT /xxx;type=d)
300 Retr / Nlst / List DataRead* (on datachannel)
301 DataRead* ReadTransferDone
302 ReadTransferDone DataTransferDone
303 Stor DataWrite* (on datachannel)
304 DataWrite* RequestPutBody** (from client)
305 RequestPutBody** DataWrite* / WriteTransferDone
306 WriteTransferDone DataTransferDone
307 DataTransferDone Quit
309 ************************************************/
311 FTPSM
*FTP_SM_FUNCS
[] = {
312 ftpReadWelcome
, /* BEGIN */
313 ftpReadUser
, /* SENT_USER */
314 ftpReadPass
, /* SENT_PASS */
315 ftpReadType
, /* SENT_TYPE */
316 ftpReadMdtm
, /* SENT_MDTM */
317 ftpReadSize
, /* SENT_SIZE */
318 ftpReadEPRT
, /* SENT_EPRT */
319 ftpReadPORT
, /* SENT_PORT */
320 ftpReadEPSV
, /* SENT_EPSV_ALL */
321 ftpReadEPSV
, /* SENT_EPSV_1 */
322 ftpReadEPSV
, /* SENT_EPSV_2 */
323 ftpReadPasv
, /* SENT_PASV */
324 ftpReadCwd
, /* SENT_CWD */
325 ftpReadList
, /* SENT_LIST */
326 ftpReadList
, /* SENT_NLST */
327 ftpReadRest
, /* SENT_REST */
328 ftpReadRetr
, /* SENT_RETR */
329 ftpReadStor
, /* SENT_STOR */
330 ftpReadQuit
, /* SENT_QUIT */
331 ftpReadTransferDone
, /* READING_DATA (RETR,LIST,NLST) */
332 ftpWriteTransferDone
, /* WRITING_DATA (STOR) */
333 ftpReadMkdir
, /* SENT_MKDIR */
334 NULL
, /* SENT_FEAT */
337 NULL
, /* SENT_DATA_REQUEST */
338 NULL
/* SENT_COMMAND */
341 /// handler called by Comm when FTP data channel is closed unexpectedly
343 Ftp::Gateway::dataClosed(const CommCloseCbParams
&io
)
345 Ftp::Client::dataClosed(io
);
346 failed(ERR_FTP_FAILURE
, 0);
347 /* failed closes ctrl.conn and frees ftpState */
349 /* NP: failure recovery may be possible when its only a data.conn failure.
350 * if the ctrl.conn is still fine, we can send ABOR down it and retry.
351 * Just need to watch out for wider Squid states like shutting down or reconfigure.
355 Ftp::Gateway::Gateway(FwdState
*fwdState
):
356 AsyncJob("FtpStateData"),
357 Ftp::Client(fwdState
)
359 const char *url
= entry
->url();
360 debugs(9, 3, HERE
<< "'" << url
<< "'" );
364 if (Config
.Ftp
.passive
&& !flags
.pasv_failed
)
365 flags
.pasv_supported
= 1;
367 flags
.rest_supported
= 1;
369 if (request
->method
== Http::METHOD_PUT
)
375 Ftp::Gateway::~Gateway()
377 debugs(9, 3, HERE
<< entry
->url() );
379 if (Comm::IsConnOpen(ctrl
.conn
)) {
380 debugs(9, DBG_IMPORTANT
, "Internal bug: FTP Gateway left open " <<
381 "control channel " << ctrl
.conn
);
385 memFree(reply_hdr
, MEM_8K_BUF
);
390 wordlistDestroy(&pathcomps
);
394 safe_free(old_filepath
);
406 * Parse a possible login username:password pair.
407 * Produces filled member variables user, password, password_url if anything found.
410 Ftp::Gateway::loginParser(const char *login
, int escaped
)
412 const char *u
= NULL
; // end of the username sub-string
413 int len
; // length of the current sub-string to handle.
415 int total_len
= strlen(login
);
417 debugs(9, 4, HERE
<< ": login='" << login
<< "', escaped=" << escaped
);
418 debugs(9, 9, HERE
<< ": IN : login='" << login
<< "', escaped=" << escaped
<< ", user=" << user
<< ", password=" << password
);
420 if ((u
= strchr(login
, ':'))) {
422 /* if there was a username part */
425 ++u
; // jump off the delimiter.
428 xstrncpy(user
, login
, len
+1);
429 debugs(9, 9, HERE
<< ": found user='" << user
<< "'(" << len
<<"), escaped=" << escaped
);
431 rfc1738_unescape(user
);
432 debugs(9, 9, HERE
<< ": found user='" << user
<< "'(" << len
<<") unescaped.");
435 /* if there was a password part */
436 len
= login
+ total_len
- u
;
440 xstrncpy(password
, u
, len
+1);
441 debugs(9, 9, HERE
<< ": found password='" << password
<< "'(" << len
<<"), escaped=" << escaped
);
443 rfc1738_unescape(password
);
446 debugs(9, 9, HERE
<< ": found password='" << password
<< "'(" << len
<<") unescaped.");
448 } else if (login
[0]) {
449 /* no password, just username */
450 if (total_len
> MAX_URL
)
451 total_len
= MAX_URL
-1;
452 xstrncpy(user
, login
, total_len
+1);
453 debugs(9, 9, HERE
<< ": found user='" << user
<< "'(" << total_len
<<"), escaped=" << escaped
);
455 rfc1738_unescape(user
);
456 debugs(9, 9, HERE
<< ": found user='" << user
<< "'(" << total_len
<<") unescaped.");
459 debugs(9, 9, HERE
<< ": OUT: login='" << login
<< "', escaped=" << escaped
<< ", user=" << user
<< ", password=" << password
);
463 Ftp::Gateway::listenForDataChannel(const Comm::ConnectionPointer
&conn
)
465 assert(!Comm::IsConnOpen(data
.conn
));
467 typedef CommCbMemFunT
<Gateway
, CommAcceptCbParams
> AcceptDialer
;
468 typedef AsyncCallT
<AcceptDialer
> AcceptCall
;
469 RefCount
<AcceptCall
> call
= static_cast<AcceptCall
*>(JobCallback(11, 5, AcceptDialer
, this, Ftp::Gateway::ftpAcceptDataConnection
));
470 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(call
);
471 const char *note
= entry
->url();
473 /* open the conn if its not already open */
474 if (!Comm::IsConnOpen(conn
)) {
475 conn
->fd
= comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
->local
, conn
->flags
, note
);
476 if (!Comm::IsConnOpen(conn
)) {
477 debugs(5, DBG_CRITICAL
, HERE
<< "comm_open_listener failed:" << conn
->local
<< " error: " << errno
);
480 debugs(9, 3, HERE
<< "Unconnected data socket created on " << conn
);
483 conn
->tos
= ctrl
.conn
->tos
;
484 conn
->nfmark
= ctrl
.conn
->nfmark
;
486 assert(Comm::IsConnOpen(conn
));
487 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
489 // Ensure we have a copy of the FD opened for listening and a close handler on it.
490 data
.opened(conn
, dataCloser());
491 switchTimeoutToDataChannel();
495 Ftp::Gateway::timeout(const CommTimeoutCbParams
&io
)
497 if (SENT_PASV
== state
) {
498 /* stupid ftp.netscape.com, of FTP server behind stupid firewall rules */
499 flags
.pasv_supported
= false;
500 debugs(9, DBG_IMPORTANT
, "FTP Gateway timeout in SENT_PASV state");
502 // cancel the data connection setup.
503 if (data
.opener
!= NULL
) {
504 data
.opener
->cancel("timeout");
510 Ftp::Client::timeout(io
);
513 static const char *Month
[] = {
514 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
515 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
519 is_month(const char *buf
)
523 for (i
= 0; i
< 12; ++i
)
524 if (!strcasecmp(buf
, Month
[i
]))
531 ftpListPartsFree(ftpListParts
** parts
)
533 safe_free((*parts
)->date
);
534 safe_free((*parts
)->name
);
535 safe_free((*parts
)->showname
);
536 safe_free((*parts
)->link
);
540 #define MAX_TOKENS 64
542 static ftpListParts
*
543 ftpListParseParts(const char *buf
, struct Ftp::GatewayFlags flags
)
545 ftpListParts
*p
= NULL
;
547 const char *ct
= NULL
;
548 char *tokens
[MAX_TOKENS
];
551 static char tbuf
[128];
553 static int scan_ftp_initialized
= 0;
554 static regex_t scan_ftp_integer
;
555 static regex_t scan_ftp_time
;
556 static regex_t scan_ftp_dostime
;
557 static regex_t scan_ftp_dosdate
;
559 if (!scan_ftp_initialized
) {
560 scan_ftp_initialized
= 1;
561 regcomp(&scan_ftp_integer
, "^[0123456789]+$", REG_EXTENDED
| REG_NOSUB
);
562 regcomp(&scan_ftp_time
, "^[0123456789:]+$", REG_EXTENDED
| REG_NOSUB
);
563 regcomp(&scan_ftp_dosdate
, "^[0123456789]+-[0123456789]+-[0123456789]+$", REG_EXTENDED
| REG_NOSUB
);
564 regcomp(&scan_ftp_dostime
, "^[0123456789]+:[0123456789]+[AP]M$", REG_EXTENDED
| REG_NOSUB
| REG_ICASE
);
573 p
= (ftpListParts
*)xcalloc(1, sizeof(ftpListParts
));
577 memset(tokens
, 0, sizeof(tokens
));
581 if (flags
.tried_nlst
) {
582 /* Machine readable format, one name per line */
588 for (t
= strtok(xbuf
, w_space
); t
&& n_tokens
< MAX_TOKENS
; t
= strtok(NULL
, w_space
)) {
589 tokens
[n_tokens
] = xstrdup(t
);
595 /* locate the Month field */
596 for (i
= 3; i
< n_tokens
- 2; ++i
) {
597 char *size
= tokens
[i
- 1];
598 char *month
= tokens
[i
];
599 char *day
= tokens
[i
+ 1];
600 char *year
= tokens
[i
+ 2];
602 if (!is_month(month
))
605 if (regexec(&scan_ftp_integer
, size
, 0, NULL
, 0) != 0)
608 if (regexec(&scan_ftp_integer
, day
, 0, NULL
, 0) != 0)
611 if (regexec(&scan_ftp_time
, year
, 0, NULL
, 0) != 0) /* Yr | hh:mm */
614 snprintf(tbuf
, 128, "%s %2s %5s",
617 if (!strstr(buf
, tbuf
))
618 snprintf(tbuf
, 128, "%s %2s %-5s",
621 char const *copyFrom
= NULL
;
623 if ((copyFrom
= strstr(buf
, tbuf
))) {
624 p
->type
= *tokens
[0];
625 p
->size
= strtoll(size
, NULL
, 10);
626 p
->date
= xstrdup(tbuf
);
628 if (flags
.skip_whitespace
) {
629 copyFrom
+= strlen(tbuf
);
631 while (strchr(w_space
, *copyFrom
))
634 /* XXX assumes a single space between date and filename
635 * suggested by: Nathan.Bailey@cc.monash.edu.au and
636 * Mike Battersby <mike@starbug.bofh.asn.au> */
637 copyFrom
+= strlen(tbuf
) + 1;
640 p
->name
= xstrdup(copyFrom
);
642 if (p
->type
== 'l' && (t
= strstr(p
->name
, " -> "))) {
644 p
->link
= xstrdup(t
+ 4);
653 /* try it as a DOS listing, 04-05-70 09:33PM ... */
655 regexec(&scan_ftp_dosdate
, tokens
[0], 0, NULL
, 0) == 0 &&
656 regexec(&scan_ftp_dostime
, tokens
[1], 0, NULL
, 0) == 0) {
657 if (!strcasecmp(tokens
[2], "<dir>")) {
661 p
->size
= strtoll(tokens
[2], NULL
, 10);
664 snprintf(tbuf
, 128, "%s %s", tokens
[0], tokens
[1]);
665 p
->date
= xstrdup(tbuf
);
667 if (p
->type
== 'd') {
668 /* Directory.. name begins with first printable after <dir> */
669 ct
= strstr(buf
, tokens
[2]);
670 ct
+= strlen(tokens
[2]);
672 while (xisspace(*ct
))
678 /* A file. Name begins after size, with a space in between */
679 snprintf(tbuf
, 128, " %s %s", tokens
[2], tokens
[3]);
680 ct
= strstr(buf
, tbuf
);
683 ct
+= strlen(tokens
[2]) + 2;
687 p
->name
= xstrdup(ct
? ct
: tokens
[3]);
691 /* Try EPLF format; carson@lehman.com */
698 int l
= strcspn(ct
, ",");
707 p
->name
= xstrndup(ct
+ 1, l
+ 1);
711 p
->size
= atoi(ct
+ 1);
715 tm
= (time_t) strtol(ct
+ 1, &tmp
, 0);
718 break; /* not a valid integer */
720 p
->date
= xstrdup(ctime(&tm
));
722 *(strstr(p
->date
, "\n")) = '\0';
744 ct
= strstr(ct
, ",");
763 for (i
= 0; i
< n_tokens
; ++i
)
767 ftpListPartsFree(&p
); /* cleanup */
773 Ftp::Gateway::htmlifyListEntry(const char *line
)
776 char href
[2048 + 40];
779 char chdir
[ 2048 + 40];
780 char view
[ 2048 + 40];
781 char download
[ 2048 + 40];
782 char link
[ 2048 + 40];
786 *icon
= *href
= *text
= *size
= *chdir
= *view
= *download
= *link
= '\0';
788 debugs(9, 7, HERE
<< " line ={" << line
<< "}");
790 if (strlen(line
) > 1024) {
793 html
->Printf("<tr><td colspan=\"5\">%s</td></tr>\n", line
);
797 if (flags
.dir_slash
&& dirpath
&& typecode
!= 'D')
798 snprintf(prefix
, 2048, "%s/", rfc1738_escape_part(dirpath
));
802 if ((parts
= ftpListParseParts(line
, flags
)) == NULL
) {
807 html
->Printf("<tr class=\"entry\"><td colspan=\"5\">%s</td></tr>\n", line
);
809 for (p
= line
; *p
&& xisspace(*p
); ++p
);
810 if (*p
&& !xisspace(*p
))
811 flags
.listformat_unknown
= 1;
816 if (!strcmp(parts
->name
, ".") || !strcmp(parts
->name
, "..")) {
817 ftpListPartsFree(&parts
);
823 parts
->showname
= xstrdup(parts
->name
);
825 /* {icon} {text} . . . {date}{size}{chdir}{view}{download}{link}\n */
826 xstrncpy(href
, rfc1738_escape_part(parts
->name
), 2048);
828 xstrncpy(text
, parts
->showname
, 2048);
830 switch (parts
->type
) {
833 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
834 mimeGetIconURL("internal-dir"),
836 strcat(href
, "/"); /* margin is allocated above */
840 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
841 mimeGetIconURL("internal-link"),
843 /* sometimes there is an 'l' flag, but no "->" link */
846 char *link2
= xstrdup(html_quote(rfc1738_escape(parts
->link
)));
847 snprintf(link
, 2048, " -> <a href=\"%s%s\">%s</a>",
848 *link2
!= '/' ? prefix
: "", link2
,
849 html_quote(parts
->link
));
856 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
857 mimeGetIconURL(parts
->name
),
859 snprintf(chdir
, 2048, "<a href=\"%s/;type=d\"><img border=\"0\" src=\"%s\" "
860 "alt=\"[DIR]\"></a>",
861 rfc1738_escape_part(parts
->name
),
862 mimeGetIconURL("internal-dir"));
868 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
869 mimeGetIconURL(parts
->name
),
871 snprintf(size
, 2048, " %6" PRId64
"k", parts
->size
);
875 if (parts
->type
!= 'd') {
876 if (mimeGetViewOption(parts
->name
)) {
877 snprintf(view
, 2048, "<a href=\"%s%s;type=a\"><img border=\"0\" src=\"%s\" "
878 "alt=\"[VIEW]\"></a>",
879 prefix
, href
, mimeGetIconURL("internal-view"));
882 if (mimeGetDownloadOption(parts
->name
)) {
883 snprintf(download
, 2048, "<a href=\"%s%s;type=i\"><img border=\"0\" src=\"%s\" "
884 "alt=\"[DOWNLOAD]\"></a>",
885 prefix
, href
, mimeGetIconURL("internal-download"));
889 /* construct the table row from parts. */
892 html
->Printf("<tr class=\"entry\">"
893 "<td class=\"icon\"><a href=\"%s%s\">%s</a></td>"
894 "<td class=\"filename\"><a href=\"%s%s\">%s</a></td>"
895 "<td class=\"date\">%s</td>"
896 "<td class=\"size\">%s</td>"
897 "<td class=\"actions\">%s%s%s%s</td>"
900 prefix
, href
, html_quote(text
),
903 chdir
, view
, download
, link
);
905 ftpListPartsFree(&parts
);
910 Ftp::Gateway::parseListing()
912 char *buf
= data
.readBuf
->content();
913 char *sbuf
; /* NULL-terminated copy of termedBuf */
920 size_t len
= data
.readBuf
->contentSize();
923 debugs(9, 3, HERE
<< "no content to parse for " << entry
->url() );
928 * We need a NULL-terminated buffer for scanning, ick
930 sbuf
= (char *)xmalloc(len
+ 1);
931 xstrncpy(sbuf
, buf
, len
+ 1);
932 end
= sbuf
+ len
- 1;
934 while (*end
!= '\r' && *end
!= '\n' && end
> sbuf
)
939 debugs(9, 3, HERE
<< "usable = " << usable
<< " of " << len
<< " bytes.");
942 if (buf
[0] == '\0' && len
== 1) {
943 debugs(9, 3, HERE
<< "NIL ends data from " << entry
->url() << " transfer problem?");
944 data
.readBuf
->consume(len
);
946 debugs(9, 3, HERE
<< "didn't find end for " << entry
->url());
947 debugs(9, 3, HERE
<< "buffer remains (" << len
<< " bytes) '" << rfc1738_do_escape(buf
,0) << "'");
953 debugs(9, 3, HERE
<< (unsigned long int)len
<< " bytes to play with");
955 line
= (char *)memAllocate(MEM_4K_BUF
);
958 s
+= strspn(s
, crlf
);
960 for (; s
< end
; s
+= strcspn(s
, crlf
), s
+= strspn(s
, crlf
)) {
961 debugs(9, 7, HERE
<< "s = {" << s
<< "}");
962 linelen
= strcspn(s
, crlf
) + 1;
970 xstrncpy(line
, s
, linelen
);
972 debugs(9, 7, HERE
<< "{" << line
<< "}");
974 if (!strncmp(line
, "total", 5))
977 t
= htmlifyListEntry(line
);
980 debugs(9, 7, HERE
<< "listing append: t = {" << t
->contentSize() << ", '" << t
->content() << "'}");
981 listing
.append(t
->content(), t
->contentSize());
986 debugs(9, 7, HERE
<< "Done.");
987 data
.readBuf
->consume(usable
);
988 memFree(line
, MEM_4K_BUF
);
993 Ftp::Gateway::processReplyBody()
995 debugs(9, 3, status());
997 if (request
->method
== Http::METHOD_HEAD
&& (flags
.isdir
|| theSize
!= -1)) {
1002 /* Directory listings are special. They write ther own headers via the error objects */
1003 if (!flags
.http_header_sent
&& data
.readBuf
->contentSize() >= 0 && !flags
.isdir
)
1004 appendSuccessHeader();
1006 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1008 * probably was aborted because content length exceeds one
1009 * of the maximum size limits.
1011 abortTransaction("entry aborted after calling appendSuccessHeader()");
1017 if (adaptationAccessCheckPending
) {
1018 debugs(9, 3, "returning from Ftp::Gateway::processReplyBody due to adaptationAccessCheckPending");
1025 if (!flags
.listing
) {
1030 maybeReadVirginBody();
1032 } else if (const int csize
= data
.readBuf
->contentSize()) {
1033 writeReplyBody(data
.readBuf
->content(), csize
);
1034 debugs(9, 5, HERE
<< "consuming " << csize
<< " bytes of readBuf");
1035 data
.readBuf
->consume(csize
);
1040 maybeReadVirginBody();
1044 * Locates the FTP user:password login.
1046 * Highest to lowest priority:
1047 * - Checks URL (ftp://user:pass@domain)
1048 * - Authorization: Basic header
1049 * - squid.conf anonymous-FTP settings (default: anonymous:Squid@).
1051 * Special Case: A username-only may be provided in the URL and password in the HTTP headers.
1053 * TODO: we might be able to do something about locating username from other sources:
1054 * ie, external ACL user=* tag or ident lookup
1056 \retval 1 if we have everything needed to complete this request.
1057 \retval 0 if something is missing.
1060 Ftp::Gateway::checkAuth(const HttpHeader
* req_hdr
)
1062 /* default username */
1063 xstrncpy(user
, "anonymous", MAX_URL
);
1065 #if HAVE_AUTH_MODULE_BASIC
1066 /* Check HTTP Authorization: headers (better than defaults, but less than URL) */
1068 if ( (auth
= req_hdr
->getAuth(HDR_AUTHORIZATION
, "Basic")) ) {
1069 flags
.authenticated
= 1;
1070 loginParser(auth
, FTP_LOGIN_NOT_ESCAPED
);
1072 /* we fail with authorization-required error later IFF the FTP server requests it */
1075 /* Test URL login syntax. Overrides any headers received. */
1076 loginParser(request
->login
, FTP_LOGIN_ESCAPED
);
1078 /* name is missing. thats fatal. */
1080 fatal("FTP login parsing destroyed username info");
1082 /* name + password == success */
1086 /* Setup default FTP password settings */
1087 /* this has to be done last so that we can have a no-password case above. */
1089 if (strcmp(user
, "anonymous") == 0 && !flags
.tried_auth_anonymous
) {
1090 xstrncpy(password
, Config
.Ftp
.anon_user
, MAX_URL
);
1091 flags
.tried_auth_anonymous
=1;
1093 } else if (!flags
.tried_auth_nopass
) {
1094 xstrncpy(password
, null_string
, MAX_URL
);
1095 flags
.tried_auth_nopass
=1;
1100 return 0; /* different username */
1103 static String str_type_eq
;
1105 Ftp::Gateway::checkUrlpath()
1110 if (str_type_eq
.size()==0) //hack. String doesn't support global-static
1111 str_type_eq
="type=";
1113 if ((t
= request
->urlpath
.rfind(';')) != String::npos
) {
1114 if (request
->urlpath
.substr(t
+1,t
+1+str_type_eq
.size())==str_type_eq
) {
1115 typecode
= (char)xtoupper(request
->urlpath
[t
+str_type_eq
.size()+1]);
1116 request
->urlpath
.cut(t
);
1120 l
= request
->urlpath
.size();
1121 /* check for null path */
1126 flags
.need_base_href
= 1; /* Work around broken browsers */
1127 } else if (!request
->urlpath
.cmp("/%2f/")) {
1128 /* UNIX root directory */
1131 } else if ((l
>= 1) && (request
->urlpath
[l
- 1] == '/')) {
1132 /* Directory URL, ending in / */
1138 flags
.dir_slash
= 1;
1143 Ftp::Gateway::buildTitleUrl()
1145 title_url
= "ftp://";
1147 if (strcmp(user
, "anonymous")) {
1148 title_url
.append(user
);
1149 title_url
.append("@");
1152 title_url
.append(request
->GetHost());
1154 if (request
->port
!= urlDefaultPort(AnyP::PROTO_FTP
)) {
1155 title_url
.append(":");
1156 title_url
.append(xitoa(request
->port
));
1159 title_url
.append (request
->urlpath
);
1161 base_href
= "ftp://";
1163 if (strcmp(user
, "anonymous") != 0) {
1164 base_href
.append(rfc1738_escape_part(user
));
1167 base_href
.append (":");
1168 base_href
.append(rfc1738_escape_part(password
));
1171 base_href
.append("@");
1174 base_href
.append(request
->GetHost());
1176 if (request
->port
!= urlDefaultPort(AnyP::PROTO_FTP
)) {
1177 base_href
.append(":");
1178 base_href
.append(xitoa(request
->port
));
1181 base_href
.append(request
->urlpath
);
1182 base_href
.append("/");
1186 Ftp::Gateway::start()
1188 if (!checkAuth(&request
->header
)) {
1189 /* create appropriate reply */
1190 HttpReply
*reply
= ftpAuthRequired(request
, ftpRealm());
1191 entry
->replaceHttpReply(reply
);
1198 debugs(9, 5, HERE
<< "FD " << ctrl
.conn
->fd
<< " : host=" << request
->GetHost() <<
1199 ", path=" << request
->urlpath
<< ", user=" << user
<< ", passwd=" << password
);
1201 Ftp::Client::start();
1204 /* ====================================================================== */
1207 Ftp::Gateway::handleControlReply()
1209 Ftp::Client::handleControlReply();
1210 if (ctrl
.message
== NULL
)
1211 return; // didn't get complete reply yet
1213 /* Copy the message except for the last line to cwd_message to be
1214 * printed in error messages.
1216 for (wordlist
*w
= ctrl
.message
; w
&& w
->next
; w
= w
->next
) {
1217 cwd_message
.append('\n');
1218 cwd_message
.append(w
->key
);
1221 FTP_SM_FUNCS
[state
] (this);
1224 /* ====================================================================== */
1227 ftpReadWelcome(Ftp::Gateway
* ftpState
)
1229 int code
= ftpState
->ctrl
.replycode
;
1232 if (ftpState
->flags
.pasv_only
)
1233 ++ ftpState
->login_att
;
1236 if (ftpState
->ctrl
.message
) {
1237 if (strstr(ftpState
->ctrl
.message
->key
, "NetWare"))
1238 ftpState
->flags
.skip_whitespace
= 1;
1241 ftpSendUser(ftpState
);
1242 } else if (code
== 120) {
1243 if (NULL
!= ftpState
->ctrl
.message
)
1244 debugs(9, DBG_IMPORTANT
, "FTP server is busy: " << ftpState
->ctrl
.message
->key
);
1253 * Translate FTP login failure into HTTP error
1254 * this is an attmpt to get the 407 message to show up outside Squid.
1255 * its NOT a general failure. But a correct FTP response type.
1258 Ftp::Gateway::loginFailed()
1260 ErrorState
*err
= NULL
;
1261 const char *command
, *reply
;
1263 if ((state
== SENT_USER
|| state
== SENT_PASS
) && ctrl
.replycode
>= 400) {
1264 if (ctrl
.replycode
== 421 || ctrl
.replycode
== 426) {
1265 // 421/426 - Service Overload - retry permitted.
1266 err
= new ErrorState(ERR_FTP_UNAVAILABLE
, Http::scServiceUnavailable
, fwd
->request
);
1267 } else if (ctrl
.replycode
>= 430 && ctrl
.replycode
<= 439) {
1268 // 43x - Invalid or Credential Error - retry challenge required.
1269 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1270 } else if (ctrl
.replycode
>= 530 && ctrl
.replycode
<= 539) {
1271 // 53x - Credentials Missing - retry challenge required
1272 if (password_url
) // but they were in the URI! major fail.
1273 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scForbidden
, fwd
->request
);
1275 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1279 // any other problems are general falures.
1285 err
->ftp
.server_msg
= ctrl
.message
;
1287 ctrl
.message
= NULL
;
1290 command
= old_request
;
1292 command
= ctrl
.last_command
;
1294 if (command
&& strncmp(command
, "PASS", 4) == 0)
1295 command
= "PASS <yourpassword>";
1300 reply
= ctrl
.last_reply
;
1303 err
->ftp
.request
= xstrdup(command
);
1306 err
->ftp
.reply
= xstrdup(reply
);
1308 HttpReply
*newrep
= err
->BuildHttpReply();
1311 #if HAVE_AUTH_MODULE_BASIC
1312 /* add Authenticate header */
1313 newrep
->header
.putAuth("Basic", ftpRealm());
1316 // add it to the store entry for response....
1317 entry
->replaceHttpReply(newrep
);
1322 Ftp::Gateway::ftpRealm()
1324 static char realm
[8192];
1326 /* This request is not fully authenticated */
1328 snprintf(realm
, 8192, "FTP %s unknown", user
);
1329 } else if (request
->port
== 21) {
1330 snprintf(realm
, 8192, "FTP %s %s", user
, request
->GetHost());
1332 snprintf(realm
, 8192, "FTP %s %s port %d", user
, request
->GetHost(), request
->port
);
1338 ftpSendUser(Ftp::Gateway
* ftpState
)
1340 /* check the server control channel is still available */
1341 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendUser"))
1344 if (ftpState
->proxy_host
!= NULL
)
1345 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s@%s\r\n",
1347 ftpState
->request
->GetHost());
1349 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s\r\n", ftpState
->user
);
1351 ftpState
->writeCommand(cbuf
);
1353 ftpState
->state
= Ftp::Client::SENT_USER
;
1357 ftpReadUser(Ftp::Gateway
* ftpState
)
1359 int code
= ftpState
->ctrl
.replycode
;
1363 ftpReadPass(ftpState
);
1364 } else if (code
== 331) {
1365 ftpSendPass(ftpState
);
1367 ftpState
->loginFailed();
1372 ftpSendPass(Ftp::Gateway
* ftpState
)
1374 /* check the server control channel is still available */
1375 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPass"))
1378 snprintf(cbuf
, CTRL_BUFLEN
, "PASS %s\r\n", ftpState
->password
);
1379 ftpState
->writeCommand(cbuf
);
1380 ftpState
->state
= Ftp::Client::SENT_PASS
;
1384 ftpReadPass(Ftp::Gateway
* ftpState
)
1386 int code
= ftpState
->ctrl
.replycode
;
1387 debugs(9, 3, HERE
<< "code=" << code
);
1390 ftpSendType(ftpState
);
1392 ftpState
->loginFailed();
1397 ftpSendType(Ftp::Gateway
* ftpState
)
1400 const char *filename
;
1403 /* check the server control channel is still available */
1404 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendType"))
1408 * Ref section 3.2.2 of RFC 1738
1410 mode
= ftpState
->typecode
;
1425 if (ftpState
->flags
.isdir
) {
1428 t
= ftpState
->request
->urlpath
.rpos('/');
1429 filename
= t
? t
+ 1 : ftpState
->request
->urlpath
.termedBuf();
1430 mode
= mimeGetTransferMode(filename
);
1437 ftpState
->flags
.binary
= 1;
1439 ftpState
->flags
.binary
= 0;
1441 snprintf(cbuf
, CTRL_BUFLEN
, "TYPE %c\r\n", mode
);
1443 ftpState
->writeCommand(cbuf
);
1445 ftpState
->state
= Ftp::Client::SENT_TYPE
;
1449 ftpReadType(Ftp::Gateway
* ftpState
)
1451 int code
= ftpState
->ctrl
.replycode
;
1454 debugs(9, 3, HERE
<< "code=" << code
);
1457 p
= path
= xstrdup(ftpState
->request
->urlpath
.termedBuf());
1464 p
+= strcspn(p
, "/");
1471 rfc1738_unescape(d
);
1474 wordlistAdd(&ftpState
->pathcomps
, d
);
1479 if (ftpState
->pathcomps
)
1480 ftpTraverseDirectory(ftpState
);
1482 ftpListDir(ftpState
);
1489 ftpTraverseDirectory(Ftp::Gateway
* ftpState
)
1492 debugs(9, 4, HERE
<< (ftpState
->filepath
? ftpState
->filepath
: "<NULL>"));
1494 safe_free(ftpState
->dirpath
);
1495 ftpState
->dirpath
= ftpState
->filepath
;
1496 ftpState
->filepath
= NULL
;
1500 if (ftpState
->pathcomps
== NULL
) {
1501 debugs(9, 3, HERE
<< "the final component was a directory");
1502 ftpListDir(ftpState
);
1506 /* Go to next path component */
1507 w
= ftpState
->pathcomps
;
1509 ftpState
->filepath
= w
->key
;
1511 ftpState
->pathcomps
= w
->next
;
1515 /* Check if we are to CWD or RETR */
1516 if (ftpState
->pathcomps
!= NULL
|| ftpState
->flags
.isdir
) {
1517 ftpSendCwd(ftpState
);
1519 debugs(9, 3, HERE
<< "final component is probably a file");
1520 ftpGetFile(ftpState
);
1526 ftpSendCwd(Ftp::Gateway
* ftpState
)
1530 /* check the server control channel is still available */
1531 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendCwd"))
1536 path
= ftpState
->filepath
;
1538 if (!strcmp(path
, "..") || !strcmp(path
, "/")) {
1539 ftpState
->flags
.no_dotdot
= 1;
1541 ftpState
->flags
.no_dotdot
= 0;
1544 snprintf(cbuf
, CTRL_BUFLEN
, "CWD %s\r\n", path
);
1546 ftpState
->writeCommand(cbuf
);
1548 ftpState
->state
= Ftp::Client::SENT_CWD
;
1552 ftpReadCwd(Ftp::Gateway
* ftpState
)
1554 int code
= ftpState
->ctrl
.replycode
;
1557 if (code
>= 200 && code
< 300) {
1561 /* Reset cwd_message to only include the last message */
1562 ftpState
->cwd_message
.reset("");
1563 for (wordlist
*w
= ftpState
->ctrl
.message
; w
; w
= w
->next
) {
1564 ftpState
->cwd_message
.append(' ');
1565 ftpState
->cwd_message
.append(w
->key
);
1567 ftpState
->ctrl
.message
= NULL
;
1569 /* Continue to traverse the path */
1570 ftpTraverseDirectory(ftpState
);
1574 if (!ftpState
->flags
.put
)
1577 ftpSendMkdir(ftpState
);
1582 ftpSendMkdir(Ftp::Gateway
* ftpState
)
1586 /* check the server control channel is still available */
1587 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMkdir"))
1590 path
= ftpState
->filepath
;
1591 debugs(9, 3, HERE
<< "with path=" << path
);
1592 snprintf(cbuf
, CTRL_BUFLEN
, "MKD %s\r\n", path
);
1593 ftpState
->writeCommand(cbuf
);
1594 ftpState
->state
= Ftp::Client::SENT_MKDIR
;
1598 ftpReadMkdir(Ftp::Gateway
* ftpState
)
1600 char *path
= ftpState
->filepath
;
1601 int code
= ftpState
->ctrl
.replycode
;
1603 debugs(9, 3, HERE
<< "path " << path
<< ", code " << code
);
1605 if (code
== 257) { /* success */
1606 ftpSendCwd(ftpState
);
1607 } else if (code
== 550) { /* dir exists */
1609 if (ftpState
->flags
.put_mkdir
) {
1610 ftpState
->flags
.put_mkdir
= 1;
1611 ftpSendCwd(ftpState
);
1613 ftpSendReply(ftpState
);
1615 ftpSendReply(ftpState
);
1619 ftpGetFile(Ftp::Gateway
* ftpState
)
1621 assert(*ftpState
->filepath
!= '\0');
1622 ftpState
->flags
.isdir
= 0;
1623 ftpSendMdtm(ftpState
);
1627 ftpListDir(Ftp::Gateway
* ftpState
)
1629 if (ftpState
->flags
.dir_slash
) {
1630 debugs(9, 3, HERE
<< "Directory path did not end in /");
1631 ftpState
->title_url
.append("/");
1632 ftpState
->flags
.isdir
= 1;
1635 ftpSendPassive(ftpState
);
1639 ftpSendMdtm(Ftp::Gateway
* ftpState
)
1641 /* check the server control channel is still available */
1642 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMdtm"))
1645 assert(*ftpState
->filepath
!= '\0');
1646 snprintf(cbuf
, CTRL_BUFLEN
, "MDTM %s\r\n", ftpState
->filepath
);
1647 ftpState
->writeCommand(cbuf
);
1648 ftpState
->state
= Ftp::Client::SENT_MDTM
;
1652 ftpReadMdtm(Ftp::Gateway
* ftpState
)
1654 int code
= ftpState
->ctrl
.replycode
;
1658 ftpState
->mdtm
= parse_iso3307_time(ftpState
->ctrl
.last_reply
);
1660 } else if (code
< 0) {
1665 ftpSendSize(ftpState
);
1669 ftpSendSize(Ftp::Gateway
* ftpState
)
1671 /* check the server control channel is still available */
1672 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendSize"))
1675 /* Only send SIZE for binary transfers. The returned size
1676 * is useless on ASCII transfers */
1678 if (ftpState
->flags
.binary
) {
1679 assert(ftpState
->filepath
!= NULL
);
1680 assert(*ftpState
->filepath
!= '\0');
1681 snprintf(cbuf
, CTRL_BUFLEN
, "SIZE %s\r\n", ftpState
->filepath
);
1682 ftpState
->writeCommand(cbuf
);
1683 ftpState
->state
= Ftp::Client::SENT_SIZE
;
1685 /* Skip to next state no non-binary transfers */
1686 ftpSendPassive(ftpState
);
1690 ftpReadSize(Ftp::Gateway
* ftpState
)
1692 int code
= ftpState
->ctrl
.replycode
;
1697 ftpState
->theSize
= strtoll(ftpState
->ctrl
.last_reply
, NULL
, 10);
1699 if (ftpState
->theSize
== 0) {
1700 debugs(9, 2, "SIZE reported " <<
1701 ftpState
->ctrl
.last_reply
<< " on " <<
1702 ftpState
->title_url
);
1703 ftpState
->theSize
= -1;
1705 } else if (code
< 0) {
1710 ftpSendPassive(ftpState
);
1714 ftpReadEPSV(Ftp::Gateway
* ftpState
)
1716 Ip::Address srvAddr
; // unused
1717 if (ftpState
->handleEpsvReply(srvAddr
)) {
1718 if (ftpState
->ctrl
.message
== NULL
)
1719 return; // didn't get complete reply yet
1721 ftpState
->connectDataChannel();
1725 /** Send Passive connection request.
1726 * Default method is to use modern EPSV request.
1727 * The failover mechanism should check for previous state and re-call with alternates on failure.
1730 ftpSendPassive(Ftp::Gateway
* ftpState
)
1732 /** Checks the server control channel is still available before running. */
1733 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPassive"))
1739 * Checks for 'HEAD' method request and passes off for special handling by Ftp::Gateway::processHeadResponse(). */
1740 if (ftpState
->request
->method
== Http::METHOD_HEAD
&& (ftpState
->flags
.isdir
|| ftpState
->theSize
!= -1)) {
1741 ftpState
->processHeadResponse(); // may call serverComplete
1745 if (ftpState
->sendPassive()) {
1746 // SENT_EPSV_ALL blocks other non-EPSV connections being attempted
1747 if (ftpState
->state
== Ftp::Client::SENT_EPSV_ALL
)
1748 ftpState
->flags
.epsv_all_sent
= true;
1753 Ftp::Gateway::processHeadResponse()
1755 debugs(9, 5, HERE
<< "handling HEAD response");
1757 appendSuccessHeader();
1760 * On rare occasions I'm seeing the entry get aborted after
1761 * readControlReply() and before here, probably when
1762 * trying to write to the client.
1764 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1765 abortTransaction("entry aborted while processing HEAD");
1770 if (adaptationAccessCheckPending
) {
1771 debugs(9,3, HERE
<< "returning due to adaptationAccessCheckPending");
1776 // processReplyBody calls serverComplete() since there is no body
1781 ftpReadPasv(Ftp::Gateway
* ftpState
)
1783 Ip::Address srvAddr
; // unused
1784 if (ftpState
->handlePasvReply(srvAddr
))
1785 ftpState
->connectDataChannel();
1787 ftpSendEPRT(ftpState
);
1793 Ftp::Gateway::dataChannelConnected(const CommConnectCbParams
&io
)
1798 if (io
.flag
!= Comm::OK
) {
1799 debugs(9, 2, HERE
<< "Failed to connect. Retrying via another method.");
1801 // ABORT on timeouts. server may be waiting on a broken TCP link.
1802 if (io
.xerrno
== Comm::TIMEOUT
)
1803 writeCommand("ABOR");
1805 // try another connection attempt with some other method
1806 ftpSendPassive(this);
1810 data
.opened(io
.conn
, dataCloser());
1811 ftpRestOrList(this);
1815 ftpOpenListenSocket(Ftp::Gateway
* ftpState
, int fallback
)
1817 /// Close old data channels, if any. We may open a new one below.
1818 if (ftpState
->data
.conn
!= NULL
) {
1819 if ((ftpState
->data
.conn
->flags
& COMM_REUSEADDR
))
1820 // NP: in fact it points to the control channel. just clear it.
1821 ftpState
->data
.clear();
1823 ftpState
->data
.close();
1825 safe_free(ftpState
->data
.host
);
1828 * Set up a listen socket on the same local address as the
1829 * control connection.
1831 Comm::ConnectionPointer temp
= new Comm::Connection
;
1832 temp
->local
= ftpState
->ctrl
.conn
->local
;
1835 * REUSEADDR is needed in fallback mode, since the same port is
1836 * used for both control and data.
1840 setsockopt(ftpState
->ctrl
.conn
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
));
1841 ftpState
->ctrl
.conn
->flags
|= COMM_REUSEADDR
;
1842 temp
->flags
|= COMM_REUSEADDR
;
1844 /* if not running in fallback mode a new port needs to be retrieved */
1845 temp
->local
.port(0);
1848 ftpState
->listenForDataChannel(temp
);
1852 ftpSendPORT(Ftp::Gateway
* ftpState
)
1854 /* check the server control channel is still available */
1855 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPort"))
1858 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1859 debugs(9, DBG_IMPORTANT
, "FTP does not allow PORT method after 'EPSV ALL' has been sent.");
1864 ftpState
->flags
.pasv_supported
= 0;
1865 ftpOpenListenSocket(ftpState
, 0);
1867 if (!Comm::IsConnOpen(ftpState
->data
.listenConn
)) {
1868 if ( ftpState
->data
.listenConn
!= NULL
&& !ftpState
->data
.listenConn
->local
.isIPv4() ) {
1869 /* non-IPv4 CANNOT send PORT command. */
1870 /* we got here by attempting and failing an EPRT */
1871 /* using the same reply code should simulate a PORT failure */
1872 ftpReadPORT(ftpState
);
1876 /* XXX Need to set error message */
1881 // pull out the internal IP address bytes to send in PORT command...
1882 // source them from the listen_conn->local
1884 struct addrinfo
*AI
= NULL
;
1885 ftpState
->data
.listenConn
->local
.getAddrInfo(AI
, AF_INET
);
1886 unsigned char *addrptr
= (unsigned char *) &((struct sockaddr_in
*)AI
->ai_addr
)->sin_addr
;
1887 unsigned char *portptr
= (unsigned char *) &((struct sockaddr_in
*)AI
->ai_addr
)->sin_port
;
1888 snprintf(cbuf
, CTRL_BUFLEN
, "PORT %d,%d,%d,%d,%d,%d\r\n",
1889 addrptr
[0], addrptr
[1], addrptr
[2], addrptr
[3],
1890 portptr
[0], portptr
[1]);
1891 ftpState
->writeCommand(cbuf
);
1892 ftpState
->state
= Ftp::Client::SENT_PORT
;
1894 Ip::Address::FreeAddrInfo(AI
);
1898 ftpReadPORT(Ftp::Gateway
* ftpState
)
1900 int code
= ftpState
->ctrl
.replycode
;
1904 /* Fall back on using the same port as the control connection */
1905 debugs(9, 3, "PORT not supported by remote end");
1906 ftpOpenListenSocket(ftpState
, 1);
1909 ftpRestOrList(ftpState
);
1913 ftpSendEPRT(Ftp::Gateway
* ftpState
)
1915 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1916 debugs(9, DBG_IMPORTANT
, "FTP does not allow EPRT method after 'EPSV ALL' has been sent.");
1920 if (!Config
.Ftp
.eprt
) {
1921 /* Disabled. Switch immediately to attempting old PORT command. */
1922 debugs(9, 3, "EPRT disabled by local administrator");
1923 ftpSendPORT(ftpState
);
1928 ftpState
->flags
.pasv_supported
= 0;
1930 ftpOpenListenSocket(ftpState
, 0);
1931 debugs(9, 3, "Listening for FTP data connection with FD " << ftpState
->data
.conn
);
1932 if (!Comm::IsConnOpen(ftpState
->data
.conn
)) {
1933 /* XXX Need to set error message */
1938 char buf
[MAX_IPSTRLEN
];
1940 /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
1941 /* Which can be used by EITHER protocol. */
1942 snprintf(cbuf
, CTRL_BUFLEN
, "EPRT |%d|%s|%d|\r\n",
1943 ( ftpState
->data
.listenConn
->local
.isIPv6() ? 2 : 1 ),
1944 ftpState
->data
.listenConn
->local
.toStr(buf
,MAX_IPSTRLEN
),
1945 ftpState
->data
.listenConn
->local
.port() );
1947 ftpState
->writeCommand(cbuf
);
1948 ftpState
->state
= Ftp::Client::SENT_EPRT
;
1952 ftpReadEPRT(Ftp::Gateway
* ftpState
)
1954 int code
= ftpState
->ctrl
.replycode
;
1958 /* Failover to attempting old PORT command. */
1959 debugs(9, 3, "EPRT not supported by remote end");
1960 ftpSendPORT(ftpState
);
1964 ftpRestOrList(ftpState
);
1967 /** "read" handler to accept FTP data connections.
1969 \param io comm accept(2) callback parameters
1972 Ftp::Gateway::ftpAcceptDataConnection(const CommAcceptCbParams
&io
)
1976 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1977 abortTransaction("entry aborted when accepting data conn");
1978 data
.listenConn
->close();
1979 data
.listenConn
= NULL
;
1983 if (io
.flag
!= Comm::OK
) {
1984 data
.listenConn
->close();
1985 data
.listenConn
= NULL
;
1986 debugs(9, DBG_IMPORTANT
, "FTP AcceptDataConnection: " << io
.conn
<< ": " << xstrerr(io
.xerrno
));
1987 /** \todo Need to send error message on control channel*/
1992 /* data listening conn is no longer even open. abort. */
1993 if (!Comm::IsConnOpen(data
.listenConn
)) {
1994 data
.listenConn
= NULL
; // ensure that it's cleared and not just closed.
1998 /* data listening conn is no longer even open. abort. */
1999 if (!Comm::IsConnOpen(data
.conn
)) {
2000 data
.clear(); // ensure that it's cleared and not just closed.
2005 * When squid.conf ftp_sanitycheck is enabled, check the new connection is actually being
2006 * made by the remote client which is connected to the FTP control socket.
2007 * Or the one which we were told to listen for by control channel messages (may differ under NAT).
2008 * This prevents third-party hacks, but also third-party load balancing handshakes.
2010 if (Config
.Ftp
.sanitycheck
) {
2011 // accept if either our data or ctrl connection is talking to this remote peer.
2012 if (data
.conn
->remote
!= io
.conn
->remote
&& ctrl
.conn
->remote
!= io
.conn
->remote
) {
2013 debugs(9, DBG_IMPORTANT
,
2014 "FTP data connection from unexpected server (" <<
2015 io
.conn
->remote
<< "), expecting " <<
2016 data
.conn
->remote
<< " or " << ctrl
.conn
->remote
);
2018 /* close the bad sources connection down ASAP. */
2021 /* drop the bad connection (io) by ignoring the attempt. */
2026 /** On Comm::OK start using the accepted data socket and discard the temporary listen socket. */
2028 data
.opened(io
.conn
, dataCloser());
2029 data
.addr(io
.conn
->remote
);
2031 debugs(9, 3, HERE
<< "Connected data socket on " <<
2032 io
.conn
<< ". FD table says: " <<
2033 "ctrl-peer= " << fd_table
[ctrl
.conn
->fd
].ipaddr
<< ", " <<
2034 "data-peer= " << fd_table
[data
.conn
->fd
].ipaddr
);
2036 assert(haveControlChannel("ftpAcceptDataConnection"));
2037 assert(ctrl
.message
== NULL
);
2039 // Ctrl channel operations will determine what happens to this data connection
2043 ftpRestOrList(Ftp::Gateway
* ftpState
)
2047 if (ftpState
->typecode
== 'D') {
2048 ftpState
->flags
.isdir
= 1;
2050 if (ftpState
->flags
.put
) {
2051 ftpSendMkdir(ftpState
); /* PUT name;type=d */
2053 ftpSendNlst(ftpState
); /* GET name;type=d sec 3.2.2 of RFC 1738 */
2055 } else if (ftpState
->flags
.put
) {
2056 ftpSendStor(ftpState
);
2057 } else if (ftpState
->flags
.isdir
)
2058 ftpSendList(ftpState
);
2059 else if (ftpState
->restartable())
2060 ftpSendRest(ftpState
);
2062 ftpSendRetr(ftpState
);
2066 ftpSendStor(Ftp::Gateway
* ftpState
)
2068 /* check the server control channel is still available */
2069 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendStor"))
2074 if (ftpState
->filepath
!= NULL
) {
2075 /* Plain file upload */
2076 snprintf(cbuf
, CTRL_BUFLEN
, "STOR %s\r\n", ftpState
->filepath
);
2077 ftpState
->writeCommand(cbuf
);
2078 ftpState
->state
= Ftp::Client::SENT_STOR
;
2079 } else if (ftpState
->request
->header
.getInt64(HDR_CONTENT_LENGTH
) > 0) {
2080 /* File upload without a filename. use STOU to generate one */
2081 snprintf(cbuf
, CTRL_BUFLEN
, "STOU\r\n");
2082 ftpState
->writeCommand(cbuf
);
2083 ftpState
->state
= Ftp::Client::SENT_STOR
;
2085 /* No file to transfer. Only create directories if needed */
2086 ftpSendReply(ftpState
);
2090 /// \deprecated use ftpState->readStor() instead.
2092 ftpReadStor(Ftp::Gateway
* ftpState
)
2094 ftpState
->readStor();
2097 void Ftp::Gateway::readStor()
2099 int code
= ctrl
.replycode
;
2102 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(data
.conn
))) {
2103 if (!originalRequest()->body_pipe
) {
2104 debugs(9, 3, "zero-size STOR?");
2105 state
= WRITING_DATA
; // make ftpWriteTransferDone() responsible
2106 dataComplete(); // XXX: keep in sync with doneSendingRequestBody()
2110 if (!startRequestBodyFlow()) { // register to receive body data
2115 /* When client status is 125, or 150 and the data connection is open, Begin data transfer. */
2116 debugs(9, 3, HERE
<< "starting data transfer");
2117 switchTimeoutToDataChannel();
2118 sendMoreRequestBody();
2119 fwd
->dontRetry(true); // dont permit re-trying if the body was sent.
2120 state
= WRITING_DATA
;
2121 debugs(9, 3, HERE
<< "writing data channel");
2122 } else if (code
== 150) {
2123 /* When client code is 150 with no data channel, Accept data channel. */
2124 debugs(9, 3, "ftpReadStor: accepting data channel");
2125 listenForDataChannel(data
.conn
);
2127 debugs(9, DBG_IMPORTANT
, HERE
<< "Unexpected reply code "<< std::setfill('0') << std::setw(3) << code
);
2133 ftpSendRest(Ftp::Gateway
* ftpState
)
2135 /* check the server control channel is still available */
2136 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRest"))
2141 snprintf(cbuf
, CTRL_BUFLEN
, "REST %" PRId64
"\r\n", ftpState
->restart_offset
);
2142 ftpState
->writeCommand(cbuf
);
2143 ftpState
->state
= Ftp::Client::SENT_REST
;
2147 Ftp::Gateway::restartable()
2149 if (restart_offset
> 0)
2152 if (!request
->range
)
2161 int64_t desired_offset
= request
->range
->lowestOffset(theSize
);
2163 if (desired_offset
<= 0)
2166 if (desired_offset
>= theSize
)
2169 restart_offset
= desired_offset
;
2174 ftpReadRest(Ftp::Gateway
* ftpState
)
2176 int code
= ftpState
->ctrl
.replycode
;
2178 assert(ftpState
->restart_offset
> 0);
2181 ftpState
->setCurrentOffset(ftpState
->restart_offset
);
2182 ftpSendRetr(ftpState
);
2183 } else if (code
> 0) {
2184 debugs(9, 3, HERE
<< "REST not supported");
2185 ftpState
->flags
.rest_supported
= 0;
2186 ftpSendRetr(ftpState
);
2193 ftpSendList(Ftp::Gateway
* ftpState
)
2195 /* check the server control channel is still available */
2196 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendList"))
2201 if (ftpState
->filepath
) {
2202 snprintf(cbuf
, CTRL_BUFLEN
, "LIST %s\r\n", ftpState
->filepath
);
2204 snprintf(cbuf
, CTRL_BUFLEN
, "LIST\r\n");
2207 ftpState
->writeCommand(cbuf
);
2208 ftpState
->state
= Ftp::Client::SENT_LIST
;
2212 ftpSendNlst(Ftp::Gateway
* ftpState
)
2214 /* check the server control channel is still available */
2215 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendNlst"))
2220 ftpState
->flags
.tried_nlst
= 1;
2222 if (ftpState
->filepath
) {
2223 snprintf(cbuf
, CTRL_BUFLEN
, "NLST %s\r\n", ftpState
->filepath
);
2225 snprintf(cbuf
, CTRL_BUFLEN
, "NLST\r\n");
2228 ftpState
->writeCommand(cbuf
);
2229 ftpState
->state
= Ftp::Client::SENT_NLST
;
2233 ftpReadList(Ftp::Gateway
* ftpState
)
2235 int code
= ftpState
->ctrl
.replycode
;
2238 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2239 /* Begin data transfer */
2240 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2241 ftpState
->switchTimeoutToDataChannel();
2242 ftpState
->maybeReadVirginBody();
2243 ftpState
->state
= Ftp::Client::READING_DATA
;
2245 } else if (code
== 150) {
2246 /* Accept data channel */
2247 debugs(9, 3, HERE
<< "accept data channel from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2248 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2250 } else if (!ftpState
->flags
.tried_nlst
&& code
> 300) {
2251 ftpSendNlst(ftpState
);
2259 ftpSendRetr(Ftp::Gateway
* ftpState
)
2261 /* check the server control channel is still available */
2262 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRetr"))
2267 assert(ftpState
->filepath
!= NULL
);
2268 snprintf(cbuf
, CTRL_BUFLEN
, "RETR %s\r\n", ftpState
->filepath
);
2269 ftpState
->writeCommand(cbuf
);
2270 ftpState
->state
= Ftp::Client::SENT_RETR
;
2274 ftpReadRetr(Ftp::Gateway
* ftpState
)
2276 int code
= ftpState
->ctrl
.replycode
;
2279 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2280 /* Begin data transfer */
2281 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2282 ftpState
->switchTimeoutToDataChannel();
2283 ftpState
->maybeReadVirginBody();
2284 ftpState
->state
= Ftp::Client::READING_DATA
;
2285 } else if (code
== 150) {
2286 /* Accept data channel */
2287 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2288 } else if (code
>= 300) {
2289 if (!ftpState
->flags
.try_slash_hack
) {
2290 /* Try this as a directory missing trailing slash... */
2291 ftpState
->hackShortcut(ftpSendCwd
);
2301 * Generate the HTTP headers and template fluff around an FTP
2302 * directory listing display.
2305 Ftp::Gateway::completedListing()
2308 entry
->lock("Ftp::Gateway");
2309 ErrorState
ferr(ERR_DIR_LISTING
, Http::scOkay
, request
);
2310 ferr
.ftp
.listing
= &listing
;
2311 ferr
.ftp
.cwd_msg
= xstrdup(cwd_message
.size()? cwd_message
.termedBuf() : "");
2312 ferr
.ftp
.server_msg
= ctrl
.message
;
2313 ctrl
.message
= NULL
;
2314 entry
->replaceHttpReply( ferr
.BuildHttpReply() );
2315 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2317 entry
->unlock("Ftp::Gateway");
2321 ftpReadTransferDone(Ftp::Gateway
* ftpState
)
2323 int code
= ftpState
->ctrl
.replycode
;
2326 if (code
== 226 || code
== 250) {
2327 /* Connection closed; retrieval done. */
2328 if (ftpState
->flags
.listing
) {
2329 ftpState
->completedListing();
2330 /* QUIT operation handles sending the reply to client */
2332 ftpSendQuit(ftpState
);
2333 } else { /* != 226 */
2334 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after reading data");
2335 ftpState
->failed(ERR_FTP_FAILURE
, 0);
2336 /* failed closes ctrl.conn and frees ftpState */
2341 // premature end of the request body
2343 Ftp::Gateway::handleRequestBodyProducerAborted()
2345 ServerStateData::handleRequestBodyProducerAborted();
2346 debugs(9, 3, HERE
<< "ftpState=" << this);
2347 failed(ERR_READ_ERROR
, 0);
2351 ftpWriteTransferDone(Ftp::Gateway
* ftpState
)
2353 int code
= ftpState
->ctrl
.replycode
;
2356 if (!(code
== 226 || code
== 250)) {
2357 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after sending data");
2358 ftpState
->failed(ERR_FTP_PUT_ERROR
, 0);
2362 ftpState
->entry
->timestampsSet(); /* XXX Is this needed? */
2363 ftpSendReply(ftpState
);
2367 ftpSendQuit(Ftp::Gateway
* ftpState
)
2369 /* check the server control channel is still available */
2370 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendQuit"))
2373 snprintf(cbuf
, CTRL_BUFLEN
, "QUIT\r\n");
2374 ftpState
->writeCommand(cbuf
);
2375 ftpState
->state
= Ftp::Client::SENT_QUIT
;
2378 /** Completes a client FTP operation with success or other page
2379 * generated and stored in the entry field by the code issuing QUIT.
2382 ftpReadQuit(Ftp::Gateway
* ftpState
)
2384 ftpState
->serverComplete();
2388 ftpTrySlashHack(Ftp::Gateway
* ftpState
)
2391 ftpState
->flags
.try_slash_hack
= 1;
2392 /* Free old paths */
2396 if (ftpState
->pathcomps
)
2397 wordlistDestroy(&ftpState
->pathcomps
);
2399 safe_free(ftpState
->filepath
);
2401 /* Build the new path (urlpath begins with /) */
2402 path
= xstrdup(ftpState
->request
->urlpath
.termedBuf());
2404 rfc1738_unescape(path
);
2406 ftpState
->filepath
= path
;
2409 ftpGetFile(ftpState
);
2413 * Forget hack status. Next error is shown to the user
2416 Ftp::Gateway::unhack()
2420 if (old_request
!= NULL
) {
2421 safe_free(old_request
);
2422 safe_free(old_reply
);
2427 Ftp::Gateway::hackShortcut(FTPSM
* nextState
)
2429 /* Clear some unwanted state */
2430 setCurrentOffset(0);
2432 /* Save old error message & some state info */
2436 if (old_request
== NULL
) {
2437 old_request
= ctrl
.last_command
;
2438 ctrl
.last_command
= NULL
;
2439 old_reply
= ctrl
.last_reply
;
2440 ctrl
.last_reply
= NULL
;
2442 if (pathcomps
== NULL
&& filepath
!= NULL
)
2443 old_filepath
= xstrdup(filepath
);
2446 /* Jump to the "hack" state */
2451 ftpFail(Ftp::Gateway
*ftpState
)
2453 debugs(9, 6, HERE
<< "flags(" <<
2454 (ftpState
->flags
.isdir
?"IS_DIR,":"") <<
2455 (ftpState
->flags
.try_slash_hack
?"TRY_SLASH_HACK":"") << "), " <<
2456 "mdtm=" << ftpState
->mdtm
<< ", size=" << ftpState
->theSize
<<
2457 "slashhack=" << (ftpState
->request
->urlpath
.caseCmp("/%2f", 4)==0? "T":"F") );
2459 /* Try the / hack to support "Netscape" FTP URL's for retreiving files */
2460 if (!ftpState
->flags
.isdir
&& /* Not a directory */
2461 !ftpState
->flags
.try_slash_hack
&& /* Not in slash hack */
2462 ftpState
->mdtm
<= 0 && ftpState
->theSize
< 0 && /* Not known as a file */
2463 ftpState
->request
->urlpath
.caseCmp("/%2f", 4) != 0) { /* No slash encoded */
2465 switch (ftpState
->state
) {
2467 case Ftp::Client::SENT_CWD
:
2469 case Ftp::Client::SENT_RETR
:
2470 /* Try the / hack */
2471 ftpState
->hackShortcut(ftpTrySlashHack
);
2479 ftpState
->failed(ERR_NONE
, 0);
2480 /* failed() closes ctrl.conn and frees this */
2484 Ftp::Gateway::failedHttpStatus(err_type
&error
)
2486 if (error
== ERR_NONE
) {
2493 if (ctrl
.replycode
> 500) {
2494 error
= ERR_FTP_FORBIDDEN
;
2495 return password_url
? Http::scForbidden
: Http::scUnauthorized
;
2496 } else if (ctrl
.replycode
== 421) {
2497 error
= ERR_FTP_UNAVAILABLE
;
2498 return Http::scServiceUnavailable
;
2505 if (ctrl
.replycode
== 550) {
2506 error
= ERR_FTP_NOT_FOUND
;
2507 return Http::scNotFound
;
2515 return Ftp::Client::failedHttpStatus(error
);
2519 ftpSendReply(Ftp::Gateway
* ftpState
)
2521 int code
= ftpState
->ctrl
.replycode
;
2522 Http::StatusCode http_code
;
2523 err_type err_code
= ERR_NONE
;
2525 debugs(9, 3, HERE
<< ftpState
->entry
->url() << ", code " << code
);
2527 if (cbdataReferenceValid(ftpState
))
2528 debugs(9, 5, HERE
<< "ftpState (" << ftpState
<< ") is valid!");
2530 if (code
== 226 || code
== 250) {
2531 err_code
= (ftpState
->mdtm
> 0) ? ERR_FTP_PUT_MODIFIED
: ERR_FTP_PUT_CREATED
;
2532 http_code
= (ftpState
->mdtm
> 0) ? Http::scAccepted
: Http::scCreated
;
2533 } else if (code
== 227) {
2534 err_code
= ERR_FTP_PUT_CREATED
;
2535 http_code
= Http::scCreated
;
2537 err_code
= ERR_FTP_PUT_ERROR
;
2538 http_code
= Http::scInternalServerError
;
2541 ErrorState
err(err_code
, http_code
, ftpState
->request
);
2543 if (ftpState
->old_request
)
2544 err
.ftp
.request
= xstrdup(ftpState
->old_request
);
2546 err
.ftp
.request
= xstrdup(ftpState
->ctrl
.last_command
);
2548 if (ftpState
->old_reply
)
2549 err
.ftp
.reply
= xstrdup(ftpState
->old_reply
);
2550 else if (ftpState
->ctrl
.last_reply
)
2551 err
.ftp
.reply
= xstrdup(ftpState
->ctrl
.last_reply
);
2553 err
.ftp
.reply
= xstrdup("");
2555 // TODO: interpret as FTP-specific error code
2556 err
.detailError(code
);
2558 ftpState
->entry
->replaceHttpReply( err
.BuildHttpReply() );
2560 ftpSendQuit(ftpState
);
2564 Ftp::Gateway::appendSuccessHeader()
2566 const char *mime_type
= NULL
;
2567 const char *mime_enc
= NULL
;
2568 String urlpath
= request
->urlpath
;
2569 const char *filename
= NULL
;
2570 const char *t
= NULL
;
2574 if (flags
.http_header_sent
)
2577 HttpReply
*reply
= new HttpReply
;
2579 flags
.http_header_sent
= 1;
2581 assert(entry
->isEmpty());
2583 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2585 entry
->buffer(); /* released when done processing current data payload */
2587 filename
= (t
= urlpath
.rpos('/')) ? t
+ 1 : urlpath
.termedBuf();
2590 mime_type
= "text/html";
2595 mime_type
= "application/octet-stream";
2596 mime_enc
= mimeGetContentEncoding(filename
);
2600 mime_type
= "text/plain";
2604 mime_type
= mimeGetContentType(filename
);
2605 mime_enc
= mimeGetContentEncoding(filename
);
2610 /* set standard stuff */
2612 if (0 == getCurrentOffset()) {
2614 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2615 } else if (theSize
< getCurrentOffset()) {
2618 * offset should not be larger than theSize. We should
2619 * not be seeing this condition any more because we'll only
2620 * send REST if we know the theSize and if it is less than theSize.
2622 debugs(0,DBG_CRITICAL
,HERE
<< "Whoops! " <<
2623 " current offset=" << getCurrentOffset() <<
2624 ", but theSize=" << theSize
<<
2625 ". assuming full content response");
2626 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2629 HttpHdrRangeSpec range_spec
;
2630 range_spec
.offset
= getCurrentOffset();
2631 range_spec
.length
= theSize
- getCurrentOffset();
2632 reply
->setHeaders(Http::scPartialContent
, "Gatewaying", mime_type
, theSize
- getCurrentOffset(), mdtm
, -2);
2633 httpHeaderAddContRange(&reply
->header
, range_spec
, theSize
);
2636 /* additional info */
2638 reply
->header
.putStr(HDR_CONTENT_ENCODING
, mime_enc
);
2640 setVirginReply(reply
);
2641 adaptOrFinalizeReply();
2645 Ftp::Gateway::haveParsedReplyHeaders()
2647 ServerStateData::haveParsedReplyHeaders();
2649 StoreEntry
*e
= entry
;
2653 if (flags
.authenticated
) {
2655 * Authenticated requests can't be cached.
2658 } else if (!EBIT_TEST(e
->flags
, RELEASE_REQUEST
) && !getCurrentOffset()) {
2666 Ftp::Gateway::ftpAuthRequired(HttpRequest
* request
, const char *realm
)
2668 ErrorState
err(ERR_CACHE_ACCESS_DENIED
, Http::scUnauthorized
, request
);
2669 HttpReply
*newrep
= err
.BuildHttpReply();
2670 #if HAVE_AUTH_MODULE_BASIC
2671 /* add Authenticate header */
2672 newrep
->header
.putAuth("Basic", realm
);
2678 Ftp::UrlWith2f(HttpRequest
* request
)
2680 String newbuf
= "%2f";
2682 if (request
->url
.getScheme() != AnyP::PROTO_FTP
)
2685 if ( request
->urlpath
[0]=='/' ) {
2686 newbuf
.append(request
->urlpath
);
2687 request
->urlpath
.absorb(newbuf
);
2688 safe_free(request
->canonical
);
2689 } else if ( !strncmp(request
->urlpath
.termedBuf(), "%2f", 3) ) {
2690 newbuf
.append(request
->urlpath
.substr(1,request
->urlpath
.size()));
2691 request
->urlpath
.absorb(newbuf
);
2692 safe_free(request
->canonical
);
2695 return urlCanonical(request
);
2699 Ftp::Gateway::printfReplyBody(const char *fmt
, ...)
2702 va_start (args
, fmt
);
2703 static char buf
[4096];
2705 vsnprintf(buf
, 4096, fmt
, args
);
2706 writeReplyBody(buf
, strlen(buf
));
2711 * Call this when there is data from the origin server
2712 * which should be sent to either StoreEntry, or to ICAP...
2715 Ftp::Gateway::writeReplyBody(const char *dataToWrite
, size_t dataLength
)
2717 debugs(9, 5, HERE
<< "writing " << dataLength
<< " bytes to the reply");
2718 addVirginReplyBody(dataToWrite
, dataLength
);
2722 * A hack to ensure we do not double-complete on the forward entry.
2724 \todo Ftp::Gateway logic should probably be rewritten to avoid
2725 * double-completion or FwdState should be rewritten to allow it.
2728 Ftp::Gateway::completeForwarding()
2730 if (fwd
== NULL
|| flags
.completed_forwarding
) {
2731 debugs(9, 3, HERE
<< "completeForwarding avoids " <<
2732 "double-complete on FD " << ctrl
.conn
->fd
<< ", Data FD " << data
.conn
->fd
<<
2733 ", this " << this << ", fwd " << fwd
);
2737 flags
.completed_forwarding
= true;
2738 ServerStateData::completeForwarding();
2742 * Have we lost the FTP server control channel?
2744 \retval true The server control channel is available.
2745 \retval false The server control channel is not available.
2748 Ftp::Gateway::haveControlChannel(const char *caller_name
) const
2750 if (doneWithServer())
2753 /* doneWithServer() only checks BOTH channels are closed. */
2754 if (!Comm::IsConnOpen(ctrl
.conn
)) {
2755 debugs(9, DBG_IMPORTANT
, "WARNING! FTP Server Control channel is closed, but Data channel still active.");
2756 debugs(9, 2, caller_name
<< ": attempted on a closed FTP channel.");
2764 Ftp::Gateway::mayReadVirginReplyBody() const
2766 // TODO: Can we do what Ftp::Relay::mayReadVirginReplyBody() does instead?
2767 return !doneWithServer();
2771 Ftp::StartGateway(FwdState
*const fwdState
)
2773 return AsyncJob::Start(new Ftp::Gateway(fwdState
));