2 * Copyright (C) 1996-2015 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"
30 #include "HttpRequest.h"
35 #include "SquidConfig.h"
36 #include "SquidString.h"
37 #include "SquidTime.h"
38 #include "StatCounters.h"
46 #include "DelayPools.h"
47 #include "MemObject.h"
58 bool pasv_supported
; ///< PASV command is allowed
59 bool epsv_all_sent
; ///< EPSV ALL has been used. Must abort on failures.
61 bool pasv_failed
; // was FwdState::flags.ftp_pasv_failed
64 bool authenticated
; ///< authentication success
65 bool tried_auth_anonymous
; ///< auth has tried to use anonymous credentials already.
66 bool tried_auth_nopass
; ///< auth tried username with no password already.
72 bool http_header_sent
;
82 bool listformat_unknown
;
84 bool completed_forwarding
;
88 typedef void (StateMethod
)(Ftp::Gateway
*);
90 /// FTP Gateway: An FTP client that takes an HTTP request with an ftp:// URI,
91 /// converts it into one or more FTP commands, and then
92 /// converts one or more FTP responses into the final HTTP response.
93 class Gateway
: public Ftp::Client
95 CBDATA_CLASS(Gateway
);
101 char password
[MAX_URL
];
115 int64_t restart_offset
;
121 MemBuf listing
; ///< FTP directory listing in HTML format.
126 // these should all be private
127 virtual void start();
128 virtual Http::StatusCode
failedHttpStatus(err_type
&error
);
130 void appendSuccessHeader();
131 void hackShortcut(StateMethod
*nextState
);
135 MemBuf
*htmlifyListEntry(const char *line
);
136 void completedListing(void);
138 /// create a data channel acceptor and start listening.
139 void listenForDataChannel(const Comm::ConnectionPointer
&conn
);
141 int checkAuth(const HttpHeader
* req_hdr
);
143 void buildTitleUrl();
144 void writeReplyBody(const char *, size_t len
);
145 void printfReplyBody(const char *fmt
, ...);
146 virtual void completeForwarding();
147 void processHeadResponse();
148 void processReplyBody();
149 void setCurrentOffset(int64_t offset
) { currentOffset
= offset
; }
150 int64_t getCurrentOffset() const { return currentOffset
; }
152 virtual void dataChannelConnected(const CommConnectCbParams
&io
);
153 static PF ftpDataWrite
;
154 virtual void timeout(const CommTimeoutCbParams
&io
);
155 void ftpAcceptDataConnection(const CommAcceptCbParams
&io
);
157 static HttpReply
*ftpAuthRequired(HttpRequest
* request
, const char *realm
);
158 const char *ftpRealm(void);
159 void loginFailed(void);
161 virtual void haveParsedReplyHeaders();
163 virtual bool haveControlChannel(const char *caller_name
) const;
166 virtual void handleControlReply();
167 virtual void dataClosed(const CommCloseCbParams
&io
);
170 virtual bool mayReadVirginReplyBody() const;
171 // BodyConsumer for HTTP: consume request body.
172 virtual void handleRequestBodyProducerAborted();
174 void loginParser(const SBuf
&login
, bool escaped
);
179 typedef Ftp::StateMethod FTPSM
; // to avoid lots of non-changes
181 CBDATA_NAMESPACED_CLASS_INIT(Ftp
, Gateway
);
192 #define CTRL_BUFLEN 1024
193 static char cbuf
[CTRL_BUFLEN
];
196 * State machine functions
197 * send == state transition
198 * read == wait for response, and select next state transition
199 * other == Transition logic
201 static FTPSM ftpReadWelcome
;
202 static FTPSM ftpSendUser
;
203 static FTPSM ftpReadUser
;
204 static FTPSM ftpSendPass
;
205 static FTPSM ftpReadPass
;
206 static FTPSM ftpSendType
;
207 static FTPSM ftpReadType
;
208 static FTPSM ftpSendMdtm
;
209 static FTPSM ftpReadMdtm
;
210 static FTPSM ftpSendSize
;
211 static FTPSM ftpReadSize
;
212 static FTPSM ftpSendEPRT
;
213 static FTPSM ftpReadEPRT
;
214 static FTPSM ftpSendPORT
;
215 static FTPSM ftpReadPORT
;
216 static FTPSM ftpSendPassive
;
217 static FTPSM ftpReadEPSV
;
218 static FTPSM ftpReadPasv
;
219 static FTPSM ftpTraverseDirectory
;
220 static FTPSM ftpListDir
;
221 static FTPSM ftpGetFile
;
222 static FTPSM ftpSendCwd
;
223 static FTPSM ftpReadCwd
;
224 static FTPSM ftpRestOrList
;
225 static FTPSM ftpSendList
;
226 static FTPSM ftpSendNlst
;
227 static FTPSM ftpReadList
;
228 static FTPSM ftpSendRest
;
229 static FTPSM ftpReadRest
;
230 static FTPSM ftpSendRetr
;
231 static FTPSM ftpReadRetr
;
232 static FTPSM ftpReadTransferDone
;
233 static FTPSM ftpSendStor
;
234 static FTPSM ftpReadStor
;
235 static FTPSM ftpWriteTransferDone
;
236 static FTPSM ftpSendReply
;
237 static FTPSM ftpSendMkdir
;
238 static FTPSM ftpReadMkdir
;
239 static FTPSM ftpFail
;
240 static FTPSM ftpSendQuit
;
241 static FTPSM ftpReadQuit
;
243 /************************************************
244 ** Debugs Levels used here **
245 *************************************************
248 Protocol and Transmission failures.
249 2 FTP Protocol Chatter
254 ************************************************/
256 /************************************************
257 ** State Machine Description (excluding hacks) **
258 *************************************************
260 ---------------------------------------
264 Type TraverseDirectory / GetFile
265 TraverseDirectory Cwd / GetFile / ListDir
266 Cwd TraverseDirectory / Mkdir
272 FileOrList Rest / Retr / Nlst / List / Mkdir (PUT /xxx;type=d)
274 Retr / Nlst / List DataRead* (on datachannel)
275 DataRead* ReadTransferDone
276 ReadTransferDone DataTransferDone
277 Stor DataWrite* (on datachannel)
278 DataWrite* RequestPutBody** (from client)
279 RequestPutBody** DataWrite* / WriteTransferDone
280 WriteTransferDone DataTransferDone
281 DataTransferDone Quit
283 ************************************************/
285 FTPSM
*FTP_SM_FUNCS
[] = {
286 ftpReadWelcome
, /* BEGIN */
287 ftpReadUser
, /* SENT_USER */
288 ftpReadPass
, /* SENT_PASS */
289 ftpReadType
, /* SENT_TYPE */
290 ftpReadMdtm
, /* SENT_MDTM */
291 ftpReadSize
, /* SENT_SIZE */
292 ftpReadEPRT
, /* SENT_EPRT */
293 ftpReadPORT
, /* SENT_PORT */
294 ftpReadEPSV
, /* SENT_EPSV_ALL */
295 ftpReadEPSV
, /* SENT_EPSV_1 */
296 ftpReadEPSV
, /* SENT_EPSV_2 */
297 ftpReadPasv
, /* SENT_PASV */
298 ftpReadCwd
, /* SENT_CWD */
299 ftpReadList
, /* SENT_LIST */
300 ftpReadList
, /* SENT_NLST */
301 ftpReadRest
, /* SENT_REST */
302 ftpReadRetr
, /* SENT_RETR */
303 ftpReadStor
, /* SENT_STOR */
304 ftpReadQuit
, /* SENT_QUIT */
305 ftpReadTransferDone
, /* READING_DATA (RETR,LIST,NLST) */
306 ftpWriteTransferDone
, /* WRITING_DATA (STOR) */
307 ftpReadMkdir
, /* SENT_MKDIR */
308 NULL
, /* SENT_FEAT */
311 NULL
, /* SENT_DATA_REQUEST */
312 NULL
/* SENT_COMMAND */
315 /// handler called by Comm when FTP data channel is closed unexpectedly
317 Ftp::Gateway::dataClosed(const CommCloseCbParams
&io
)
319 Ftp::Client::dataClosed(io
);
320 failed(ERR_FTP_FAILURE
, 0);
321 /* failed closes ctrl.conn and frees ftpState */
323 /* NP: failure recovery may be possible when its only a data.conn failure.
324 * if the ctrl.conn is still fine, we can send ABOR down it and retry.
325 * Just need to watch out for wider Squid states like shutting down or reconfigure.
329 Ftp::Gateway::Gateway(FwdState
*fwdState
):
330 AsyncJob("FtpStateData"),
331 Ftp::Client(fwdState
),
348 debugs(9, 3, entry
->url());
352 memset(&flags
, 0, sizeof(flags
));
354 if (Config
.Ftp
.passive
&& !flags
.pasv_failed
)
355 flags
.pasv_supported
= 1;
357 flags
.rest_supported
= 1;
359 if (request
->method
== Http::METHOD_PUT
)
365 Ftp::Gateway::~Gateway()
367 debugs(9, 3, entry
->url());
369 if (Comm::IsConnOpen(ctrl
.conn
)) {
370 debugs(9, DBG_IMPORTANT
, "Internal bug: FTP Gateway left open " <<
371 "control channel " << ctrl
.conn
);
375 memFree(reply_hdr
, MEM_8K_BUF
);
380 wordlistDestroy(&pathcomps
);
391 * Parse a possible login username:password pair.
392 * Produces filled member variables user, password, password_url if anything found.
394 * \param login a decoded Basic authentication credential token or URI user-info token
395 * \param escaped whether to URL-decode the token after extracting user and password
398 Ftp::Gateway::loginParser(const SBuf
&login
, bool escaped
)
400 debugs(9, 4, "login=" << login
<< ", escaped=" << escaped
);
401 debugs(9, 9, "IN : login=" << login
<< ", escaped=" << escaped
<< ", user=" << user
<< ", password=" << password
);
406 const SBuf::size_type colonPos
= login
.find(':');
408 /* If there was a username part with at least one character use it.
409 * Ignore 0-length username portion, retain what we have already.
411 if (colonPos
== SBuf::npos
|| colonPos
> 0) {
412 const SBuf userName
= login
.substr(0, colonPos
);
413 SBuf::size_type upto
= userName
.copy(user
, sizeof(user
)-1);
415 debugs(9, 9, "found user=" << userName
<< ' ' <<
416 (upto
!= userName
.length() ? ", truncated-to=" : ", length=") << upto
<<
417 ", escaped=" << escaped
);
419 rfc1738_unescape(user
);
420 debugs(9, 9, "found user=" << user
<< " (" << strlen(user
) << ") unescaped.");
423 /* If there was a password part.
424 * For 0-length password clobber what we have already, this means explicitly none
426 if (colonPos
!= SBuf::npos
) {
427 const SBuf pass
= login
.substr(colonPos
+1, SBuf::npos
);
428 SBuf::size_type upto
= pass
.copy(password
, sizeof(password
)-1);
430 debugs(9, 9, "found password=" << pass
<< " " <<
431 (upto
!= pass
.length() ? ", truncated-to=" : ", length=") << upto
<<
432 ", escaped=" << escaped
);
434 rfc1738_unescape(password
);
437 debugs(9, 9, "found password=" << password
<< " (" << strlen(password
) << ") unescaped.");
440 debugs(9, 9, "OUT: login=" << login
<< ", escaped=" << escaped
<< ", user=" << user
<< ", password=" << password
);
444 Ftp::Gateway::listenForDataChannel(const Comm::ConnectionPointer
&conn
)
446 assert(!Comm::IsConnOpen(data
.conn
));
448 typedef CommCbMemFunT
<Gateway
, CommAcceptCbParams
> AcceptDialer
;
449 typedef AsyncCallT
<AcceptDialer
> AcceptCall
;
450 RefCount
<AcceptCall
> call
= static_cast<AcceptCall
*>(JobCallback(11, 5, AcceptDialer
, this, Ftp::Gateway::ftpAcceptDataConnection
));
451 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(call
);
452 const char *note
= entry
->url();
454 /* open the conn if its not already open */
455 if (!Comm::IsConnOpen(conn
)) {
456 conn
->fd
= comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
->local
, conn
->flags
, note
);
457 if (!Comm::IsConnOpen(conn
)) {
458 debugs(5, DBG_CRITICAL
, HERE
<< "comm_open_listener failed:" << conn
->local
<< " error: " << errno
);
461 debugs(9, 3, HERE
<< "Unconnected data socket created on " << conn
);
464 conn
->tos
= ctrl
.conn
->tos
;
465 conn
->nfmark
= ctrl
.conn
->nfmark
;
467 assert(Comm::IsConnOpen(conn
));
468 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
470 // Ensure we have a copy of the FD opened for listening and a close handler on it.
471 data
.opened(conn
, dataCloser());
472 switchTimeoutToDataChannel();
476 Ftp::Gateway::timeout(const CommTimeoutCbParams
&io
)
478 if (SENT_PASV
== state
) {
479 /* stupid ftp.netscape.com, of FTP server behind stupid firewall rules */
480 flags
.pasv_supported
= false;
481 debugs(9, DBG_IMPORTANT
, "FTP Gateway timeout in SENT_PASV state");
483 // cancel the data connection setup.
484 if (data
.opener
!= NULL
) {
485 data
.opener
->cancel("timeout");
491 Ftp::Client::timeout(io
);
494 static const char *Month
[] = {
495 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
496 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
500 is_month(const char *buf
)
504 for (i
= 0; i
< 12; ++i
)
505 if (!strcasecmp(buf
, Month
[i
]))
512 ftpListPartsFree(ftpListParts
** parts
)
514 safe_free((*parts
)->date
);
515 safe_free((*parts
)->name
);
516 safe_free((*parts
)->showname
);
517 safe_free((*parts
)->link
);
521 #define MAX_TOKENS 64
523 static ftpListParts
*
524 ftpListParseParts(const char *buf
, struct Ftp::GatewayFlags flags
)
526 ftpListParts
*p
= NULL
;
528 const char *ct
= NULL
;
529 char *tokens
[MAX_TOKENS
];
532 static char tbuf
[128];
534 static int scan_ftp_initialized
= 0;
535 static regex_t scan_ftp_integer
;
536 static regex_t scan_ftp_time
;
537 static regex_t scan_ftp_dostime
;
538 static regex_t scan_ftp_dosdate
;
540 if (!scan_ftp_initialized
) {
541 scan_ftp_initialized
= 1;
542 regcomp(&scan_ftp_integer
, "^[0123456789]+$", REG_EXTENDED
| REG_NOSUB
);
543 regcomp(&scan_ftp_time
, "^[0123456789:]+$", REG_EXTENDED
| REG_NOSUB
);
544 regcomp(&scan_ftp_dosdate
, "^[0123456789]+-[0123456789]+-[0123456789]+$", REG_EXTENDED
| REG_NOSUB
);
545 regcomp(&scan_ftp_dostime
, "^[0123456789]+:[0123456789]+[AP]M$", REG_EXTENDED
| REG_NOSUB
| REG_ICASE
);
554 p
= (ftpListParts
*)xcalloc(1, sizeof(ftpListParts
));
558 memset(tokens
, 0, sizeof(tokens
));
562 if (flags
.tried_nlst
) {
563 /* Machine readable format, one name per line */
569 for (t
= strtok(xbuf
, w_space
); t
&& n_tokens
< MAX_TOKENS
; t
= strtok(NULL
, w_space
)) {
570 tokens
[n_tokens
] = xstrdup(t
);
576 /* locate the Month field */
577 for (i
= 3; i
< n_tokens
- 2; ++i
) {
578 char *size
= tokens
[i
- 1];
579 char *month
= tokens
[i
];
580 char *day
= tokens
[i
+ 1];
581 char *year
= tokens
[i
+ 2];
583 if (!is_month(month
))
586 if (regexec(&scan_ftp_integer
, size
, 0, NULL
, 0) != 0)
589 if (regexec(&scan_ftp_integer
, day
, 0, NULL
, 0) != 0)
592 if (regexec(&scan_ftp_time
, year
, 0, NULL
, 0) != 0) /* Yr | hh:mm */
595 snprintf(tbuf
, 128, "%s %2s %5s",
598 if (!strstr(buf
, tbuf
))
599 snprintf(tbuf
, 128, "%s %2s %-5s",
602 char const *copyFrom
= NULL
;
604 if ((copyFrom
= strstr(buf
, tbuf
))) {
605 p
->type
= *tokens
[0];
606 p
->size
= strtoll(size
, NULL
, 10);
607 p
->date
= xstrdup(tbuf
);
609 if (flags
.skip_whitespace
) {
610 copyFrom
+= strlen(tbuf
);
612 while (strchr(w_space
, *copyFrom
))
615 /* XXX assumes a single space between date and filename
616 * suggested by: Nathan.Bailey@cc.monash.edu.au and
617 * Mike Battersby <mike@starbug.bofh.asn.au> */
618 copyFrom
+= strlen(tbuf
) + 1;
621 p
->name
= xstrdup(copyFrom
);
623 if (p
->type
== 'l' && (t
= strstr(p
->name
, " -> "))) {
625 p
->link
= xstrdup(t
+ 4);
634 /* try it as a DOS listing, 04-05-70 09:33PM ... */
636 regexec(&scan_ftp_dosdate
, tokens
[0], 0, NULL
, 0) == 0 &&
637 regexec(&scan_ftp_dostime
, tokens
[1], 0, NULL
, 0) == 0) {
638 if (!strcasecmp(tokens
[2], "<dir>")) {
642 p
->size
= strtoll(tokens
[2], NULL
, 10);
645 snprintf(tbuf
, 128, "%s %s", tokens
[0], tokens
[1]);
646 p
->date
= xstrdup(tbuf
);
648 if (p
->type
== 'd') {
649 /* Directory.. name begins with first printable after <dir> */
650 ct
= strstr(buf
, tokens
[2]);
651 ct
+= strlen(tokens
[2]);
653 while (xisspace(*ct
))
659 /* A file. Name begins after size, with a space in between */
660 snprintf(tbuf
, 128, " %s %s", tokens
[2], tokens
[3]);
661 ct
= strstr(buf
, tbuf
);
664 ct
+= strlen(tokens
[2]) + 2;
668 p
->name
= xstrdup(ct
? ct
: tokens
[3]);
672 /* Try EPLF format; carson@lehman.com */
679 int l
= strcspn(ct
, ",");
688 p
->name
= xstrndup(ct
+ 1, l
+ 1);
692 p
->size
= atoi(ct
+ 1);
696 tm
= (time_t) strtol(ct
+ 1, &tmp
, 0);
699 break; /* not a valid integer */
701 p
->date
= xstrdup(ctime(&tm
));
703 *(strstr(p
->date
, "\n")) = '\0';
725 ct
= strstr(ct
, ",");
744 for (i
= 0; i
< n_tokens
; ++i
)
748 ftpListPartsFree(&p
); /* cleanup */
754 Ftp::Gateway::htmlifyListEntry(const char *line
)
757 char href
[2048 + 40];
760 char chdir
[ 2048 + 40];
761 char view
[ 2048 + 40];
762 char download
[ 2048 + 40];
763 char link
[ 2048 + 40];
767 *icon
= *href
= *text
= *size
= *chdir
= *view
= *download
= *link
= '\0';
769 debugs(9, 7, HERE
<< " line ={" << line
<< "}");
771 if (strlen(line
) > 1024) {
774 html
->appendf("<tr><td colspan=\"5\">%s</td></tr>\n", line
);
778 if (flags
.dir_slash
&& dirpath
&& typecode
!= 'D')
779 snprintf(prefix
, 2048, "%s/", rfc1738_escape_part(dirpath
));
783 if ((parts
= ftpListParseParts(line
, flags
)) == NULL
) {
788 html
->appendf("<tr class=\"entry\"><td colspan=\"5\">%s</td></tr>\n", line
);
790 for (p
= line
; *p
&& xisspace(*p
); ++p
);
791 if (*p
&& !xisspace(*p
))
792 flags
.listformat_unknown
= 1;
797 if (!strcmp(parts
->name
, ".") || !strcmp(parts
->name
, "..")) {
798 ftpListPartsFree(&parts
);
804 parts
->showname
= xstrdup(parts
->name
);
806 /* {icon} {text} . . . {date}{size}{chdir}{view}{download}{link}\n */
807 xstrncpy(href
, rfc1738_escape_part(parts
->name
), 2048);
809 xstrncpy(text
, parts
->showname
, 2048);
811 switch (parts
->type
) {
814 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
815 mimeGetIconURL("internal-dir"),
817 strcat(href
, "/"); /* margin is allocated above */
821 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
822 mimeGetIconURL("internal-link"),
824 /* sometimes there is an 'l' flag, but no "->" link */
827 char *link2
= xstrdup(html_quote(rfc1738_escape(parts
->link
)));
828 snprintf(link
, 2048, " -> <a href=\"%s%s\">%s</a>",
829 *link2
!= '/' ? prefix
: "", link2
,
830 html_quote(parts
->link
));
837 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
838 mimeGetIconURL(parts
->name
),
840 snprintf(chdir
, 2048, "<a href=\"%s/;type=d\"><img border=\"0\" src=\"%s\" "
841 "alt=\"[DIR]\"></a>",
842 rfc1738_escape_part(parts
->name
),
843 mimeGetIconURL("internal-dir"));
849 snprintf(icon
, 2048, "<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
850 mimeGetIconURL(parts
->name
),
852 snprintf(size
, 2048, " %6" PRId64
"k", parts
->size
);
856 if (parts
->type
!= 'd') {
857 if (mimeGetViewOption(parts
->name
)) {
858 snprintf(view
, 2048, "<a href=\"%s%s;type=a\"><img border=\"0\" src=\"%s\" "
859 "alt=\"[VIEW]\"></a>",
860 prefix
, href
, mimeGetIconURL("internal-view"));
863 if (mimeGetDownloadOption(parts
->name
)) {
864 snprintf(download
, 2048, "<a href=\"%s%s;type=i\"><img border=\"0\" src=\"%s\" "
865 "alt=\"[DOWNLOAD]\"></a>",
866 prefix
, href
, mimeGetIconURL("internal-download"));
870 /* construct the table row from parts. */
873 html
->appendf("<tr class=\"entry\">"
874 "<td class=\"icon\"><a href=\"%s%s\">%s</a></td>"
875 "<td class=\"filename\"><a href=\"%s%s\">%s</a></td>"
876 "<td class=\"date\">%s</td>"
877 "<td class=\"size\">%s</td>"
878 "<td class=\"actions\">%s%s%s%s</td>"
881 prefix
, href
, html_quote(text
),
884 chdir
, view
, download
, link
);
886 ftpListPartsFree(&parts
);
891 Ftp::Gateway::parseListing()
893 char *buf
= data
.readBuf
->content();
894 char *sbuf
; /* NULL-terminated copy of termedBuf */
901 size_t len
= data
.readBuf
->contentSize();
904 debugs(9, 3, HERE
<< "no content to parse for " << entry
->url() );
909 * We need a NULL-terminated buffer for scanning, ick
911 sbuf
= (char *)xmalloc(len
+ 1);
912 xstrncpy(sbuf
, buf
, len
+ 1);
913 end
= sbuf
+ len
- 1;
915 while (*end
!= '\r' && *end
!= '\n' && end
> sbuf
)
920 debugs(9, 3, HERE
<< "usable = " << usable
<< " of " << len
<< " bytes.");
923 if (buf
[0] == '\0' && len
== 1) {
924 debugs(9, 3, HERE
<< "NIL ends data from " << entry
->url() << " transfer problem?");
925 data
.readBuf
->consume(len
);
927 debugs(9, 3, HERE
<< "didn't find end for " << entry
->url());
928 debugs(9, 3, HERE
<< "buffer remains (" << len
<< " bytes) '" << rfc1738_do_escape(buf
,0) << "'");
934 debugs(9, 3, HERE
<< (unsigned long int)len
<< " bytes to play with");
936 line
= (char *)memAllocate(MEM_4K_BUF
);
939 s
+= strspn(s
, crlf
);
941 for (; s
< end
; s
+= strcspn(s
, crlf
), s
+= strspn(s
, crlf
)) {
942 debugs(9, 7, HERE
<< "s = {" << s
<< "}");
943 linelen
= strcspn(s
, crlf
) + 1;
951 xstrncpy(line
, s
, linelen
);
953 debugs(9, 7, HERE
<< "{" << line
<< "}");
955 if (!strncmp(line
, "total", 5))
958 t
= htmlifyListEntry(line
);
961 debugs(9, 7, HERE
<< "listing append: t = {" << t
->contentSize() << ", '" << t
->content() << "'}");
962 listing
.append(t
->content(), t
->contentSize());
967 debugs(9, 7, HERE
<< "Done.");
968 data
.readBuf
->consume(usable
);
969 memFree(line
, MEM_4K_BUF
);
974 Ftp::Gateway::processReplyBody()
976 debugs(9, 3, status());
978 if (request
->method
== Http::METHOD_HEAD
&& (flags
.isdir
|| theSize
!= -1)) {
983 /* Directory listings are special. They write ther own headers via the error objects */
984 if (!flags
.http_header_sent
&& data
.readBuf
->contentSize() >= 0 && !flags
.isdir
)
985 appendSuccessHeader();
987 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
989 * probably was aborted because content length exceeds one
990 * of the maximum size limits.
992 abortTransaction("entry aborted after calling appendSuccessHeader()");
998 if (adaptationAccessCheckPending
) {
999 debugs(9, 3, "returning from Ftp::Gateway::processReplyBody due to adaptationAccessCheckPending");
1006 if (!flags
.listing
) {
1011 maybeReadVirginBody();
1013 } else if (const int csize
= data
.readBuf
->contentSize()) {
1014 writeReplyBody(data
.readBuf
->content(), csize
);
1015 debugs(9, 5, HERE
<< "consuming " << csize
<< " bytes of readBuf");
1016 data
.readBuf
->consume(csize
);
1021 maybeReadVirginBody();
1025 * Locates the FTP user:password login.
1027 * Highest to lowest priority:
1028 * - Checks URL (ftp://user:pass@domain)
1029 * - Authorization: Basic header
1030 * - squid.conf anonymous-FTP settings (default: anonymous:Squid@).
1032 * Special Case: A username-only may be provided in the URL and password in the HTTP headers.
1034 * TODO: we might be able to do something about locating username from other sources:
1035 * ie, external ACL user=* tag or ident lookup
1037 \retval 1 if we have everything needed to complete this request.
1038 \retval 0 if something is missing.
1041 Ftp::Gateway::checkAuth(const HttpHeader
* req_hdr
)
1043 /* default username */
1044 xstrncpy(user
, "anonymous", MAX_URL
);
1046 #if HAVE_AUTH_MODULE_BASIC
1047 /* Check HTTP Authorization: headers (better than defaults, but less than URL) */
1048 const SBuf
auth(req_hdr
->getAuth(HDR_AUTHORIZATION
, "Basic"));
1049 if (!auth
.isEmpty()) {
1050 flags
.authenticated
= 1;
1051 loginParser(auth
, false);
1053 /* we fail with authorization-required error later IFF the FTP server requests it */
1056 /* Test URL login syntax. Overrides any headers received. */
1057 loginParser(request
->url
.userInfo(), true);
1059 /* name is missing. thats fatal. */
1061 fatal("FTP login parsing destroyed username info");
1063 /* name + password == success */
1067 /* Setup default FTP password settings */
1068 /* this has to be done last so that we can have a no-password case above. */
1070 if (strcmp(user
, "anonymous") == 0 && !flags
.tried_auth_anonymous
) {
1071 xstrncpy(password
, Config
.Ftp
.anon_user
, MAX_URL
);
1072 flags
.tried_auth_anonymous
=1;
1074 } else if (!flags
.tried_auth_nopass
) {
1075 xstrncpy(password
, null_string
, MAX_URL
);
1076 flags
.tried_auth_nopass
=1;
1081 return 0; /* different username */
1085 Ftp::Gateway::checkUrlpath()
1087 static SBuf
str_type_eq("type=");
1088 auto t
= request
->url
.path().rfind(';');
1090 if (t
!= SBuf::npos
) {
1091 auto filenameEnd
= t
-1;
1092 if (request
->url
.path().substr(++t
).cmp(str_type_eq
, str_type_eq
.length()) == 0) {
1093 t
+= str_type_eq
.length();
1094 typecode
= (char)xtoupper(request
->url
.path()[t
]);
1095 request
->url
.path(request
->url
.path().substr(0,filenameEnd
));
1099 int l
= request
->url
.path().length();
1100 /* check for null path */
1105 flags
.need_base_href
= 1; /* Work around broken browsers */
1106 } else if (!request
->url
.path().cmp("/%2f/")) {
1107 /* UNIX root directory */
1110 } else if ((l
>= 1) && (request
->url
.path()[l
-1] == '/')) {
1111 /* Directory URL, ending in / */
1117 flags
.dir_slash
= 1;
1122 Ftp::Gateway::buildTitleUrl()
1124 title_url
= "ftp://";
1126 if (strcmp(user
, "anonymous")) {
1127 title_url
.append(user
);
1128 title_url
.append("@");
1131 SBuf authority
= request
->url
.authority(request
->url
.getScheme() != AnyP::PROTO_FTP
);
1133 title_url
.append(authority
.rawContent(), authority
.length());
1134 title_url
.append(request
->url
.path().rawContent(), request
->url
.path().length());
1136 base_href
= "ftp://";
1138 if (strcmp(user
, "anonymous") != 0) {
1139 base_href
.append(rfc1738_escape_part(user
));
1142 base_href
.append(":");
1143 base_href
.append(rfc1738_escape_part(password
));
1146 base_href
.append("@");
1149 base_href
.append(authority
.rawContent(), authority
.length());
1150 base_href
.append(request
->url
.path().rawContent(), request
->url
.path().length());
1151 base_href
.append("/");
1155 Ftp::Gateway::start()
1157 if (!checkAuth(&request
->header
)) {
1158 /* create appropriate reply */
1159 HttpReply
*reply
= ftpAuthRequired(request
, ftpRealm());
1160 entry
->replaceHttpReply(reply
);
1167 debugs(9, 5, "FD " << ctrl
.conn
->fd
<< " : host=" << request
->url
.host() <<
1168 ", path=" << request
->url
.path() << ", user=" << user
<< ", passwd=" << password
);
1170 Ftp::Client::start();
1173 /* ====================================================================== */
1176 Ftp::Gateway::handleControlReply()
1178 Ftp::Client::handleControlReply();
1179 if (ctrl
.message
== NULL
)
1180 return; // didn't get complete reply yet
1182 /* Copy the message except for the last line to cwd_message to be
1183 * printed in error messages.
1185 for (wordlist
*w
= ctrl
.message
; w
&& w
->next
; w
= w
->next
) {
1186 cwd_message
.append('\n');
1187 cwd_message
.append(w
->key
);
1190 FTP_SM_FUNCS
[state
] (this);
1193 /* ====================================================================== */
1196 ftpReadWelcome(Ftp::Gateway
* ftpState
)
1198 int code
= ftpState
->ctrl
.replycode
;
1201 if (ftpState
->flags
.pasv_only
)
1202 ++ ftpState
->login_att
;
1205 if (ftpState
->ctrl
.message
) {
1206 if (strstr(ftpState
->ctrl
.message
->key
, "NetWare"))
1207 ftpState
->flags
.skip_whitespace
= 1;
1210 ftpSendUser(ftpState
);
1211 } else if (code
== 120) {
1212 if (NULL
!= ftpState
->ctrl
.message
)
1213 debugs(9, DBG_IMPORTANT
, "FTP server is busy: " << ftpState
->ctrl
.message
->key
);
1222 * Translate FTP login failure into HTTP error
1223 * this is an attmpt to get the 407 message to show up outside Squid.
1224 * its NOT a general failure. But a correct FTP response type.
1227 Ftp::Gateway::loginFailed()
1229 ErrorState
*err
= NULL
;
1230 const char *command
, *reply
;
1232 if ((state
== SENT_USER
|| state
== SENT_PASS
) && ctrl
.replycode
>= 400) {
1233 if (ctrl
.replycode
== 421 || ctrl
.replycode
== 426) {
1234 // 421/426 - Service Overload - retry permitted.
1235 err
= new ErrorState(ERR_FTP_UNAVAILABLE
, Http::scServiceUnavailable
, fwd
->request
);
1236 } else if (ctrl
.replycode
>= 430 && ctrl
.replycode
<= 439) {
1237 // 43x - Invalid or Credential Error - retry challenge required.
1238 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1239 } else if (ctrl
.replycode
>= 530 && ctrl
.replycode
<= 539) {
1240 // 53x - Credentials Missing - retry challenge required
1241 if (password_url
) // but they were in the URI! major fail.
1242 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scForbidden
, fwd
->request
);
1244 err
= new ErrorState(ERR_FTP_FORBIDDEN
, Http::scUnauthorized
, fwd
->request
);
1248 // any other problems are general falures.
1254 err
->ftp
.server_msg
= ctrl
.message
;
1256 ctrl
.message
= NULL
;
1259 command
= old_request
;
1261 command
= ctrl
.last_command
;
1263 if (command
&& strncmp(command
, "PASS", 4) == 0)
1264 command
= "PASS <yourpassword>";
1269 reply
= ctrl
.last_reply
;
1272 err
->ftp
.request
= xstrdup(command
);
1275 err
->ftp
.reply
= xstrdup(reply
);
1277 HttpReply
*newrep
= err
->BuildHttpReply();
1280 #if HAVE_AUTH_MODULE_BASIC
1281 /* add Authenticate header */
1282 newrep
->header
.putAuth("Basic", ftpRealm());
1285 // add it to the store entry for response....
1286 entry
->replaceHttpReply(newrep
);
1291 Ftp::Gateway::ftpRealm()
1293 static char realm
[8192];
1295 /* This request is not fully authenticated */
1297 snprintf(realm
, 8192, "FTP %s unknown", user
);
1298 } else if (request
->url
.port() == 21) {
1299 snprintf(realm
, 8192, "FTP %s %s", user
, request
->url
.host());
1301 snprintf(realm
, 8192, "FTP %s %s port %d", user
, request
->url
.host(), request
->url
.port());
1307 ftpSendUser(Ftp::Gateway
* ftpState
)
1309 /* check the server control channel is still available */
1310 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendUser"))
1313 if (ftpState
->proxy_host
!= NULL
)
1314 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s@%s\r\n", ftpState
->user
, ftpState
->request
->url
.host());
1316 snprintf(cbuf
, CTRL_BUFLEN
, "USER %s\r\n", ftpState
->user
);
1318 ftpState
->writeCommand(cbuf
);
1320 ftpState
->state
= Ftp::Client::SENT_USER
;
1324 ftpReadUser(Ftp::Gateway
* ftpState
)
1326 int code
= ftpState
->ctrl
.replycode
;
1330 ftpReadPass(ftpState
);
1331 } else if (code
== 331) {
1332 ftpSendPass(ftpState
);
1334 ftpState
->loginFailed();
1339 ftpSendPass(Ftp::Gateway
* ftpState
)
1341 /* check the server control channel is still available */
1342 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPass"))
1345 snprintf(cbuf
, CTRL_BUFLEN
, "PASS %s\r\n", ftpState
->password
);
1346 ftpState
->writeCommand(cbuf
);
1347 ftpState
->state
= Ftp::Client::SENT_PASS
;
1351 ftpReadPass(Ftp::Gateway
* ftpState
)
1353 int code
= ftpState
->ctrl
.replycode
;
1354 debugs(9, 3, HERE
<< "code=" << code
);
1357 ftpSendType(ftpState
);
1359 ftpState
->loginFailed();
1364 ftpSendType(Ftp::Gateway
* ftpState
)
1366 /* check the server control channel is still available */
1367 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendType"))
1371 * Ref section 3.2.2 of RFC 1738
1373 char mode
= ftpState
->typecode
;
1388 if (ftpState
->flags
.isdir
) {
1391 auto t
= ftpState
->request
->url
.path().rfind('/');
1392 // XXX: performance regression, c_str() may reallocate
1393 SBuf filename
= ftpState
->request
->url
.path().substr(t
!= SBuf::npos
? t
+ 1 : 0);
1394 mode
= mimeGetTransferMode(filename
.c_str());
1401 ftpState
->flags
.binary
= 1;
1403 ftpState
->flags
.binary
= 0;
1405 snprintf(cbuf
, CTRL_BUFLEN
, "TYPE %c\r\n", mode
);
1407 ftpState
->writeCommand(cbuf
);
1409 ftpState
->state
= Ftp::Client::SENT_TYPE
;
1413 ftpReadType(Ftp::Gateway
* ftpState
)
1415 int code
= ftpState
->ctrl
.replycode
;
1418 debugs(9, 3, HERE
<< "code=" << code
);
1421 const SBuf tmp
= ftpState
->request
->url
.path();
1422 p
= path
= xstrndup(tmp
.rawContent(),tmp
.length());
1429 p
+= strcspn(p
, "/");
1436 rfc1738_unescape(d
);
1439 wordlistAdd(&ftpState
->pathcomps
, d
);
1444 if (ftpState
->pathcomps
)
1445 ftpTraverseDirectory(ftpState
);
1447 ftpListDir(ftpState
);
1454 ftpTraverseDirectory(Ftp::Gateway
* ftpState
)
1457 debugs(9, 4, HERE
<< (ftpState
->filepath
? ftpState
->filepath
: "<NULL>"));
1459 safe_free(ftpState
->dirpath
);
1460 ftpState
->dirpath
= ftpState
->filepath
;
1461 ftpState
->filepath
= NULL
;
1465 if (ftpState
->pathcomps
== NULL
) {
1466 debugs(9, 3, HERE
<< "the final component was a directory");
1467 ftpListDir(ftpState
);
1471 /* Go to next path component */
1472 w
= ftpState
->pathcomps
;
1474 ftpState
->filepath
= w
->key
;
1476 ftpState
->pathcomps
= w
->next
;
1480 /* Check if we are to CWD or RETR */
1481 if (ftpState
->pathcomps
!= NULL
|| ftpState
->flags
.isdir
) {
1482 ftpSendCwd(ftpState
);
1484 debugs(9, 3, HERE
<< "final component is probably a file");
1485 ftpGetFile(ftpState
);
1491 ftpSendCwd(Ftp::Gateway
* ftpState
)
1495 /* check the server control channel is still available */
1496 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendCwd"))
1501 path
= ftpState
->filepath
;
1503 if (!strcmp(path
, "..") || !strcmp(path
, "/")) {
1504 ftpState
->flags
.no_dotdot
= 1;
1506 ftpState
->flags
.no_dotdot
= 0;
1509 snprintf(cbuf
, CTRL_BUFLEN
, "CWD %s\r\n", path
);
1511 ftpState
->writeCommand(cbuf
);
1513 ftpState
->state
= Ftp::Client::SENT_CWD
;
1517 ftpReadCwd(Ftp::Gateway
* ftpState
)
1519 int code
= ftpState
->ctrl
.replycode
;
1522 if (code
>= 200 && code
< 300) {
1526 /* Reset cwd_message to only include the last message */
1527 ftpState
->cwd_message
.reset("");
1528 for (wordlist
*w
= ftpState
->ctrl
.message
; w
; w
= w
->next
) {
1529 ftpState
->cwd_message
.append(' ');
1530 ftpState
->cwd_message
.append(w
->key
);
1532 ftpState
->ctrl
.message
= NULL
;
1534 /* Continue to traverse the path */
1535 ftpTraverseDirectory(ftpState
);
1539 if (!ftpState
->flags
.put
)
1542 ftpSendMkdir(ftpState
);
1547 ftpSendMkdir(Ftp::Gateway
* ftpState
)
1551 /* check the server control channel is still available */
1552 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMkdir"))
1555 path
= ftpState
->filepath
;
1556 debugs(9, 3, HERE
<< "with path=" << path
);
1557 snprintf(cbuf
, CTRL_BUFLEN
, "MKD %s\r\n", path
);
1558 ftpState
->writeCommand(cbuf
);
1559 ftpState
->state
= Ftp::Client::SENT_MKDIR
;
1563 ftpReadMkdir(Ftp::Gateway
* ftpState
)
1565 char *path
= ftpState
->filepath
;
1566 int code
= ftpState
->ctrl
.replycode
;
1568 debugs(9, 3, HERE
<< "path " << path
<< ", code " << code
);
1570 if (code
== 257) { /* success */
1571 ftpSendCwd(ftpState
);
1572 } else if (code
== 550) { /* dir exists */
1574 if (ftpState
->flags
.put_mkdir
) {
1575 ftpState
->flags
.put_mkdir
= 1;
1576 ftpSendCwd(ftpState
);
1578 ftpSendReply(ftpState
);
1580 ftpSendReply(ftpState
);
1584 ftpGetFile(Ftp::Gateway
* ftpState
)
1586 assert(*ftpState
->filepath
!= '\0');
1587 ftpState
->flags
.isdir
= 0;
1588 ftpSendMdtm(ftpState
);
1592 ftpListDir(Ftp::Gateway
* ftpState
)
1594 if (ftpState
->flags
.dir_slash
) {
1595 debugs(9, 3, HERE
<< "Directory path did not end in /");
1596 ftpState
->title_url
.append("/");
1597 ftpState
->flags
.isdir
= 1;
1600 ftpSendPassive(ftpState
);
1604 ftpSendMdtm(Ftp::Gateway
* ftpState
)
1606 /* check the server control channel is still available */
1607 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendMdtm"))
1610 assert(*ftpState
->filepath
!= '\0');
1611 snprintf(cbuf
, CTRL_BUFLEN
, "MDTM %s\r\n", ftpState
->filepath
);
1612 ftpState
->writeCommand(cbuf
);
1613 ftpState
->state
= Ftp::Client::SENT_MDTM
;
1617 ftpReadMdtm(Ftp::Gateway
* ftpState
)
1619 int code
= ftpState
->ctrl
.replycode
;
1623 ftpState
->mdtm
= parse_iso3307_time(ftpState
->ctrl
.last_reply
);
1625 } else if (code
< 0) {
1630 ftpSendSize(ftpState
);
1634 ftpSendSize(Ftp::Gateway
* ftpState
)
1636 /* check the server control channel is still available */
1637 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendSize"))
1640 /* Only send SIZE for binary transfers. The returned size
1641 * is useless on ASCII transfers */
1643 if (ftpState
->flags
.binary
) {
1644 assert(ftpState
->filepath
!= NULL
);
1645 assert(*ftpState
->filepath
!= '\0');
1646 snprintf(cbuf
, CTRL_BUFLEN
, "SIZE %s\r\n", ftpState
->filepath
);
1647 ftpState
->writeCommand(cbuf
);
1648 ftpState
->state
= Ftp::Client::SENT_SIZE
;
1650 /* Skip to next state no non-binary transfers */
1651 ftpSendPassive(ftpState
);
1655 ftpReadSize(Ftp::Gateway
* ftpState
)
1657 int code
= ftpState
->ctrl
.replycode
;
1662 ftpState
->theSize
= strtoll(ftpState
->ctrl
.last_reply
, NULL
, 10);
1664 if (ftpState
->theSize
== 0) {
1665 debugs(9, 2, "SIZE reported " <<
1666 ftpState
->ctrl
.last_reply
<< " on " <<
1667 ftpState
->title_url
);
1668 ftpState
->theSize
= -1;
1670 } else if (code
< 0) {
1675 ftpSendPassive(ftpState
);
1679 ftpReadEPSV(Ftp::Gateway
* ftpState
)
1681 Ip::Address srvAddr
; // unused
1682 if (ftpState
->handleEpsvReply(srvAddr
)) {
1683 if (ftpState
->ctrl
.message
== NULL
)
1684 return; // didn't get complete reply yet
1686 ftpState
->connectDataChannel();
1690 /** Send Passive connection request.
1691 * Default method is to use modern EPSV request.
1692 * The failover mechanism should check for previous state and re-call with alternates on failure.
1695 ftpSendPassive(Ftp::Gateway
* ftpState
)
1697 /** Checks the server control channel is still available before running. */
1698 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendPassive"))
1704 * Checks for 'HEAD' method request and passes off for special handling by Ftp::Gateway::processHeadResponse(). */
1705 if (ftpState
->request
->method
== Http::METHOD_HEAD
&& (ftpState
->flags
.isdir
|| ftpState
->theSize
!= -1)) {
1706 ftpState
->processHeadResponse(); // may call serverComplete
1710 if (ftpState
->sendPassive()) {
1711 // SENT_EPSV_ALL blocks other non-EPSV connections being attempted
1712 if (ftpState
->state
== Ftp::Client::SENT_EPSV_ALL
)
1713 ftpState
->flags
.epsv_all_sent
= true;
1718 Ftp::Gateway::processHeadResponse()
1720 debugs(9, 5, HERE
<< "handling HEAD response");
1722 appendSuccessHeader();
1725 * On rare occasions I'm seeing the entry get aborted after
1726 * readControlReply() and before here, probably when
1727 * trying to write to the client.
1729 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1730 abortTransaction("entry aborted while processing HEAD");
1735 if (adaptationAccessCheckPending
) {
1736 debugs(9,3, HERE
<< "returning due to adaptationAccessCheckPending");
1741 // processReplyBody calls serverComplete() since there is no body
1746 ftpReadPasv(Ftp::Gateway
* ftpState
)
1748 Ip::Address srvAddr
; // unused
1749 if (ftpState
->handlePasvReply(srvAddr
))
1750 ftpState
->connectDataChannel();
1752 ftpSendEPRT(ftpState
);
1758 Ftp::Gateway::dataChannelConnected(const CommConnectCbParams
&io
)
1763 if (io
.flag
!= Comm::OK
) {
1764 debugs(9, 2, HERE
<< "Failed to connect. Retrying via another method.");
1766 // ABORT on timeouts. server may be waiting on a broken TCP link.
1767 if (io
.xerrno
== Comm::TIMEOUT
)
1768 writeCommand("ABOR");
1770 // try another connection attempt with some other method
1771 ftpSendPassive(this);
1775 data
.opened(io
.conn
, dataCloser());
1776 ftpRestOrList(this);
1780 ftpOpenListenSocket(Ftp::Gateway
* ftpState
, int fallback
)
1782 /// Close old data channels, if any. We may open a new one below.
1783 if (ftpState
->data
.conn
!= NULL
) {
1784 if ((ftpState
->data
.conn
->flags
& COMM_REUSEADDR
))
1785 // NP: in fact it points to the control channel. just clear it.
1786 ftpState
->data
.clear();
1788 ftpState
->data
.close();
1790 safe_free(ftpState
->data
.host
);
1793 * Set up a listen socket on the same local address as the
1794 * control connection.
1796 Comm::ConnectionPointer temp
= new Comm::Connection
;
1797 temp
->local
= ftpState
->ctrl
.conn
->local
;
1800 * REUSEADDR is needed in fallback mode, since the same port is
1801 * used for both control and data.
1805 setsockopt(ftpState
->ctrl
.conn
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
));
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
);
1878 ftpSendEPRT(Ftp::Gateway
* ftpState
)
1880 if (Config
.Ftp
.epsv_all
&& ftpState
->flags
.epsv_all_sent
) {
1881 debugs(9, DBG_IMPORTANT
, "FTP does not allow EPRT method after 'EPSV ALL' has been sent.");
1885 if (!Config
.Ftp
.eprt
) {
1886 /* Disabled. Switch immediately to attempting old PORT command. */
1887 debugs(9, 3, "EPRT disabled by local administrator");
1888 ftpSendPORT(ftpState
);
1893 ftpState
->flags
.pasv_supported
= 0;
1895 ftpOpenListenSocket(ftpState
, 0);
1896 debugs(9, 3, "Listening for FTP data connection with FD " << ftpState
->data
.conn
);
1897 if (!Comm::IsConnOpen(ftpState
->data
.conn
)) {
1898 /* XXX Need to set error message */
1903 char buf
[MAX_IPSTRLEN
];
1905 /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
1906 /* Which can be used by EITHER protocol. */
1907 snprintf(cbuf
, CTRL_BUFLEN
, "EPRT |%d|%s|%d|\r\n",
1908 ( ftpState
->data
.listenConn
->local
.isIPv6() ? 2 : 1 ),
1909 ftpState
->data
.listenConn
->local
.toStr(buf
,MAX_IPSTRLEN
),
1910 ftpState
->data
.listenConn
->local
.port() );
1912 ftpState
->writeCommand(cbuf
);
1913 ftpState
->state
= Ftp::Client::SENT_EPRT
;
1917 ftpReadEPRT(Ftp::Gateway
* ftpState
)
1919 int code
= ftpState
->ctrl
.replycode
;
1923 /* Failover to attempting old PORT command. */
1924 debugs(9, 3, "EPRT not supported by remote end");
1925 ftpSendPORT(ftpState
);
1929 ftpRestOrList(ftpState
);
1932 /** "read" handler to accept FTP data connections.
1934 \param io comm accept(2) callback parameters
1937 Ftp::Gateway::ftpAcceptDataConnection(const CommAcceptCbParams
&io
)
1941 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1942 abortTransaction("entry aborted when accepting data conn");
1943 data
.listenConn
->close();
1944 data
.listenConn
= NULL
;
1948 if (io
.flag
!= Comm::OK
) {
1949 data
.listenConn
->close();
1950 data
.listenConn
= NULL
;
1951 debugs(9, DBG_IMPORTANT
, "FTP AcceptDataConnection: " << io
.conn
<< ": " << xstrerr(io
.xerrno
));
1952 /** \todo Need to send error message on control channel*/
1957 /* data listening conn is no longer even open. abort. */
1958 if (!Comm::IsConnOpen(data
.listenConn
)) {
1959 data
.listenConn
= NULL
; // ensure that it's cleared and not just closed.
1963 /* data listening conn is no longer even open. abort. */
1964 if (!Comm::IsConnOpen(data
.conn
)) {
1965 data
.clear(); // ensure that it's cleared and not just closed.
1970 * When squid.conf ftp_sanitycheck is enabled, check the new connection is actually being
1971 * made by the remote client which is connected to the FTP control socket.
1972 * Or the one which we were told to listen for by control channel messages (may differ under NAT).
1973 * This prevents third-party hacks, but also third-party load balancing handshakes.
1975 if (Config
.Ftp
.sanitycheck
) {
1976 // accept if either our data or ctrl connection is talking to this remote peer.
1977 if (data
.conn
->remote
!= io
.conn
->remote
&& ctrl
.conn
->remote
!= io
.conn
->remote
) {
1978 debugs(9, DBG_IMPORTANT
,
1979 "FTP data connection from unexpected server (" <<
1980 io
.conn
->remote
<< "), expecting " <<
1981 data
.conn
->remote
<< " or " << ctrl
.conn
->remote
);
1983 /* close the bad sources connection down ASAP. */
1986 /* drop the bad connection (io) by ignoring the attempt. */
1991 /** On Comm::OK start using the accepted data socket and discard the temporary listen socket. */
1993 data
.opened(io
.conn
, dataCloser());
1994 data
.addr(io
.conn
->remote
);
1996 debugs(9, 3, HERE
<< "Connected data socket on " <<
1997 io
.conn
<< ". FD table says: " <<
1998 "ctrl-peer= " << fd_table
[ctrl
.conn
->fd
].ipaddr
<< ", " <<
1999 "data-peer= " << fd_table
[data
.conn
->fd
].ipaddr
);
2001 assert(haveControlChannel("ftpAcceptDataConnection"));
2002 assert(ctrl
.message
== NULL
);
2004 // Ctrl channel operations will determine what happens to this data connection
2008 ftpRestOrList(Ftp::Gateway
* ftpState
)
2012 if (ftpState
->typecode
== 'D') {
2013 ftpState
->flags
.isdir
= 1;
2015 if (ftpState
->flags
.put
) {
2016 ftpSendMkdir(ftpState
); /* PUT name;type=d */
2018 ftpSendNlst(ftpState
); /* GET name;type=d sec 3.2.2 of RFC 1738 */
2020 } else if (ftpState
->flags
.put
) {
2021 ftpSendStor(ftpState
);
2022 } else if (ftpState
->flags
.isdir
)
2023 ftpSendList(ftpState
);
2024 else if (ftpState
->restartable())
2025 ftpSendRest(ftpState
);
2027 ftpSendRetr(ftpState
);
2031 ftpSendStor(Ftp::Gateway
* ftpState
)
2033 /* check the server control channel is still available */
2034 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendStor"))
2039 if (ftpState
->filepath
!= NULL
) {
2040 /* Plain file upload */
2041 snprintf(cbuf
, CTRL_BUFLEN
, "STOR %s\r\n", ftpState
->filepath
);
2042 ftpState
->writeCommand(cbuf
);
2043 ftpState
->state
= Ftp::Client::SENT_STOR
;
2044 } else if (ftpState
->request
->header
.getInt64(HDR_CONTENT_LENGTH
) > 0) {
2045 /* File upload without a filename. use STOU to generate one */
2046 snprintf(cbuf
, CTRL_BUFLEN
, "STOU\r\n");
2047 ftpState
->writeCommand(cbuf
);
2048 ftpState
->state
= Ftp::Client::SENT_STOR
;
2050 /* No file to transfer. Only create directories if needed */
2051 ftpSendReply(ftpState
);
2055 /// \deprecated use ftpState->readStor() instead.
2057 ftpReadStor(Ftp::Gateway
* ftpState
)
2059 ftpState
->readStor();
2062 void Ftp::Gateway::readStor()
2064 int code
= ctrl
.replycode
;
2067 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(data
.conn
))) {
2068 if (!originalRequest()->body_pipe
) {
2069 debugs(9, 3, "zero-size STOR?");
2070 state
= WRITING_DATA
; // make ftpWriteTransferDone() responsible
2071 dataComplete(); // XXX: keep in sync with doneSendingRequestBody()
2075 if (!startRequestBodyFlow()) { // register to receive body data
2080 /* When client status is 125, or 150 and the data connection is open, Begin data transfer. */
2081 debugs(9, 3, HERE
<< "starting data transfer");
2082 switchTimeoutToDataChannel();
2083 sendMoreRequestBody();
2084 fwd
->dontRetry(true); // dont permit re-trying if the body was sent.
2085 state
= WRITING_DATA
;
2086 debugs(9, 3, HERE
<< "writing data channel");
2087 } else if (code
== 150) {
2088 /* When client code is 150 with no data channel, Accept data channel. */
2089 debugs(9, 3, "ftpReadStor: accepting data channel");
2090 listenForDataChannel(data
.conn
);
2092 debugs(9, DBG_IMPORTANT
, HERE
<< "Unexpected reply code "<< std::setfill('0') << std::setw(3) << code
);
2098 ftpSendRest(Ftp::Gateway
* ftpState
)
2100 /* check the server control channel is still available */
2101 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRest"))
2106 snprintf(cbuf
, CTRL_BUFLEN
, "REST %" PRId64
"\r\n", ftpState
->restart_offset
);
2107 ftpState
->writeCommand(cbuf
);
2108 ftpState
->state
= Ftp::Client::SENT_REST
;
2112 Ftp::Gateway::restartable()
2114 if (restart_offset
> 0)
2117 if (!request
->range
)
2126 int64_t desired_offset
= request
->range
->lowestOffset(theSize
);
2128 if (desired_offset
<= 0)
2131 if (desired_offset
>= theSize
)
2134 restart_offset
= desired_offset
;
2139 ftpReadRest(Ftp::Gateway
* ftpState
)
2141 int code
= ftpState
->ctrl
.replycode
;
2143 assert(ftpState
->restart_offset
> 0);
2146 ftpState
->setCurrentOffset(ftpState
->restart_offset
);
2147 ftpSendRetr(ftpState
);
2148 } else if (code
> 0) {
2149 debugs(9, 3, HERE
<< "REST not supported");
2150 ftpState
->flags
.rest_supported
= 0;
2151 ftpSendRetr(ftpState
);
2158 ftpSendList(Ftp::Gateway
* ftpState
)
2160 /* check the server control channel is still available */
2161 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendList"))
2166 if (ftpState
->filepath
) {
2167 snprintf(cbuf
, CTRL_BUFLEN
, "LIST %s\r\n", ftpState
->filepath
);
2169 snprintf(cbuf
, CTRL_BUFLEN
, "LIST\r\n");
2172 ftpState
->writeCommand(cbuf
);
2173 ftpState
->state
= Ftp::Client::SENT_LIST
;
2177 ftpSendNlst(Ftp::Gateway
* ftpState
)
2179 /* check the server control channel is still available */
2180 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendNlst"))
2185 ftpState
->flags
.tried_nlst
= 1;
2187 if (ftpState
->filepath
) {
2188 snprintf(cbuf
, CTRL_BUFLEN
, "NLST %s\r\n", ftpState
->filepath
);
2190 snprintf(cbuf
, CTRL_BUFLEN
, "NLST\r\n");
2193 ftpState
->writeCommand(cbuf
);
2194 ftpState
->state
= Ftp::Client::SENT_NLST
;
2198 ftpReadList(Ftp::Gateway
* ftpState
)
2200 int code
= ftpState
->ctrl
.replycode
;
2203 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2204 /* Begin data transfer */
2205 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2206 ftpState
->switchTimeoutToDataChannel();
2207 ftpState
->maybeReadVirginBody();
2208 ftpState
->state
= Ftp::Client::READING_DATA
;
2210 } else if (code
== 150) {
2211 /* Accept data channel */
2212 debugs(9, 3, HERE
<< "accept data channel from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2213 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2215 } else if (!ftpState
->flags
.tried_nlst
&& code
> 300) {
2216 ftpSendNlst(ftpState
);
2224 ftpSendRetr(Ftp::Gateway
* ftpState
)
2226 /* check the server control channel is still available */
2227 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendRetr"))
2232 assert(ftpState
->filepath
!= NULL
);
2233 snprintf(cbuf
, CTRL_BUFLEN
, "RETR %s\r\n", ftpState
->filepath
);
2234 ftpState
->writeCommand(cbuf
);
2235 ftpState
->state
= Ftp::Client::SENT_RETR
;
2239 ftpReadRetr(Ftp::Gateway
* ftpState
)
2241 int code
= ftpState
->ctrl
.replycode
;
2244 if (code
== 125 || (code
== 150 && Comm::IsConnOpen(ftpState
->data
.conn
))) {
2245 /* Begin data transfer */
2246 debugs(9, 3, HERE
<< "begin data transfer from " << ftpState
->data
.conn
->remote
<< " (" << ftpState
->data
.conn
->local
<< ")");
2247 ftpState
->switchTimeoutToDataChannel();
2248 ftpState
->maybeReadVirginBody();
2249 ftpState
->state
= Ftp::Client::READING_DATA
;
2250 } else if (code
== 150) {
2251 /* Accept data channel */
2252 ftpState
->listenForDataChannel(ftpState
->data
.conn
);
2253 } else if (code
>= 300) {
2254 if (!ftpState
->flags
.try_slash_hack
) {
2255 /* Try this as a directory missing trailing slash... */
2256 ftpState
->hackShortcut(ftpSendCwd
);
2266 * Generate the HTTP headers and template fluff around an FTP
2267 * directory listing display.
2270 Ftp::Gateway::completedListing()
2273 entry
->lock("Ftp::Gateway");
2274 ErrorState
ferr(ERR_DIR_LISTING
, Http::scOkay
, request
);
2275 ferr
.ftp
.listing
= &listing
;
2276 ferr
.ftp
.cwd_msg
= xstrdup(cwd_message
.size()? cwd_message
.termedBuf() : "");
2277 ferr
.ftp
.server_msg
= ctrl
.message
;
2278 ctrl
.message
= NULL
;
2279 entry
->replaceHttpReply( ferr
.BuildHttpReply() );
2280 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2282 entry
->unlock("Ftp::Gateway");
2286 ftpReadTransferDone(Ftp::Gateway
* ftpState
)
2288 int code
= ftpState
->ctrl
.replycode
;
2291 if (code
== 226 || code
== 250) {
2292 /* Connection closed; retrieval done. */
2293 if (ftpState
->flags
.listing
) {
2294 ftpState
->completedListing();
2295 /* QUIT operation handles sending the reply to client */
2297 ftpSendQuit(ftpState
);
2298 } else { /* != 226 */
2299 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after reading data");
2300 ftpState
->failed(ERR_FTP_FAILURE
, 0);
2301 /* failed closes ctrl.conn and frees ftpState */
2306 // premature end of the request body
2308 Ftp::Gateway::handleRequestBodyProducerAborted()
2310 Client::handleRequestBodyProducerAborted();
2311 debugs(9, 3, HERE
<< "ftpState=" << this);
2312 failed(ERR_READ_ERROR
, 0);
2316 ftpWriteTransferDone(Ftp::Gateway
* ftpState
)
2318 int code
= ftpState
->ctrl
.replycode
;
2321 if (!(code
== 226 || code
== 250)) {
2322 debugs(9, DBG_IMPORTANT
, HERE
<< "Got code " << code
<< " after sending data");
2323 ftpState
->failed(ERR_FTP_PUT_ERROR
, 0);
2327 ftpState
->entry
->timestampsSet(); /* XXX Is this needed? */
2328 ftpSendReply(ftpState
);
2332 ftpSendQuit(Ftp::Gateway
* ftpState
)
2334 /* check the server control channel is still available */
2335 if (!ftpState
|| !ftpState
->haveControlChannel("ftpSendQuit"))
2338 snprintf(cbuf
, CTRL_BUFLEN
, "QUIT\r\n");
2339 ftpState
->writeCommand(cbuf
);
2340 ftpState
->state
= Ftp::Client::SENT_QUIT
;
2343 /** Completes a client FTP operation with success or other page
2344 * generated and stored in the entry field by the code issuing QUIT.
2347 ftpReadQuit(Ftp::Gateway
* ftpState
)
2349 ftpState
->serverComplete();
2353 ftpTrySlashHack(Ftp::Gateway
* ftpState
)
2356 ftpState
->flags
.try_slash_hack
= 1;
2357 /* Free old paths */
2361 if (ftpState
->pathcomps
)
2362 wordlistDestroy(&ftpState
->pathcomps
);
2364 safe_free(ftpState
->filepath
);
2366 /* Build the new path (urlpath begins with /) */
2367 const SBuf tmp
= ftpState
->request
->url
.path();
2368 path
= xstrndup(tmp
.rawContent(), tmp
.length());
2369 path
[tmp
.length()] = '\0';
2371 rfc1738_unescape(path
);
2373 ftpState
->filepath
= path
;
2376 ftpGetFile(ftpState
);
2380 * Forget hack status. Next error is shown to the user
2383 Ftp::Gateway::unhack()
2387 if (old_request
!= NULL
) {
2388 safe_free(old_request
);
2389 safe_free(old_reply
);
2394 Ftp::Gateway::hackShortcut(FTPSM
* nextState
)
2396 /* Clear some unwanted state */
2397 setCurrentOffset(0);
2399 /* Save old error message & some state info */
2403 if (old_request
== NULL
) {
2404 old_request
= ctrl
.last_command
;
2405 ctrl
.last_command
= NULL
;
2406 old_reply
= ctrl
.last_reply
;
2407 ctrl
.last_reply
= NULL
;
2409 if (pathcomps
== NULL
&& filepath
!= NULL
)
2410 old_filepath
= xstrdup(filepath
);
2413 /* Jump to the "hack" state */
2418 ftpFail(Ftp::Gateway
*ftpState
)
2420 const bool slashHack
= ftpState
->request
->url
.path().caseCmp("/%2f", 4)==0;
2421 debugs(9, 6, "flags(" <<
2422 (ftpState
->flags
.isdir
?"IS_DIR,":"") <<
2423 (ftpState
->flags
.try_slash_hack
?"TRY_SLASH_HACK":"") << "), " <<
2424 "mdtm=" << ftpState
->mdtm
<< ", size=" << ftpState
->theSize
<<
2425 "slashhack=" << (slashHack
? "T":"F"));
2427 /* Try the / hack to support "Netscape" FTP URL's for retreiving files */
2428 if (!ftpState
->flags
.isdir
&& /* Not a directory */
2429 !ftpState
->flags
.try_slash_hack
&& !slashHack
&& /* Not doing slash hack */
2430 ftpState
->mdtm
<= 0 && ftpState
->theSize
< 0) { /* Not known as a file */
2432 switch (ftpState
->state
) {
2434 case Ftp::Client::SENT_CWD
:
2436 case Ftp::Client::SENT_RETR
:
2437 /* Try the / hack */
2438 ftpState
->hackShortcut(ftpTrySlashHack
);
2446 ftpState
->failed(ERR_NONE
, 0);
2447 /* failed() closes ctrl.conn and frees this */
2451 Ftp::Gateway::failedHttpStatus(err_type
&error
)
2453 if (error
== ERR_NONE
) {
2460 if (ctrl
.replycode
> 500) {
2461 error
= ERR_FTP_FORBIDDEN
;
2462 return password_url
? Http::scForbidden
: Http::scUnauthorized
;
2463 } else if (ctrl
.replycode
== 421) {
2464 error
= ERR_FTP_UNAVAILABLE
;
2465 return Http::scServiceUnavailable
;
2472 if (ctrl
.replycode
== 550) {
2473 error
= ERR_FTP_NOT_FOUND
;
2474 return Http::scNotFound
;
2482 return Ftp::Client::failedHttpStatus(error
);
2486 ftpSendReply(Ftp::Gateway
* ftpState
)
2488 int code
= ftpState
->ctrl
.replycode
;
2489 Http::StatusCode http_code
;
2490 err_type err_code
= ERR_NONE
;
2492 debugs(9, 3, HERE
<< ftpState
->entry
->url() << ", code " << code
);
2494 if (cbdataReferenceValid(ftpState
))
2495 debugs(9, 5, HERE
<< "ftpState (" << ftpState
<< ") is valid!");
2497 if (code
== 226 || code
== 250) {
2498 err_code
= (ftpState
->mdtm
> 0) ? ERR_FTP_PUT_MODIFIED
: ERR_FTP_PUT_CREATED
;
2499 http_code
= (ftpState
->mdtm
> 0) ? Http::scAccepted
: Http::scCreated
;
2500 } else if (code
== 227) {
2501 err_code
= ERR_FTP_PUT_CREATED
;
2502 http_code
= Http::scCreated
;
2504 err_code
= ERR_FTP_PUT_ERROR
;
2505 http_code
= Http::scInternalServerError
;
2508 ErrorState
err(err_code
, http_code
, ftpState
->request
);
2510 if (ftpState
->old_request
)
2511 err
.ftp
.request
= xstrdup(ftpState
->old_request
);
2513 err
.ftp
.request
= xstrdup(ftpState
->ctrl
.last_command
);
2515 if (ftpState
->old_reply
)
2516 err
.ftp
.reply
= xstrdup(ftpState
->old_reply
);
2517 else if (ftpState
->ctrl
.last_reply
)
2518 err
.ftp
.reply
= xstrdup(ftpState
->ctrl
.last_reply
);
2520 err
.ftp
.reply
= xstrdup("");
2522 // TODO: interpret as FTP-specific error code
2523 err
.detailError(code
);
2525 ftpState
->entry
->replaceHttpReply( err
.BuildHttpReply() );
2527 ftpSendQuit(ftpState
);
2531 Ftp::Gateway::appendSuccessHeader()
2535 if (flags
.http_header_sent
)
2538 HttpReply
*reply
= new HttpReply
;
2540 flags
.http_header_sent
= 1;
2542 assert(entry
->isEmpty());
2544 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
2546 entry
->buffer(); /* released when done processing current data payload */
2548 SBuf urlPath
= request
->url
.path();
2549 auto t
= urlPath
.rfind('/');
2550 SBuf filename
= urlPath
.substr(t
!= SBuf::npos
? t
: 0);
2552 const char *mime_type
= NULL
;
2553 const char *mime_enc
= NULL
;
2556 mime_type
= "text/html";
2561 mime_type
= "application/octet-stream";
2562 // XXX: performance regression, c_str() may reallocate
2563 mime_enc
= mimeGetContentEncoding(filename
.c_str());
2567 mime_type
= "text/plain";
2571 // XXX: performance regression, c_str() may reallocate
2572 mime_type
= mimeGetContentType(filename
.c_str());
2573 mime_enc
= mimeGetContentEncoding(filename
.c_str());
2578 /* set standard stuff */
2580 if (0 == getCurrentOffset()) {
2582 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2583 } else if (theSize
< getCurrentOffset()) {
2586 * offset should not be larger than theSize. We should
2587 * not be seeing this condition any more because we'll only
2588 * send REST if we know the theSize and if it is less than theSize.
2590 debugs(0,DBG_CRITICAL
,HERE
<< "Whoops! " <<
2591 " current offset=" << getCurrentOffset() <<
2592 ", but theSize=" << theSize
<<
2593 ". assuming full content response");
2594 reply
->setHeaders(Http::scOkay
, "Gatewaying", mime_type
, theSize
, mdtm
, -2);
2597 HttpHdrRangeSpec range_spec
;
2598 range_spec
.offset
= getCurrentOffset();
2599 range_spec
.length
= theSize
- getCurrentOffset();
2600 reply
->setHeaders(Http::scPartialContent
, "Gatewaying", mime_type
, theSize
- getCurrentOffset(), mdtm
, -2);
2601 httpHeaderAddContRange(&reply
->header
, range_spec
, theSize
);
2604 /* additional info */
2606 reply
->header
.putStr(HDR_CONTENT_ENCODING
, mime_enc
);
2608 setVirginReply(reply
);
2609 adaptOrFinalizeReply();
2613 Ftp::Gateway::haveParsedReplyHeaders()
2615 Client::haveParsedReplyHeaders();
2617 StoreEntry
*e
= entry
;
2621 if (flags
.authenticated
) {
2623 * Authenticated requests can't be cached.
2626 } else if (!EBIT_TEST(e
->flags
, RELEASE_REQUEST
) && !getCurrentOffset()) {
2634 Ftp::Gateway::ftpAuthRequired(HttpRequest
* request
, const char *realm
)
2636 ErrorState
err(ERR_CACHE_ACCESS_DENIED
, Http::scUnauthorized
, request
);
2637 HttpReply
*newrep
= err
.BuildHttpReply();
2638 #if HAVE_AUTH_MODULE_BASIC
2639 /* add Authenticate header */
2640 newrep
->header
.putAuth("Basic", realm
);
2646 Ftp::UrlWith2f(HttpRequest
* request
)
2650 if (request
->url
.getScheme() != AnyP::PROTO_FTP
) {
2651 static const SBuf nil
;
2655 if (request
->url
.path()[0] == '/') {
2656 newbuf
.append(request
->url
.path());
2657 request
->url
.path(newbuf
);
2658 } else if (!request
->url
.path().startsWith(newbuf
)) {
2659 newbuf
.append(request
->url
.path().substr(1));
2660 request
->url
.path(newbuf
);
2663 return request
->effectiveRequestUri();
2667 Ftp::Gateway::printfReplyBody(const char *fmt
, ...)
2670 va_start (args
, fmt
);
2671 static char buf
[4096];
2673 vsnprintf(buf
, 4096, fmt
, args
);
2674 writeReplyBody(buf
, strlen(buf
));
2679 * Call this when there is data from the origin server
2680 * which should be sent to either StoreEntry, or to ICAP...
2683 Ftp::Gateway::writeReplyBody(const char *dataToWrite
, size_t dataLength
)
2685 debugs(9, 5, HERE
<< "writing " << dataLength
<< " bytes to the reply");
2686 addVirginReplyBody(dataToWrite
, dataLength
);
2690 * A hack to ensure we do not double-complete on the forward entry.
2692 \todo Ftp::Gateway logic should probably be rewritten to avoid
2693 * double-completion or FwdState should be rewritten to allow it.
2696 Ftp::Gateway::completeForwarding()
2698 if (fwd
== NULL
|| flags
.completed_forwarding
) {
2699 debugs(9, 3, HERE
<< "completeForwarding avoids " <<
2700 "double-complete on FD " << ctrl
.conn
->fd
<< ", Data FD " << data
.conn
->fd
<<
2701 ", this " << this << ", fwd " << fwd
);
2705 flags
.completed_forwarding
= true;
2706 Client::completeForwarding();
2710 * Have we lost the FTP server control channel?
2712 \retval true The server control channel is available.
2713 \retval false The server control channel is not available.
2716 Ftp::Gateway::haveControlChannel(const char *caller_name
) const
2718 if (doneWithServer())
2721 /* doneWithServer() only checks BOTH channels are closed. */
2722 if (!Comm::IsConnOpen(ctrl
.conn
)) {
2723 debugs(9, DBG_IMPORTANT
, "WARNING! FTP Server Control channel is closed, but Data channel still active.");
2724 debugs(9, 2, caller_name
<< ": attempted on a closed FTP channel.");
2732 Ftp::Gateway::mayReadVirginReplyBody() const
2734 // TODO: Can we do what Ftp::Relay::mayReadVirginReplyBody() does instead?
2735 return !doneWithServer();
2739 Ftp::StartGateway(FwdState
*const fwdState
)
2741 return AsyncJob::Start(new Ftp::Gateway(fwdState
));