2 * Copyright (C) 1996-2018 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 09 File Transfer Protocol (FTP) */
12 #include "acl/FilledChecklist.h"
13 #include "clients/forward.h"
14 #include "clients/FtpClient.h"
16 #include "comm/ConnOpener.h"
17 #include "comm/Read.h"
18 #include "comm/TcpAcceptor.h"
19 #include "CommCalls.h"
20 #include "compat/strtoll.h"
21 #include "errorpage.h"
25 #include "html_quote.h"
26 #include "HttpHdrContRange.h"
27 #include "HttpHeader.h"
28 #include "HttpHeaderRange.h"
29 #include "HttpReply.h"
34 #include "SquidConfig.h"
35 #include "SquidString.h"
36 #include "SquidTime.h"
37 #include "StatCounters.h"
45 #include "DelayPools.h"
46 #include "MemObject.h"
57 bool pasv_supported
; ///< PASV command is allowed
58 bool epsv_all_sent
; ///< EPSV ALL has been used. Must abort on failures.
60 bool pasv_failed
; // was FwdState::flags.ftp_pasv_failed
63 bool authenticated
; ///< authentication success
64 bool tried_auth_anonymous
; ///< auth has tried to use anonymous credentials already.
65 bool tried_auth_nopass
; ///< auth tried username with no password already.
71 bool http_header_sent
;
81 bool listformat_unknown
;
83 bool completed_forwarding
;
87 typedef void (StateMethod
)(Ftp::Gateway
*);
89 /// FTP Gateway: An FTP client that takes an HTTP request with an ftp:// URI,
90 /// converts it into one or more FTP commands, and then
91 /// converts one or more FTP responses into the final HTTP response.
92 class Gateway
: public Ftp::Client
94 CBDATA_CLASS(Gateway
);
100 char password
[MAX_URL
];
114 int64_t restart_offset
;
120 MemBuf listing
; ///< FTP directory listing in HTML format.
125 // these should all be private
126 virtual void start();
127 virtual Http::StatusCode
failedHttpStatus(err_type
&error
);
129 void appendSuccessHeader();
130 void hackShortcut(StateMethod
*nextState
);
134 MemBuf
*htmlifyListEntry(const char *line
);
135 void completedListing(void);
137 /// create a data channel acceptor and start listening.
138 void listenForDataChannel(const Comm::ConnectionPointer
&conn
);
140 int checkAuth(const HttpHeader
* req_hdr
);
142 void buildTitleUrl();
143 void writeReplyBody(const char *, size_t len
);
144 void printfReplyBody(const char *fmt
, ...);
145 virtual void completeForwarding();
146 void processHeadResponse();
147 void processReplyBody();
148 void setCurrentOffset(int64_t offset
) { currentOffset
= offset
; }
149 int64_t getCurrentOffset() const { return currentOffset
; }
151 virtual void dataChannelConnected(const CommConnectCbParams
&io
);
152 static PF ftpDataWrite
;
153 virtual void timeout(const CommTimeoutCbParams
&io
);
154 void ftpAcceptDataConnection(const CommAcceptCbParams
&io
);
156 static HttpReply
*ftpAuthRequired(HttpRequest
* request
, SBuf
&realm
);
158 void loginFailed(void);
160 virtual void haveParsedReplyHeaders();
162 virtual bool haveControlChannel(const char *caller_name
) const;
165 virtual void handleControlReply();
166 virtual void dataClosed(const CommCloseCbParams
&io
);
169 virtual bool mayReadVirginReplyBody() const;
170 // BodyConsumer for HTTP: consume request body.
171 virtual void handleRequestBodyProducerAborted();
173 void loginParser(const SBuf
&login
, bool escaped
);
178 typedef Ftp::StateMethod FTPSM
; // to avoid lots of non-changes
180 CBDATA_NAMESPACED_CLASS_INIT(Ftp
, Gateway
);
191 #define CTRL_BUFLEN 16*1024
192 static char cbuf
[CTRL_BUFLEN
];
195 * State machine functions
196 * send == state transition
197 * read == wait for response, and select next state transition
198 * other == Transition logic
200 static FTPSM ftpReadWelcome
;
201 static FTPSM ftpSendUser
;
202 static FTPSM ftpReadUser
;
203 static FTPSM ftpSendPass
;
204 static FTPSM ftpReadPass
;
205 static FTPSM ftpSendType
;
206 static FTPSM ftpReadType
;
207 static FTPSM ftpSendMdtm
;
208 static FTPSM ftpReadMdtm
;
209 static FTPSM ftpSendSize
;
210 static FTPSM ftpReadSize
;
212 static FTPSM ftpSendEPRT
;
214 static FTPSM ftpReadEPRT
;
215 static FTPSM ftpSendPORT
;
216 static FTPSM ftpReadPORT
;
217 static FTPSM ftpSendPassive
;
218 static FTPSM ftpReadEPSV
;
219 static FTPSM ftpReadPasv
;
220 static FTPSM ftpTraverseDirectory
;
221 static FTPSM ftpListDir
;
222 static FTPSM ftpGetFile
;
223 static FTPSM ftpSendCwd
;
224 static FTPSM ftpReadCwd
;
225 static FTPSM ftpRestOrList
;
226 static FTPSM ftpSendList
;
227 static FTPSM ftpSendNlst
;
228 static FTPSM ftpReadList
;
229 static FTPSM ftpSendRest
;
230 static FTPSM ftpReadRest
;
231 static FTPSM ftpSendRetr
;
232 static FTPSM ftpReadRetr
;
233 static FTPSM ftpReadTransferDone
;
234 static FTPSM ftpSendStor
;
235 static FTPSM ftpReadStor
;
236 static FTPSM ftpWriteTransferDone
;
237 static FTPSM ftpSendReply
;
238 static FTPSM ftpSendMkdir
;
239 static FTPSM ftpReadMkdir
;
240 static FTPSM ftpFail
;
241 static FTPSM ftpSendQuit
;
242 static FTPSM ftpReadQuit
;
244 /************************************************
245 ** Debugs Levels used here **
246 *************************************************
249 Protocol and Transmission failures.
250 2 FTP Protocol Chatter
255 ************************************************/
257 /************************************************
258 ** State Machine Description (excluding hacks) **
259 *************************************************
261 ---------------------------------------
265 Type TraverseDirectory / GetFile
266 TraverseDirectory Cwd / GetFile / ListDir
267 Cwd TraverseDirectory / Mkdir
273 FileOrList Rest / Retr / Nlst / List / Mkdir (PUT /xxx;type=d)
275 Retr / Nlst / List DataRead* (on datachannel)
276 DataRead* ReadTransferDone
277 ReadTransferDone DataTransferDone
278 Stor DataWrite* (on datachannel)
279 DataWrite* RequestPutBody** (from client)
280 RequestPutBody** DataWrite* / WriteTransferDone
281 WriteTransferDone DataTransferDone
282 DataTransferDone Quit
284 ************************************************/
286 FTPSM
*FTP_SM_FUNCS
[] = {
287 ftpReadWelcome
, /* BEGIN */
288 ftpReadUser
, /* SENT_USER */
289 ftpReadPass
, /* SENT_PASS */
290 ftpReadType
, /* SENT_TYPE */
291 ftpReadMdtm
, /* SENT_MDTM */
292 ftpReadSize
, /* SENT_SIZE */
293 ftpReadEPRT
, /* SENT_EPRT */
294 ftpReadPORT
, /* SENT_PORT */
295 ftpReadEPSV
, /* SENT_EPSV_ALL */
296 ftpReadEPSV
, /* SENT_EPSV_1 */
297 ftpReadEPSV
, /* SENT_EPSV_2 */
298 ftpReadPasv
, /* SENT_PASV */
299 ftpReadCwd
, /* SENT_CWD */
300 ftpReadList
, /* SENT_LIST */
301 ftpReadList
, /* SENT_NLST */
302 ftpReadRest
, /* SENT_REST */
303 ftpReadRetr
, /* SENT_RETR */
304 ftpReadStor
, /* SENT_STOR */
305 ftpReadQuit
, /* SENT_QUIT */
306 ftpReadTransferDone
, /* READING_DATA (RETR,LIST,NLST) */
307 ftpWriteTransferDone
, /* WRITING_DATA (STOR) */
308 ftpReadMkdir
, /* SENT_MKDIR */
309 NULL
, /* SENT_FEAT */
312 NULL
, /* SENT_DATA_REQUEST */
313 NULL
/* SENT_COMMAND */
316 /// handler called by Comm when FTP data channel is closed unexpectedly
318 Ftp::Gateway::dataClosed(const CommCloseCbParams
&io
)
320 Ftp::Client::dataClosed(io
);
321 failed(ERR_FTP_FAILURE
, 0);
322 /* failed closes ctrl.conn and frees ftpState */
324 /* NP: failure recovery may be possible when its only a data.conn failure.
325 * if the ctrl.conn is still fine, we can send ABOR down it and retry.
326 * Just need to watch out for wider Squid states like shutting down or reconfigure.
330 Ftp::Gateway::Gateway(FwdState
*fwdState
):
331 AsyncJob("FtpStateData"),
332 Ftp::Client(fwdState
),
349 debugs(9, 3, entry
->url());
353 memset(&flags
, 0, sizeof(flags
));
355 if (Config
.Ftp
.passive
&& !flags
.pasv_failed
)
356 flags
.pasv_supported
= 1;
358 flags
.rest_supported
= 1;
360 if (request
->method
== Http::METHOD_PUT
)
366 Ftp::Gateway::~Gateway()
368 debugs(9, 3, entry
->url());
370 if (Comm::IsConnOpen(ctrl
.conn
)) {
371 debugs(9, DBG_IMPORTANT
, "Internal bug: FTP Gateway left open " <<
372 "control channel " << ctrl
.conn
);
376 memFree(reply_hdr
, MEM_8K_BUF
);
381 wordlistDestroy(&pathcomps
);
392 * Parse a possible login username:password pair.
393 * Produces filled member variables user, password, password_url if anything found.
395 * \param login a decoded Basic authentication credential token or URI user-info token
396 * \param escaped whether to URL-decode the token after extracting user and password
399 Ftp::Gateway::loginParser(const SBuf
&login
, bool escaped
)
401 debugs(9, 4, "login=" << login
<< ", escaped=" << escaped
);
402 debugs(9, 9, "IN : login=" << login
<< ", escaped=" << escaped
<< ", user=" << user
<< ", password=" << password
);
407 const SBuf::size_type colonPos
= login
.find(':');
409 /* If there was a username part with at least one character use it.
410 * Ignore 0-length username portion, retain what we have already.
412 if (colonPos
== SBuf::npos
|| colonPos
> 0) {
413 const SBuf userName
= login
.substr(0, colonPos
);
414 SBuf::size_type upto
= userName
.copy(user
, sizeof(user
)-1);
416 debugs(9, 9, "found user=" << userName
<< ' ' <<
417 (upto
!= userName
.length() ? ", truncated-to=" : ", length=") << upto
<<
418 ", escaped=" << escaped
);
420 rfc1738_unescape(user
);
421 debugs(9, 9, "found user=" << user
<< " (" << strlen(user
) << ") unescaped.");
424 /* If there was a password part.
425 * For 0-length password clobber what we have already, this means explicitly none
427 if (colonPos
!= SBuf::npos
) {
428 const SBuf pass
= login
.substr(colonPos
+1, SBuf::npos
);
429 SBuf::size_type upto
= pass
.copy(password
, sizeof(password
)-1);
431 debugs(9, 9, "found password=" << pass
<< " " <<
432 (upto
!= pass
.length() ? ", truncated-to=" : ", length=") << upto
<<
433 ", escaped=" << escaped
);
435 rfc1738_unescape(password
);
438 debugs(9, 9, "found password=" << password
<< " (" << strlen(password
) << ") unescaped.");
441 debugs(9, 9, "OUT: login=" << login
<< ", escaped=" << escaped
<< ", user=" << user
<< ", password=" << password
);
445 Ftp::Gateway::listenForDataChannel(const Comm::ConnectionPointer
&conn
)
447 if (!Comm::IsConnOpen(ctrl
.conn
)) {
448 debugs(9, 5, "The control connection to the remote end is closed");
452 assert(!Comm::IsConnOpen(data
.conn
));
454 typedef CommCbMemFunT
<Gateway
, CommAcceptCbParams
> AcceptDialer
;
455 typedef AsyncCallT
<AcceptDialer
> AcceptCall
;
456 RefCount
<AcceptCall
> call
= static_cast<AcceptCall
*>(JobCallback(11, 5, AcceptDialer
, this, Ftp::Gateway::ftpAcceptDataConnection
));
457 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(call
);
458 const char *note
= entry
->url();
460 /* open the conn if its not already open */
461 if (!Comm::IsConnOpen(conn
)) {
462 conn
->fd
= comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
->local
, conn
->flags
, note
);
463 if (!Comm::IsConnOpen(conn
)) {
464 debugs(5, DBG_CRITICAL
, HERE
<< "comm_open_listener failed:" << conn
->local
<< " error: " << errno
);
467 debugs(9, 3, HERE
<< "Unconnected data socket created on " << conn
);
470 conn
->tos
= ctrl
.conn
->tos
;
471 conn
->nfmark
= ctrl
.conn
->nfmark
;
473 assert(Comm::IsConnOpen(conn
));
474 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
476 // Ensure we have a copy of the FD opened for listening and a close handler on it.
477 data
.opened(conn
, dataCloser());
478 switchTimeoutToDataChannel();
482 Ftp::Gateway::timeout(const CommTimeoutCbParams
&io
)
484 if (SENT_PASV
== state
) {
485 /* stupid ftp.netscape.com, of FTP server behind stupid firewall rules */
486 flags
.pasv_supported
= false;
487 debugs(9, DBG_IMPORTANT
, "FTP Gateway timeout in SENT_PASV state");
489 // cancel the data connection setup.
490 if (data
.opener
!= NULL
) {
491 data
.opener
->cancel("timeout");
497 Ftp::Client::timeout(io
);
500 static const char *Month
[] = {
501 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
502 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
506 is_month(const char *buf
)
510 for (i
= 0; i
< 12; ++i
)
511 if (!strcasecmp(buf
, Month
[i
]))
518 ftpListPartsFree(ftpListParts
** parts
)
520 safe_free((*parts
)->date
);
521 safe_free((*parts
)->name
);
522 safe_free((*parts
)->showname
);
523 safe_free((*parts
)->link
);
527 #define MAX_TOKENS 64
529 static ftpListParts
*
530 ftpListParseParts(const char *buf
, struct Ftp::GatewayFlags flags
)
532 ftpListParts
*p
= NULL
;
534 const char *ct
= NULL
;
535 char *tokens
[MAX_TOKENS
];
538 static char tbuf
[128];
540 static int scan_ftp_initialized
= 0;
541 static regex_t scan_ftp_integer
;
542 static regex_t scan_ftp_time
;
543 static regex_t scan_ftp_dostime
;
544 static regex_t scan_ftp_dosdate
;
546 if (!scan_ftp_initialized
) {
547 scan_ftp_initialized
= 1;
548 regcomp(&scan_ftp_integer
, "^[0123456789]+$", REG_EXTENDED
| REG_NOSUB
);
549 regcomp(&scan_ftp_time
, "^[0123456789:]+$", REG_EXTENDED
| REG_NOSUB
);
550 regcomp(&scan_ftp_dosdate
, "^[0123456789]+-[0123456789]+-[0123456789]+$", REG_EXTENDED
| REG_NOSUB
);
551 regcomp(&scan_ftp_dostime
, "^[0123456789]+:[0123456789]+[AP]M$", REG_EXTENDED
| REG_NOSUB
| REG_ICASE
);
560 p
= (ftpListParts
*)xcalloc(1, sizeof(ftpListParts
));
564 memset(tokens
, 0, sizeof(tokens
));
568 if (flags
.tried_nlst
) {
569 /* Machine readable format, one name per line */
575 for (t
= strtok(xbuf
, w_space
); t
&& n_tokens
< MAX_TOKENS
; t
= strtok(NULL
, w_space
)) {
576 tokens
[n_tokens
] = xstrdup(t
);
582 /* locate the Month field */
583 for (i
= 3; i
< n_tokens
- 2; ++i
) {
584 char *size
= tokens
[i
- 1];
585 char *month
= tokens
[i
];
586 char *day
= tokens
[i
+ 1];
587 char *year
= tokens
[i
+ 2];
589 if (!is_month(month
))
592 if (regexec(&scan_ftp_integer
, size
, 0, NULL
, 0) != 0)
595 if (regexec(&scan_ftp_integer
, day
, 0, NULL
, 0) != 0)
598 if (regexec(&scan_ftp_time
, year
, 0, NULL
, 0) != 0) /* Yr | hh:mm */
601 snprintf(tbuf
, 128, "%s %2s %5s",
604 if (!strstr(buf
, tbuf
))
605 snprintf(tbuf
, 128, "%s %2s %-5s",
608 char const *copyFrom
= NULL
;
610 if ((copyFrom
= strstr(buf
, tbuf
))) {
611 p
->type
= *tokens
[0];
612 p
->size
= strtoll(size
, NULL
, 10);
613 p
->date
= xstrdup(tbuf
);
615 if (flags
.skip_whitespace
) {
616 copyFrom
+= strlen(tbuf
);
618 while (strchr(w_space
, *copyFrom
))
621 /* Handle the following four formats:
626 * Assuming a single space between date and filename
627 * suggested by: Nathan.Bailey@cc.monash.edu.au and
628 * Mike Battersby <mike@starbug.bofh.asn.au> */
629 copyFrom
+= strlen(tbuf
);
630 if (strchr(w_space
, *copyFrom
))
634 p
->name
= xstrdup(copyFrom
);
636 if (p
->type
== 'l' && (t
= strstr(p
->name
, " -> "))) {
638 p
->link
= xstrdup(t
+ 4);
647 /* try it as a DOS listing, 04-05-70 09:33PM ... */
649 regexec(&scan_ftp_dosdate
, tokens
[0], 0, NULL
, 0) == 0 &&
650 regexec(&scan_ftp_dostime
, tokens
[1], 0, NULL
, 0) == 0) {
651 if (!strcasecmp(tokens
[2], "<dir>")) {
655 p
->size
= strtoll(tokens
[2], NULL
, 10);
658 snprintf(tbuf
, 128, "%s %s", tokens
[0], tokens
[1]);
659 p
->date
= xstrdup(tbuf
);
661 if (p
->type
== 'd') {
662 /* Directory.. name begins with first printable after <dir> */
663 ct
= strstr(buf
, tokens
[2]);
664 ct
+= strlen(tokens
[2]);
666 while (xisspace(*ct
))
672 /* A file. Name begins after size, with a space in between */
673 snprintf(tbuf
, 128, " %s %s", tokens
[2], tokens
[3]);
674 ct
= strstr(buf
, tbuf
);
677 ct
+= strlen(tokens
[2]) + 2;
681 p
->name
= xstrdup(ct
? ct
: tokens
[3]);
685 /* Try EPLF format; carson@lehman.com */
692 int l
= strcspn(ct
, ",");
701 p
->name
= xstrndup(ct
+ 1, l
+ 1);
705 p
->size
= atoi(ct
+ 1);
709 tm
= (time_t) strtol(ct
+ 1, &tmp
, 0);
712 break; /* not a valid integer */
714 p
->date
= xstrdup(ctime(&tm
));
716 *(strstr(p
->date
, "\n")) = '\0';
738 ct
= strstr(ct
, ",");
757 for (i
= 0; i
< n_tokens
; ++i
)
761 ftpListPartsFree(&p
); /* cleanup */
767 Ftp::Gateway::htmlifyListEntry(const char *line
)
770 char href
[2048 + 40];
773 char chdir
[ 2048 + 40];
774 char view
[ 2048 + 40];
775 char download
[ 2048 + 40];
776 char link
[ 2048 + 40];
780 *icon
= *href
= *text
= *size
= *chdir
= *view
= *download
= *link
= '\0';
782 debugs(9, 7, HERE
<< " line ={" << line
<< "}");
784 if (strlen(line
) > 1024) {
787 html
->appendf("<tr><td colspan=\"5\">%s</td></tr>\n", line
);
791 if (flags
.dir_slash
&& dirpath
&& typecode
!= 'D')
792 snprintf(prefix
, 2048, "%s/", rfc1738_escape_part(dirpath
));
796 if ((parts
= ftpListParseParts(line
, flags
)) == NULL
) {
801 html
->appendf("<tr class=\"entry\"><td colspan=\"5\">%s</td></tr>\n", line
);
803 for (p
= line
; *p
&& xisspace(*p
); ++p
);
804 if (*p
&& !xisspace(*p
))
805 flags
.listformat_unknown
= 1;
810 if (!strcmp(parts
->name
, ".") || !strcmp(parts
->name
, "..")) {
811 ftpListPartsFree(&parts
);
817 parts
->showname
= xstrdup(parts
->name
);
819 /* {icon} {text} . . . {date}{size}{chdir}{view}{download}{link}\n */
820 xstrncpy(href
, rfc1738_escape_part(parts
->name
), 2048);
822 xstrncpy(text
, parts
->showname
, 2048);
824 switch (parts
->type
) {
827 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
828 mimeGetIconURL("internal-dir"),
830 strcat(href
, "/"); /* margin is allocated above */
834 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
835 mimeGetIconURL("internal-link"),
837 /* sometimes there is an 'l' flag, but no "->" link */
840 char *link2
= xstrdup(html_quote(rfc1738_escape(parts
->link
)));
841 snprintf(link
, 2048, " -> <a href=\"%s%s\">%s</a>",
842 *link2
!= '/' ? prefix
: "", link2
,
843 html_quote(parts
->link
));
850 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
851 mimeGetIconURL(parts
->name
),
853 snprintf(chdir
, 2048, "<a href=\"%s/;type=d\"><img border=\"0\" src=\"%s\" "
854 "alt=\"[DIR]\"></a>",
855 rfc1738_escape_part(parts
->name
),
856 mimeGetIconURL("internal-dir"));
862 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
863 mimeGetIconURL(parts
->name
),
865 snprintf(size
, 2048, " %6" PRId64
"k", parts
->size
);
869 if (parts
->type
!= 'd') {
870 if (mimeGetViewOption(parts
->name
)) {
871 snprintf(view
, 2048, "<a href=\"%s%s;type=a\"><img border=\"0\" src=\"%s\" "
872 "alt=\"[VIEW]\"></a>",
873 prefix
, href
, mimeGetIconURL("internal-view"));
876 if (mimeGetDownloadOption(parts
->name
)) {
877 snprintf(download
, 2048, "<a href=\"%s%s;type=i\"><img border=\"0\" src=\"%s\" "
878 "alt=\"[DOWNLOAD]\"></a>",
879 prefix
, href
, mimeGetIconURL("internal-download"));
883 /* construct the table row from parts. */
886 html
->appendf("<tr class=\"entry\">"
887 "<td class=\"icon\"><a href=\"%s%s\">%s</a></td>"
888 "<td class=\"filename\"><a href=\"%s%s\">%s</a></td>"
889 "<td class=\"date\">%s</td>"
890 "<td class=\"size\">%s</td>"
891 "<td class=\"actions\">%s%s%s%s</td>"
894 prefix
, href
, html_quote(text
),
897 chdir
, view
, download
, link
);
899 ftpListPartsFree(&parts
);
904 Ftp::Gateway::parseListing()
906 char *buf
= data
.readBuf
->content();
907 char *sbuf
; /* NULL-terminated copy of termedBuf */
914 size_t len
= data
.readBuf
->contentSize();
917 debugs(9, 3, HERE
<< "no content to parse for " << entry
->url() );
922 * We need a NULL-terminated buffer for scanning, ick
924 sbuf
= (char *)xmalloc(len
+ 1);
925 xstrncpy(sbuf
, buf
, len
+ 1);
926 end
= sbuf
+ len
- 1;
928 while (*end
!= '\r' && *end
!= '\n' && end
> sbuf
)
933 debugs(9, 3, HERE
<< "usable = " << usable
<< " of " << len
<< " bytes.");
936 if (buf
[0] == '\0' && len
== 1) {
937 debugs(9, 3, HERE
<< "NIL ends data from " << entry
->url() << " transfer problem?");
938 data
.readBuf
->consume(len
);
940 debugs(9, 3, HERE
<< "didn't find end for " << entry
->url());
941 debugs(9, 3, HERE
<< "buffer remains (" << len
<< " bytes) '" << rfc1738_do_escape(buf
,0) << "'");
947 debugs(9, 3, HERE
<< (unsigned long int)len
<< " bytes to play with");
949 line
= (char *)memAllocate(MEM_4K_BUF
);
952 s
+= strspn(s
, crlf
);
954 for (; s
< end
; s
+= strcspn(s
, crlf
), s
+= strspn(s
, crlf
)) {
955 debugs(9, 7, HERE
<< "s = {" << s
<< "}");
956 linelen
= strcspn(s
, crlf
) + 1;
964 xstrncpy(line
, s
, linelen
);
966 debugs(9, 7, HERE
<< "{" << line
<< "}");
968 if (!strncmp(line
, "total", 5))
971 t
= htmlifyListEntry(line
);
974 debugs(9, 7, HERE
<< "listing append: t = {" << t
->contentSize() << ", '" << t
->content() << "'}");
975 listing
.append(t
->content(), t
->contentSize());
980 debugs(9, 7, HERE
<< "Done.");
981 data
.readBuf
->consume(usable
);
982 memFree(line
, MEM_4K_BUF
);
987 Ftp::Gateway::processReplyBody()
989 debugs(9, 3, status());
991 if (request
->method
== Http::METHOD_HEAD
&& (flags
.isdir
|| theSize
!= -1)) {
996 /* Directory listings are special. They write ther own headers via the error objects */
997 if (!flags
.http_header_sent
&& data
.readBuf
->contentSize() >= 0 && !flags
.isdir
)
998 appendSuccessHeader();
1000 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1002 * probably was aborted because content length exceeds one
1003 * of the maximum size limits.
1005 abortAll("entry aborted after calling appendSuccessHeader()");
1011 if (adaptationAccessCheckPending
) {
1012 debugs(9, 3, "returning from Ftp::Gateway::processReplyBody due to adaptationAccessCheckPending");
1019 if (!flags
.listing
) {
1024 maybeReadVirginBody();
1026 } else if (const int csize
= data
.readBuf
->contentSize()) {
1027 writeReplyBody(data
.readBuf
->content(), csize
);
1028 debugs(9, 5, HERE
<< "consuming " << csize
<< " bytes of readBuf");
1029 data
.readBuf
->consume(csize
);
1034 maybeReadVirginBody();
1038 * Locates the FTP user:password login.
1040 * Highest to lowest priority:
1041 * - Checks URL (ftp://user:pass@domain)
1042 * - Authorization: Basic header
1043 * - squid.conf anonymous-FTP settings (default: anonymous:Squid@).
1045 * Special Case: A username-only may be provided in the URL and password in the HTTP headers.
1047 * TODO: we might be able to do something about locating username from other sources:
1048 * ie, external ACL user=* tag or ident lookup
1050 \retval 1 if we have everything needed to complete this request.
1051 \retval 0 if something is missing.
1054 Ftp::Gateway::checkAuth(const HttpHeader
* req_hdr
)
1056 /* default username */
1057 xstrncpy(user
, "anonymous", MAX_URL
);
1059 #if HAVE_AUTH_MODULE_BASIC
1060 /* Check HTTP Authorization: headers (better than defaults, but less than URL) */
1061 const SBuf
auth(req_hdr
->getAuth(Http::HdrType::AUTHORIZATION
, "Basic"));
1062 if (!auth
.isEmpty()) {
1063 flags
.authenticated
= 1;
1064 loginParser(auth
, false);
1066 /* we fail with authorization-required error later IFF the FTP server requests it */
1069 /* Test URL login syntax. Overrides any headers received. */
1070 loginParser(request
->url
.userInfo(), true);
1072 /* name is missing. thats fatal. */
1074 fatal("FTP login parsing destroyed username info");
1076 /* name + password == success */
1080 /* Setup default FTP password settings */
1081 /* this has to be done last so that we can have a no-password case above. */
1083 if (strcmp(user
, "anonymous") == 0 && !flags
.tried_auth_anonymous
) {
1084 xstrncpy(password
, Config
.Ftp
.anon_user
, MAX_URL
);
1085 flags
.tried_auth_anonymous
=1;
1087 } else if (!flags
.tried_auth_nopass
) {
1088 xstrncpy(password
, null_string
, MAX_URL
);
1089 flags
.tried_auth_nopass
=1;
1094 return 0; /* different username */
1098 Ftp::Gateway::checkUrlpath()
1100 static SBuf
str_type_eq("type=");
1101 auto t
= request
->url
.path().rfind(';');
1103 if (t
!= SBuf::npos
) {
1104 auto filenameEnd
= t
-1;
1105 if (request
->url
.path().substr(++t
).cmp(str_type_eq
, str_type_eq
.length()) == 0) {
1106 t
+= str_type_eq
.length();
1107 typecode
= (char)xtoupper(request
->url
.path()[t
]);
1108 request
->url
.path(request
->url
.path().substr(0,filenameEnd
));
1112 int l
= request
->url
.path().length();
1113 /* check for null path */
1118 flags
.need_base_href
= 1; /* Work around broken browsers */
1119 } else if (!request
->url
.path().cmp("/%2f/")) {
1120 /* UNIX root directory */
1123 } else if ((l
>= 1) && (request
->url
.path()[l
-1] == '/')) {
1124 /* Directory URL, ending in / */
1130 flags
.dir_slash
= 1;
1135 Ftp::Gateway::buildTitleUrl()
1137 title_url
= "ftp://";
1139 if (strcmp(user
, "anonymous")) {
1140 title_url
.append(user
);
1141 title_url
.append("@");
1144 SBuf authority
= request
->url
.authority(request
->url
.getScheme() != AnyP::PROTO_FTP
);
1146 title_url
.append(authority
.rawContent(), authority
.length());
1147 title_url
.append(request
->url
.path().rawContent(), request
->url
.path().length());
1149 base_href
= "ftp://";
1151 if (strcmp(user
, "anonymous") != 0) {
1152 base_href
.append(rfc1738_escape_part(user
));
1155 base_href
.append(":");
1156 base_href
.append(rfc1738_escape_part(password
));
1159 base_href
.append("@");
1162 base_href
.append(authority
.rawContent(), authority
.length());
1163 base_href
.append(request
->url
.path().rawContent(), request
->url
.path().length());
1164 base_href
.append("/");
1168 Ftp::Gateway::start()
1170 if (!checkAuth(&request
->header
)) {
1171 /* create appropriate reply */
1172 SBuf
realm(ftpRealm()); // local copy so SBuf wont disappear too early
1173 HttpReply
*reply
= ftpAuthRequired(request
.getRaw(), realm
);
1174 entry
->replaceHttpReply(reply
);
1181 debugs(9, 5, "FD " << (ctrl
.conn
? ctrl
.conn
->fd
: -1) << " : host=" << request
->url
.host() <<
1182 ", path=" << request
->url
.path() << ", user=" << user
<< ", passwd=" << password
);
1184 Ftp::Client::start();
1187 /* ====================================================================== */
1190 Ftp::Gateway::handleControlReply()
1192 Ftp::Client::handleControlReply();
1193 if (ctrl
.message
== NULL
)
1194 return; // didn't get complete reply yet
1196 /* Copy the message except for the last line to cwd_message to be
1197 * printed in error messages.
1199 for (wordlist
*w
= ctrl
.message
; w
&& w
->next
; w
= w
->next
) {
1200 cwd_message
.append('\n');
1201 cwd_message
.append(w
->key
);
1204 FTP_SM_FUNCS
[state
] (this);
1207 /* ====================================================================== */
1210 ftpReadWelcome(Ftp::Gateway
* ftpState
)
1212 int code
= ftpState
->ctrl
.replycode
;
1215 if (ftpState
->flags
.pasv_only
)
1216 ++ ftpState
->login_att
;
1219 if (ftpState
->ctrl
.message
) {
1220 if (strstr(ftpState
->ctrl
.message
->key
, "NetWare"))
1221 ftpState
->flags
.skip_whitespace
= 1;
1224 ftpSendUser(ftpState
);
1225 } else if (code
== 120) {
1226 if (NULL
!= ftpState
->ctrl
.message
)
1227 debugs(9, DBG_IMPORTANT
, "FTP server is busy: " << ftpState
->ctrl
.message
->key
);
1236 * Translate FTP login failure into HTTP error
1237 * this is an attmpt to get the 407 message to show up outside Squid.
1238 * its NOT a general failure. But a correct FTP response type.
1241 Ftp::Gateway::loginFailed()
1243 ErrorState
*err
= NULL
;
1245 if ((state
== SENT_USER
|| state
== SENT_PASS
) && ctrl
.replycode
>= 400) {
1246 if (ctrl
.replycode
== 421 || ctrl
.replycode
== 426) {
1247 // 421/426 - Service Overload - retry permitted.
1248 err
= new ErrorState(ERR_FTP_UNAVAILABLE
, Http::scServiceUnavailable
, fwd
->request
);
1249 } else if (ctrl
.replycode
>= 430 && ctrl
.replycode
<= 439) {
1250 // 43x - Invalid or Credential Error - retry challenge required.
1251 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1252 } else if (ctrl
.replycode
>= 530 && ctrl
.replycode
<= 539) {
1253 // 53x - Credentials Missing - retry challenge required
1254 if (password_url
) // but they were in the URI! major fail.
1255 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scForbidden
, fwd
->request
);
1257 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1266 failed(ERR_NONE
, ctrl
.replycode
, err
);
1267 // any other problems are general falures.
1269 HttpReply
*newrep
= err
->BuildHttpReply();
1272 #if HAVE_AUTH_MODULE_BASIC
1273 /* add Authenticate header */
1274 // XXX: performance regression. c_str() may reallocate
1275 SBuf
realm(ftpRealm()); // local copy so SBuf wont disappear too early
1276 newrep
->header
.putAuth("Basic", realm
.c_str());
1279 // add it to the store entry for response....
1280 entry
->replaceHttpReply(newrep
);
1285 Ftp::Gateway::ftpRealm()
1289 /* This request is not fully authenticated */
1290 realm
.appendf("FTP %s ", user
);
1292 realm
.append("unknown", 7);
1294 realm
.append(request
->url
.host());
1295 if (request
->url
.port() != 21)
1296 realm
.appendf(" port %d", request
->url
.port());
1302 ftpSendUser(Ftp::Gateway
* ftpState
)
1304 /* check the server control channel is still available */
1305 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendUser"))
1308 if (ftpState
->proxy_host
!= NULL
)
1309 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s@%s\r\n", ftpState
->user
, ftpState
->request
->url
.host());
1311 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s\r\n", ftpState
->user
);
1313 ftpState
->writeCommand(cbuf
);
1315 ftpState
->state
= Ftp::Client::SENT_USER
;
1319 ftpReadUser(Ftp::Gateway
* ftpState
)
1321 int code
= ftpState
->ctrl
.replycode
;
1325 ftpReadPass(ftpState
);
1326 } else if (code
== 331) {
1327 ftpSendPass(ftpState
);
1329 ftpState
->loginFailed();
1334 ftpSendPass(Ftp::Gateway
* ftpState
)
1336 /* check the server control channel is still available */
1337 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPass"))
1340 snprintf(cbuf
, CTRL_BUFLEN
, "PASS %s\r\n", ftpState
->password
);
1341 ftpState
->writeCommand(cbuf
);
1342 ftpState
->state
= Ftp::Client::SENT_PASS
;
1346 ftpReadPass(Ftp::Gateway
* ftpState
)
1348 int code
= ftpState
->ctrl
.replycode
;
1349 debugs(9, 3, HERE
<< "code=" << code
);
1352 ftpSendType(ftpState
);
1354 ftpState
->loginFailed();
1359 ftpSendType(Ftp::Gateway
* ftpState
)
1361 /* check the server control channel is still available */
1362 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendType"))
1366 * Ref section 3.2.2 of RFC 1738
1368 char mode
= ftpState
->typecode
;
1383 if (ftpState
->flags
.isdir
) {
1386 auto t
= ftpState
->request
->url
.path().rfind('/');
1387 // XXX: performance regression, c_str() may reallocate
1388 SBuf filename
= ftpState
->request
->url
.path().substr(t
!= SBuf::npos
? t
+ 1 : 0);
1389 mode
= mimeGetTransferMode(filename
.c_str());
1396 ftpState
->flags
.binary
= 1;
1398 ftpState
->flags
.binary
= 0;
1400 snprintf(cbuf
, CTRL_BUFLEN
, "TYPE %c\r\n", mode
);
1402 ftpState
->writeCommand(cbuf
);
1404 ftpState
->state
= Ftp::Client::SENT_TYPE
;
1408 ftpReadType(Ftp::Gateway
* ftpState
)
1410 int code
= ftpState
->ctrl
.replycode
;
1413 debugs(9, 3, HERE
<< "code=" << code
);
1416 p
= path
= SBufToCstring(ftpState
->request
->url
.path());
1423 p
+= strcspn(p
, "/");
1430 rfc1738_unescape(d
);
1433 wordlistAdd(&ftpState
->pathcomps
, d
);
1438 if (ftpState
->pathcomps
)
1439 ftpTraverseDirectory(ftpState
);
1441 ftpListDir(ftpState
);
1448 ftpTraverseDirectory(Ftp::Gateway
* ftpState
)
1450 debugs(9, 4, HERE
<< (ftpState
->filepath
? ftpState
->filepath
: "<NULL>"));
1452 safe_free(ftpState
->dirpath
);
1453 ftpState
->dirpath
= ftpState
->filepath
;
1454 ftpState
->filepath
= NULL
;
1458 if (ftpState
->pathcomps
== NULL
) {
1459 debugs(9, 3, HERE
<< "the final component was a directory");
1460 ftpListDir(ftpState
);
1464 /* Go to next path component */
1465 ftpState
->filepath
= wordlistChopHead(& ftpState
->pathcomps
);
1467 /* Check if we are to CWD or RETR */
1468 if (ftpState
->pathcomps
!= NULL
|| ftpState
->flags
.isdir
) {
1469 ftpSendCwd(ftpState
);
1471 debugs(9, 3, HERE
<< "final component is probably a file");
1472 ftpGetFile(ftpState
);
1478 ftpSendCwd(Ftp::Gateway
* ftpState
)
1482 /* check the server control channel is still available */
1483 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendCwd"))
1488 path
= ftpState
->filepath
;
1490 if (!strcmp(path
, "..") || !strcmp(path
, "/")) {
1491 ftpState
->flags
.no_dotdot
= 1;
1493 ftpState
->flags
.no_dotdot
= 0;
1496 snprintf(cbuf
, CTRL_BUFLEN
, "CWD %s\r\n", path
);
1498 ftpState
->writeCommand(cbuf
);
1500 ftpState
->state
= Ftp::Client::SENT_CWD
;
1504 ftpReadCwd(Ftp::Gateway
* ftpState
)
1506 int code
= ftpState
->ctrl
.replycode
;
1509 if (code
>= 200 && code
< 300) {
1513 /* Reset cwd_message to only include the last message */
1514 ftpState
->cwd_message
.reset("");
1515 for (wordlist
*w
= ftpState
->ctrl
.message
; w
; w
= w
->next
) {
1516 ftpState
->cwd_message
.append('\n');
1517 ftpState
->cwd_message
.append(w
->key
);
1519 ftpState
->ctrl
.message
= NULL
;
1521 /* Continue to traverse the path */
1522 ftpTraverseDirectory(ftpState
);
1526 if (!ftpState
->flags
.put
)
1529 ftpSendMkdir(ftpState
);
1534 ftpSendMkdir(Ftp::Gateway
* ftpState
)
1538 /* check the server control channel is still available */
1539 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMkdir"))
1542 path
= ftpState
->filepath
;
1543 debugs(9, 3, HERE
<< "with path=" << path
);
1544 snprintf(cbuf
, CTRL_BUFLEN
, "MKD %s\r\n", path
);
1545 ftpState
->writeCommand(cbuf
);
1546 ftpState
->state
= Ftp::Client::SENT_MKDIR
;
1550 ftpReadMkdir(Ftp::Gateway
* ftpState
)
1552 char *path
= ftpState
->filepath
;
1553 int code
= ftpState
->ctrl
.replycode
;
1555 debugs(9, 3, HERE
<< "path " << path
<< ", code " << code
);
1557 if (code
== 257) { /* success */
1558 ftpSendCwd(ftpState
);
1559 } else if (code
== 550) { /* dir exists */
1561 if (ftpState
->flags
.put_mkdir
) {
1562 ftpState
->flags
.put_mkdir
= 1;
1563 ftpSendCwd(ftpState
);
1565 ftpSendReply(ftpState
);
1567 ftpSendReply(ftpState
);
1571 ftpGetFile(Ftp::Gateway
* ftpState
)
1573 assert(*ftpState
->filepath
!= '\0');
1574 ftpState
->flags
.isdir
= 0;
1575 ftpSendMdtm(ftpState
);
1579 ftpListDir(Ftp::Gateway
* ftpState
)
1581 if (ftpState
->flags
.dir_slash
) {
1582 debugs(9, 3, HERE
<< "Directory path did not end in /");
1583 ftpState
->title_url
.append("/");
1584 ftpState
->flags
.isdir
= 1;
1587 ftpSendPassive(ftpState
);
1591 ftpSendMdtm(Ftp::Gateway
* ftpState
)
1593 /* check the server control channel is still available */
1594 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMdtm"))
1597 assert(*ftpState
->filepath
!= '\0');
1598 snprintf(cbuf
, CTRL_BUFLEN
, "MDTM %s\r\n", ftpState
->filepath
);
1599 ftpState
->writeCommand(cbuf
);
1600 ftpState
->state
= Ftp::Client::SENT_MDTM
;
1604 ftpReadMdtm(Ftp::Gateway
* ftpState
)
1606 int code
= ftpState
->ctrl
.replycode
;
1610 ftpState
->mdtm
= parse_iso3307_time(ftpState
->ctrl
.last_reply
);
1612 } else if (code
< 0) {
1617 ftpSendSize(ftpState
);
1621 ftpSendSize(Ftp::Gateway
* ftpState
)
1623 /* check the server control channel is still available */
1624 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendSize"))
1627 /* Only send SIZE for binary transfers. The returned size
1628 * is useless on ASCII transfers */
1630 if (ftpState
->flags
.binary
) {
1631 assert(ftpState
->filepath
!= NULL
);
1632 assert(*ftpState
->filepath
!= '\0');
1633 snprintf(cbuf
, CTRL_BUFLEN
, "SIZE %s\r\n", ftpState
->filepath
);
1634 ftpState
->writeCommand(cbuf
);
1635 ftpState
->state
= Ftp::Client::SENT_SIZE
;
1637 /* Skip to next state no non-binary transfers */
1638 ftpSendPassive(ftpState
);
1642 ftpReadSize(Ftp::Gateway
* ftpState
)
1644 int code
= ftpState
->ctrl
.replycode
;
1649 ftpState
->theSize
= strtoll(ftpState
->ctrl
.last_reply
, NULL
, 10);
1651 if (ftpState
->theSize
== 0) {
1652 debugs(9, 2, "SIZE reported " <<
1653 ftpState
->ctrl
.last_reply
<< " on " <<
1654 ftpState
->title_url
);
1655 ftpState
->theSize
= -1;
1657 } else if (code
< 0) {
1662 ftpSendPassive(ftpState
);
1666 ftpReadEPSV(Ftp::Gateway
* ftpState
)
1668 Ip::Address srvAddr
; // unused
1669 if (ftpState
->handleEpsvReply(srvAddr
)) {
1670 if (ftpState
->ctrl
.message
== NULL
)
1671 return; // didn't get complete reply yet
1673 ftpState
->connectDataChannel();
1677 /** Send Passive connection request.
1678 * Default method is to use modern EPSV request.
1679 * The failover mechanism should check for previous state and re-call with alternates on failure.
1682 ftpSendPassive(Ftp::Gateway
* ftpState
)
1684 /** Checks the server control channel is still available before running. */
1685 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPassive"))
1691 * Checks for 'HEAD' method request and passes off for special handling by Ftp::Gateway::processHeadResponse(). */
1692 if (ftpState
->request
->method
== Http::METHOD_HEAD
&& (ftpState
->flags
.isdir
|| ftpState
->theSize
!= -1)) {
1693 ftpState
->processHeadResponse(); // may call serverComplete
1697 if (ftpState
->sendPassive()) {
1698 // SENT_EPSV_ALL blocks other non-EPSV connections being attempted
1699 if (ftpState
->state
== Ftp::Client::SENT_EPSV_ALL
)
1700 ftpState
->flags
.epsv_all_sent
= true;
1705 Ftp::Gateway::processHeadResponse()
1707 debugs(9, 5, HERE
<< "handling HEAD response");
1709 appendSuccessHeader();
1712 * On rare occasions I'm seeing the entry get aborted after
1713 * readControlReply() and before here, probably when
1714 * trying to write to the client.
1716 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1717 abortAll("entry aborted while processing HEAD");
1722 if (adaptationAccessCheckPending
) {
1723 debugs(9,3, HERE
<< "returning due to adaptationAccessCheckPending");
1728 // processReplyBody calls serverComplete() since there is no body
1733 ftpReadPasv(Ftp::Gateway
* ftpState
)
1735 Ip::Address srvAddr
; // unused
1736 if (ftpState
->handlePasvReply(srvAddr
))
1737 ftpState
->connectDataChannel();
1740 // Currently disabled, does not work correctly:
1741 // ftpSendEPRT(ftpState);
1747 Ftp::Gateway::dataChannelConnected(const CommConnectCbParams
&io
)
1752 if (io
.flag
!= Comm::OK
) {
1753 debugs(9, 2, HERE
<< "Failed to connect. Retrying via another method.");
1755 // ABORT on timeouts. server may be waiting on a broken TCP link.
1756 if (io
.xerrno
== Comm::TIMEOUT
)
1757 writeCommand("ABOR\r\n");
1759 // try another connection attempt with some other method
1760 ftpSendPassive(this);
1764 data
.opened(io
.conn
, dataCloser());
1765 ftpRestOrList(this);
1769 ftpOpenListenSocket(Ftp::Gateway
* ftpState
, int fallback
)
1771 /// Close old data channels, if any. We may open a new one below.
1772 if (ftpState
->data
.conn
!= NULL
) {
1773 if ((ftpState
->data
.conn
->flags
& COMM_REUSEADDR
))
1774 // NP: in fact it points to the control channel. just clear it.
1775 ftpState
->data
.clear();
1777 ftpState
->data
.close();
1779 safe_free(ftpState
->data
.host
);
1781 if (!Comm::IsConnOpen(ftpState
->ctrl
.conn
)) {
1782 debugs(9, 5, "The control connection to the remote end is closed");
1787 * Set up a listen socket on the same local address as the
1788 * control connection.
1790 Comm::ConnectionPointer temp
= new Comm::Connection
;
1791 temp
->local
= ftpState
->ctrl
.conn
->local
;
1794 * REUSEADDR is needed in fallback mode, since the same port is
1795 * used for both control and data.
1800 if (setsockopt(ftpState
->ctrl
.conn
->fd
, SOL_SOCKET
, SO_REUSEADDR
,
1801 (char *) &on
, sizeof(on
)) == -1) {
1803 // SO_REUSEADDR is only an optimization, no need to be verbose about error
1804 debugs(9, 4, "setsockopt failed: " << xstrerr(xerrno
));
1806 ftpState
->ctrl
.conn
->flags
|= COMM_REUSEADDR
;
1807 temp
->flags
|= COMM_REUSEADDR
;
1809 /* if not running in fallback mode a new port needs to be retrieved */
1810 temp
->local
.port(0);
1813 ftpState
->listenForDataChannel(temp
);
1817 ftpSendPORT(Ftp::Gateway
* ftpState
)
1819 /* check the server control channel is still available */
1820 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPort"))
1823 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1824 debugs(9, DBG_IMPORTANT
, "FTP does not allow PORT method after 'EPSV ALL' has been sent.");
1829 ftpState
->flags
.pasv_supported
= 0;
1830 ftpOpenListenSocket(ftpState
, 0);
1832 if (!Comm::IsConnOpen(ftpState
->data
.listenConn
)) {
1833 if ( ftpState
->data
.listenConn
!= NULL
&& !ftpState
->data
.listenConn
->local
.isIPv4() ) {
1834 /* non-IPv4 CANNOT send PORT command. */
1835 /* we got here by attempting and failing an EPRT */
1836 /* using the same reply code should simulate a PORT failure */
1837 ftpReadPORT(ftpState
);
1841 /* XXX Need to set error message */
1846 // pull out the internal IP address bytes to send in PORT command...
1847 // source them from the listen_conn->local
1849 struct addrinfo
*AI
= NULL
;
1850 ftpState
->data
.listenConn
->local
.getAddrInfo(AI
, AF_INET
);
1851 unsigned char *addrptr
= (unsigned char *) &((struct sockaddr_in
*)AI
->ai_addr
)->sin_addr
;
1852 unsigned char *portptr
= (unsigned char *) &((struct sockaddr_in
*)AI
->ai_addr
)->sin_port
;
1853 snprintf(cbuf
, CTRL_BUFLEN
, "PORT %d,%d,%d,%d,%d,%d\r\n",
1854 addrptr
[0], addrptr
[1], addrptr
[2], addrptr
[3],
1855 portptr
[0], portptr
[1]);
1856 ftpState
->writeCommand(cbuf
);
1857 ftpState
->state
= Ftp::Client::SENT_PORT
;
1859 Ip::Address::FreeAddr(AI
);
1863 ftpReadPORT(Ftp::Gateway
* ftpState
)
1865 int code
= ftpState
->ctrl
.replycode
;
1869 /* Fall back on using the same port as the control connection */
1870 debugs(9, 3, "PORT not supported by remote end");
1871 ftpOpenListenSocket(ftpState
, 1);
1874 ftpRestOrList(ftpState
);
1879 ftpSendEPRT(Ftp::Gateway
* ftpState
)
1881 /* check the server control channel is still available */
1882 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendEPRT"))
1885 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1886 debugs(9, DBG_IMPORTANT
, "FTP does not allow EPRT method after 'EPSV ALL' has been sent.");
1890 if (!Config
.Ftp
.eprt
) {
1891 /* Disabled. Switch immediately to attempting old PORT command. */
1892 debugs(9, 3, "EPRT disabled by local administrator");
1893 ftpSendPORT(ftpState
);
1898 ftpState
->flags
.pasv_supported
= 0;
1900 ftpOpenListenSocket(ftpState
, 0);
1901 debugs(9, 3, "Listening for FTP data connection with FD " << ftpState
->data
.conn
);
1902 if (!Comm::IsConnOpen(ftpState
->data
.conn
)) {
1903 /* XXX Need to set error message */
1908 char buf
[MAX_IPSTRLEN
];
1910 /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
1911 /* Which can be used by EITHER protocol. */
1912 snprintf(cbuf
, CTRL_BUFLEN
, "EPRT |%d|%s|%d|\r\n",
1913 ( ftpState
->data
.listenConn
->local
.isIPv6() ? 2 : 1 ),
1914 ftpState
->data
.listenConn
->local
.toStr(buf
,MAX_IPSTRLEN
),
1915 ftpState
->data
.listenConn
->local
.port() );
1917 ftpState
->writeCommand(cbuf
);
1918 ftpState
->state
= Ftp::Client::SENT_EPRT
;
1923 ftpReadEPRT(Ftp::Gateway
* ftpState
)
1925 int code
= ftpState
->ctrl
.replycode
;
1929 /* Failover to attempting old PORT command. */
1930 debugs(9, 3, "EPRT not supported by remote end");
1931 ftpSendPORT(ftpState
);
1935 ftpRestOrList(ftpState
);
1938 /** "read" handler to accept FTP data connections.
1940 \param io comm accept(2) callback parameters
1943 Ftp::Gateway::ftpAcceptDataConnection(const CommAcceptCbParams
&io
)
1947 if (!Comm::IsConnOpen(ctrl
.conn
)) { /*Close handlers will cleanup*/
1948 debugs(9, 5, "The control connection to the remote end is closed");
1952 if (io
.flag
!= Comm::OK
) {
1953 data
.listenConn
->close();
1954 data
.listenConn
= NULL
;
1955 debugs(9, DBG_IMPORTANT
, "FTP AcceptDataConnection: " << io
.conn
<< ": " << xstrerr(io
.xerrno
));
1956 /** \todo Need to send error message on control channel*/
1961 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1962 abortAll("entry aborted when accepting data conn");
1963 data
.listenConn
->close();
1964 data
.listenConn
= NULL
;
1969 /* data listening conn is no longer even open. abort. */
1970 if (!Comm::IsConnOpen(data
.listenConn
)) {
1971 data
.listenConn
= NULL
; // ensure that it's cleared and not just closed.
1975 /* data listening conn is no longer even open. abort. */
1976 if (!Comm::IsConnOpen(data
.conn
)) {
1977 data
.clear(); // ensure that it's cleared and not just closed.
1982 * When squid.conf ftp_sanitycheck is enabled, check the new connection is actually being
1983 * made by the remote client which is connected to the FTP control socket.
1984 * Or the one which we were told to listen for by control channel messages (may differ under NAT).
1985 * This prevents third-party hacks, but also third-party load balancing handshakes.
1987 if (Config
.Ftp
.sanitycheck
) {
1988 // accept if either our data or ctrl connection is talking to this remote peer.
1989 if (data
.conn
->remote
!= io
.conn
->remote
&& ctrl
.conn
->remote
!= io
.conn
->remote
) {
1990 debugs(9, DBG_IMPORTANT
,
1991 "FTP data connection from unexpected server (" <<
1992 io
.conn
->remote
<< "), expecting " <<
1993 data
.conn
->remote
<< " or " << ctrl
.conn
->remote
);
1995 /* close the bad sources connection down ASAP. */
1998 /* drop the bad connection (io) by ignoring the attempt. */
2003 /** On Comm::OK start using the accepted data socket and discard the temporary listen socket. */
2005 data
.opened(io
.conn
, dataCloser());
2006 data
.addr(io
.conn
->remote
);
2008 debugs(9, 3, HERE
<< "Connected data socket on " <<
2009 io
.conn
<< ". FD table says: " <<
2010 "ctrl-peer= " << fd_table
[ctrl
.conn
->fd
].ipaddr
<< ", " <<
2011 "data-peer= " << fd_table
[data
.conn
->fd
].ipaddr
);
2013 assert(haveControlChannel("ftpAcceptDataConnection"));
2014 assert(ctrl
.message
== NULL
);
2016 // Ctrl channel operations will determine what happens to this data connection
2020 ftpRestOrList(Ftp::Gateway
* ftpState
)
2024 if (ftpState
->typecode
== 'D') {
2025 ftpState
->flags
.isdir
= 1;
2027 if (ftpState
->flags
.put
) {
2028 ftpSendMkdir(ftpState
); /* PUT name;type=d */
2030 ftpSendNlst(ftpState
); /* GET name;type=d sec 3.2.2 of RFC 1738 */
2032 } else if (ftpState
->flags
.put
) {
2033 ftpSendStor(ftpState
);
2034 } else if (ftpState
->flags
.isdir
)
2035 ftpSendList(ftpState
);
2036 else if (ftpState
->restartable())
2037 ftpSendRest(ftpState
);
2039 ftpSendRetr(ftpState
);
2043 ftpSendStor(Ftp::Gateway
* ftpState
)
2045 /* check the server control channel is still available */
2046 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendStor"))
2051 if (ftpState
->filepath
!= NULL
) {
2052 /* Plain file upload */
2053 snprintf(cbuf
, CTRL_BUFLEN
, "STOR %s\r\n", ftpState
->filepath
);
2054 ftpState
->writeCommand(cbuf
);
2055 ftpState
->state
= Ftp::Client::SENT_STOR
;
2056 } else if (ftpState
->request
->header
.getInt64(Http::HdrType::CONTENT_LENGTH
) > 0) {
2057 /* File upload without a filename. use STOU to generate one */
2058 snprintf(cbuf
, CTRL_BUFLEN
, "STOU\r\n");
2059 ftpState
->writeCommand(cbuf
);
2060 ftpState
->state
= Ftp::Client::SENT_STOR
;
2062 /* No file to transfer. Only create directories if needed */
2063 ftpSendReply(ftpState
);
2067 /// \deprecated use ftpState->readStor() instead.
2069 ftpReadStor(Ftp::Gateway
* ftpState
)
2071 ftpState
->readStor();
2074 void Ftp::Gateway::readStor()
2076 int code
= ctrl
.replycode
;
2079 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(data
.conn
))) {
2080 if (!originalRequest()->body_pipe
) {
2081 debugs(9, 3, "zero-size STOR?");
2082 state
= WRITING_DATA
; // make ftpWriteTransferDone() responsible
2083 dataComplete(); // XXX: keep in sync with doneSendingRequestBody()
2087 if (!startRequestBodyFlow()) { // register to receive body data
2092 /* When client status is 125, or 150 and the data connection is open, Begin data transfer. */
2093 debugs(9, 3, HERE
<< "starting data transfer");
2094 switchTimeoutToDataChannel();
2095 sendMoreRequestBody();
2096 fwd
->dontRetry(true); // dont permit re-trying if the body was sent.
2097 state
= WRITING_DATA
;
2098 debugs(9, 3, HERE
<< "writing data channel");
2099 } else if (code
== 150) {
2100 /* When client code is 150 with no data channel, Accept data channel. */
2101 debugs(9, 3, "ftpReadStor: accepting data channel");
2102 listenForDataChannel(data
.conn
);
2104 debugs(9, DBG_IMPORTANT
, HERE
<< "Unexpected reply code "<< std::setfill('0') << std::setw(3) << code
);
2110 ftpSendRest(Ftp::Gateway
* ftpState
)
2112 /* check the server control channel is still available */
2113 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRest"))
2118 snprintf(cbuf
, CTRL_BUFLEN
, "REST %" PRId64
"\r\n", ftpState
->restart_offset
);
2119 ftpState
->writeCommand(cbuf
);
2120 ftpState
->state
= Ftp::Client::SENT_REST
;
2124 Ftp::Gateway::restartable()
2126 if (restart_offset
> 0)
2129 if (!request
->range
)
2138 int64_t desired_offset
= request
->range
->lowestOffset(theSize
);
2140 if (desired_offset
<= 0)
2143 if (desired_offset
>= theSize
)
2146 restart_offset
= desired_offset
;
2151 ftpReadRest(Ftp::Gateway
* ftpState
)
2153 int code
= ftpState
->ctrl
.replycode
;
2155 assert(ftpState
->restart_offset
> 0);
2158 ftpState
->setCurrentOffset(ftpState
->restart_offset
);
2159 ftpSendRetr(ftpState
);
2160 } else if (code
> 0) {
2161 debugs(9, 3, HERE
<< "REST not supported");
2162 ftpState
->flags
.rest_supported
= 0;
2163 ftpSendRetr(ftpState
);
2170 ftpSendList(Ftp::Gateway
* ftpState
)
2172 /* check the server control channel is still available */
2173 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendList"))
2178 if (ftpState
->filepath
) {
2179 snprintf(cbuf
, CTRL_BUFLEN
, "LIST %s\r\n", ftpState
->filepath
);
2181 snprintf(cbuf
, CTRL_BUFLEN
, "LIST\r\n");
2184 ftpState
->writeCommand(cbuf
);
2185 ftpState
->state
= Ftp::Client::SENT_LIST
;
2189 ftpSendNlst(Ftp::Gateway
* ftpState
)
2191 /* check the server control channel is still available */
2192 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendNlst"))
2197 ftpState
->flags
.tried_nlst
= 1;
2199 if (ftpState
->filepath
) {
2200 snprintf(cbuf
, CTRL_BUFLEN
, "NLST %s\r\n", ftpState
->filepath
);
2202 snprintf(cbuf
, CTRL_BUFLEN
, "NLST\r\n");
2205 ftpState
->writeCommand(cbuf
);
2206 ftpState
->state
= Ftp::Client::SENT_NLST
;
2210 ftpReadList(Ftp::Gateway
* ftpState
)
2212 int code
= ftpState
->ctrl
.replycode
;
2215 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2216 /* Begin data transfer */
2217 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2218 ftpState
->switchTimeoutToDataChannel();
2219 ftpState
->maybeReadVirginBody();
2220 ftpState
->state
= Ftp::Client::READING_DATA
;
2222 } else if (code
== 150) {
2223 /* Accept data channel */
2224 debugs(9, 3, HERE
<< "accept data channel from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2225 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2227 } else if (!ftpState
->flags
.tried_nlst
&& code
> 300) {
2228 ftpSendNlst(ftpState
);
2236 ftpSendRetr(Ftp::Gateway
* ftpState
)
2238 /* check the server control channel is still available */
2239 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRetr"))
2244 assert(ftpState
->filepath
!= NULL
);
2245 snprintf(cbuf
, CTRL_BUFLEN
, "RETR %s\r\n", ftpState
->filepath
);
2246 ftpState
->writeCommand(cbuf
);
2247 ftpState
->state
= Ftp::Client::SENT_RETR
;
2251 ftpReadRetr(Ftp::Gateway
* ftpState
)
2253 int code
= ftpState
->ctrl
.replycode
;
2256 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2257 /* Begin data transfer */
2258 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2259 ftpState
->switchTimeoutToDataChannel();
2260 ftpState
->maybeReadVirginBody();
2261 ftpState
->state
= Ftp::Client::READING_DATA
;
2262 } else if (code
== 150) {
2263 /* Accept data channel */
2264 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2265 } else if (code
>= 300) {
2266 if (!ftpState
->flags
.try_slash_hack
) {
2267 /* Try this as a directory missing trailing slash... */
2268 ftpState
->hackShortcut(ftpSendCwd
);
2278 * Generate the HTTP headers and template fluff around an FTP
2279 * directory listing display.
2282 Ftp::Gateway::completedListing()
2285 entry
->lock("Ftp::Gateway");
2286 ErrorState
ferr(ERR_DIR_LISTING
, Http::scOkay
, request
.getRaw());
2287 ferr
.ftp
.listing
= &listing
;
2288 ferr
.ftp
.cwd_msg
= xstrdup(cwd_message
.size()? cwd_message
.termedBuf() : "");
2289 ferr
.ftp
.server_msg
= ctrl
.message
;
2290 ctrl
.message
= NULL
;
2291 entry
->replaceHttpReply(ferr
.BuildHttpReply());
2292 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2294 entry
->unlock("Ftp::Gateway");
2298 ftpReadTransferDone(Ftp::Gateway
* ftpState
)
2300 int code
= ftpState
->ctrl
.replycode
;
2303 if (code
== 226 || code
== 250) {
2304 /* Connection closed; retrieval done. */
2305 if (ftpState
->flags
.listing
) {
2306 ftpState
->completedListing();
2307 /* QUIT operation handles sending the reply to client */
2309 ftpSendQuit(ftpState
);
2310 } else { /* != 226 */
2311 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after reading data");
2312 ftpState
->failed(ERR_FTP_FAILURE
, 0);
2313 /* failed closes ctrl.conn and frees ftpState */
2318 // premature end of the request body
2320 Ftp::Gateway::handleRequestBodyProducerAborted()
2322 Client::handleRequestBodyProducerAborted();
2323 debugs(9, 3, HERE
<< "ftpState=" << this);
2324 failed(ERR_READ_ERROR
, 0);
2328 ftpWriteTransferDone(Ftp::Gateway
* ftpState
)
2330 int code
= ftpState
->ctrl
.replycode
;
2333 if (!(code
== 226 || code
== 250)) {
2334 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after sending data");
2335 ftpState
->failed(ERR_FTP_PUT_ERROR
, 0);
2339 ftpState
->entry
->timestampsSet(); /* XXX Is this needed? */
2340 ftpSendReply(ftpState
);
2344 ftpSendQuit(Ftp::Gateway
* ftpState
)
2346 /* check the server control channel is still available */
2347 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendQuit"))
2350 snprintf(cbuf
, CTRL_BUFLEN
, "QUIT\r\n");
2351 ftpState
->writeCommand(cbuf
);
2352 ftpState
->state
= Ftp::Client::SENT_QUIT
;
2355 /** Completes a client FTP operation with success or other page
2356 * generated and stored in the entry field by the code issuing QUIT.
2359 ftpReadQuit(Ftp::Gateway
* ftpState
)
2361 ftpState
->serverComplete();
2365 ftpTrySlashHack(Ftp::Gateway
* ftpState
)
2368 ftpState
->flags
.try_slash_hack
= 1;
2369 /* Free old paths */
2373 if (ftpState
->pathcomps
)
2374 wordlistDestroy(&ftpState
->pathcomps
);
2376 safe_free(ftpState
->filepath
);
2378 /* Build the new path (urlpath begins with /) */
2379 path
= SBufToCstring(ftpState
->request
->url
.path());
2381 rfc1738_unescape(path
);
2383 ftpState
->filepath
= path
;
2386 ftpGetFile(ftpState
);
2390 * Forget hack status. Next error is shown to the user
2393 Ftp::Gateway::unhack()
2397 if (old_request
!= NULL
) {
2398 safe_free(old_request
);
2399 safe_free(old_reply
);
2404 Ftp::Gateway::hackShortcut(FTPSM
* nextState
)
2406 /* Clear some unwanted state */
2407 setCurrentOffset(0);
2409 /* Save old error message & some state info */
2413 if (old_request
== NULL
) {
2414 old_request
= ctrl
.last_command
;
2415 ctrl
.last_command
= NULL
;
2416 old_reply
= ctrl
.last_reply
;
2417 ctrl
.last_reply
= NULL
;
2419 if (pathcomps
== NULL
&& filepath
!= NULL
)
2420 old_filepath
= xstrdup(filepath
);
2423 /* Jump to the "hack" state */
2428 ftpFail(Ftp::Gateway
*ftpState
)
2430 const bool slashHack
= ftpState
->request
->url
.path().caseCmp("/%2f", 4)==0;
2431 int code
= ftpState
->ctrl
.replycode
;
2432 err_type error_code
= ERR_NONE
;
2434 debugs(9, 6, "state " << ftpState
->state
<<
2435 " reply code " << code
<< "flags(" <<
2436 (ftpState
->flags
.isdir
?"IS_DIR,":"") <<
2437 (ftpState
->flags
.try_slash_hack
?"TRY_SLASH_HACK":"") << "), " <<
2438 "mdtm=" << ftpState
->mdtm
<< ", size=" << ftpState
->theSize
<<
2439 "slashhack=" << (slashHack
? "T":"F"));
2441 /* Try the / hack to support "Netscape" FTP URL's for retreiving files */
2442 if (!ftpState
->flags
.isdir
&& /* Not a directory */
2443 !ftpState
->flags
.try_slash_hack
&& !slashHack
&& /* Not doing slash hack */
2444 ftpState
->mdtm
<= 0 && ftpState
->theSize
< 0) { /* Not known as a file */
2446 switch (ftpState
->state
) {
2448 case Ftp::Client::SENT_CWD
:
2450 case Ftp::Client::SENT_RETR
:
2451 /* Try the / hack */
2452 ftpState
->hackShortcut(ftpTrySlashHack
);
2460 Http::StatusCode sc
= ftpState
->failedHttpStatus(error_code
);
2461 ErrorState
*ftperr
= new ErrorState(error_code
, sc
, ftpState
->fwd
->request
);
2462 ftpState
->failed(error_code
, code
, ftperr
);
2463 ftperr
->detailError(code
);
2464 HttpReply
*newrep
= ftperr
->BuildHttpReply();
2467 ftpState
->entry
->replaceHttpReply(newrep
);
2468 ftpSendQuit(ftpState
);
2472 Ftp::Gateway::failedHttpStatus(err_type
&error
)
2474 if (error
== ERR_NONE
) {
2481 if (ctrl
.replycode
> 500) {
2482 error
= ERR_FTP_FORBIDDEN
;
2483 return password_url
? Http::scForbidden
: Http::scUnauthorized
;
2484 } else if (ctrl
.replycode
== 421) {
2485 error
= ERR_FTP_UNAVAILABLE
;
2486 return Http::scServiceUnavailable
;
2493 if (ctrl
.replycode
== 550) {
2494 error
= ERR_FTP_NOT_FOUND
;
2495 return Http::scNotFound
;
2503 return Ftp::Client::failedHttpStatus(error
);
2507 ftpSendReply(Ftp::Gateway
* ftpState
)
2509 int code
= ftpState
->ctrl
.replycode
;
2510 Http::StatusCode http_code
;
2511 err_type err_code
= ERR_NONE
;
2513 debugs(9, 3, HERE
<< ftpState
->entry
->url() << ", code " << code
);
2515 if (cbdataReferenceValid(ftpState
))
2516 debugs(9, 5, HERE
<< "ftpState (" << ftpState
<< ") is valid!");
2518 if (code
== 226 || code
== 250) {
2519 err_code
= (ftpState
->mdtm
> 0) ? ERR_FTP_PUT_MODIFIED
: ERR_FTP_PUT_CREATED
;
2520 http_code
= (ftpState
->mdtm
> 0) ? Http::scAccepted
: Http::scCreated
;
2521 } else if (code
== 227) {
2522 err_code
= ERR_FTP_PUT_CREATED
;
2523 http_code
= Http::scCreated
;
2525 err_code
= ERR_FTP_PUT_ERROR
;
2526 http_code
= Http::scInternalServerError
;
2529 ErrorState
err(err_code
, http_code
, ftpState
->request
.getRaw());
2531 if (ftpState
->old_request
)
2532 err
.ftp
.request
= xstrdup(ftpState
->old_request
);
2534 err
.ftp
.request
= xstrdup(ftpState
->ctrl
.last_command
);
2536 if (ftpState
->old_reply
)
2537 err
.ftp
.reply
= xstrdup(ftpState
->old_reply
);
2538 else if (ftpState
->ctrl
.last_reply
)
2539 err
.ftp
.reply
= xstrdup(ftpState
->ctrl
.last_reply
);
2541 err
.ftp
.reply
= xstrdup("");
2543 // TODO: interpret as FTP-specific error code
2544 err
.detailError(code
);
2546 ftpState
->entry
->replaceHttpReply(err
.BuildHttpReply());
2548 ftpSendQuit(ftpState
);
2552 Ftp::Gateway::appendSuccessHeader()
2556 if (flags
.http_header_sent
)
2559 HttpReply
*reply
= new HttpReply
;
2561 flags
.http_header_sent
= 1;
2563 assert(entry
->isEmpty());
2565 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2567 entry
->buffer(); /* released when done processing current data payload */
2569 SBuf urlPath
= request
->url
.path();
2570 auto t
= urlPath
.rfind('/');
2571 SBuf filename
= urlPath
.substr(t
!= SBuf::npos
? t
: 0);
2573 const char *mime_type
= NULL
;
2574 const char *mime_enc
= NULL
;
2577 mime_type
= "text/html";
2582 mime_type
= "application/octet-stream";
2583 // XXX: performance regression, c_str() may reallocate
2584 mime_enc
= mimeGetContentEncoding(filename
.c_str());
2588 mime_type
= "text/plain";
2592 // XXX: performance regression, c_str() may reallocate
2593 mime_type
= mimeGetContentType(filename
.c_str());
2594 mime_enc
= mimeGetContentEncoding(filename
.c_str());
2599 /* set standard stuff */
2601 if (0 == getCurrentOffset()) {
2603 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2604 } else if (theSize
< getCurrentOffset()) {
2607 * offset should not be larger than theSize. We should
2608 * not be seeing this condition any more because we'll only
2609 * send REST if we know the theSize and if it is less than theSize.
2611 debugs(0,DBG_CRITICAL
,HERE
<< "Whoops! " <<
2612 " current offset=" << getCurrentOffset() <<
2613 ", but theSize=" << theSize
<<
2614 ". assuming full content response");
2615 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2618 HttpHdrRangeSpec range_spec
;
2619 range_spec
.offset
= getCurrentOffset();
2620 range_spec
.length
= theSize
- getCurrentOffset();
2621 reply
->setHeaders(Http::scPartialContent
, "Gatewaying", mime_type
, theSize
- getCurrentOffset(), mdtm
, -2);
2622 httpHeaderAddContRange(&reply
->header
, range_spec
, theSize
);
2625 /* additional info */
2627 reply
->header
.putStr(Http::HdrType::CONTENT_ENCODING
, mime_enc
);
2629 reply
->sources
|= Http::Message::srcFtp
;
2630 setVirginReply(reply
);
2631 adaptOrFinalizeReply();
2635 Ftp::Gateway::haveParsedReplyHeaders()
2637 Client::haveParsedReplyHeaders();
2639 StoreEntry
*e
= entry
;
2643 // makePublic() if allowed/possible or release() otherwise
2644 if (flags
.authenticated
|| // authenticated requests can't be cached
2645 getCurrentOffset() ||
2652 Ftp::Gateway::ftpAuthRequired(HttpRequest
* request
, SBuf
&realm
)
2654 ErrorState
err(ERR_CACHE_ACCESS_DENIED
, Http::scUnauthorized
, request
);
2655 HttpReply
*newrep
= err
.BuildHttpReply();
2656 #if HAVE_AUTH_MODULE_BASIC
2657 /* add Authenticate header */
2658 // XXX: performance regression. c_str() may reallocate
2659 newrep
->header
.putAuth("Basic", realm
.c_str());
2665 Ftp::UrlWith2f(HttpRequest
* request
)
2669 if (request
->url
.getScheme() != AnyP::PROTO_FTP
) {
2670 static const SBuf nil
;
2674 if (request
->url
.path()[0] == '/') {
2675 newbuf
.append(request
->url
.path());
2676 request
->url
.path(newbuf
);
2677 } else if (!request
->url
.path().startsWith(newbuf
)) {
2678 newbuf
.append(request
->url
.path().substr(1));
2679 request
->url
.path(newbuf
);
2682 return request
->effectiveRequestUri();
2686 Ftp::Gateway::printfReplyBody(const char *fmt
, ...)
2689 va_start (args
, fmt
);
2690 static char buf
[4096];
2692 vsnprintf(buf
, 4096, fmt
, args
);
2693 writeReplyBody(buf
, strlen(buf
));
2698 * Call this when there is data from the origin server
2699 * which should be sent to either StoreEntry, or to ICAP...
2702 Ftp::Gateway::writeReplyBody(const char *dataToWrite
, size_t dataLength
)
2704 debugs(9, 5, HERE
<< "writing " << dataLength
<< " bytes to the reply");
2705 addVirginReplyBody(dataToWrite
, dataLength
);
2709 * A hack to ensure we do not double-complete on the forward entry.
2711 \todo Ftp::Gateway logic should probably be rewritten to avoid
2712 * double-completion or FwdState should be rewritten to allow it.
2715 Ftp::Gateway::completeForwarding()
2717 if (fwd
== NULL
|| flags
.completed_forwarding
) {
2718 debugs(9, 3, "avoid double-complete on FD " <<
2719 (ctrl
.conn
? ctrl
.conn
->fd
: -1) << ", Data FD " << data
.conn
->fd
<<
2720 ", this " << this << ", fwd " << fwd
);
2724 flags
.completed_forwarding
= true;
2725 Client::completeForwarding();
2729 * Have we lost the FTP server control channel?
2731 \retval true The server control channel is available.
2732 \retval false The server control channel is not available.
2735 Ftp::Gateway::haveControlChannel(const char *caller_name
) const
2737 if (doneWithServer())
2740 /* doneWithServer() only checks BOTH channels are closed. */
2741 if (!Comm::IsConnOpen(ctrl
.conn
)) {
2742 debugs(9, DBG_IMPORTANT
, "WARNING! FTP Server Control channel is closed, but Data channel still active.");
2743 debugs(9, 2, caller_name
<< ": attempted on a closed FTP channel.");
2751 Ftp::Gateway::mayReadVirginReplyBody() const
2753 // TODO: Can we do what Ftp::Relay::mayReadVirginReplyBody() does instead?
2754 return !doneWithServer();
2758 Ftp::StartGateway(FwdState
*const fwdState
)
2760 return AsyncJob::Start(new Ftp::Gateway(fwdState
));