2 * Copyright (C) 1996-2017 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
, const char *realm
);
157 const char *ftpRealm(void);
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 /* XXX assumes a single space between date and filename
622 * suggested by: Nathan.Bailey@cc.monash.edu.au and
623 * Mike Battersby <mike@starbug.bofh.asn.au> */
624 copyFrom
+= strlen(tbuf
) + 1;
627 p
->name
= xstrdup(copyFrom
);
629 if (p
->type
== 'l' && (t
= strstr(p
->name
, " -> "))) {
631 p
->link
= xstrdup(t
+ 4);
640 /* try it as a DOS listing, 04-05-70 09:33PM ... */
642 regexec(&scan_ftp_dosdate
, tokens
[0], 0, NULL
, 0) == 0 &&
643 regexec(&scan_ftp_dostime
, tokens
[1], 0, NULL
, 0) == 0) {
644 if (!strcasecmp(tokens
[2], "<dir>")) {
648 p
->size
= strtoll(tokens
[2], NULL
, 10);
651 snprintf(tbuf
, 128, "%s %s", tokens
[0], tokens
[1]);
652 p
->date
= xstrdup(tbuf
);
654 if (p
->type
== 'd') {
655 /* Directory.. name begins with first printable after <dir> */
656 ct
= strstr(buf
, tokens
[2]);
657 ct
+= strlen(tokens
[2]);
659 while (xisspace(*ct
))
665 /* A file. Name begins after size, with a space in between */
666 snprintf(tbuf
, 128, " %s %s", tokens
[2], tokens
[3]);
667 ct
= strstr(buf
, tbuf
);
670 ct
+= strlen(tokens
[2]) + 2;
674 p
->name
= xstrdup(ct
? ct
: tokens
[3]);
678 /* Try EPLF format; carson@lehman.com */
685 int l
= strcspn(ct
, ",");
694 p
->name
= xstrndup(ct
+ 1, l
+ 1);
698 p
->size
= atoi(ct
+ 1);
702 tm
= (time_t) strtol(ct
+ 1, &tmp
, 0);
705 break; /* not a valid integer */
707 p
->date
= xstrdup(ctime(&tm
));
709 *(strstr(p
->date
, "\n")) = '\0';
731 ct
= strstr(ct
, ",");
750 for (i
= 0; i
< n_tokens
; ++i
)
754 ftpListPartsFree(&p
); /* cleanup */
760 Ftp::Gateway::htmlifyListEntry(const char *line
)
763 char href
[2048 + 40];
766 char chdir
[ 2048 + 40];
767 char view
[ 2048 + 40];
768 char download
[ 2048 + 40];
769 char link
[ 2048 + 40];
773 *icon
= *href
= *text
= *size
= *chdir
= *view
= *download
= *link
= '\0';
775 debugs(9, 7, HERE
<< " line ={" << line
<< "}");
777 if (strlen(line
) > 1024) {
780 html
->appendf("<tr><td colspan=\"5\">%s</td></tr>\n", line
);
784 if (flags
.dir_slash
&& dirpath
&& typecode
!= 'D')
785 snprintf(prefix
, 2048, "%s/", rfc1738_escape_part(dirpath
));
789 if ((parts
= ftpListParseParts(line
, flags
)) == NULL
) {
794 html
->appendf("<tr class=\"entry\"><td colspan=\"5\">%s</td></tr>\n", line
);
796 for (p
= line
; *p
&& xisspace(*p
); ++p
);
797 if (*p
&& !xisspace(*p
))
798 flags
.listformat_unknown
= 1;
803 if (!strcmp(parts
->name
, ".") || !strcmp(parts
->name
, "..")) {
804 ftpListPartsFree(&parts
);
810 parts
->showname
= xstrdup(parts
->name
);
812 /* {icon} {text} . . . {date}{size}{chdir}{view}{download}{link}\n */
813 xstrncpy(href
, rfc1738_escape_part(parts
->name
), 2048);
815 xstrncpy(text
, parts
->showname
, 2048);
817 switch (parts
->type
) {
820 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
821 mimeGetIconURL("internal-dir"),
823 strcat(href
, "/"); /* margin is allocated above */
827 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
828 mimeGetIconURL("internal-link"),
830 /* sometimes there is an 'l' flag, but no "->" link */
833 char *link2
= xstrdup(html_quote(rfc1738_escape(parts
->link
)));
834 snprintf(link
, 2048, " -> <a href=\"%s%s\">%s</a>",
835 *link2
!= '/' ? prefix
: "", link2
,
836 html_quote(parts
->link
));
843 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
844 mimeGetIconURL(parts
->name
),
846 snprintf(chdir
, 2048, "<a href=\"%s/;type=d\"><img border=\"0\" src=\"%s\" "
847 "alt=\"[DIR]\"></a>",
848 rfc1738_escape_part(parts
->name
),
849 mimeGetIconURL("internal-dir"));
855 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
856 mimeGetIconURL(parts
->name
),
858 snprintf(size
, 2048, " %6" PRId64
"k", parts
->size
);
862 if (parts
->type
!= 'd') {
863 if (mimeGetViewOption(parts
->name
)) {
864 snprintf(view
, 2048, "<a href=\"%s%s;type=a\"><img border=\"0\" src=\"%s\" "
865 "alt=\"[VIEW]\"></a>",
866 prefix
, href
, mimeGetIconURL("internal-view"));
869 if (mimeGetDownloadOption(parts
->name
)) {
870 snprintf(download
, 2048, "<a href=\"%s%s;type=i\"><img border=\"0\" src=\"%s\" "
871 "alt=\"[DOWNLOAD]\"></a>",
872 prefix
, href
, mimeGetIconURL("internal-download"));
876 /* construct the table row from parts. */
879 html
->appendf("<tr class=\"entry\">"
880 "<td class=\"icon\"><a href=\"%s%s\">%s</a></td>"
881 "<td class=\"filename\"><a href=\"%s%s\">%s</a></td>"
882 "<td class=\"date\">%s</td>"
883 "<td class=\"size\">%s</td>"
884 "<td class=\"actions\">%s%s%s%s</td>"
887 prefix
, href
, html_quote(text
),
890 chdir
, view
, download
, link
);
892 ftpListPartsFree(&parts
);
897 Ftp::Gateway::parseListing()
899 char *buf
= data
.readBuf
->content();
900 char *sbuf
; /* NULL-terminated copy of termedBuf */
907 size_t len
= data
.readBuf
->contentSize();
910 debugs(9, 3, HERE
<< "no content to parse for " << entry
->url() );
915 * We need a NULL-terminated buffer for scanning, ick
917 sbuf
= (char *)xmalloc(len
+ 1);
918 xstrncpy(sbuf
, buf
, len
+ 1);
919 end
= sbuf
+ len
- 1;
921 while (*end
!= '\r' && *end
!= '\n' && end
> sbuf
)
926 debugs(9, 3, HERE
<< "usable = " << usable
<< " of " << len
<< " bytes.");
929 if (buf
[0] == '\0' && len
== 1) {
930 debugs(9, 3, HERE
<< "NIL ends data from " << entry
->url() << " transfer problem?");
931 data
.readBuf
->consume(len
);
933 debugs(9, 3, HERE
<< "didn't find end for " << entry
->url());
934 debugs(9, 3, HERE
<< "buffer remains (" << len
<< " bytes) '" << rfc1738_do_escape(buf
,0) << "'");
940 debugs(9, 3, HERE
<< (unsigned long int)len
<< " bytes to play with");
942 line
= (char *)memAllocate(MEM_4K_BUF
);
945 s
+= strspn(s
, crlf
);
947 for (; s
< end
; s
+= strcspn(s
, crlf
), s
+= strspn(s
, crlf
)) {
948 debugs(9, 7, HERE
<< "s = {" << s
<< "}");
949 linelen
= strcspn(s
, crlf
) + 1;
957 xstrncpy(line
, s
, linelen
);
959 debugs(9, 7, HERE
<< "{" << line
<< "}");
961 if (!strncmp(line
, "total", 5))
964 t
= htmlifyListEntry(line
);
967 debugs(9, 7, HERE
<< "listing append: t = {" << t
->contentSize() << ", '" << t
->content() << "'}");
968 listing
.append(t
->content(), t
->contentSize());
973 debugs(9, 7, HERE
<< "Done.");
974 data
.readBuf
->consume(usable
);
975 memFree(line
, MEM_4K_BUF
);
980 Ftp::Gateway::processReplyBody()
982 debugs(9, 3, status());
984 if (request
->method
== Http::METHOD_HEAD
&& (flags
.isdir
|| theSize
!= -1)) {
989 /* Directory listings are special. They write ther own headers via the error objects */
990 if (!flags
.http_header_sent
&& data
.readBuf
->contentSize() >= 0 && !flags
.isdir
)
991 appendSuccessHeader();
993 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
995 * probably was aborted because content length exceeds one
996 * of the maximum size limits.
998 abortAll("entry aborted after calling appendSuccessHeader()");
1004 if (adaptationAccessCheckPending
) {
1005 debugs(9, 3, "returning from Ftp::Gateway::processReplyBody due to adaptationAccessCheckPending");
1012 if (!flags
.listing
) {
1017 maybeReadVirginBody();
1019 } else if (const int csize
= data
.readBuf
->contentSize()) {
1020 writeReplyBody(data
.readBuf
->content(), csize
);
1021 debugs(9, 5, HERE
<< "consuming " << csize
<< " bytes of readBuf");
1022 data
.readBuf
->consume(csize
);
1027 maybeReadVirginBody();
1031 * Locates the FTP user:password login.
1033 * Highest to lowest priority:
1034 * - Checks URL (ftp://user:pass@domain)
1035 * - Authorization: Basic header
1036 * - squid.conf anonymous-FTP settings (default: anonymous:Squid@).
1038 * Special Case: A username-only may be provided in the URL and password in the HTTP headers.
1040 * TODO: we might be able to do something about locating username from other sources:
1041 * ie, external ACL user=* tag or ident lookup
1043 \retval 1 if we have everything needed to complete this request.
1044 \retval 0 if something is missing.
1047 Ftp::Gateway::checkAuth(const HttpHeader
* req_hdr
)
1049 /* default username */
1050 xstrncpy(user
, "anonymous", MAX_URL
);
1052 #if HAVE_AUTH_MODULE_BASIC
1053 /* Check HTTP Authorization: headers (better than defaults, but less than URL) */
1054 const SBuf
auth(req_hdr
->getAuth(Http::HdrType::AUTHORIZATION
, "Basic"));
1055 if (!auth
.isEmpty()) {
1056 flags
.authenticated
= 1;
1057 loginParser(auth
, false);
1059 /* we fail with authorization-required error later IFF the FTP server requests it */
1062 /* Test URL login syntax. Overrides any headers received. */
1063 loginParser(request
->url
.userInfo(), true);
1065 /* name is missing. thats fatal. */
1067 fatal("FTP login parsing destroyed username info");
1069 /* name + password == success */
1073 /* Setup default FTP password settings */
1074 /* this has to be done last so that we can have a no-password case above. */
1076 if (strcmp(user
, "anonymous") == 0 && !flags
.tried_auth_anonymous
) {
1077 xstrncpy(password
, Config
.Ftp
.anon_user
, MAX_URL
);
1078 flags
.tried_auth_anonymous
=1;
1080 } else if (!flags
.tried_auth_nopass
) {
1081 xstrncpy(password
, null_string
, MAX_URL
);
1082 flags
.tried_auth_nopass
=1;
1087 return 0; /* different username */
1091 Ftp::Gateway::checkUrlpath()
1093 static SBuf
str_type_eq("type=");
1094 auto t
= request
->url
.path().rfind(';');
1096 if (t
!= SBuf::npos
) {
1097 auto filenameEnd
= t
-1;
1098 if (request
->url
.path().substr(++t
).cmp(str_type_eq
, str_type_eq
.length()) == 0) {
1099 t
+= str_type_eq
.length();
1100 typecode
= (char)xtoupper(request
->url
.path()[t
]);
1101 request
->url
.path(request
->url
.path().substr(0,filenameEnd
));
1105 int l
= request
->url
.path().length();
1106 /* check for null path */
1111 flags
.need_base_href
= 1; /* Work around broken browsers */
1112 } else if (!request
->url
.path().cmp("/%2f/")) {
1113 /* UNIX root directory */
1116 } else if ((l
>= 1) && (request
->url
.path()[l
-1] == '/')) {
1117 /* Directory URL, ending in / */
1123 flags
.dir_slash
= 1;
1128 Ftp::Gateway::buildTitleUrl()
1130 title_url
= "ftp://";
1132 if (strcmp(user
, "anonymous")) {
1133 title_url
.append(user
);
1134 title_url
.append("@");
1137 SBuf authority
= request
->url
.authority(request
->url
.getScheme() != AnyP::PROTO_FTP
);
1139 title_url
.append(authority
.rawContent(), authority
.length());
1140 title_url
.append(request
->url
.path().rawContent(), request
->url
.path().length());
1142 base_href
= "ftp://";
1144 if (strcmp(user
, "anonymous") != 0) {
1145 base_href
.append(rfc1738_escape_part(user
));
1148 base_href
.append(":");
1149 base_href
.append(rfc1738_escape_part(password
));
1152 base_href
.append("@");
1155 base_href
.append(authority
.rawContent(), authority
.length());
1156 base_href
.append(request
->url
.path().rawContent(), request
->url
.path().length());
1157 base_href
.append("/");
1161 Ftp::Gateway::start()
1163 if (!checkAuth(&request
->header
)) {
1164 /* create appropriate reply */
1165 HttpReply
*reply
= ftpAuthRequired(request
, ftpRealm());
1166 entry
->replaceHttpReply(reply
);
1173 debugs(9, 5, "FD " << (ctrl
.conn
? ctrl
.conn
->fd
: -1) << " : host=" << request
->url
.host() <<
1174 ", path=" << request
->url
.path() << ", user=" << user
<< ", passwd=" << password
);
1176 Ftp::Client::start();
1179 /* ====================================================================== */
1182 Ftp::Gateway::handleControlReply()
1184 Ftp::Client::handleControlReply();
1185 if (ctrl
.message
== NULL
)
1186 return; // didn't get complete reply yet
1188 /* Copy the message except for the last line to cwd_message to be
1189 * printed in error messages.
1191 for (wordlist
*w
= ctrl
.message
; w
&& w
->next
; w
= w
->next
) {
1192 cwd_message
.append('\n');
1193 cwd_message
.append(w
->key
);
1196 FTP_SM_FUNCS
[state
] (this);
1199 /* ====================================================================== */
1202 ftpReadWelcome(Ftp::Gateway
* ftpState
)
1204 int code
= ftpState
->ctrl
.replycode
;
1207 if (ftpState
->flags
.pasv_only
)
1208 ++ ftpState
->login_att
;
1211 if (ftpState
->ctrl
.message
) {
1212 if (strstr(ftpState
->ctrl
.message
->key
, "NetWare"))
1213 ftpState
->flags
.skip_whitespace
= 1;
1216 ftpSendUser(ftpState
);
1217 } else if (code
== 120) {
1218 if (NULL
!= ftpState
->ctrl
.message
)
1219 debugs(9, DBG_IMPORTANT
, "FTP server is busy: " << ftpState
->ctrl
.message
->key
);
1228 * Translate FTP login failure into HTTP error
1229 * this is an attmpt to get the 407 message to show up outside Squid.
1230 * its NOT a general failure. But a correct FTP response type.
1233 Ftp::Gateway::loginFailed()
1235 ErrorState
*err
= NULL
;
1237 if ((state
== SENT_USER
|| state
== SENT_PASS
) && ctrl
.replycode
>= 400) {
1238 if (ctrl
.replycode
== 421 || ctrl
.replycode
== 426) {
1239 // 421/426 - Service Overload - retry permitted.
1240 err
= new ErrorState(ERR_FTP_UNAVAILABLE
, Http::scServiceUnavailable
, fwd
->request
);
1241 } else if (ctrl
.replycode
>= 430 && ctrl
.replycode
<= 439) {
1242 // 43x - Invalid or Credential Error - retry challenge required.
1243 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1244 } else if (ctrl
.replycode
>= 530 && ctrl
.replycode
<= 539) {
1245 // 53x - Credentials Missing - retry challenge required
1246 if (password_url
) // but they were in the URI! major fail.
1247 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scForbidden
, fwd
->request
);
1249 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1258 failed(ERR_NONE
, ctrl
.replycode
, err
);
1259 // any other problems are general falures.
1261 HttpReply
*newrep
= err
->BuildHttpReply();
1264 #if HAVE_AUTH_MODULE_BASIC
1265 /* add Authenticate header */
1266 newrep
->header
.putAuth("Basic", ftpRealm());
1269 // add it to the store entry for response....
1270 entry
->replaceHttpReply(newrep
);
1275 Ftp::Gateway::ftpRealm()
1277 static char realm
[8192];
1279 /* This request is not fully authenticated */
1281 snprintf(realm
, 8192, "FTP %s unknown", user
);
1282 } else if (request
->url
.port() == 21) {
1283 snprintf(realm
, 8192, "FTP %s %s", user
, request
->url
.host());
1285 snprintf(realm
, 8192, "FTP %s %s port %d", user
, request
->url
.host(), request
->url
.port());
1291 ftpSendUser(Ftp::Gateway
* ftpState
)
1293 /* check the server control channel is still available */
1294 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendUser"))
1297 if (ftpState
->proxy_host
!= NULL
)
1298 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s@%s\r\n", ftpState
->user
, ftpState
->request
->url
.host());
1300 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s\r\n", ftpState
->user
);
1302 ftpState
->writeCommand(cbuf
);
1304 ftpState
->state
= Ftp::Client::SENT_USER
;
1308 ftpReadUser(Ftp::Gateway
* ftpState
)
1310 int code
= ftpState
->ctrl
.replycode
;
1314 ftpReadPass(ftpState
);
1315 } else if (code
== 331) {
1316 ftpSendPass(ftpState
);
1318 ftpState
->loginFailed();
1323 ftpSendPass(Ftp::Gateway
* ftpState
)
1325 /* check the server control channel is still available */
1326 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPass"))
1329 snprintf(cbuf
, CTRL_BUFLEN
, "PASS %s\r\n", ftpState
->password
);
1330 ftpState
->writeCommand(cbuf
);
1331 ftpState
->state
= Ftp::Client::SENT_PASS
;
1335 ftpReadPass(Ftp::Gateway
* ftpState
)
1337 int code
= ftpState
->ctrl
.replycode
;
1338 debugs(9, 3, HERE
<< "code=" << code
);
1341 ftpSendType(ftpState
);
1343 ftpState
->loginFailed();
1348 ftpSendType(Ftp::Gateway
* ftpState
)
1350 /* check the server control channel is still available */
1351 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendType"))
1355 * Ref section 3.2.2 of RFC 1738
1357 char mode
= ftpState
->typecode
;
1372 if (ftpState
->flags
.isdir
) {
1375 auto t
= ftpState
->request
->url
.path().rfind('/');
1376 // XXX: performance regression, c_str() may reallocate
1377 SBuf filename
= ftpState
->request
->url
.path().substr(t
!= SBuf::npos
? t
+ 1 : 0);
1378 mode
= mimeGetTransferMode(filename
.c_str());
1385 ftpState
->flags
.binary
= 1;
1387 ftpState
->flags
.binary
= 0;
1389 snprintf(cbuf
, CTRL_BUFLEN
, "TYPE %c\r\n", mode
);
1391 ftpState
->writeCommand(cbuf
);
1393 ftpState
->state
= Ftp::Client::SENT_TYPE
;
1397 ftpReadType(Ftp::Gateway
* ftpState
)
1399 int code
= ftpState
->ctrl
.replycode
;
1402 debugs(9, 3, HERE
<< "code=" << code
);
1405 p
= path
= SBufToCstring(ftpState
->request
->url
.path());
1412 p
+= strcspn(p
, "/");
1419 rfc1738_unescape(d
);
1422 wordlistAdd(&ftpState
->pathcomps
, d
);
1427 if (ftpState
->pathcomps
)
1428 ftpTraverseDirectory(ftpState
);
1430 ftpListDir(ftpState
);
1437 ftpTraverseDirectory(Ftp::Gateway
* ftpState
)
1439 debugs(9, 4, HERE
<< (ftpState
->filepath
? ftpState
->filepath
: "<NULL>"));
1441 safe_free(ftpState
->dirpath
);
1442 ftpState
->dirpath
= ftpState
->filepath
;
1443 ftpState
->filepath
= NULL
;
1447 if (ftpState
->pathcomps
== NULL
) {
1448 debugs(9, 3, HERE
<< "the final component was a directory");
1449 ftpListDir(ftpState
);
1453 /* Go to next path component */
1454 ftpState
->filepath
= wordlistChopHead(& ftpState
->pathcomps
);
1456 /* Check if we are to CWD or RETR */
1457 if (ftpState
->pathcomps
!= NULL
|| ftpState
->flags
.isdir
) {
1458 ftpSendCwd(ftpState
);
1460 debugs(9, 3, HERE
<< "final component is probably a file");
1461 ftpGetFile(ftpState
);
1467 ftpSendCwd(Ftp::Gateway
* ftpState
)
1471 /* check the server control channel is still available */
1472 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendCwd"))
1477 path
= ftpState
->filepath
;
1479 if (!strcmp(path
, "..") || !strcmp(path
, "/")) {
1480 ftpState
->flags
.no_dotdot
= 1;
1482 ftpState
->flags
.no_dotdot
= 0;
1485 snprintf(cbuf
, CTRL_BUFLEN
, "CWD %s\r\n", path
);
1487 ftpState
->writeCommand(cbuf
);
1489 ftpState
->state
= Ftp::Client::SENT_CWD
;
1493 ftpReadCwd(Ftp::Gateway
* ftpState
)
1495 int code
= ftpState
->ctrl
.replycode
;
1498 if (code
>= 200 && code
< 300) {
1502 /* Reset cwd_message to only include the last message */
1503 ftpState
->cwd_message
.reset("");
1504 for (wordlist
*w
= ftpState
->ctrl
.message
; w
; w
= w
->next
) {
1505 ftpState
->cwd_message
.append(' ');
1506 ftpState
->cwd_message
.append(w
->key
);
1508 ftpState
->ctrl
.message
= NULL
;
1510 /* Continue to traverse the path */
1511 ftpTraverseDirectory(ftpState
);
1515 if (!ftpState
->flags
.put
)
1518 ftpSendMkdir(ftpState
);
1523 ftpSendMkdir(Ftp::Gateway
* ftpState
)
1527 /* check the server control channel is still available */
1528 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMkdir"))
1531 path
= ftpState
->filepath
;
1532 debugs(9, 3, HERE
<< "with path=" << path
);
1533 snprintf(cbuf
, CTRL_BUFLEN
, "MKD %s\r\n", path
);
1534 ftpState
->writeCommand(cbuf
);
1535 ftpState
->state
= Ftp::Client::SENT_MKDIR
;
1539 ftpReadMkdir(Ftp::Gateway
* ftpState
)
1541 char *path
= ftpState
->filepath
;
1542 int code
= ftpState
->ctrl
.replycode
;
1544 debugs(9, 3, HERE
<< "path " << path
<< ", code " << code
);
1546 if (code
== 257) { /* success */
1547 ftpSendCwd(ftpState
);
1548 } else if (code
== 550) { /* dir exists */
1550 if (ftpState
->flags
.put_mkdir
) {
1551 ftpState
->flags
.put_mkdir
= 1;
1552 ftpSendCwd(ftpState
);
1554 ftpSendReply(ftpState
);
1556 ftpSendReply(ftpState
);
1560 ftpGetFile(Ftp::Gateway
* ftpState
)
1562 assert(*ftpState
->filepath
!= '\0');
1563 ftpState
->flags
.isdir
= 0;
1564 ftpSendMdtm(ftpState
);
1568 ftpListDir(Ftp::Gateway
* ftpState
)
1570 if (ftpState
->flags
.dir_slash
) {
1571 debugs(9, 3, HERE
<< "Directory path did not end in /");
1572 ftpState
->title_url
.append("/");
1573 ftpState
->flags
.isdir
= 1;
1576 ftpSendPassive(ftpState
);
1580 ftpSendMdtm(Ftp::Gateway
* ftpState
)
1582 /* check the server control channel is still available */
1583 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMdtm"))
1586 assert(*ftpState
->filepath
!= '\0');
1587 snprintf(cbuf
, CTRL_BUFLEN
, "MDTM %s\r\n", ftpState
->filepath
);
1588 ftpState
->writeCommand(cbuf
);
1589 ftpState
->state
= Ftp::Client::SENT_MDTM
;
1593 ftpReadMdtm(Ftp::Gateway
* ftpState
)
1595 int code
= ftpState
->ctrl
.replycode
;
1599 ftpState
->mdtm
= parse_iso3307_time(ftpState
->ctrl
.last_reply
);
1601 } else if (code
< 0) {
1606 ftpSendSize(ftpState
);
1610 ftpSendSize(Ftp::Gateway
* ftpState
)
1612 /* check the server control channel is still available */
1613 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendSize"))
1616 /* Only send SIZE for binary transfers. The returned size
1617 * is useless on ASCII transfers */
1619 if (ftpState
->flags
.binary
) {
1620 assert(ftpState
->filepath
!= NULL
);
1621 assert(*ftpState
->filepath
!= '\0');
1622 snprintf(cbuf
, CTRL_BUFLEN
, "SIZE %s\r\n", ftpState
->filepath
);
1623 ftpState
->writeCommand(cbuf
);
1624 ftpState
->state
= Ftp::Client::SENT_SIZE
;
1626 /* Skip to next state no non-binary transfers */
1627 ftpSendPassive(ftpState
);
1631 ftpReadSize(Ftp::Gateway
* ftpState
)
1633 int code
= ftpState
->ctrl
.replycode
;
1638 ftpState
->theSize
= strtoll(ftpState
->ctrl
.last_reply
, NULL
, 10);
1640 if (ftpState
->theSize
== 0) {
1641 debugs(9, 2, "SIZE reported " <<
1642 ftpState
->ctrl
.last_reply
<< " on " <<
1643 ftpState
->title_url
);
1644 ftpState
->theSize
= -1;
1646 } else if (code
< 0) {
1651 ftpSendPassive(ftpState
);
1655 ftpReadEPSV(Ftp::Gateway
* ftpState
)
1657 Ip::Address srvAddr
; // unused
1658 if (ftpState
->handleEpsvReply(srvAddr
)) {
1659 if (ftpState
->ctrl
.message
== NULL
)
1660 return; // didn't get complete reply yet
1662 ftpState
->connectDataChannel();
1666 /** Send Passive connection request.
1667 * Default method is to use modern EPSV request.
1668 * The failover mechanism should check for previous state and re-call with alternates on failure.
1671 ftpSendPassive(Ftp::Gateway
* ftpState
)
1673 /** Checks the server control channel is still available before running. */
1674 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPassive"))
1680 * Checks for 'HEAD' method request and passes off for special handling by Ftp::Gateway::processHeadResponse(). */
1681 if (ftpState
->request
->method
== Http::METHOD_HEAD
&& (ftpState
->flags
.isdir
|| ftpState
->theSize
!= -1)) {
1682 ftpState
->processHeadResponse(); // may call serverComplete
1686 if (ftpState
->sendPassive()) {
1687 // SENT_EPSV_ALL blocks other non-EPSV connections being attempted
1688 if (ftpState
->state
== Ftp::Client::SENT_EPSV_ALL
)
1689 ftpState
->flags
.epsv_all_sent
= true;
1694 Ftp::Gateway::processHeadResponse()
1696 debugs(9, 5, HERE
<< "handling HEAD response");
1698 appendSuccessHeader();
1701 * On rare occasions I'm seeing the entry get aborted after
1702 * readControlReply() and before here, probably when
1703 * trying to write to the client.
1705 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1706 abortAll("entry aborted while processing HEAD");
1711 if (adaptationAccessCheckPending
) {
1712 debugs(9,3, HERE
<< "returning due to adaptationAccessCheckPending");
1717 // processReplyBody calls serverComplete() since there is no body
1722 ftpReadPasv(Ftp::Gateway
* ftpState
)
1724 Ip::Address srvAddr
; // unused
1725 if (ftpState
->handlePasvReply(srvAddr
))
1726 ftpState
->connectDataChannel();
1729 // Currently disabled, does not work correctly:
1730 // ftpSendEPRT(ftpState);
1736 Ftp::Gateway::dataChannelConnected(const CommConnectCbParams
&io
)
1741 if (io
.flag
!= Comm::OK
) {
1742 debugs(9, 2, HERE
<< "Failed to connect. Retrying via another method.");
1744 // ABORT on timeouts. server may be waiting on a broken TCP link.
1745 if (io
.xerrno
== Comm::TIMEOUT
)
1746 writeCommand("ABOR\r\n");
1748 // try another connection attempt with some other method
1749 ftpSendPassive(this);
1753 data
.opened(io
.conn
, dataCloser());
1754 ftpRestOrList(this);
1758 ftpOpenListenSocket(Ftp::Gateway
* ftpState
, int fallback
)
1760 /// Close old data channels, if any. We may open a new one below.
1761 if (ftpState
->data
.conn
!= NULL
) {
1762 if ((ftpState
->data
.conn
->flags
& COMM_REUSEADDR
))
1763 // NP: in fact it points to the control channel. just clear it.
1764 ftpState
->data
.clear();
1766 ftpState
->data
.close();
1768 safe_free(ftpState
->data
.host
);
1770 if (!Comm::IsConnOpen(ftpState
->ctrl
.conn
)) {
1771 debugs(9, 5, "The control connection to the remote end is closed");
1776 * Set up a listen socket on the same local address as the
1777 * control connection.
1779 Comm::ConnectionPointer temp
= new Comm::Connection
;
1780 temp
->local
= ftpState
->ctrl
.conn
->local
;
1783 * REUSEADDR is needed in fallback mode, since the same port is
1784 * used for both control and data.
1789 if (setsockopt(ftpState
->ctrl
.conn
->fd
, SOL_SOCKET
, SO_REUSEADDR
,
1790 (char *) &on
, sizeof(on
)) == -1) {
1792 // SO_REUSEADDR is only an optimization, no need to be verbose about error
1793 debugs(9, 4, "setsockopt failed: " << xstrerr(xerrno
));
1795 ftpState
->ctrl
.conn
->flags
|= COMM_REUSEADDR
;
1796 temp
->flags
|= COMM_REUSEADDR
;
1798 /* if not running in fallback mode a new port needs to be retrieved */
1799 temp
->local
.port(0);
1802 ftpState
->listenForDataChannel(temp
);
1806 ftpSendPORT(Ftp::Gateway
* ftpState
)
1808 /* check the server control channel is still available */
1809 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPort"))
1812 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1813 debugs(9, DBG_IMPORTANT
, "FTP does not allow PORT method after 'EPSV ALL' has been sent.");
1818 ftpState
->flags
.pasv_supported
= 0;
1819 ftpOpenListenSocket(ftpState
, 0);
1821 if (!Comm::IsConnOpen(ftpState
->data
.listenConn
)) {
1822 if ( ftpState
->data
.listenConn
!= NULL
&& !ftpState
->data
.listenConn
->local
.isIPv4() ) {
1823 /* non-IPv4 CANNOT send PORT command. */
1824 /* we got here by attempting and failing an EPRT */
1825 /* using the same reply code should simulate a PORT failure */
1826 ftpReadPORT(ftpState
);
1830 /* XXX Need to set error message */
1835 // pull out the internal IP address bytes to send in PORT command...
1836 // source them from the listen_conn->local
1838 struct addrinfo
*AI
= NULL
;
1839 ftpState
->data
.listenConn
->local
.getAddrInfo(AI
, AF_INET
);
1840 unsigned char *addrptr
= (unsigned char *) &((struct sockaddr_in
*)AI
->ai_addr
)->sin_addr
;
1841 unsigned char *portptr
= (unsigned char *) &((struct sockaddr_in
*)AI
->ai_addr
)->sin_port
;
1842 snprintf(cbuf
, CTRL_BUFLEN
, "PORT %d,%d,%d,%d,%d,%d\r\n",
1843 addrptr
[0], addrptr
[1], addrptr
[2], addrptr
[3],
1844 portptr
[0], portptr
[1]);
1845 ftpState
->writeCommand(cbuf
);
1846 ftpState
->state
= Ftp::Client::SENT_PORT
;
1848 Ip::Address::FreeAddr(AI
);
1852 ftpReadPORT(Ftp::Gateway
* ftpState
)
1854 int code
= ftpState
->ctrl
.replycode
;
1858 /* Fall back on using the same port as the control connection */
1859 debugs(9, 3, "PORT not supported by remote end");
1860 ftpOpenListenSocket(ftpState
, 1);
1863 ftpRestOrList(ftpState
);
1868 ftpSendEPRT(Ftp::Gateway
* ftpState
)
1870 /* check the server control channel is still available */
1871 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendEPRT"))
1874 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1875 debugs(9, DBG_IMPORTANT
, "FTP does not allow EPRT method after 'EPSV ALL' has been sent.");
1879 if (!Config
.Ftp
.eprt
) {
1880 /* Disabled. Switch immediately to attempting old PORT command. */
1881 debugs(9, 3, "EPRT disabled by local administrator");
1882 ftpSendPORT(ftpState
);
1887 ftpState
->flags
.pasv_supported
= 0;
1889 ftpOpenListenSocket(ftpState
, 0);
1890 debugs(9, 3, "Listening for FTP data connection with FD " << ftpState
->data
.conn
);
1891 if (!Comm::IsConnOpen(ftpState
->data
.conn
)) {
1892 /* XXX Need to set error message */
1897 char buf
[MAX_IPSTRLEN
];
1899 /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
1900 /* Which can be used by EITHER protocol. */
1901 snprintf(cbuf
, CTRL_BUFLEN
, "EPRT |%d|%s|%d|\r\n",
1902 ( ftpState
->data
.listenConn
->local
.isIPv6() ? 2 : 1 ),
1903 ftpState
->data
.listenConn
->local
.toStr(buf
,MAX_IPSTRLEN
),
1904 ftpState
->data
.listenConn
->local
.port() );
1906 ftpState
->writeCommand(cbuf
);
1907 ftpState
->state
= Ftp::Client::SENT_EPRT
;
1912 ftpReadEPRT(Ftp::Gateway
* ftpState
)
1914 int code
= ftpState
->ctrl
.replycode
;
1918 /* Failover to attempting old PORT command. */
1919 debugs(9, 3, "EPRT not supported by remote end");
1920 ftpSendPORT(ftpState
);
1924 ftpRestOrList(ftpState
);
1927 /** "read" handler to accept FTP data connections.
1929 \param io comm accept(2) callback parameters
1932 Ftp::Gateway::ftpAcceptDataConnection(const CommAcceptCbParams
&io
)
1936 if (!Comm::IsConnOpen(ctrl
.conn
)) { /*Close handlers will cleanup*/
1937 debugs(9, 5, "The control connection to the remote end is closed");
1941 if (io
.flag
!= Comm::OK
) {
1942 data
.listenConn
->close();
1943 data
.listenConn
= NULL
;
1944 debugs(9, DBG_IMPORTANT
, "FTP AcceptDataConnection: " << io
.conn
<< ": " << xstrerr(io
.xerrno
));
1945 /** \todo Need to send error message on control channel*/
1950 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1951 abortAll("entry aborted when accepting data conn");
1952 data
.listenConn
->close();
1953 data
.listenConn
= NULL
;
1958 /* data listening conn is no longer even open. abort. */
1959 if (!Comm::IsConnOpen(data
.listenConn
)) {
1960 data
.listenConn
= NULL
; // ensure that it's cleared and not just closed.
1964 /* data listening conn is no longer even open. abort. */
1965 if (!Comm::IsConnOpen(data
.conn
)) {
1966 data
.clear(); // ensure that it's cleared and not just closed.
1971 * When squid.conf ftp_sanitycheck is enabled, check the new connection is actually being
1972 * made by the remote client which is connected to the FTP control socket.
1973 * Or the one which we were told to listen for by control channel messages (may differ under NAT).
1974 * This prevents third-party hacks, but also third-party load balancing handshakes.
1976 if (Config
.Ftp
.sanitycheck
) {
1977 // accept if either our data or ctrl connection is talking to this remote peer.
1978 if (data
.conn
->remote
!= io
.conn
->remote
&& ctrl
.conn
->remote
!= io
.conn
->remote
) {
1979 debugs(9, DBG_IMPORTANT
,
1980 "FTP data connection from unexpected server (" <<
1981 io
.conn
->remote
<< "), expecting " <<
1982 data
.conn
->remote
<< " or " << ctrl
.conn
->remote
);
1984 /* close the bad sources connection down ASAP. */
1987 /* drop the bad connection (io) by ignoring the attempt. */
1992 /** On Comm::OK start using the accepted data socket and discard the temporary listen socket. */
1994 data
.opened(io
.conn
, dataCloser());
1995 data
.addr(io
.conn
->remote
);
1997 debugs(9, 3, HERE
<< "Connected data socket on " <<
1998 io
.conn
<< ". FD table says: " <<
1999 "ctrl-peer= " << fd_table
[ctrl
.conn
->fd
].ipaddr
<< ", " <<
2000 "data-peer= " << fd_table
[data
.conn
->fd
].ipaddr
);
2002 assert(haveControlChannel("ftpAcceptDataConnection"));
2003 assert(ctrl
.message
== NULL
);
2005 // Ctrl channel operations will determine what happens to this data connection
2009 ftpRestOrList(Ftp::Gateway
* ftpState
)
2013 if (ftpState
->typecode
== 'D') {
2014 ftpState
->flags
.isdir
= 1;
2016 if (ftpState
->flags
.put
) {
2017 ftpSendMkdir(ftpState
); /* PUT name;type=d */
2019 ftpSendNlst(ftpState
); /* GET name;type=d sec 3.2.2 of RFC 1738 */
2021 } else if (ftpState
->flags
.put
) {
2022 ftpSendStor(ftpState
);
2023 } else if (ftpState
->flags
.isdir
)
2024 ftpSendList(ftpState
);
2025 else if (ftpState
->restartable())
2026 ftpSendRest(ftpState
);
2028 ftpSendRetr(ftpState
);
2032 ftpSendStor(Ftp::Gateway
* ftpState
)
2034 /* check the server control channel is still available */
2035 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendStor"))
2040 if (ftpState
->filepath
!= NULL
) {
2041 /* Plain file upload */
2042 snprintf(cbuf
, CTRL_BUFLEN
, "STOR %s\r\n", ftpState
->filepath
);
2043 ftpState
->writeCommand(cbuf
);
2044 ftpState
->state
= Ftp::Client::SENT_STOR
;
2045 } else if (ftpState
->request
->header
.getInt64(Http::HdrType::CONTENT_LENGTH
) > 0) {
2046 /* File upload without a filename. use STOU to generate one */
2047 snprintf(cbuf
, CTRL_BUFLEN
, "STOU\r\n");
2048 ftpState
->writeCommand(cbuf
);
2049 ftpState
->state
= Ftp::Client::SENT_STOR
;
2051 /* No file to transfer. Only create directories if needed */
2052 ftpSendReply(ftpState
);
2056 /// \deprecated use ftpState->readStor() instead.
2058 ftpReadStor(Ftp::Gateway
* ftpState
)
2060 ftpState
->readStor();
2063 void Ftp::Gateway::readStor()
2065 int code
= ctrl
.replycode
;
2068 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(data
.conn
))) {
2069 if (!originalRequest()->body_pipe
) {
2070 debugs(9, 3, "zero-size STOR?");
2071 state
= WRITING_DATA
; // make ftpWriteTransferDone() responsible
2072 dataComplete(); // XXX: keep in sync with doneSendingRequestBody()
2076 if (!startRequestBodyFlow()) { // register to receive body data
2081 /* When client status is 125, or 150 and the data connection is open, Begin data transfer. */
2082 debugs(9, 3, HERE
<< "starting data transfer");
2083 switchTimeoutToDataChannel();
2084 sendMoreRequestBody();
2085 fwd
->dontRetry(true); // dont permit re-trying if the body was sent.
2086 state
= WRITING_DATA
;
2087 debugs(9, 3, HERE
<< "writing data channel");
2088 } else if (code
== 150) {
2089 /* When client code is 150 with no data channel, Accept data channel. */
2090 debugs(9, 3, "ftpReadStor: accepting data channel");
2091 listenForDataChannel(data
.conn
);
2093 debugs(9, DBG_IMPORTANT
, HERE
<< "Unexpected reply code "<< std::setfill('0') << std::setw(3) << code
);
2099 ftpSendRest(Ftp::Gateway
* ftpState
)
2101 /* check the server control channel is still available */
2102 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRest"))
2107 snprintf(cbuf
, CTRL_BUFLEN
, "REST %" PRId64
"\r\n", ftpState
->restart_offset
);
2108 ftpState
->writeCommand(cbuf
);
2109 ftpState
->state
= Ftp::Client::SENT_REST
;
2113 Ftp::Gateway::restartable()
2115 if (restart_offset
> 0)
2118 if (!request
->range
)
2127 int64_t desired_offset
= request
->range
->lowestOffset(theSize
);
2129 if (desired_offset
<= 0)
2132 if (desired_offset
>= theSize
)
2135 restart_offset
= desired_offset
;
2140 ftpReadRest(Ftp::Gateway
* ftpState
)
2142 int code
= ftpState
->ctrl
.replycode
;
2144 assert(ftpState
->restart_offset
> 0);
2147 ftpState
->setCurrentOffset(ftpState
->restart_offset
);
2148 ftpSendRetr(ftpState
);
2149 } else if (code
> 0) {
2150 debugs(9, 3, HERE
<< "REST not supported");
2151 ftpState
->flags
.rest_supported
= 0;
2152 ftpSendRetr(ftpState
);
2159 ftpSendList(Ftp::Gateway
* ftpState
)
2161 /* check the server control channel is still available */
2162 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendList"))
2167 if (ftpState
->filepath
) {
2168 snprintf(cbuf
, CTRL_BUFLEN
, "LIST %s\r\n", ftpState
->filepath
);
2170 snprintf(cbuf
, CTRL_BUFLEN
, "LIST\r\n");
2173 ftpState
->writeCommand(cbuf
);
2174 ftpState
->state
= Ftp::Client::SENT_LIST
;
2178 ftpSendNlst(Ftp::Gateway
* ftpState
)
2180 /* check the server control channel is still available */
2181 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendNlst"))
2186 ftpState
->flags
.tried_nlst
= 1;
2188 if (ftpState
->filepath
) {
2189 snprintf(cbuf
, CTRL_BUFLEN
, "NLST %s\r\n", ftpState
->filepath
);
2191 snprintf(cbuf
, CTRL_BUFLEN
, "NLST\r\n");
2194 ftpState
->writeCommand(cbuf
);
2195 ftpState
->state
= Ftp::Client::SENT_NLST
;
2199 ftpReadList(Ftp::Gateway
* ftpState
)
2201 int code
= ftpState
->ctrl
.replycode
;
2204 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2205 /* Begin data transfer */
2206 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2207 ftpState
->switchTimeoutToDataChannel();
2208 ftpState
->maybeReadVirginBody();
2209 ftpState
->state
= Ftp::Client::READING_DATA
;
2211 } else if (code
== 150) {
2212 /* Accept data channel */
2213 debugs(9, 3, HERE
<< "accept data channel from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2214 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2216 } else if (!ftpState
->flags
.tried_nlst
&& code
> 300) {
2217 ftpSendNlst(ftpState
);
2225 ftpSendRetr(Ftp::Gateway
* ftpState
)
2227 /* check the server control channel is still available */
2228 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRetr"))
2233 assert(ftpState
->filepath
!= NULL
);
2234 snprintf(cbuf
, CTRL_BUFLEN
, "RETR %s\r\n", ftpState
->filepath
);
2235 ftpState
->writeCommand(cbuf
);
2236 ftpState
->state
= Ftp::Client::SENT_RETR
;
2240 ftpReadRetr(Ftp::Gateway
* ftpState
)
2242 int code
= ftpState
->ctrl
.replycode
;
2245 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2246 /* Begin data transfer */
2247 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2248 ftpState
->switchTimeoutToDataChannel();
2249 ftpState
->maybeReadVirginBody();
2250 ftpState
->state
= Ftp::Client::READING_DATA
;
2251 } else if (code
== 150) {
2252 /* Accept data channel */
2253 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2254 } else if (code
>= 300) {
2255 if (!ftpState
->flags
.try_slash_hack
) {
2256 /* Try this as a directory missing trailing slash... */
2257 ftpState
->hackShortcut(ftpSendCwd
);
2267 * Generate the HTTP headers and template fluff around an FTP
2268 * directory listing display.
2271 Ftp::Gateway::completedListing()
2274 entry
->lock("Ftp::Gateway");
2275 ErrorState
ferr(ERR_DIR_LISTING
, Http::scOkay
, request
);
2276 ferr
.ftp
.listing
= &listing
;
2277 ferr
.ftp
.cwd_msg
= xstrdup(cwd_message
.size()? cwd_message
.termedBuf() : "");
2278 ferr
.ftp
.server_msg
= ctrl
.message
;
2279 ctrl
.message
= NULL
;
2280 entry
->replaceHttpReply( ferr
.BuildHttpReply() );
2281 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2283 entry
->unlock("Ftp::Gateway");
2287 ftpReadTransferDone(Ftp::Gateway
* ftpState
)
2289 int code
= ftpState
->ctrl
.replycode
;
2292 if (code
== 226 || code
== 250) {
2293 /* Connection closed; retrieval done. */
2294 if (ftpState
->flags
.listing
) {
2295 ftpState
->completedListing();
2296 /* QUIT operation handles sending the reply to client */
2298 ftpSendQuit(ftpState
);
2299 } else { /* != 226 */
2300 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after reading data");
2301 ftpState
->failed(ERR_FTP_FAILURE
, 0);
2302 /* failed closes ctrl.conn and frees ftpState */
2307 // premature end of the request body
2309 Ftp::Gateway::handleRequestBodyProducerAborted()
2311 Client::handleRequestBodyProducerAborted();
2312 debugs(9, 3, HERE
<< "ftpState=" << this);
2313 failed(ERR_READ_ERROR
, 0);
2317 ftpWriteTransferDone(Ftp::Gateway
* ftpState
)
2319 int code
= ftpState
->ctrl
.replycode
;
2322 if (!(code
== 226 || code
== 250)) {
2323 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after sending data");
2324 ftpState
->failed(ERR_FTP_PUT_ERROR
, 0);
2328 ftpState
->entry
->timestampsSet(); /* XXX Is this needed? */
2329 ftpSendReply(ftpState
);
2333 ftpSendQuit(Ftp::Gateway
* ftpState
)
2335 /* check the server control channel is still available */
2336 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendQuit"))
2339 snprintf(cbuf
, CTRL_BUFLEN
, "QUIT\r\n");
2340 ftpState
->writeCommand(cbuf
);
2341 ftpState
->state
= Ftp::Client::SENT_QUIT
;
2344 /** Completes a client FTP operation with success or other page
2345 * generated and stored in the entry field by the code issuing QUIT.
2348 ftpReadQuit(Ftp::Gateway
* ftpState
)
2350 ftpState
->serverComplete();
2354 ftpTrySlashHack(Ftp::Gateway
* ftpState
)
2357 ftpState
->flags
.try_slash_hack
= 1;
2358 /* Free old paths */
2362 if (ftpState
->pathcomps
)
2363 wordlistDestroy(&ftpState
->pathcomps
);
2365 safe_free(ftpState
->filepath
);
2367 /* Build the new path (urlpath begins with /) */
2368 path
= SBufToCstring(ftpState
->request
->url
.path());
2370 rfc1738_unescape(path
);
2372 ftpState
->filepath
= path
;
2375 ftpGetFile(ftpState
);
2379 * Forget hack status. Next error is shown to the user
2382 Ftp::Gateway::unhack()
2386 if (old_request
!= NULL
) {
2387 safe_free(old_request
);
2388 safe_free(old_reply
);
2393 Ftp::Gateway::hackShortcut(FTPSM
* nextState
)
2395 /* Clear some unwanted state */
2396 setCurrentOffset(0);
2398 /* Save old error message & some state info */
2402 if (old_request
== NULL
) {
2403 old_request
= ctrl
.last_command
;
2404 ctrl
.last_command
= NULL
;
2405 old_reply
= ctrl
.last_reply
;
2406 ctrl
.last_reply
= NULL
;
2408 if (pathcomps
== NULL
&& filepath
!= NULL
)
2409 old_filepath
= xstrdup(filepath
);
2412 /* Jump to the "hack" state */
2417 ftpFail(Ftp::Gateway
*ftpState
)
2419 const bool slashHack
= ftpState
->request
->url
.path().caseCmp("/%2f", 4)==0;
2420 int code
= ftpState
->ctrl
.replycode
;
2421 err_type error_code
= ERR_NONE
;
2423 debugs(9, 6, "state " << ftpState
->state
<<
2424 " reply code " << code
<< "flags(" <<
2425 (ftpState
->flags
.isdir
?"IS_DIR,":"") <<
2426 (ftpState
->flags
.try_slash_hack
?"TRY_SLASH_HACK":"") << "), " <<
2427 "mdtm=" << ftpState
->mdtm
<< ", size=" << ftpState
->theSize
<<
2428 "slashhack=" << (slashHack
? "T":"F"));
2430 /* Try the / hack to support "Netscape" FTP URL's for retreiving files */
2431 if (!ftpState
->flags
.isdir
&& /* Not a directory */
2432 !ftpState
->flags
.try_slash_hack
&& !slashHack
&& /* Not doing slash hack */
2433 ftpState
->mdtm
<= 0 && ftpState
->theSize
< 0) { /* Not known as a file */
2435 switch (ftpState
->state
) {
2437 case Ftp::Client::SENT_CWD
:
2439 case Ftp::Client::SENT_RETR
:
2440 /* Try the / hack */
2441 ftpState
->hackShortcut(ftpTrySlashHack
);
2449 Http::StatusCode sc
= ftpState
->failedHttpStatus(error_code
);
2450 ErrorState
*ftperr
= new ErrorState(error_code
, sc
, ftpState
->fwd
->request
);
2451 ftpState
->failed(error_code
, code
, ftperr
);
2452 ftperr
->detailError(code
);
2453 HttpReply
*newrep
= ftperr
->BuildHttpReply();
2456 ftpState
->entry
->replaceHttpReply(newrep
);
2457 ftpSendQuit(ftpState
);
2461 Ftp::Gateway::failedHttpStatus(err_type
&error
)
2463 if (error
== ERR_NONE
) {
2470 if (ctrl
.replycode
> 500) {
2471 error
= ERR_FTP_FORBIDDEN
;
2472 return password_url
? Http::scForbidden
: Http::scUnauthorized
;
2473 } else if (ctrl
.replycode
== 421) {
2474 error
= ERR_FTP_UNAVAILABLE
;
2475 return Http::scServiceUnavailable
;
2482 if (ctrl
.replycode
== 550) {
2483 error
= ERR_FTP_NOT_FOUND
;
2484 return Http::scNotFound
;
2492 return Ftp::Client::failedHttpStatus(error
);
2496 ftpSendReply(Ftp::Gateway
* ftpState
)
2498 int code
= ftpState
->ctrl
.replycode
;
2499 Http::StatusCode http_code
;
2500 err_type err_code
= ERR_NONE
;
2502 debugs(9, 3, HERE
<< ftpState
->entry
->url() << ", code " << code
);
2504 if (cbdataReferenceValid(ftpState
))
2505 debugs(9, 5, HERE
<< "ftpState (" << ftpState
<< ") is valid!");
2507 if (code
== 226 || code
== 250) {
2508 err_code
= (ftpState
->mdtm
> 0) ? ERR_FTP_PUT_MODIFIED
: ERR_FTP_PUT_CREATED
;
2509 http_code
= (ftpState
->mdtm
> 0) ? Http::scAccepted
: Http::scCreated
;
2510 } else if (code
== 227) {
2511 err_code
= ERR_FTP_PUT_CREATED
;
2512 http_code
= Http::scCreated
;
2514 err_code
= ERR_FTP_PUT_ERROR
;
2515 http_code
= Http::scInternalServerError
;
2518 ErrorState
err(err_code
, http_code
, ftpState
->request
);
2520 if (ftpState
->old_request
)
2521 err
.ftp
.request
= xstrdup(ftpState
->old_request
);
2523 err
.ftp
.request
= xstrdup(ftpState
->ctrl
.last_command
);
2525 if (ftpState
->old_reply
)
2526 err
.ftp
.reply
= xstrdup(ftpState
->old_reply
);
2527 else if (ftpState
->ctrl
.last_reply
)
2528 err
.ftp
.reply
= xstrdup(ftpState
->ctrl
.last_reply
);
2530 err
.ftp
.reply
= xstrdup("");
2532 // TODO: interpret as FTP-specific error code
2533 err
.detailError(code
);
2535 ftpState
->entry
->replaceHttpReply( err
.BuildHttpReply() );
2537 ftpSendQuit(ftpState
);
2541 Ftp::Gateway::appendSuccessHeader()
2545 if (flags
.http_header_sent
)
2548 HttpReply
*reply
= new HttpReply
;
2550 flags
.http_header_sent
= 1;
2552 assert(entry
->isEmpty());
2554 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2556 entry
->buffer(); /* released when done processing current data payload */
2558 SBuf urlPath
= request
->url
.path();
2559 auto t
= urlPath
.rfind('/');
2560 SBuf filename
= urlPath
.substr(t
!= SBuf::npos
? t
: 0);
2562 const char *mime_type
= NULL
;
2563 const char *mime_enc
= NULL
;
2566 mime_type
= "text/html";
2571 mime_type
= "application/octet-stream";
2572 // XXX: performance regression, c_str() may reallocate
2573 mime_enc
= mimeGetContentEncoding(filename
.c_str());
2577 mime_type
= "text/plain";
2581 // XXX: performance regression, c_str() may reallocate
2582 mime_type
= mimeGetContentType(filename
.c_str());
2583 mime_enc
= mimeGetContentEncoding(filename
.c_str());
2588 /* set standard stuff */
2590 if (0 == getCurrentOffset()) {
2592 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2593 } else if (theSize
< getCurrentOffset()) {
2596 * offset should not be larger than theSize. We should
2597 * not be seeing this condition any more because we'll only
2598 * send REST if we know the theSize and if it is less than theSize.
2600 debugs(0,DBG_CRITICAL
,HERE
<< "Whoops! " <<
2601 " current offset=" << getCurrentOffset() <<
2602 ", but theSize=" << theSize
<<
2603 ". assuming full content response");
2604 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2607 HttpHdrRangeSpec range_spec
;
2608 range_spec
.offset
= getCurrentOffset();
2609 range_spec
.length
= theSize
- getCurrentOffset();
2610 reply
->setHeaders(Http::scPartialContent
, "Gatewaying", mime_type
, theSize
- getCurrentOffset(), mdtm
, -2);
2611 httpHeaderAddContRange(&reply
->header
, range_spec
, theSize
);
2614 /* additional info */
2616 reply
->header
.putStr(Http::HdrType::CONTENT_ENCODING
, mime_enc
);
2618 reply
->sources
|= Http::Message::srcFtp
;
2619 setVirginReply(reply
);
2620 adaptOrFinalizeReply();
2624 Ftp::Gateway::haveParsedReplyHeaders()
2626 Client::haveParsedReplyHeaders();
2628 StoreEntry
*e
= entry
;
2632 if (flags
.authenticated
) {
2634 * Authenticated requests can't be cached.
2637 } else if (!EBIT_TEST(e
->flags
, RELEASE_REQUEST
) && !getCurrentOffset()) {
2645 Ftp::Gateway::ftpAuthRequired(HttpRequest
* request
, const char *realm
)
2647 ErrorState
err(ERR_CACHE_ACCESS_DENIED
, Http::scUnauthorized
, request
);
2648 HttpReply
*newrep
= err
.BuildHttpReply();
2649 #if HAVE_AUTH_MODULE_BASIC
2650 /* add Authenticate header */
2651 newrep
->header
.putAuth("Basic", realm
);
2657 Ftp::UrlWith2f(HttpRequest
* request
)
2661 if (request
->url
.getScheme() != AnyP::PROTO_FTP
) {
2662 static const SBuf nil
;
2666 if (request
->url
.path()[0] == '/') {
2667 newbuf
.append(request
->url
.path());
2668 request
->url
.path(newbuf
);
2669 } else if (!request
->url
.path().startsWith(newbuf
)) {
2670 newbuf
.append(request
->url
.path().substr(1));
2671 request
->url
.path(newbuf
);
2674 return request
->effectiveRequestUri();
2678 Ftp::Gateway::printfReplyBody(const char *fmt
, ...)
2681 va_start (args
, fmt
);
2682 static char buf
[4096];
2684 vsnprintf(buf
, 4096, fmt
, args
);
2685 writeReplyBody(buf
, strlen(buf
));
2690 * Call this when there is data from the origin server
2691 * which should be sent to either StoreEntry, or to ICAP...
2694 Ftp::Gateway::writeReplyBody(const char *dataToWrite
, size_t dataLength
)
2696 debugs(9, 5, HERE
<< "writing " << dataLength
<< " bytes to the reply");
2697 addVirginReplyBody(dataToWrite
, dataLength
);
2701 * A hack to ensure we do not double-complete on the forward entry.
2703 \todo Ftp::Gateway logic should probably be rewritten to avoid
2704 * double-completion or FwdState should be rewritten to allow it.
2707 Ftp::Gateway::completeForwarding()
2709 if (fwd
== NULL
|| flags
.completed_forwarding
) {
2710 debugs(9, 3, "avoid double-complete on FD " <<
2711 (ctrl
.conn
? ctrl
.conn
->fd
: -1) << ", Data FD " << data
.conn
->fd
<<
2712 ", this " << this << ", fwd " << fwd
);
2716 flags
.completed_forwarding
= true;
2717 Client::completeForwarding();
2721 * Have we lost the FTP server control channel?
2723 \retval true The server control channel is available.
2724 \retval false The server control channel is not available.
2727 Ftp::Gateway::haveControlChannel(const char *caller_name
) const
2729 if (doneWithServer())
2732 /* doneWithServer() only checks BOTH channels are closed. */
2733 if (!Comm::IsConnOpen(ctrl
.conn
)) {
2734 debugs(9, DBG_IMPORTANT
, "WARNING! FTP Server Control channel is closed, but Data channel still active.");
2735 debugs(9, 2, caller_name
<< ": attempted on a closed FTP channel.");
2743 Ftp::Gateway::mayReadVirginReplyBody() const
2745 // TODO: Can we do what Ftp::Relay::mayReadVirginReplyBody() does instead?
2746 return !doneWithServer();
2750 Ftp::StartGateway(FwdState
*const fwdState
)
2752 return AsyncJob::Start(new Ftp::Gateway(fwdState
));