FtpGateway.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
3  *
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.
7  */
8 
9 /* DEBUG: section 09 File Transfer Protocol (FTP) */
10 
11 #include "squid.h"
12 #include "acl/FilledChecklist.h"
13 #include "base/PackableStream.h"
14 #include "clients/forward.h"
15 #include "clients/FtpClient.h"
16 #include "comm.h"
17 #include "comm/ConnOpener.h"
18 #include "comm/Read.h"
19 #include "comm/TcpAcceptor.h"
20 #include "CommCalls.h"
21 #include "compat/strtoll.h"
22 #include "errorpage.h"
23 #include "fd.h"
24 #include "fde.h"
25 #include "FwdState.h"
26 #include "html_quote.h"
27 #include "HttpHdrContRange.h"
28 #include "HttpHeader.h"
29 #include "HttpHeaderRange.h"
30 #include "HttpReply.h"
31 #include "ip/tools.h"
32 #include "MemBuf.h"
33 #include "mime.h"
34 #include "rfc1738.h"
35 #include "SquidConfig.h"
36 #include "SquidString.h"
37 #include "SquidTime.h"
38 #include "StatCounters.h"
39 #include "Store.h"
40 #include "tools.h"
41 #include "util.h"
42 #include "wordlist.h"
43 
44 #if USE_DELAY_POOLS
45 #include "DelayPools.h"
46 #include "MemObject.h"
47 #endif
48 
49 #include <cerrno>
50 
51 namespace Ftp
52 {
53 
54 struct GatewayFlags {
55 
56  /* passive mode */
59  bool pasv_only;
60  bool pasv_failed; // was FwdState::flags.ftp_pasv_failed
61 
62  /* authentication */
66 
67  /* other */
68  bool isdir;
72  bool tried_nlst;
74  bool dir_slash;
75  bool root_dir;
76  bool no_dotdot;
77  bool binary;
79  bool put;
80  bool put_mkdir;
82  bool listing;
84 };
85 
86 class Gateway;
87 typedef void (StateMethod)(Ftp::Gateway *);
88 
92 class Gateway : public Ftp::Client
93 {
95 
96 public:
97  Gateway(FwdState *);
98  virtual ~Gateway();
99  char user[MAX_URL];
102  char *reply_hdr;
107  int conn_att;
109  time_t mdtm;
110  int64_t theSize;
112  char *filepath;
113  char *dirpath;
114  int64_t restart_offset;
115  char *proxy_host;
116  size_t list_width;
119  char typecode;
121 
123 
124 public:
125  // these should all be private
126  virtual void start();
128  int restartable();
129  void appendSuccessHeader();
130  void hackShortcut(StateMethod *nextState);
131  void unhack();
132  void readStor();
133  void parseListing();
134  bool htmlifyListEntry(const char *line, PackableStream &);
135  void completedListing(void);
136 
139 
140  int checkAuth(const HttpHeader * req_hdr);
141  void checkUrlpath();
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; }
150 
151  virtual void dataChannelConnected(const CommConnectCbParams &io);
152  static PF ftpDataWrite;
153  virtual void timeout(const CommTimeoutCbParams &io);
155 
157  SBuf ftpRealm();
158  void loginFailed(void);
159 
160  virtual void haveParsedReplyHeaders();
161 
162  virtual bool haveControlChannel(const char *caller_name) const;
163 
164 protected:
165  virtual void handleControlReply();
166  virtual void dataClosed(const CommCloseCbParams &io);
167 
168 private:
169  virtual bool mayReadVirginReplyBody() const;
170  // BodyConsumer for HTTP: consume request body.
171  virtual void handleRequestBodyProducerAborted();
172 
173  void loginParser(const SBuf &login, bool escaped);
174 };
175 
176 } // namespace Ftp
177 
178 typedef Ftp::StateMethod FTPSM; // to avoid lots of non-changes
179 
181 
182 typedef struct {
183  char type;
184  int64_t size;
185  char *date;
186  char *name;
187  char *showname;
188  char *link;
189 } ftpListParts;
190 
191 #define CTRL_BUFLEN 16*1024
192 static char cbuf[CTRL_BUFLEN];
193 
194 /*
195  * State machine functions
196  * send == state transition
197  * read == wait for response, and select next state transition
198  * other == Transition logic
199  */
211 #if 0
212 static FTPSM ftpSendEPRT;
213 #endif
240 static FTPSM ftpFail;
243 
244 /************************************************
245 ** Debugs Levels used here **
246 *************************************************
247 0 CRITICAL Events
248 1 IMPORTANT Events
249  Protocol and Transmission failures.
250 2 FTP Protocol Chatter
251 3 Logic Flows
252 4 Data Parsing Flows
253 5 Data Dumps
254 7 ??
255 ************************************************/
256 
257 /************************************************
258 ** State Machine Description (excluding hacks) **
259 *************************************************
260 From To
261 ---------------------------------------
262 Welcome User
263 User Pass
264 Pass Type
265 Type TraverseDirectory / GetFile
266 TraverseDirectory Cwd / GetFile / ListDir
267 Cwd TraverseDirectory / Mkdir
268 GetFile Mdtm
269 Mdtm Size
270 Size Epsv
271 ListDir Epsv
272 Epsv FileOrList
273 FileOrList Rest / Retr / Nlst / List / Mkdir (PUT /xxx;type=d)
274 Rest Retr
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
283 Quit -
284 ************************************************/
285 
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 */
310  NULL, /* SENT_PWD */
311  NULL, /* SENT_CDUP*/
312  NULL, /* SENT_DATA_REQUEST */
313  NULL /* SENT_COMMAND */
314 };
315 
317 void
319 {
322  /* failed closes ctrl.conn and frees ftpState */
323 
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.
327  */
328 }
329 
331  AsyncJob("FtpStateData"),
332  Ftp::Client(fwdState),
333  password_url(0),
334  reply_hdr(NULL),
335  reply_hdr_state(0),
336  conn_att(0),
337  login_att(0),
338  mdtm(-1),
339  theSize(-1),
340  pathcomps(NULL),
341  filepath(NULL),
342  dirpath(NULL),
343  restart_offset(0),
344  proxy_host(NULL),
345  list_width(0),
346  old_filepath(NULL),
347  typecode('\0')
348 {
349  debugs(9, 3, entry->url());
350 
351  *user = 0;
352  *password = 0;
353  memset(&flags, 0, sizeof(flags));
354 
356  flags.pasv_supported = 1;
357 
358  flags.rest_supported = 1;
359 
361  flags.put = 1;
362 
363  initReadBuf();
364 }
365 
367 {
368  debugs(9, 3, entry->url());
369 
370  if (Comm::IsConnOpen(ctrl.conn)) {
371  debugs(9, DBG_IMPORTANT, "Internal bug: FTP Gateway left open " <<
372  "control channel " << ctrl.conn);
373  }
374 
375  if (reply_hdr) {
376  memFree(reply_hdr, MEM_8K_BUF);
377  reply_hdr = NULL;
378  }
379 
380  if (pathcomps)
381  wordlistDestroy(&pathcomps);
382 
383  cwd_message.clean();
384  xfree(old_filepath);
385  title_url.clean();
386  base_href.clean();
387  xfree(filepath);
388  xfree(dirpath);
389 }
390 
398 void
399 Ftp::Gateway::loginParser(const SBuf &login, bool escaped)
400 {
401  debugs(9, 4, "login=" << login << ", escaped=" << escaped);
402  debugs(9, 9, "IN : login=" << login << ", escaped=" << escaped << ", user=" << user << ", password=" << password);
403 
404  if (login.isEmpty())
405  return;
406 
407  const SBuf::size_type colonPos = login.find(':');
408 
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.
411  */
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);
415  user[upto]='\0';
416  debugs(9, 9, "found user=" << userName << ' ' <<
417  (upto != userName.length() ? ", truncated-to=" : ", length=") << upto <<
418  ", escaped=" << escaped);
419  if (escaped)
420  rfc1738_unescape(user);
421  debugs(9, 9, "found user=" << user << " (" << strlen(user) << ") unescaped.");
422  }
423 
424  /* If there was a password part.
425  * For 0-length password clobber what we have already, this means explicitly none
426  */
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);
430  password[upto]='\0';
431  debugs(9, 9, "found password=" << pass << " " <<
432  (upto != pass.length() ? ", truncated-to=" : ", length=") << upto <<
433  ", escaped=" << escaped);
434  if (escaped) {
435  rfc1738_unescape(password);
436  password_url = 1;
437  }
438  debugs(9, 9, "found password=" << password << " (" << strlen(password) << ") unescaped.");
439  }
440 
441  debugs(9, 9, "OUT: login=" << login << ", escaped=" << escaped << ", user=" << user << ", password=" << password);
442 }
443 
444 void
446 {
447  if (!Comm::IsConnOpen(ctrl.conn)) {
448  debugs(9, 5, "The control connection to the remote end is closed");
449  return;
450  }
451 
452  assert(!Comm::IsConnOpen(data.conn));
453 
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));
458  const char *note = entry->url();
459 
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);
465  return;
466  }
467  debugs(9, 3, HERE << "Unconnected data socket created on " << conn);
468  }
469 
470  conn->tos = ctrl.conn->tos;
471  conn->nfmark = ctrl.conn->nfmark;
472 
474  AsyncJob::Start(new Comm::TcpAcceptor(conn, note, sub));
475 
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();
479 }
480 
481 void
483 {
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");
488 
489  // cancel the data connection setup.
490  if (data.opener != NULL) {
491  data.opener->cancel("timeout");
492  data.opener = NULL;
493  }
494  data.close();
495  }
496 
498 }
499 
500 static const char *Month[] = {
501  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
502  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
503 };
504 
505 static int
506 is_month(const char *buf)
507 {
508  int i;
509 
510  for (i = 0; i < 12; ++i)
511  if (!strcasecmp(buf, Month[i]))
512  return 1;
513 
514  return 0;
515 }
516 
517 static void
519 {
520  safe_free((*parts)->date);
521  safe_free((*parts)->name);
522  safe_free((*parts)->showname);
523  safe_free((*parts)->link);
524  safe_free(*parts);
525 }
526 
527 #define MAX_TOKENS 64
528 
529 static ftpListParts *
530 ftpListParseParts(const char *buf, struct Ftp::GatewayFlags flags)
531 {
532  ftpListParts *p = NULL;
533  char *t = NULL;
534  struct FtpLineToken {
535  char *token = nullptr;
536  size_t pos = 0;
537  } tokens[MAX_TOKENS];
538  int i;
539  int n_tokens;
540  static char tbuf[128];
541  char *xbuf = NULL;
542  static int scan_ftp_initialized = 0;
543  static regex_t scan_ftp_integer;
544  static regex_t scan_ftp_time;
545  static regex_t scan_ftp_dostime;
546  static regex_t scan_ftp_dosdate;
547 
548  if (!scan_ftp_initialized) {
549  scan_ftp_initialized = 1;
550  regcomp(&scan_ftp_integer, "^[0123456789]+$", REG_EXTENDED | REG_NOSUB);
551  regcomp(&scan_ftp_time, "^[0123456789:]+$", REG_EXTENDED | REG_NOSUB);
552  regcomp(&scan_ftp_dosdate, "^[0123456789]+-[0123456789]+-[0123456789]+$", REG_EXTENDED | REG_NOSUB);
553  regcomp(&scan_ftp_dostime, "^[0123456789]+:[0123456789]+[AP]M$", REG_EXTENDED | REG_NOSUB | REG_ICASE);
554  }
555 
556  if (buf == NULL)
557  return NULL;
558 
559  if (*buf == '\0')
560  return NULL;
561 
562  p = (ftpListParts *)xcalloc(1, sizeof(ftpListParts));
563 
564  n_tokens = 0;
565 
566  xbuf = xstrdup(buf);
567 
568  if (flags.tried_nlst) {
569  /* Machine readable format, one name per line */
570  p->name = xbuf;
571  p->type = '\0';
572  return p;
573  }
574 
575  for (t = strtok(xbuf, w_space); t && n_tokens < MAX_TOKENS; t = strtok(NULL, w_space)) {
576  tokens[n_tokens].token = xstrdup(t);
577  tokens[n_tokens].pos = t - xbuf;
578  ++n_tokens;
579  }
580 
581  xfree(xbuf);
582 
583  /* locate the Month field */
584  for (i = 3; i < n_tokens - 2; ++i) {
585  const auto size = tokens[i - 1].token;
586  char *month = tokens[i].token;
587  char *day = tokens[i + 1].token;
588  char *year = tokens[i + 2].token;
589 
590  if (!is_month(month))
591  continue;
592 
593  if (regexec(&scan_ftp_integer, size, 0, NULL, 0) != 0)
594  continue;
595 
596  if (regexec(&scan_ftp_integer, day, 0, NULL, 0) != 0)
597  continue;
598 
599  if (regexec(&scan_ftp_time, year, 0, NULL, 0) != 0) /* Yr | hh:mm */
600  continue;
601 
602  const auto *copyFrom = buf + tokens[i].pos;
603 
604  // "MMM DD [ YYYY|hh:mm]" with at most two spaces between DD and YYYY
605  auto dateSize = snprintf(tbuf, sizeof(tbuf), "%s %2s %5s", month, day, year);
606  bool isTypeA = (dateSize == 12) && (strncmp(copyFrom, tbuf, dateSize) == 0);
607 
608  // "MMM DD [YYYY|hh:mm]" with one space between DD and YYYY
609  dateSize = snprintf(tbuf, sizeof(tbuf), "%s %2s %-5s", month, day, year);
610  bool isTypeB = (dateSize == 12 || dateSize == 11) && (strncmp(copyFrom, tbuf, dateSize) == 0);
611 
612  // TODO: replace isTypeA and isTypeB with a regex.
613  if (isTypeA || isTypeB) {
614  p->type = *tokens[0].token;
615  p->size = strtoll(size, NULL, 10);
616  const auto finalDateSize = snprintf(tbuf, sizeof(tbuf), "%s %2s %5s", month, day, year);
617  assert(finalDateSize >= 0);
618  p->date = xstrdup(tbuf);
619 
620  // point after tokens[i+2] :
621  copyFrom = buf + tokens[i + 2].pos + strlen(tokens[i + 2].token);
622  if (flags.skip_whitespace) {
623  while (strchr(w_space, *copyFrom))
624  ++copyFrom;
625  } else {
626  /* Handle the following four formats:
627  * "MMM DD YYYY Name"
628  * "MMM DD YYYYName"
629  * "MMM DD YYYY Name"
630  * "MMM DD YYYY Name"
631  * Assuming a single space between date and filename
632  * suggested by: Nathan.Bailey@cc.monash.edu.au and
633  * Mike Battersby <mike@starbug.bofh.asn.au> */
634  if (strchr(w_space, *copyFrom))
635  ++copyFrom;
636  }
637 
638  p->name = xstrdup(copyFrom);
639 
640  if (p->type == 'l' && (t = strstr(p->name, " -> "))) {
641  *t = '\0';
642  p->link = xstrdup(t + 4);
643  }
644 
645  goto found;
646  }
647 
648  break;
649  }
650 
651  /* try it as a DOS listing, 04-05-70 09:33PM ... */
652  if (n_tokens > 3 &&
653  regexec(&scan_ftp_dosdate, tokens[0].token, 0, NULL, 0) == 0 &&
654  regexec(&scan_ftp_dostime, tokens[1].token, 0, NULL, 0) == 0) {
655  if (!strcasecmp(tokens[2].token, "<dir>")) {
656  p->type = 'd';
657  } else {
658  p->type = '-';
659  p->size = strtoll(tokens[2].token, NULL, 10);
660  }
661 
662  snprintf(tbuf, sizeof(tbuf), "%s %s", tokens[0].token, tokens[1].token);
663  p->date = xstrdup(tbuf);
664 
665  if (p->type == 'd') {
666  // Directory.. name begins with first printable after <dir>
667  // Because of the "n_tokens > 3", the next printable after <dir>
668  // is stored at token[3]. No need for more checks here.
669  } else {
670  // A file. Name begins after size, with a space in between.
671  // Also a space should exist before size.
672  // But there is not needed to be very strict with spaces.
673  // The name is stored at token[3], take it from here.
674  }
675 
676  p->name = xstrdup(tokens[3].token);
677  goto found;
678  }
679 
680  /* Try EPLF format; carson@lehman.com */
681  if (buf[0] == '+') {
682  const char *ct = buf + 1;
683  p->type = 0;
684 
685  while (ct && *ct) {
686  time_t tm;
687  int l = strcspn(ct, ",");
688  char *tmp;
689 
690  if (l < 1)
691  goto blank;
692 
693  switch (*ct) {
694 
695  case '\t':
696  p->name = xstrndup(ct + 1, l + 1);
697  break;
698 
699  case 's':
700  p->size = atoi(ct + 1);
701  break;
702 
703  case 'm':
704  tm = (time_t) strtol(ct + 1, &tmp, 0);
705 
706  if (tmp != ct + 1)
707  break; /* not a valid integer */
708 
709  p->date = xstrdup(ctime(&tm));
710 
711  *(strstr(p->date, "\n")) = '\0';
712 
713  break;
714 
715  case '/':
716  p->type = 'd';
717 
718  break;
719 
720  case 'r':
721  p->type = '-';
722 
723  break;
724 
725  case 'i':
726  break;
727 
728  default:
729  break;
730  }
731 
732 blank:
733  ct = strstr(ct, ",");
734 
735  if (ct) {
736  ++ct;
737  }
738  }
739 
740  if (p->type == 0) {
741  p->type = '-';
742  }
743 
744  if (p->name)
745  goto found;
746  else
747  safe_free(p->date);
748  }
749 
750 found:
751 
752  for (i = 0; i < n_tokens; ++i)
753  xfree(tokens[i].token);
754 
755  if (!p->name)
756  ftpListPartsFree(&p); /* cleanup */
757 
758  return p;
759 }
760 
761 bool
763 {
764  debugs(9, 7, "line={" << line << "}");
765 
766  if (strlen(line) > 1024) {
767  html << "<tr><td colspan=\"5\">" << line << "</td></tr>\n";
768  return true;
769  }
770 
771  SBuf prefix;
772  if (flags.dir_slash && dirpath && typecode != 'D') {
773  prefix.append(rfc1738_escape_part(dirpath));
774  prefix.append("/", 1);
775  }
776 
777  ftpListParts *parts = ftpListParseParts(line, flags);
778  if (!parts) {
779  html << "<tr class=\"entry\"><td colspan=\"5\">" << line << "</td></tr>\n";
780 
781  const char *p;
782  for (p = line; *p && xisspace(*p); ++p);
783  if (*p && !xisspace(*p))
784  flags.listformat_unknown = 1;
785 
786  return true;
787  }
788 
789  if (!strcmp(parts->name, ".") || !strcmp(parts->name, "..")) {
790  ftpListPartsFree(&parts);
791  return false;
792  }
793 
794  parts->size += 1023;
795  parts->size >>= 10;
796  parts->showname = xstrdup(parts->name);
797 
798  /* {icon} {text} . . . {date}{size}{chdir}{view}{download}{link}\n */
799  SBuf href(prefix);
800  href.append(rfc1738_escape_part(parts->name));
801 
802  SBuf text(parts->showname);
803 
804  SBuf icon, size, chdir, link;
805  switch (parts->type) {
806 
807  case 'd':
808  icon.appendf("<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
809  mimeGetIconURL("internal-dir"),
810  "[DIR]");
811  href.append("/", 1); /* margin is allocated above */
812  break;
813 
814  case 'l':
815  icon.appendf("<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
816  mimeGetIconURL("internal-link"),
817  "[LINK]");
818  /* sometimes there is an 'l' flag, but no "->" link */
819 
820  if (parts->link) {
821  SBuf link2(html_quote(rfc1738_escape(parts->link)));
822  link.appendf(" -&gt; <a href=\"%s" SQUIDSBUFPH "\">%s</a>",
823  link2[0] != '/' ? prefix.c_str() : "", SQUIDSBUFPRINT(link2),
824  html_quote(parts->link));
825  }
826 
827  break;
828 
829  case '\0':
830  icon.appendf("<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
831  mimeGetIconURL(parts->name),
832  "[UNKNOWN]");
833  chdir.appendf("<a href=\"%s/;type=d\"><img border=\"0\" src=\"%s\" "
834  "alt=\"[DIR]\"></a>",
835  rfc1738_escape_part(parts->name),
836  mimeGetIconURL("internal-dir"));
837  break;
838 
839  case '-':
840 
841  default:
842  icon.appendf("<img border=\"0\" src=\"%s\" alt=\"%-6s\">",
843  mimeGetIconURL(parts->name),
844  "[FILE]");
845  size.appendf(" %6" PRId64 "k", parts->size);
846  break;
847  }
848 
849  SBuf view, download;
850  if (parts->type != 'd') {
851  if (mimeGetViewOption(parts->name)) {
852  view.appendf("<a href=\"" SQUIDSBUFPH ";type=a\"><img border=\"0\" src=\"%s\" "
853  "alt=\"[VIEW]\"></a>",
854  SQUIDSBUFPRINT(href), mimeGetIconURL("internal-view"));
855  }
856 
857  if (mimeGetDownloadOption(parts->name)) {
858  download.appendf("<a href=\"" SQUIDSBUFPH ";type=i\"><img border=\"0\" src=\"%s\" "
859  "alt=\"[DOWNLOAD]\"></a>",
860  SQUIDSBUFPRINT(href), mimeGetIconURL("internal-download"));
861  }
862  }
863 
864  /* construct the table row from parts. */
865  html << "<tr class=\"entry\">"
866  "<td class=\"icon\"><a href=\"" << href << "\">" << icon << "</a></td>"
867  "<td class=\"filename\"><a href=\"" << href << "\">" << html_quote(text.c_str()) << "</a></td>"
868  "<td class=\"date\">" << parts->date << "</td>"
869  "<td class=\"size\">" << size << "</td>"
870  "<td class=\"actions\">" << chdir << view << download << link << "</td>"
871  "</tr>\n";
872 
873  ftpListPartsFree(&parts);
874  return true;
875 }
876 
877 void
879 {
880  char *buf = data.readBuf->content();
881  char *sbuf; /* NULL-terminated copy of termedBuf */
882  char *end;
883  char *line;
884  char *s;
885  size_t linelen;
886  size_t usable;
887  size_t len = data.readBuf->contentSize();
888 
889  if (!len) {
890  debugs(9, 3, HERE << "no content to parse for " << entry->url() );
891  return;
892  }
893 
894  /*
895  * We need a NULL-terminated buffer for scanning, ick
896  */
897  sbuf = (char *)xmalloc(len + 1);
898  xstrncpy(sbuf, buf, len + 1);
899  end = sbuf + len - 1;
900 
901  while (*end != '\r' && *end != '\n' && end > sbuf)
902  --end;
903 
904  usable = end - sbuf;
905 
906  debugs(9, 3, HERE << "usable = " << usable << " of " << len << " bytes.");
907 
908  if (usable == 0) {
909  if (buf[0] == '\0' && len == 1) {
910  debugs(9, 3, HERE << "NIL ends data from " << entry->url() << " transfer problem?");
911  data.readBuf->consume(len);
912  } else {
913  debugs(9, 3, HERE << "didn't find end for " << entry->url());
914  debugs(9, 3, HERE << "buffer remains (" << len << " bytes) '" << rfc1738_do_escape(buf,0) << "'");
915  }
916  xfree(sbuf);
917  return;
918  }
919 
920  debugs(9, 3, HERE << (unsigned long int)len << " bytes to play with");
921 
922  line = (char *)memAllocate(MEM_4K_BUF);
923  ++end;
924  s = sbuf;
925  s += strspn(s, crlf);
926 
927  for (; s < end; s += strcspn(s, crlf), s += strspn(s, crlf)) {
928  debugs(9, 7, HERE << "s = {" << s << "}");
929  linelen = strcspn(s, crlf) + 1;
930 
931  if (linelen < 2)
932  break;
933 
934  if (linelen > 4096)
935  linelen = 4096;
936 
937  xstrncpy(line, s, linelen);
938 
939  debugs(9, 7, HERE << "{" << line << "}");
940 
941  if (!strncmp(line, "total", 5))
942  continue;
943 
944  MemBuf htmlPage;
945  htmlPage.init();
946  PackableStream html(htmlPage);
947 
948  if (htmlifyListEntry(line, html)) {
949  html.flush();
950  debugs(9, 7, "listing append: t = {" << htmlPage.contentSize() << ", '" << htmlPage.content() << "'}");
951  listing.append(htmlPage.content(), htmlPage.contentSize());
952  }
953  }
954 
955  debugs(9, 7, HERE << "Done.");
956  data.readBuf->consume(usable);
957  memFree(line, MEM_4K_BUF);
958  xfree(sbuf);
959 }
960 
961 void
963 {
964  debugs(9, 3, status());
965 
966  if (request->method == Http::METHOD_HEAD && (flags.isdir || theSize != -1)) {
967  serverComplete();
968  return;
969  }
970 
971  /* Directory listings are special. They write ther own headers via the error objects */
972  if (!flags.http_header_sent && data.readBuf->contentSize() >= 0 && !flags.isdir)
973  appendSuccessHeader();
974 
975  if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
976  /*
977  * probably was aborted because content length exceeds one
978  * of the maximum size limits.
979  */
980  abortAll("entry aborted after calling appendSuccessHeader()");
981  return;
982  }
983 
984 #if USE_ADAPTATION
985 
986  if (adaptationAccessCheckPending) {
987  debugs(9, 3, "returning from Ftp::Gateway::processReplyBody due to adaptationAccessCheckPending");
988  return;
989  }
990 
991 #endif
992 
993  if (flags.isdir) {
994  if (!flags.listing) {
995  flags.listing = 1;
996  listing.reset();
997  }
998  parseListing();
999  maybeReadVirginBody();
1000  return;
1001  } else if (const int csize = data.readBuf->contentSize()) {
1002  writeReplyBody(data.readBuf->content(), csize);
1003  debugs(9, 5, HERE << "consuming " << csize << " bytes of readBuf");
1004  data.readBuf->consume(csize);
1005  }
1006 
1007  entry->flush();
1008 
1009  maybeReadVirginBody();
1010 }
1011 
1028 int
1030 {
1031  /* default username */
1032  xstrncpy(user, "anonymous", MAX_URL);
1033 
1034 #if HAVE_AUTH_MODULE_BASIC
1035  /* Check HTTP Authorization: headers (better than defaults, but less than URL) */
1036  const auto auth(req_hdr->getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
1037  if (!auth.isEmpty()) {
1038  flags.authenticated = 1;
1039  loginParser(auth, false);
1040  }
1041  /* we fail with authorization-required error later IFF the FTP server requests it */
1042 #endif
1043 
1044  /* Test URL login syntax. Overrides any headers received. */
1045  loginParser(request->url.userInfo(), true);
1046 
1047  /* name is missing. that's fatal. */
1048  if (!user[0])
1049  fatal("FTP login parsing destroyed username info");
1050 
1051  /* name + password == success */
1052  if (password[0])
1053  return 1;
1054 
1055  /* Setup default FTP password settings */
1056  /* this has to be done last so that we can have a no-password case above. */
1057  if (!password[0]) {
1058  if (strcmp(user, "anonymous") == 0 && !flags.tried_auth_anonymous) {
1059  xstrncpy(password, Config.Ftp.anon_user, MAX_URL);
1060  flags.tried_auth_anonymous=1;
1061  return 1;
1062  } else if (!flags.tried_auth_nopass) {
1063  xstrncpy(password, null_string, MAX_URL);
1064  flags.tried_auth_nopass=1;
1065  return 1;
1066  }
1067  }
1068 
1069  return 0; /* different username */
1070 }
1071 
1072 void
1074 {
1075  static SBuf str_type_eq("type=");
1076  auto t = request->url.path().rfind(';');
1077 
1078  if (t != SBuf::npos) {
1079  auto filenameEnd = t-1;
1080  if (request->url.path().substr(++t).cmp(str_type_eq, str_type_eq.length()) == 0) {
1081  t += str_type_eq.length();
1082  typecode = (char)xtoupper(request->url.path()[t]);
1083  request->url.path(request->url.path().substr(0,filenameEnd));
1084  }
1085  }
1086 
1087  int l = request->url.path().length();
1088  /* check for null path */
1089 
1090  if (!l) {
1091  flags.isdir = 1;
1092  flags.root_dir = 1;
1093  flags.need_base_href = 1; /* Work around broken browsers */
1094  } else if (!request->url.path().cmp("/%2f/")) {
1095  /* UNIX root directory */
1096  flags.isdir = 1;
1097  flags.root_dir = 1;
1098  } else if ((l >= 1) && (request->url.path()[l-1] == '/')) {
1099  /* Directory URL, ending in / */
1100  flags.isdir = 1;
1101 
1102  if (l == 1)
1103  flags.root_dir = 1;
1104  } else {
1105  flags.dir_slash = 1;
1106  }
1107 }
1108 
1109 void
1111 {
1112  title_url = "ftp://";
1113 
1114  if (strcmp(user, "anonymous")) {
1115  title_url.append(user);
1116  title_url.append("@");
1117  }
1118 
1119  SBuf authority = request->url.authority(request->url.getScheme() != AnyP::PROTO_FTP);
1120 
1121  title_url.append(authority.rawContent(), authority.length());
1122  title_url.append(request->url.path().rawContent(), request->url.path().length());
1123 
1124  base_href = "ftp://";
1125 
1126  if (strcmp(user, "anonymous") != 0) {
1127  base_href.append(rfc1738_escape_part(user));
1128 
1129  if (password_url) {
1130  base_href.append(":");
1131  base_href.append(rfc1738_escape_part(password));
1132  }
1133 
1134  base_href.append("@");
1135  }
1136 
1137  base_href.append(authority.rawContent(), authority.length());
1138  base_href.append(request->url.path().rawContent(), request->url.path().length());
1139  base_href.append("/");
1140 }
1141 
1142 void
1144 {
1145  if (!checkAuth(&request->header)) {
1146  /* create appropriate reply */
1147  SBuf realm(ftpRealm()); // local copy so SBuf will not disappear too early
1148  const auto reply = ftpAuthRequired(request.getRaw(), realm, fwd->al);
1149  entry->replaceHttpReply(reply);
1150  serverComplete();
1151  return;
1152  }
1153 
1154  checkUrlpath();
1155  buildTitleUrl();
1156  debugs(9, 5, "FD " << (ctrl.conn ? ctrl.conn->fd : -1) << " : host=" << request->url.host() <<
1157  ", path=" << request->url.path() << ", user=" << user << ", passwd=" << password);
1158  state = BEGIN;
1160 }
1161 
1162 /* ====================================================================== */
1163 
1164 void
1166 {
1168  if (ctrl.message == NULL)
1169  return; // didn't get complete reply yet
1170 
1171  /* Copy the message except for the last line to cwd_message to be
1172  * printed in error messages.
1173  */
1174  for (wordlist *w = ctrl.message; w && w->next; w = w->next) {
1175  cwd_message.append('\n');
1176  cwd_message.append(w->key);
1177  }
1178 
1179  FTP_SM_FUNCS[state] (this);
1180 }
1181 
1182 /* ====================================================================== */
1183 
1184 static void
1186 {
1187  int code = ftpState->ctrl.replycode;
1188  debugs(9, 3, HERE);
1189 
1190  if (ftpState->flags.pasv_only)
1191  ++ ftpState->login_att;
1192 
1193  if (code == 220) {
1194  if (ftpState->ctrl.message) {
1195  if (strstr(ftpState->ctrl.message->key, "NetWare"))
1196  ftpState->flags.skip_whitespace = 1;
1197  }
1198 
1199  ftpSendUser(ftpState);
1200  } else if (code == 120) {
1201  if (NULL != ftpState->ctrl.message)
1202  debugs(9, DBG_IMPORTANT, "FTP server is busy: " << ftpState->ctrl.message->key);
1203 
1204  return;
1205  } else {
1206  ftpFail(ftpState);
1207  }
1208 }
1209 
1215 void
1217 {
1218  ErrorState *err = NULL;
1219 
1220  if ((state == SENT_USER || state == SENT_PASS) && ctrl.replycode >= 400) {
1221  if (ctrl.replycode == 421 || ctrl.replycode == 426) {
1222  // 421/426 - Service Overload - retry permitted.
1223  err = new ErrorState(ERR_FTP_UNAVAILABLE, Http::scServiceUnavailable, fwd->request, fwd->al);
1224  } else if (ctrl.replycode >= 430 && ctrl.replycode <= 439) {
1225  // 43x - Invalid or Credential Error - retry challenge required.
1226  err = new ErrorState(ERR_FTP_FORBIDDEN, Http::scUnauthorized, fwd->request, fwd->al);
1227  } else if (ctrl.replycode >= 530 && ctrl.replycode <= 539) {
1228  // 53x - Credentials Missing - retry challenge required
1229  if (password_url) // but they were in the URI! major fail.
1230  err = new ErrorState(ERR_FTP_FORBIDDEN, Http::scForbidden, fwd->request, fwd->al);
1231  else
1232  err = new ErrorState(ERR_FTP_FORBIDDEN, Http::scUnauthorized, fwd->request, fwd->al);
1233  }
1234  }
1235 
1236  if (!err) {
1237  ftpFail(this);
1238  return;
1239  }
1240 
1241  failed(ERR_NONE, ctrl.replycode, err);
1242  // any other problems are general falures.
1243 
1244  HttpReply *newrep = err->BuildHttpReply();
1245  delete err;
1246 
1247 #if HAVE_AUTH_MODULE_BASIC
1248  /* add Authenticate header */
1249  // XXX: performance regression. c_str() may reallocate
1250  SBuf realm(ftpRealm()); // local copy so SBuf will not disappear too early
1251  newrep->header.putAuth("Basic", realm.c_str());
1252 #endif
1253 
1254  // add it to the store entry for response....
1255  entry->replaceHttpReply(newrep);
1256  serverComplete();
1257 }
1258 
1259 SBuf
1261 {
1262  SBuf realm;
1263 
1264  /* This request is not fully authenticated */
1265  realm.appendf("FTP %s ", user);
1266  if (!request)
1267  realm.append("unknown", 7);
1268  else {
1269  realm.append(request->url.host());
1270  if (request->url.port() != 21)
1271  realm.appendf(" port %d", request->url.port());
1272  }
1273  return realm;
1274 }
1275 
1276 static void
1278 {
1279  /* check the server control channel is still available */
1280  if (!ftpState || !ftpState->haveControlChannel("ftpSendUser"))
1281  return;
1282 
1283  if (ftpState->proxy_host != NULL)
1284  snprintf(cbuf, CTRL_BUFLEN, "USER %s@%s\r\n", ftpState->user, ftpState->request->url.host());
1285  else
1286  snprintf(cbuf, CTRL_BUFLEN, "USER %s\r\n", ftpState->user);
1287 
1288  ftpState->writeCommand(cbuf);
1289 
1290  ftpState->state = Ftp::Client::SENT_USER;
1291 }
1292 
1293 static void
1295 {
1296  int code = ftpState->ctrl.replycode;
1297  debugs(9, 3, HERE);
1298 
1299  if (code == 230) {
1300  ftpReadPass(ftpState);
1301  } else if (code == 331) {
1302  ftpSendPass(ftpState);
1303  } else {
1304  ftpState->loginFailed();
1305  }
1306 }
1307 
1308 static void
1310 {
1311  /* check the server control channel is still available */
1312  if (!ftpState || !ftpState->haveControlChannel("ftpSendPass"))
1313  return;
1314 
1315  snprintf(cbuf, CTRL_BUFLEN, "PASS %s\r\n", ftpState->password);
1316  ftpState->writeCommand(cbuf);
1317  ftpState->state = Ftp::Client::SENT_PASS;
1318 }
1319 
1320 static void
1322 {
1323  int code = ftpState->ctrl.replycode;
1324  debugs(9, 3, HERE << "code=" << code);
1325 
1326  if (code == 230) {
1327  ftpSendType(ftpState);
1328  } else {
1329  ftpState->loginFailed();
1330  }
1331 }
1332 
1333 static void
1335 {
1336  /* check the server control channel is still available */
1337  if (!ftpState || !ftpState->haveControlChannel("ftpSendType"))
1338  return;
1339 
1340  /*
1341  * Ref section 3.2.2 of RFC 1738
1342  */
1343  char mode = ftpState->typecode;
1344 
1345  switch (mode) {
1346 
1347  case 'D':
1348  mode = 'A';
1349  break;
1350 
1351  case 'A':
1352 
1353  case 'I':
1354  break;
1355 
1356  default:
1357 
1358  if (ftpState->flags.isdir) {
1359  mode = 'A';
1360  } else {
1361  auto t = ftpState->request->url.path().rfind('/');
1362  // XXX: performance regression, c_str() may reallocate
1363  SBuf filename = ftpState->request->url.path().substr(t != SBuf::npos ? t + 1 : 0);
1364  mode = mimeGetTransferMode(filename.c_str());
1365  }
1366 
1367  break;
1368  }
1369 
1370  if (mode == 'I')
1371  ftpState->flags.binary = 1;
1372  else
1373  ftpState->flags.binary = 0;
1374 
1375  snprintf(cbuf, CTRL_BUFLEN, "TYPE %c\r\n", mode);
1376 
1377  ftpState->writeCommand(cbuf);
1378 
1379  ftpState->state = Ftp::Client::SENT_TYPE;
1380 }
1381 
1382 static void
1384 {
1385  int code = ftpState->ctrl.replycode;
1386  char *path;
1387  char *d, *p;
1388  debugs(9, 3, HERE << "code=" << code);
1389 
1390  if (code == 200) {
1391  p = path = SBufToCstring(ftpState->request->url.path());
1392 
1393  if (*p == '/')
1394  ++p;
1395 
1396  while (*p) {
1397  d = p;
1398  p += strcspn(p, "/");
1399 
1400  if (*p) {
1401  *p = '\0';
1402  ++p;
1403  }
1404 
1405  rfc1738_unescape(d);
1406 
1407  if (*d)
1408  wordlistAdd(&ftpState->pathcomps, d);
1409  }
1410 
1411  xfree(path);
1412 
1413  if (ftpState->pathcomps)
1414  ftpTraverseDirectory(ftpState);
1415  else
1416  ftpListDir(ftpState);
1417  } else {
1418  ftpFail(ftpState);
1419  }
1420 }
1421 
1422 static void
1424 {
1425  debugs(9, 4, HERE << (ftpState->filepath ? ftpState->filepath : "<NULL>"));
1426 
1427  safe_free(ftpState->dirpath);
1428  ftpState->dirpath = ftpState->filepath;
1429  ftpState->filepath = NULL;
1430 
1431  /* Done? */
1432 
1433  if (ftpState->pathcomps == NULL) {
1434  debugs(9, 3, HERE << "the final component was a directory");
1435  ftpListDir(ftpState);
1436  return;
1437  }
1438 
1439  /* Go to next path component */
1440  ftpState->filepath = wordlistChopHead(& ftpState->pathcomps);
1441 
1442  /* Check if we are to CWD or RETR */
1443  if (ftpState->pathcomps != NULL || ftpState->flags.isdir) {
1444  ftpSendCwd(ftpState);
1445  } else {
1446  debugs(9, 3, HERE << "final component is probably a file");
1447  ftpGetFile(ftpState);
1448  return;
1449  }
1450 }
1451 
1452 static void
1454 {
1455  char *path = NULL;
1456 
1457  /* check the server control channel is still available */
1458  if (!ftpState || !ftpState->haveControlChannel("ftpSendCwd"))
1459  return;
1460 
1461  debugs(9, 3, HERE);
1462 
1463  path = ftpState->filepath;
1464 
1465  if (!strcmp(path, "..") || !strcmp(path, "/")) {
1466  ftpState->flags.no_dotdot = 1;
1467  } else {
1468  ftpState->flags.no_dotdot = 0;
1469  }
1470 
1471  snprintf(cbuf, CTRL_BUFLEN, "CWD %s\r\n", path);
1472 
1473  ftpState->writeCommand(cbuf);
1474 
1475  ftpState->state = Ftp::Client::SENT_CWD;
1476 }
1477 
1478 static void
1480 {
1481  int code = ftpState->ctrl.replycode;
1482  debugs(9, 3, HERE);
1483 
1484  if (code >= 200 && code < 300) {
1485  /* CWD OK */
1486  ftpState->unhack();
1487 
1488  /* Reset cwd_message to only include the last message */
1489  ftpState->cwd_message.reset("");
1490  for (wordlist *w = ftpState->ctrl.message; w; w = w->next) {
1491  ftpState->cwd_message.append('\n');
1492  ftpState->cwd_message.append(w->key);
1493  }
1494  ftpState->ctrl.message = NULL;
1495 
1496  /* Continue to traverse the path */
1497  ftpTraverseDirectory(ftpState);
1498  } else {
1499  /* CWD FAILED */
1500 
1501  if (!ftpState->flags.put)
1502  ftpFail(ftpState);
1503  else
1504  ftpSendMkdir(ftpState);
1505  }
1506 }
1507 
1508 static void
1510 {
1511  char *path = NULL;
1512 
1513  /* check the server control channel is still available */
1514  if (!ftpState || !ftpState->haveControlChannel("ftpSendMkdir"))
1515  return;
1516 
1517  path = ftpState->filepath;
1518  debugs(9, 3, HERE << "with path=" << path);
1519  snprintf(cbuf, CTRL_BUFLEN, "MKD %s\r\n", path);
1520  ftpState->writeCommand(cbuf);
1521  ftpState->state = Ftp::Client::SENT_MKDIR;
1522 }
1523 
1524 static void
1526 {
1527  char *path = ftpState->filepath;
1528  int code = ftpState->ctrl.replycode;
1529 
1530  debugs(9, 3, HERE << "path " << path << ", code " << code);
1531 
1532  if (code == 257) { /* success */
1533  ftpSendCwd(ftpState);
1534  } else if (code == 550) { /* dir exists */
1535 
1536  if (ftpState->flags.put_mkdir) {
1537  ftpState->flags.put_mkdir = 1;
1538  ftpSendCwd(ftpState);
1539  } else
1540  ftpSendReply(ftpState);
1541  } else
1542  ftpSendReply(ftpState);
1543 }
1544 
1545 static void
1547 {
1548  assert(*ftpState->filepath != '\0');
1549  ftpState->flags.isdir = 0;
1550  ftpSendMdtm(ftpState);
1551 }
1552 
1553 static void
1555 {
1556  if (ftpState->flags.dir_slash) {
1557  debugs(9, 3, HERE << "Directory path did not end in /");
1558  ftpState->title_url.append("/");
1559  ftpState->flags.isdir = 1;
1560  }
1561 
1562  ftpSendPassive(ftpState);
1563 }
1564 
1565 static void
1567 {
1568  /* check the server control channel is still available */
1569  if (!ftpState || !ftpState->haveControlChannel("ftpSendMdtm"))
1570  return;
1571 
1572  assert(*ftpState->filepath != '\0');
1573  snprintf(cbuf, CTRL_BUFLEN, "MDTM %s\r\n", ftpState->filepath);
1574  ftpState->writeCommand(cbuf);
1575  ftpState->state = Ftp::Client::SENT_MDTM;
1576 }
1577 
1578 static void
1580 {
1581  int code = ftpState->ctrl.replycode;
1582  debugs(9, 3, HERE);
1583 
1584  if (code == 213) {
1585  ftpState->mdtm = parse_iso3307_time(ftpState->ctrl.last_reply);
1586  ftpState->unhack();
1587  } else if (code < 0) {
1588  ftpFail(ftpState);
1589  return;
1590  }
1591 
1592  ftpSendSize(ftpState);
1593 }
1594 
1595 static void
1597 {
1598  /* check the server control channel is still available */
1599  if (!ftpState || !ftpState->haveControlChannel("ftpSendSize"))
1600  return;
1601 
1602  /* Only send SIZE for binary transfers. The returned size
1603  * is useless on ASCII transfers */
1604 
1605  if (ftpState->flags.binary) {
1606  assert(ftpState->filepath != NULL);
1607  assert(*ftpState->filepath != '\0');
1608  snprintf(cbuf, CTRL_BUFLEN, "SIZE %s\r\n", ftpState->filepath);
1609  ftpState->writeCommand(cbuf);
1610  ftpState->state = Ftp::Client::SENT_SIZE;
1611  } else
1612  /* Skip to next state no non-binary transfers */
1613  ftpSendPassive(ftpState);
1614 }
1615 
1616 static void
1618 {
1619  int code = ftpState->ctrl.replycode;
1620  debugs(9, 3, HERE);
1621 
1622  if (code == 213) {
1623  ftpState->unhack();
1624  ftpState->theSize = strtoll(ftpState->ctrl.last_reply, NULL, 10);
1625 
1626  if (ftpState->theSize == 0) {
1627  debugs(9, 2, "SIZE reported " <<
1628  ftpState->ctrl.last_reply << " on " <<
1629  ftpState->title_url);
1630  ftpState->theSize = -1;
1631  }
1632  } else if (code < 0) {
1633  ftpFail(ftpState);
1634  return;
1635  }
1636 
1637  ftpSendPassive(ftpState);
1638 }
1639 
1640 static void
1642 {
1643  Ip::Address srvAddr; // unused
1644  if (ftpState->handleEpsvReply(srvAddr)) {
1645  if (ftpState->ctrl.message == NULL)
1646  return; // didn't get complete reply yet
1647 
1648  ftpState->connectDataChannel();
1649  }
1650 }
1651 
1656 static void
1658 {
1660  if (!ftpState || !ftpState->haveControlChannel("ftpSendPassive"))
1661  return;
1662 
1663  debugs(9, 3, HERE);
1664 
1667  if (ftpState->request->method == Http::METHOD_HEAD && (ftpState->flags.isdir || ftpState->theSize != -1)) {
1668  ftpState->processHeadResponse(); // may call serverComplete
1669  return;
1670  }
1671 
1672  if (ftpState->sendPassive()) {
1673  // SENT_EPSV_ALL blocks other non-EPSV connections being attempted
1674  if (ftpState->state == Ftp::Client::SENT_EPSV_ALL)
1675  ftpState->flags.epsv_all_sent = true;
1676  }
1677 }
1678 
1679 void
1681 {
1682  debugs(9, 5, HERE << "handling HEAD response");
1683  ftpSendQuit(this);
1684  appendSuccessHeader();
1685 
1686  /*
1687  * On rare occasions I'm seeing the entry get aborted after
1688  * readControlReply() and before here, probably when
1689  * trying to write to the client.
1690  */
1691  if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1692  abortAll("entry aborted while processing HEAD");
1693  return;
1694  }
1695 
1696 #if USE_ADAPTATION
1697  if (adaptationAccessCheckPending) {
1698  debugs(9,3, HERE << "returning due to adaptationAccessCheckPending");
1699  return;
1700  }
1701 #endif
1702 
1703  // processReplyBody calls serverComplete() since there is no body
1704  processReplyBody();
1705 }
1706 
1707 static void
1709 {
1710  Ip::Address srvAddr; // unused
1711  if (ftpState->handlePasvReply(srvAddr))
1712  ftpState->connectDataChannel();
1713  else {
1714  ftpFail(ftpState);
1715  // Currently disabled, does not work correctly:
1716  // ftpSendEPRT(ftpState);
1717  return;
1718  }
1719 }
1720 
1721 void
1723 {
1724  debugs(9, 3, HERE);
1725  data.opener = NULL;
1726 
1727  if (io.flag != Comm::OK) {
1728  debugs(9, 2, HERE << "Failed to connect. Retrying via another method.");
1729 
1730  // ABORT on timeouts. server may be waiting on a broken TCP link.
1731  if (io.xerrno == Comm::TIMEOUT)
1732  writeCommand("ABOR\r\n");
1733 
1734  // try another connection attempt with some other method
1735  ftpSendPassive(this);
1736  return;
1737  }
1738 
1739  data.opened(io.conn, dataCloser());
1740  ftpRestOrList(this);
1741 }
1742 
1743 static void
1744 ftpOpenListenSocket(Ftp::Gateway * ftpState, int fallback)
1745 {
1747  if (ftpState->data.conn != NULL) {
1748  if ((ftpState->data.conn->flags & COMM_REUSEADDR))
1749  // NP: in fact it points to the control channel. just clear it.
1750  ftpState->data.clear();
1751  else
1752  ftpState->data.close();
1753  }
1754  safe_free(ftpState->data.host);
1755 
1756  if (!Comm::IsConnOpen(ftpState->ctrl.conn)) {
1757  debugs(9, 5, "The control connection to the remote end is closed");
1758  return;
1759  }
1760 
1761  /*
1762  * Set up a listen socket on the same local address as the
1763  * control connection.
1764  */
1766  temp->local = ftpState->ctrl.conn->local;
1767 
1768  /*
1769  * REUSEADDR is needed in fallback mode, since the same port is
1770  * used for both control and data.
1771  */
1772  if (fallback) {
1773  int on = 1;
1774  errno = 0;
1775  if (setsockopt(ftpState->ctrl.conn->fd, SOL_SOCKET, SO_REUSEADDR,
1776  (char *) &on, sizeof(on)) == -1) {
1777  int xerrno = errno;
1778  // SO_REUSEADDR is only an optimization, no need to be verbose about error
1779  debugs(9, 4, "setsockopt failed: " << xstrerr(xerrno));
1780  }
1781  ftpState->ctrl.conn->flags |= COMM_REUSEADDR;
1782  temp->flags |= COMM_REUSEADDR;
1783  } else {
1784  /* if not running in fallback mode a new port needs to be retrieved */
1785  temp->local.port(0);
1786  }
1787 
1788  ftpState->listenForDataChannel(temp);
1789 }
1790 
1791 static void
1793 {
1794  /* check the server control channel is still available */
1795  if (!ftpState || !ftpState->haveControlChannel("ftpSendPort"))
1796  return;
1797 
1798  if (Config.Ftp.epsv_all && ftpState->flags.epsv_all_sent) {
1799  debugs(9, DBG_IMPORTANT, "FTP does not allow PORT method after 'EPSV ALL' has been sent.");
1800  return;
1801  }
1802 
1803  debugs(9, 3, HERE);
1804  ftpState->flags.pasv_supported = 0;
1805  ftpOpenListenSocket(ftpState, 0);
1806 
1807  if (!Comm::IsConnOpen(ftpState->data.listenConn)) {
1808  if ( ftpState->data.listenConn != NULL && !ftpState->data.listenConn->local.isIPv4() ) {
1809  /* non-IPv4 CANNOT send PORT command. */
1810  /* we got here by attempting and failing an EPRT */
1811  /* using the same reply code should simulate a PORT failure */
1812  ftpReadPORT(ftpState);
1813  return;
1814  }
1815 
1816  /* XXX Need to set error message */
1817  ftpFail(ftpState);
1818  return;
1819  }
1820 
1821  // pull out the internal IP address bytes to send in PORT command...
1822  // source them from the listen_conn->local
1823 
1824  struct addrinfo *AI = NULL;
1825  ftpState->data.listenConn->local.getAddrInfo(AI, AF_INET);
1826  unsigned char *addrptr = (unsigned char *) &((struct sockaddr_in*)AI->ai_addr)->sin_addr;
1827  unsigned char *portptr = (unsigned char *) &((struct sockaddr_in*)AI->ai_addr)->sin_port;
1828  snprintf(cbuf, CTRL_BUFLEN, "PORT %d,%d,%d,%d,%d,%d\r\n",
1829  addrptr[0], addrptr[1], addrptr[2], addrptr[3],
1830  portptr[0], portptr[1]);
1831  ftpState->writeCommand(cbuf);
1832  ftpState->state = Ftp::Client::SENT_PORT;
1833 
1835 }
1836 
1837 static void
1839 {
1840  int code = ftpState->ctrl.replycode;
1841  debugs(9, 3, HERE);
1842 
1843  if (code != 200) {
1844  /* Fall back on using the same port as the control connection */
1845  debugs(9, 3, "PORT not supported by remote end");
1846  ftpOpenListenSocket(ftpState, 1);
1847  }
1848 
1849  ftpRestOrList(ftpState);
1850 }
1851 
1852 #if 0
1853 static void
1854 ftpSendEPRT(Ftp::Gateway * ftpState)
1855 {
1856  /* check the server control channel is still available */
1857  if (!ftpState || !ftpState->haveControlChannel("ftpSendEPRT"))
1858  return;
1859 
1860  if (Config.Ftp.epsv_all && ftpState->flags.epsv_all_sent) {
1861  debugs(9, DBG_IMPORTANT, "FTP does not allow EPRT method after 'EPSV ALL' has been sent.");
1862  return;
1863  }
1864 
1865  if (!Config.Ftp.eprt) {
1866  /* Disabled. Switch immediately to attempting old PORT command. */
1867  debugs(9, 3, "EPRT disabled by local administrator");
1868  ftpSendPORT(ftpState);
1869  return;
1870  }
1871 
1872  debugs(9, 3, HERE);
1873  ftpState->flags.pasv_supported = 0;
1874 
1875  ftpOpenListenSocket(ftpState, 0);
1876  debugs(9, 3, "Listening for FTP data connection with FD " << ftpState->data.conn);
1877  if (!Comm::IsConnOpen(ftpState->data.conn)) {
1878  /* XXX Need to set error message */
1879  ftpFail(ftpState);
1880  return;
1881  }
1882 
1883  char buf[MAX_IPSTRLEN];
1884 
1885  /* RFC 2428 defines EPRT as IPv6 equivalent to IPv4 PORT command. */
1886  /* Which can be used by EITHER protocol. */
1887  snprintf(cbuf, CTRL_BUFLEN, "EPRT |%d|%s|%d|\r\n",
1888  ( ftpState->data.listenConn->local.isIPv6() ? 2 : 1 ),
1889  ftpState->data.listenConn->local.toStr(buf,MAX_IPSTRLEN),
1890  ftpState->data.listenConn->local.port() );
1891 
1892  ftpState->writeCommand(cbuf);
1893  ftpState->state = Ftp::Client::SENT_EPRT;
1894 }
1895 #endif
1896 
1897 static void
1899 {
1900  int code = ftpState->ctrl.replycode;
1901  debugs(9, 3, HERE);
1902 
1903  if (code != 200) {
1904  /* Failover to attempting old PORT command. */
1905  debugs(9, 3, "EPRT not supported by remote end");
1906  ftpSendPORT(ftpState);
1907  return;
1908  }
1909 
1910  ftpRestOrList(ftpState);
1911 }
1912 
1917 void
1919 {
1920  debugs(9, 3, HERE);
1921 
1922  if (!Comm::IsConnOpen(ctrl.conn)) { /*Close handlers will cleanup*/
1923  debugs(9, 5, "The control connection to the remote end is closed");
1924  return;
1925  }
1926 
1927  if (io.flag != Comm::OK) {
1928  data.listenConn->close();
1929  data.listenConn = NULL;
1930  debugs(9, DBG_IMPORTANT, "FTP AcceptDataConnection: " << io.conn << ": " << xstrerr(io.xerrno));
1931  // TODO: need to send error message on control channel
1932  ftpFail(this);
1933  return;
1934  }
1935 
1936  if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
1937  abortAll("entry aborted when accepting data conn");
1938  data.listenConn->close();
1939  data.listenConn = NULL;
1940  io.conn->close();
1941  return;
1942  }
1943 
1944  /* data listening conn is no longer even open. abort. */
1945  if (!Comm::IsConnOpen(data.listenConn)) {
1946  data.listenConn = NULL; // ensure that it's cleared and not just closed.
1947  return;
1948  }
1949 
1950  /* data listening conn is no longer even open. abort. */
1951  if (!Comm::IsConnOpen(data.conn)) {
1952  data.clear(); // ensure that it's cleared and not just closed.
1953  return;
1954  }
1955 
1962  if (Config.Ftp.sanitycheck) {
1963  // accept if either our data or ctrl connection is talking to this remote peer.
1964  if (data.conn->remote != io.conn->remote && ctrl.conn->remote != io.conn->remote) {
1965  debugs(9, DBG_IMPORTANT,
1966  "FTP data connection from unexpected server (" <<
1967  io.conn->remote << "), expecting " <<
1968  data.conn->remote << " or " << ctrl.conn->remote);
1969 
1970  /* close the bad sources connection down ASAP. */
1971  io.conn->close();
1972 
1973  /* drop the bad connection (io) by ignoring the attempt. */
1974  return;
1975  }
1976  }
1977 
1979  data.close();
1980  data.opened(io.conn, dataCloser());
1981  data.addr(io.conn->remote);
1982 
1983  debugs(9, 3, HERE << "Connected data socket on " <<
1984  io.conn << ". FD table says: " <<
1985  "ctrl-peer= " << fd_table[ctrl.conn->fd].ipaddr << ", " <<
1986  "data-peer= " << fd_table[data.conn->fd].ipaddr);
1987 
1988  assert(haveControlChannel("ftpAcceptDataConnection"));
1989  assert(ctrl.message == NULL);
1990 
1991  // Ctrl channel operations will determine what happens to this data connection
1992 }
1993 
1994 static void
1996 {
1997  debugs(9, 3, HERE);
1998 
1999  if (ftpState->typecode == 'D') {
2000  ftpState->flags.isdir = 1;
2001 
2002  if (ftpState->flags.put) {
2003  ftpSendMkdir(ftpState); /* PUT name;type=d */
2004  } else {
2005  ftpSendNlst(ftpState); /* GET name;type=d sec 3.2.2 of RFC 1738 */
2006  }
2007  } else if (ftpState->flags.put) {
2008  ftpSendStor(ftpState);
2009  } else if (ftpState->flags.isdir)
2010  ftpSendList(ftpState);
2011  else if (ftpState->restartable())
2012  ftpSendRest(ftpState);
2013  else
2014  ftpSendRetr(ftpState);
2015 }
2016 
2017 static void
2019 {
2020  /* check the server control channel is still available */
2021  if (!ftpState || !ftpState->haveControlChannel("ftpSendStor"))
2022  return;
2023 
2024  debugs(9, 3, HERE);
2025 
2026  if (ftpState->filepath != NULL) {
2027  /* Plain file upload */
2028  snprintf(cbuf, CTRL_BUFLEN, "STOR %s\r\n", ftpState->filepath);
2029  ftpState->writeCommand(cbuf);
2030  ftpState->state = Ftp::Client::SENT_STOR;
2031  } else if (ftpState->request->header.getInt64(Http::HdrType::CONTENT_LENGTH) > 0) {
2032  /* File upload without a filename. use STOU to generate one */
2033  snprintf(cbuf, CTRL_BUFLEN, "STOU\r\n");
2034  ftpState->writeCommand(cbuf);
2035  ftpState->state = Ftp::Client::SENT_STOR;
2036  } else {
2037  /* No file to transfer. Only create directories if needed */
2038  ftpSendReply(ftpState);
2039  }
2040 }
2041 
2043 static void
2045 {
2046  ftpState->readStor();
2047 }
2048 
2050 {
2051  int code = ctrl.replycode;
2052  debugs(9, 3, HERE);
2053 
2054  if (code == 125 || (code == 150 && Comm::IsConnOpen(data.conn))) {
2055  if (!originalRequest()->body_pipe) {
2056  debugs(9, 3, "zero-size STOR?");
2057  state = WRITING_DATA; // make ftpWriteTransferDone() responsible
2058  dataComplete(); // XXX: keep in sync with doneSendingRequestBody()
2059  return;
2060  }
2061 
2062  if (!startRequestBodyFlow()) { // register to receive body data
2063  ftpFail(this);
2064  return;
2065  }
2066 
2067  /* When client status is 125, or 150 and the data connection is open, Begin data transfer. */
2068  debugs(9, 3, HERE << "starting data transfer");
2069  switchTimeoutToDataChannel();
2070  sendMoreRequestBody();
2071  fwd->dontRetry(true); // do not permit re-trying if the body was sent.
2072  state = WRITING_DATA;
2073  debugs(9, 3, HERE << "writing data channel");
2074  } else if (code == 150) {
2075  /* When client code is 150 with no data channel, Accept data channel. */
2076  debugs(9, 3, "ftpReadStor: accepting data channel");
2077  listenForDataChannel(data.conn);
2078  } else {
2079  debugs(9, DBG_IMPORTANT, HERE << "Unexpected reply code "<< std::setfill('0') << std::setw(3) << code);
2080  ftpFail(this);
2081  }
2082 }
2083 
2084 static void
2086 {
2087  /* check the server control channel is still available */
2088  if (!ftpState || !ftpState->haveControlChannel("ftpSendRest"))
2089  return;
2090 
2091  debugs(9, 3, HERE);
2092 
2093  snprintf(cbuf, CTRL_BUFLEN, "REST %" PRId64 "\r\n", ftpState->restart_offset);
2094  ftpState->writeCommand(cbuf);
2095  ftpState->state = Ftp::Client::SENT_REST;
2096 }
2097 
2098 int
2100 {
2101  if (restart_offset > 0)
2102  return 1;
2103 
2104  if (!request->range)
2105  return 0;
2106 
2107  if (!flags.binary)
2108  return 0;
2109 
2110  if (theSize <= 0)
2111  return 0;
2112 
2113  int64_t desired_offset = request->range->lowestOffset(theSize);
2114 
2115  if (desired_offset <= 0)
2116  return 0;
2117 
2118  if (desired_offset >= theSize)
2119  return 0;
2120 
2121  restart_offset = desired_offset;
2122  return 1;
2123 }
2124 
2125 static void
2127 {
2128  int code = ftpState->ctrl.replycode;
2129  debugs(9, 3, HERE);
2130  assert(ftpState->restart_offset > 0);
2131 
2132  if (code == 350) {
2133  ftpState->setCurrentOffset(ftpState->restart_offset);
2134  ftpSendRetr(ftpState);
2135  } else if (code > 0) {
2136  debugs(9, 3, HERE << "REST not supported");
2137  ftpState->flags.rest_supported = 0;
2138  ftpSendRetr(ftpState);
2139  } else {
2140  ftpFail(ftpState);
2141  }
2142 }
2143 
2144 static void
2146 {
2147  /* check the server control channel is still available */
2148  if (!ftpState || !ftpState->haveControlChannel("ftpSendList"))
2149  return;
2150 
2151  debugs(9, 3, HERE);
2152 
2153  if (ftpState->filepath) {
2154  snprintf(cbuf, CTRL_BUFLEN, "LIST %s\r\n", ftpState->filepath);
2155  } else {
2156  snprintf(cbuf, CTRL_BUFLEN, "LIST\r\n");
2157  }
2158 
2159  ftpState->writeCommand(cbuf);
2160  ftpState->state = Ftp::Client::SENT_LIST;
2161 }
2162 
2163 static void
2165 {
2166  /* check the server control channel is still available */
2167  if (!ftpState || !ftpState->haveControlChannel("ftpSendNlst"))
2168  return;
2169 
2170  debugs(9, 3, HERE);
2171 
2172  ftpState->flags.tried_nlst = 1;
2173 
2174  if (ftpState->filepath) {
2175  snprintf(cbuf, CTRL_BUFLEN, "NLST %s\r\n", ftpState->filepath);
2176  } else {
2177  snprintf(cbuf, CTRL_BUFLEN, "NLST\r\n");
2178  }
2179 
2180  ftpState->writeCommand(cbuf);
2181  ftpState->state = Ftp::Client::SENT_NLST;
2182 }
2183 
2184 static void
2186 {
2187  int code = ftpState->ctrl.replycode;
2188  debugs(9, 3, HERE);
2189 
2190  if (code == 125 || (code == 150 && Comm::IsConnOpen(ftpState->data.conn))) {
2191  /* Begin data transfer */
2192  debugs(9, 3, HERE << "begin data transfer from " << ftpState->data.conn->remote << " (" << ftpState->data.conn->local << ")");
2193  ftpState->switchTimeoutToDataChannel();
2194  ftpState->maybeReadVirginBody();
2195  ftpState->state = Ftp::Client::READING_DATA;
2196  return;
2197  } else if (code == 150) {
2198  /* Accept data channel */
2199  debugs(9, 3, HERE << "accept data channel from " << ftpState->data.conn->remote << " (" << ftpState->data.conn->local << ")");
2200  ftpState->listenForDataChannel(ftpState->data.conn);
2201  return;
2202  } else if (!ftpState->flags.tried_nlst && code > 300) {
2203  ftpSendNlst(ftpState);
2204  } else {
2205  ftpFail(ftpState);
2206  return;
2207  }
2208 }
2209 
2210 static void
2212 {
2213  /* check the server control channel is still available */
2214  if (!ftpState || !ftpState->haveControlChannel("ftpSendRetr"))
2215  return;
2216 
2217  debugs(9, 3, HERE);
2218 
2219  assert(ftpState->filepath != NULL);
2220  snprintf(cbuf, CTRL_BUFLEN, "RETR %s\r\n", ftpState->filepath);
2221  ftpState->writeCommand(cbuf);
2222  ftpState->state = Ftp::Client::SENT_RETR;
2223 }
2224 
2225 static void
2227 {
2228  int code = ftpState->ctrl.replycode;
2229  debugs(9, 3, HERE);
2230 
2231  if (code == 125 || (code == 150 && Comm::IsConnOpen(ftpState->data.conn))) {
2232  /* Begin data transfer */
2233  debugs(9, 3, HERE << "begin data transfer from " << ftpState->data.conn->remote << " (" << ftpState->data.conn->local << ")");
2234  ftpState->switchTimeoutToDataChannel();
2235  ftpState->maybeReadVirginBody();
2236  ftpState->state = Ftp::Client::READING_DATA;
2237  } else if (code == 150) {
2238  /* Accept data channel */
2239  ftpState->listenForDataChannel(ftpState->data.conn);
2240  } else if (code >= 300) {
2241  if (!ftpState->flags.try_slash_hack) {
2242  /* Try this as a directory missing trailing slash... */
2243  ftpState->hackShortcut(ftpSendCwd);
2244  } else {
2245  ftpFail(ftpState);
2246  }
2247  } else {
2248  ftpFail(ftpState);
2249  }
2250 }
2251 
2256 void
2258 {
2259  assert(entry);
2260  entry->lock("Ftp::Gateway");
2261  ErrorState ferr(ERR_DIR_LISTING, Http::scOkay, request.getRaw(), fwd->al);
2262  ferr.ftp.listing = &listing;
2263  ferr.ftp.cwd_msg = xstrdup(cwd_message.size()? cwd_message.termedBuf() : "");
2264  ferr.ftp.server_msg = ctrl.message;
2265  ctrl.message = NULL;
2266  entry->replaceHttpReply(ferr.BuildHttpReply());
2267  entry->flush();
2268  entry->unlock("Ftp::Gateway");
2269 }
2270 
2271 static void
2273 {
2274  int code = ftpState->ctrl.replycode;
2275  debugs(9, 3, HERE);
2276 
2277  if (code == 226 || code == 250) {
2278  /* Connection closed; retrieval done. */
2279  if (ftpState->flags.listing) {
2280  ftpState->completedListing();
2281  /* QUIT operation handles sending the reply to client */
2282  }
2283  ftpSendQuit(ftpState);
2284  } else { /* != 226 */
2285  debugs(9, DBG_IMPORTANT, HERE << "Got code " << code << " after reading data");
2286  ftpState->failed(ERR_FTP_FAILURE, 0);
2287  /* failed closes ctrl.conn and frees ftpState */
2288  return;
2289  }
2290 }
2291 
2292 // premature end of the request body
2293 void
2295 {
2297  debugs(9, 3, HERE << "ftpState=" << this);
2298  failed(ERR_READ_ERROR, 0);
2299 }
2300 
2301 static void
2303 {
2304  int code = ftpState->ctrl.replycode;
2305  debugs(9, 3, HERE);
2306 
2307  if (!(code == 226 || code == 250)) {
2308  debugs(9, DBG_IMPORTANT, HERE << "Got code " << code << " after sending data");
2309  ftpState->failed(ERR_FTP_PUT_ERROR, 0);
2310  return;
2311  }
2312 
2313  ftpState->entry->timestampsSet(); /* XXX Is this needed? */
2314  ftpSendReply(ftpState);
2315 }
2316 
2317 static void
2319 {
2320  /* check the server control channel is still available */
2321  if (!ftpState || !ftpState->haveControlChannel("ftpSendQuit"))
2322  return;
2323 
2324  snprintf(cbuf, CTRL_BUFLEN, "QUIT\r\n");
2325  ftpState->writeCommand(cbuf);
2326  ftpState->state = Ftp::Client::SENT_QUIT;
2327 }
2328 
2332 static void
2334 {
2335  ftpState->serverComplete();
2336 }
2337 
2338 static void
2340 {
2341  char *path;
2342  ftpState->flags.try_slash_hack = 1;
2343  /* Free old paths */
2344 
2345  debugs(9, 3, HERE);
2346 
2347  if (ftpState->pathcomps)
2348  wordlistDestroy(&ftpState->pathcomps);
2349 
2350  safe_free(ftpState->filepath);
2351 
2352  /* Build the new path (urlpath begins with /) */
2353  path = SBufToCstring(ftpState->request->url.path());
2354 
2355  rfc1738_unescape(path);
2356 
2357  ftpState->filepath = path;
2358 
2359  /* And off we go */
2360  ftpGetFile(ftpState);
2361 }
2362 
2366 void
2368 {
2369  debugs(9, 3, HERE);
2370 
2371  if (old_request != NULL) {
2372  safe_free(old_request);
2373  safe_free(old_reply);
2374  }
2375 }
2376 
2377 void
2379 {
2380  /* Clear some unwanted state */
2381  setCurrentOffset(0);
2382  restart_offset = 0;
2383  /* Save old error message & some state info */
2384 
2385  debugs(9, 3, HERE);
2386 
2387  if (old_request == NULL) {
2388  old_request = ctrl.last_command;
2389  ctrl.last_command = NULL;
2390  old_reply = ctrl.last_reply;
2391  ctrl.last_reply = NULL;
2392 
2393  if (pathcomps == NULL && filepath != NULL)
2394  old_filepath = xstrdup(filepath);
2395  }
2396 
2397  /* Jump to the "hack" state */
2398  nextState(this);
2399 }
2400 
2401 static void
2403 {
2404  const bool slashHack = ftpState->request->url.path().caseCmp("/%2f", 4)==0;
2405  int code = ftpState->ctrl.replycode;
2406  err_type error_code = ERR_NONE;
2407 
2408  debugs(9, 6, "state " << ftpState->state <<
2409  " reply code " << code << "flags(" <<
2410  (ftpState->flags.isdir?"IS_DIR,":"") <<
2411  (ftpState->flags.try_slash_hack?"TRY_SLASH_HACK":"") << "), " <<
2412  "mdtm=" << ftpState->mdtm << ", size=" << ftpState->theSize <<
2413  "slashhack=" << (slashHack? "T":"F"));
2414 
2415  /* Try the / hack to support "Netscape" FTP URL's for retrieving files */
2416  if (!ftpState->flags.isdir && /* Not a directory */
2417  !ftpState->flags.try_slash_hack && !slashHack && /* Not doing slash hack */
2418  ftpState->mdtm <= 0 && ftpState->theSize < 0) { /* Not known as a file */
2419 
2420  switch (ftpState->state) {
2421 
2422  case Ftp::Client::SENT_CWD:
2423 
2425  /* Try the / hack */
2426  ftpState->hackShortcut(ftpTrySlashHack);
2427  return;
2428 
2429  default:
2430  break;
2431  }
2432  }
2433 
2434  Http::StatusCode sc = ftpState->failedHttpStatus(error_code);
2435  const auto ftperr = new ErrorState(error_code, sc, ftpState->fwd->request, ftpState->fwd->al);
2436  ftpState->failed(error_code, code, ftperr);
2437  ftperr->detailError(code);
2438  HttpReply *newrep = ftperr->BuildHttpReply();
2439  delete ftperr;
2440 
2441  ftpState->entry->replaceHttpReply(newrep);
2442  ftpSendQuit(ftpState);
2443 }
2444 
2447 {
2448  if (error == ERR_NONE) {
2449  switch (state) {
2450 
2451  case SENT_USER:
2452 
2453  case SENT_PASS:
2454 
2455  if (ctrl.replycode > 500) {
2457  return password_url ? Http::scForbidden : Http::scUnauthorized;
2458  } else if (ctrl.replycode == 421) {
2461  }
2462  break;
2463 
2464  case SENT_CWD:
2465 
2466  case SENT_RETR:
2467  if (ctrl.replycode == 550) {
2469  return Http::scNotFound;
2470  }
2471  break;
2472 
2473  default:
2474  break;
2475  }
2476  }
2478 }
2479 
2480 static void
2482 {
2483  int code = ftpState->ctrl.replycode;
2484  Http::StatusCode http_code;
2485  err_type err_code = ERR_NONE;
2486 
2487  debugs(9, 3, HERE << ftpState->entry->url() << ", code " << code);
2488 
2489  if (cbdataReferenceValid(ftpState))
2490  debugs(9, 5, HERE << "ftpState (" << ftpState << ") is valid!");
2491 
2492  if (code == 226 || code == 250) {
2493  err_code = (ftpState->mdtm > 0) ? ERR_FTP_PUT_MODIFIED : ERR_FTP_PUT_CREATED;
2494  http_code = (ftpState->mdtm > 0) ? Http::scAccepted : Http::scCreated;
2495  } else if (code == 227) {
2496  err_code = ERR_FTP_PUT_CREATED;
2497  http_code = Http::scCreated;
2498  } else {
2499  err_code = ERR_FTP_PUT_ERROR;
2500  http_code = Http::scInternalServerError;
2501  }
2502 
2503  ErrorState err(err_code, http_code, ftpState->request.getRaw(), ftpState->fwd->al);
2504 
2505  if (ftpState->old_request)
2506  err.ftp.request = xstrdup(ftpState->old_request);
2507  else
2508  err.ftp.request = xstrdup(ftpState->ctrl.last_command);
2509 
2510  if (ftpState->old_reply)
2511  err.ftp.reply = xstrdup(ftpState->old_reply);
2512  else if (ftpState->ctrl.last_reply)
2513  err.ftp.reply = xstrdup(ftpState->ctrl.last_reply);
2514  else
2515  err.ftp.reply = xstrdup("");
2516 
2517  // TODO: interpret as FTP-specific error code
2518  err.detailError(code);
2519 
2520  ftpState->entry->replaceHttpReply(err.BuildHttpReply());
2521 
2522  ftpSendQuit(ftpState);
2523 }
2524 
2525 void
2527 {
2528  debugs(9, 3, HERE);
2529 
2530  if (flags.http_header_sent)
2531  return;
2532 
2533  HttpReply *reply = new HttpReply;
2534 
2535  flags.http_header_sent = 1;
2536 
2537  assert(entry->isEmpty());
2538 
2539  entry->buffer(); /* released when done processing current data payload */
2540 
2541  SBuf urlPath = request->url.path();
2542  auto t = urlPath.rfind('/');
2543  SBuf filename = urlPath.substr(t != SBuf::npos ? t : 0);
2544 
2545  const char *mime_type = NULL;
2546  const char *mime_enc = NULL;
2547 
2548  if (flags.isdir) {
2549  mime_type = "text/html";
2550  } else {
2551  switch (typecode) {
2552 
2553  case 'I':
2554  mime_type = "application/octet-stream";
2555  // XXX: performance regression, c_str() may reallocate
2556  mime_enc = mimeGetContentEncoding(filename.c_str());
2557  break;
2558 
2559  case 'A':
2560  mime_type = "text/plain";
2561  break;
2562 
2563  default:
2564  // XXX: performance regression, c_str() may reallocate
2565  mime_type = mimeGetContentType(filename.c_str());
2566  mime_enc = mimeGetContentEncoding(filename.c_str());
2567  break;
2568  }
2569  }
2570 
2571  /* set standard stuff */
2572 
2573  if (0 == getCurrentOffset()) {
2574  /* Full reply */
2575  reply->setHeaders(Http::scOkay, "Gatewaying", mime_type, theSize, mdtm, -2);
2576  } else if (theSize < getCurrentOffset()) {
2577  /*
2578  * DPW 2007-05-04
2579  * offset should not be larger than theSize. We should
2580  * not be seeing this condition any more because we'll only
2581  * send REST if we know the theSize and if it is less than theSize.
2582  */
2583  debugs(0,DBG_CRITICAL,HERE << "Whoops! " <<
2584  " current offset=" << getCurrentOffset() <<
2585  ", but theSize=" << theSize <<
2586  ". assuming full content response");
2587  reply->setHeaders(Http::scOkay, "Gatewaying", mime_type, theSize, mdtm, -2);
2588  } else {
2589  /* Partial reply */
2590  HttpHdrRangeSpec range_spec;
2591  range_spec.offset = getCurrentOffset();
2592  range_spec.length = theSize - getCurrentOffset();
2593  reply->setHeaders(Http::scPartialContent, "Gatewaying", mime_type, theSize - getCurrentOffset(), mdtm, -2);
2594  httpHeaderAddContRange(&reply->header, range_spec, theSize);
2595  }
2596 
2597  /* additional info */
2598  if (mime_enc)
2599  reply->header.putStr(Http::HdrType::CONTENT_ENCODING, mime_enc);
2600 
2601  reply->sources |= Http::Message::srcFtp;
2602  setVirginReply(reply);
2603  adaptOrFinalizeReply();
2604 }
2605 
2606 void
2608 {
2610 
2611  StoreEntry *e = entry;
2612 
2613  e->timestampsSet();
2614 
2615  // makePublic() if allowed/possible or release() otherwise
2616  if (flags.authenticated || // authenticated requests can't be cached
2617  getCurrentOffset() ||
2618  !e->makePublic()) {
2619  e->release();
2620  }
2621 }
2622 
2623 HttpReply *
2625 {
2627  HttpReply *newrep = err.BuildHttpReply();
2628 #if HAVE_AUTH_MODULE_BASIC
2629  /* add Authenticate header */
2630  // XXX: performance regression. c_str() may reallocate
2631  newrep->header.putAuth("Basic", realm.c_str());
2632 #endif
2633  return newrep;
2634 }
2635 
2636 const SBuf &
2638 {
2639  SBuf newbuf("%2f");
2640 
2641  if (request->url.getScheme() != AnyP::PROTO_FTP) {
2642  static const SBuf nil;
2643  return nil;
2644  }
2645 
2646  if (request->url.path()[0] == '/') {
2647  newbuf.append(request->url.path());
2648  request->url.path(newbuf);
2649  } else if (!request->url.path().startsWith(newbuf)) {
2650  newbuf.append(request->url.path().substr(1));
2651  request->url.path(newbuf);
2652  }
2653 
2654  return request->effectiveRequestUri();
2655 }
2656 
2657 void
2658 Ftp::Gateway::printfReplyBody(const char *fmt, ...)
2659 {
2660  va_list args;
2661  va_start (args, fmt);
2662  static char buf[4096];
2663  buf[0] = '\0';
2664  vsnprintf(buf, 4096, fmt, args);
2665  writeReplyBody(buf, strlen(buf));
2666  va_end(args);
2667 }
2668 
2673 void
2674 Ftp::Gateway::writeReplyBody(const char *dataToWrite, size_t dataLength)
2675 {
2676  debugs(9, 5, HERE << "writing " << dataLength << " bytes to the reply");
2677  addVirginReplyBody(dataToWrite, dataLength);
2678 }
2679 
2686 void
2688 {
2689  if (fwd == NULL || flags.completed_forwarding) {
2690  debugs(9, 3, "avoid double-complete on FD " <<
2691  (ctrl.conn ? ctrl.conn->fd : -1) << ", Data FD " << data.conn->fd <<
2692  ", this " << this << ", fwd " << fwd);
2693  return;
2694  }
2695 
2696  flags.completed_forwarding = true;
2698 }
2699 
2706 bool
2707 Ftp::Gateway::haveControlChannel(const char *caller_name) const
2708 {
2709  if (doneWithServer())
2710  return false;
2711 
2712  /* doneWithServer() only checks BOTH channels are closed. */
2713  if (!Comm::IsConnOpen(ctrl.conn)) {
2714  debugs(9, DBG_IMPORTANT, "WARNING! FTP Server Control channel is closed, but Data channel still active.");
2715  debugs(9, 2, caller_name << ": attempted on a closed FTP channel.");
2716  return false;
2717  }
2718 
2719  return true;
2720 }
2721 
2722 bool
2724 {
2725  // TODO: Can we do what Ftp::Relay::mayReadVirginReplyBody() does instead?
2726  return !doneWithServer();
2727 }
2728 
2730 Ftp::StartGateway(FwdState *const fwdState)
2731 {
2732  return AsyncJob::Start(new Ftp::Gateway(fwdState));
2733 }
2734 
virtual bool mayReadVirginReplyBody() const
whether we may receive more virgin response body bytes
Definition: FtpGateway.cc:2723
static void ftpTrySlashHack(Ftp::Gateway *ftpState)
Definition: FtpGateway.cc:2339
void fatal(const char *message)
Definition: fatal.cc:28
const char * xstrerr(int error)
Definition: xstrerror.cc:83
char method[16]
Definition: tcp-banger2.c:115
@ ERR_FTP_NOT_FOUND
Definition: err_type.h:53
static FTPSM ftpSendCwd
Definition: FtpGateway.cc:223
static FTPSM ftpReadQuit
Definition: FtpGateway.cc:242
void * xcalloc(size_t n, size_t sz)
Definition: xalloc.cc:72
StoreEntry * entry
Definition: Client.h:164
size_type find(char c, size_type startPos=0) const
Definition: SBuf.cc:594
void wordlistDestroy(wordlist **list)
destroy a wordlist
Definition: wordlist.cc:16
Gateway(FwdState *)
Definition: FtpGateway.cc:330
@ scAccepted
Definition: StatusCode.h:28
char * cwd_msg
Definition: errorpage.h:194
@ scUnauthorized
Definition: StatusCode.h:45
@ METHOD_HEAD
Definition: MethodType.h:28
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
#define xmalloc
static PF ftpDataWrite
Definition: FtpGateway.cc:152
MemBuf * listing
Definition: errorpage.h:195
SBuf ftpRealm()
Definition: FtpGateway.cc:1260
@ ERR_FTP_PUT_ERROR
Definition: err_type.h:52
bool makePublic(const KeyScope keyScope=ksDefault)
Definition: store.cc:165
HttpHeader header
Definition: Message.h:75
char * old_filepath
Definition: FtpGateway.cc:118
static FTPSM ftpReadTransferDone
Definition: FtpGateway.cc:233
bool isEmpty() const
Definition: SBuf.h:420
@ ERR_CACHE_ACCESS_DENIED
Definition: err_type.h:17
char * reply
Definition: errorpage.h:193
const char * url() const
Definition: store.cc:1622
void connectDataChannel()
Definition: FtpClient.cc:746
const char *const crlf
Definition: FtpClient.cc:35
void writeCommand(const char *buf)
Definition: FtpClient.cc:806
bool pasv_supported
PASV command is allowed.
Definition: FtpGateway.cc:57
virtual void timeout(const CommTimeoutCbParams &io)
read timeout handler
Definition: FtpGateway.cc:482
static void ftpOpenListenSocket(Ftp::Gateway *ftpState, int fallback)
Definition: FtpGateway.cc:1744
@ ERR_NONE
Definition: err_type.h:13
HttpReply * BuildHttpReply(void)
Definition: errorpage.cc:1281
virtual void handleRequestBodyProducerAborted()=0
Definition: Client.cc:331
void error(char *format,...)
AccessLogEntryPointer al
info for the future access.log entry
Definition: FwdState.h:174
static FTPSM ftpSendRest
Definition: FtpGateway.cc:229
bool tried_auth_nopass
auth tried username with no password already.
Definition: FtpGateway.cc:65
void init(mb_size_t szInit, mb_size_t szMax)
Definition: MemBuf.cc:96
Definition: SBuf.h:86
SQUIDCEXTERN time_t parse_iso3307_time(const char *buf)
Definition: iso3307.c:25
static HttpReply * ftpAuthRequired(HttpRequest *request, SBuf &realm, AccessLogEntry::Pointer &)
Definition: FtpGateway.cc:2624
bool sendPassive()
Definition: FtpClient.cc:637
struct SquidConfig::@114 Ftp
bool htmlifyListEntry(const char *line, PackableStream &)
Definition: FtpGateway.cc:762
static FTPSM ftpReadSize
Definition: FtpGateway.cc:210
void SBufToCstring(char *d, const SBuf &s)
Definition: SBuf.h:741
#define xtoupper(x)
Definition: xis.h:18
#define xstrdup
char * html_quote(const char *)
Definition: html_quote.c:53
@ TIMEOUT
Definition: Flag.h:19
static FTPSM ftpSendRetr
Definition: FtpGateway.cc:231
@ CONTENT_ENCODING
int checkAuth(const HttpHeader *req_hdr)
Definition: FtpGateway.cc:1029
static void FreeAddr(struct addrinfo *&ai)
Definition: Address.cc:686
C * getRaw() const
Definition: RefCount.h:80
void initReadBuf()
Definition: FtpClient.cc:205
void loginParser(const SBuf &login, bool escaped)
Definition: FtpGateway.cc:399
#define REG_ICASE
Definition: GnuRegex.h:230
char * xstrncpy(char *dst, const char *src, size_t n)
Definition: xstring.cc:37
int cbdataReferenceValid(const void *p)
Definition: cbdata.cc:412
bool IsConnOpen(const Comm::ConnectionPointer &conn)
Definition: Connection.cc:26
@ OK
Definition: Flag.h:16
static FTPSM ftpSendUser
Definition: FtpGateway.cc:201
#define rfc1738_escape(x)
Definition: rfc1738.h:52
virtual void failed(err_type error=ERR_NONE, int xerrno=0, ErrorState *ftperr=nullptr)
handle a fatal transaction error, closing the control connection
Definition: FtpClient.cc:246
static FTPSM ftpReadRest
Definition: FtpGateway.cc:230
static FTPSM ftpReadList
Definition: FtpGateway.cc:228
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1782
void * memAllocate(mem_type)
Allocate one element from the typed pool.
Definition: old_api.cc:214
#define DBG_CRITICAL
Definition: Debug.h:45
static FTPSM ftpSendNlst
Definition: FtpGateway.cc:227
bool isIPv4() const
Definition: Address.cc:158
StatusCode
Definition: StatusCode.h:20
static FTPSM ftpSendMkdir
Definition: FtpGateway.cc:238
static FTPSM ftpRestOrList
Definition: FtpGateway.cc:225
@ ERR_FTP_PUT_MODIFIED
Definition: err_type.h:56
virtual void haveParsedReplyHeaders()
called when we have final (possibly adapted) reply headers; kids extend
Definition: Client.cc:517
int64_t currentOffset
Definition: Client.h:160
void processReplyBody()
Definition: FtpGateway.cc:962
static FTPSM ftpSendType
Definition: FtpGateway.cc:205
virtual void dataClosed(const CommCloseCbParams &io)
handler called by Comm when FTP data channel is closed unexpectedly
Definition: FtpGateway.cc:318
char * wordlistChopHead(wordlist **wl)
Definition: wordlist.cc:55
#define DBG_IMPORTANT
Definition: Debug.h:46
#define w_space
int xerrno
The last errno to occur. non-zero if flag is Comm::COMM_ERROR.
Definition: CommCalls.h:88
int64_t theSize
Definition: FtpGateway.cc:110
SBuf substr(size_type pos, size_type n=npos) const
Definition: SBuf.cc:586
virtual void dataChannelConnected(const CommConnectCbParams &io)
Definition: FtpGateway.cc:1722
char * toStr(char *buf, const unsigned int blen, int force=AF_UNSPEC) const
Definition: Address.cc:802
void serverComplete()
Definition: Client.cc:160
FTP client functionality shared among FTP Gateway and Relay clients.
Definition: FtpClient.h:92
@ CONTENT_LENGTH
Definition: forward.h:27
virtual void maybeReadVirginBody()
read response data from the network
Definition: FtpClient.cc:889
virtual void completeForwarding()
Definition: Client.cc:210
CBDATA_CLASS(Gateway)
void() StateMethod(Ftp::Gateway *)
Definition: FtpGateway.cc:87
#define MAX_IPSTRLEN
Length of buffer that needs to be allocated to old a null-terminated IP-string.
Definition: forward.h:23
CBDATA_NAMESPACED_CLASS_INIT(Ftp, Gateway)
static FTPSM ftpListDir
Definition: FtpGateway.cc:221
char * showname
Definition: FtpGateway.cc:187
struct sockaddr * ai_addr
void comm_open_listener(int sock_type, int proto, Comm::ConnectionPointer &conn, const char *note)
Definition: comm.cc:233
virtual bool haveControlChannel(const char *caller_name) const
Definition: FtpGateway.cc:2707
size_type rfind(char c, size_type endPos=npos) const
Definition: SBuf.cc:702
#define MAX_URL
Definition: defines.h:118
bool handlePasvReply(Ip::Address &remoteAddr)
Definition: FtpClient.cc:439
virtual void start()
called by AsyncStart; do not call directly
Definition: FtpClient.cc:199
static FTPSM ftpSendQuit
Definition: FtpGateway.cc:241
struct tok tokens[]
Definition: parse.c:168
static FTPSM ftpReadCwd
Definition: FtpGateway.cc:224
static FTPSM ftpReadUser
Definition: FtpGateway.cc:202
char * proxy_host
Definition: FtpGateway.cc:115
mb_size_t contentSize() const
available data size
Definition: MemBuf.h:47
wordlist * server_msg
Definition: errorpage.h:191
int size
Definition: ModDevPoll.cc:77
wordlist * message
Definition: FtpClient.h:64
static FTPSM ftpReadMkdir
Definition: FtpGateway.cc:239
#define NULL
Definition: types.h:166
#define REG_EXTENDED
Definition: GnuRegex.h:226
static char cbuf[CTRL_BUFLEN]
Definition: FtpGateway.cc:192
const char * rawContent() const
Definition: SBuf.cc:519
bool completed_forwarding
Definition: FtpGateway.cc:83
String base_href
Definition: FtpGateway.cc:106
static FTPSM ftpSendSize
Definition: FtpGateway.cc:209
@ ERR_DIR_LISTING
Definition: err_type.h:68
void rfc1738_unescape(char *url)
Definition: rfc1738.c:146
@ scForbidden
Definition: StatusCode.h:47
#define SQUIDSBUFPRINT(s)
Definition: SBuf.h:32
virtual void handleControlReply()
Definition: FtpClient.cc:403
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Debug.h:128
char * last_command
Definition: FtpClient.h:65
static FTPSM ftpSendPass
Definition: FtpGateway.cc:203
struct ErrorState::@60 ftp
virtual void dataClosed(const CommCloseCbParams &io)
handler called by Comm when FTP data channel is closed unexpectedly
Definition: FtpClient.cc:794
void buildTitleUrl()
Definition: FtpGateway.cc:1110
MemBlob::size_type size_type
Definition: SBuf.h:89
#define COMM_REUSEADDR
Definition: Connection.h:48
void append(char const *buf, int len)
Definition: String.cc:161
static FTPSM ftpReadWelcome
Definition: FtpGateway.cc:200
String clean_url
Definition: FtpGateway.cc:104
const char * text
Definition: errorpage.cc:153
int64_t size
Definition: FtpGateway.cc:184
HttpRequestPointer request
Definition: errorpage.h:178
void putAuth(const char *auth_scheme, const char *realm)
Definition: HttpHeader.cc:1077
static Pointer Start(AsyncJob *job)
starts a freshly created job (i.e., makes the job asynchronous)
Definition: AsyncJob.cc:23
void appendSuccessHeader()
Definition: FtpGateway.cc:2526
unsigned short port() const
Definition: Address.cc:778
bool isIPv6() const
Definition: Address.cc:164
Definition: MemBuf.h:23
Ip::Address local
Definition: Connection.h:156
#define EBIT_TEST(flag, bit)
Definition: defines.h:107
void detailError(int dCode)
set error type-specific detail code
Definition: errorpage.h:112
bool handleEpsvReply(Ip::Address &remoteAddr)
Definition: FtpClient.cc:475
unsigned char code
Definition: html_quote.c:20
std::ostream & HERE(std::ostream &s)
Definition: Debug.h:157
String cwd_message
Definition: FtpGateway.cc:117
@ scPartialContent
Definition: StatusCode.h:32
size_t list_width
Definition: FtpGateway.cc:116
static FTPSM ftpReadEPRT
Definition: FtpGateway.cc:214
err_type
Definition: err_type.h:12
void const char HLPCB void * data
Definition: stub_helper.cc:16
FTPSM * FTP_SM_FUNCS[]
Definition: FtpGateway.cc:286
Comm::ConnectionPointer conn
Definition: CommCalls.h:85
@ scCreated
Definition: StatusCode.h:27
int64_t getInt64(Http::HdrType id) const
Definition: HttpHeader.cc:1178
#define safe_free(x)
Definition: xalloc.h:73
@ srcFtp
ftp_port or FTP server
Definition: Message.h:40
Ip::Address remote
Definition: Connection.h:159
void close()
planned close: removes the close handler and calls comm_close
Definition: FtpClient.cc:87
void ftpAcceptDataConnection(const CommAcceptCbParams &io)
Definition: FtpGateway.cc:1918
SBuf getAuthToken(Http::HdrType id, const char *auth_scheme) const
Definition: HttpHeader.cc:1323
int conn
the current server connection FD
Definition: Transport.cc:26
#define assert(EX)
Definition: assert.h:19
bool tried_auth_anonymous
auth has tried to use anonymous credentials already.
Definition: FtpGateway.cc:64
bool authenticated
authentication success
Definition: FtpGateway.cc:63
@ ERR_FTP_FAILURE
Definition: err_type.h:51
FwdState::Pointer fwd
Definition: Client.h:165
static FTPSM ftpSendList
Definition: FtpGateway.cc:226
@ METHOD_PUT
Definition: MethodType.h:27
Comm::Flag flag
comm layer result status.
Definition: CommCalls.h:87
void parseListing()
Definition: FtpGateway.cc:878
static FTPSM ftpTraverseDirectory
Definition: FtpGateway.cc:220
virtual void completeForwarding()
Definition: FtpGateway.cc:2687
String title_url
Definition: FtpGateway.cc:105
@ scServiceUnavailable
Definition: StatusCode.h:74
@ ERR_READ_ERROR
Definition: err_type.h:26
static FTPSM ftpReadEPSV
Definition: FtpGateway.cc:218
#define JobCallback(dbgSection, dbgLevel, Dialer, job, method)
Convenience macro to create a Dialer-based job callback.
Definition: AsyncJobCalls.h:69
char * filepath
Definition: FtpGateway.cc:112
@ scInternalServerError
Definition: StatusCode.h:71
Comm::ConnectionPointer conn
channel descriptor
Definition: FtpClient.h:39
static int sc[16]
Definition: smbdes.c:121
wordlist * pathcomps
Definition: FtpGateway.cc:111
const char * null_string
const char * c_str()
Definition: SBuf.cc:526
int64_t strtoll(const char *nptr, char **endptr, int base)
Definition: strtoll.c:81
AsyncJobPointer StartGateway(FwdState *const fwdState)
A new FTP Gateway job.
Definition: FtpGateway.cc:2730
size_type length() const
Returns the number of bytes stored in SBuf.
Definition: SBuf.h:404
char * xstrndup(const char *s, size_t n)
Definition: xstring.cc:56
SBuf & append(const SBuf &S)
Definition: SBuf.cc:195
int reply_hdr_state
Definition: FtpGateway.cc:103
#define xfree
char * anon_user
Definition: SquidConfig.h:417
char * reply_hdr
Definition: FtpGateway.cc:102
DataChannel data
FTP data channel state.
Definition: FtpClient.h:125
static FTPSM ftpSendPassive
Definition: FtpGateway.cc:217
int regexec(regex_t *preg, const char *string, size_t nmatch, pmatch, int eflags) const
Definition: GnuRegex.c:4188
wordlist * next
Definition: wordlist.h:34
bool mimeGetViewOption(const char *fn)
Definition: mime.cc:219
static const size_type npos
Definition: SBuf.h:92
virtual void handleControlReply()
Definition: FtpGateway.cc:1165
@ ERR_FTP_PUT_CREATED
Definition: err_type.h:55
uint32_t sources
The message sources.
Definition: Message.h:100
void writeReplyBody(const char *, size_t len)
Definition: FtpGateway.cc:2674
static void ftpListPartsFree(ftpListParts **parts)
Definition: FtpGateway.cc:518
static const char * Month[]
Definition: FtpGateway.cc:500
void hackShortcut(StateMethod *nextState)
Definition: FtpGateway.cc:2378
#define fd_table
Definition: fde.h:189
static FTPSM ftpReadPasv
Definition: FtpGateway.cc:219
void clear()
remove the close handler, leave connection open
Definition: FtpClient.cc:108
virtual void handleRequestBodyProducerAborted()
Definition: FtpGateway.cc:2294
char user[MAX_URL]
Definition: FtpGateway.cc:99
@ MEM_4K_BUF
Definition: forward.h:42
void checkUrlpath()
Definition: FtpGateway.cc:1073
HttpRequestMethod method
Definition: HttpRequest.h:114
void path(const char *p)
Definition: Uri.h:99
static FTPSM ftpReadType
Definition: FtpGateway.cc:206
Comm::ConnectionPointer listenConn
Definition: FtpClient.h:46
@ scNotFound
Definition: StatusCode.h:48
const char * mimeGetContentType(const char *fn)
Definition: mime.cc:177
virtual Http::StatusCode failedHttpStatus(err_type &error)
Definition: FtpClient.cc:295
MemBuf listing
FTP directory listing in HTML format.
Definition: FtpGateway.cc:120
@ PROTO_FTP
Definition: ProtocolType.h:26
@ ENTRY_ABORTED
Definition: enums.h:115
void getAddrInfo(struct addrinfo *&ai, int force=AF_UNSPEC) const
Definition: Address.cc:599
char * key
Definition: wordlist.h:33
virtual Http::StatusCode failedHttpStatus(err_type &error)
Definition: FtpGateway.cc:2446
@ MEM_8K_BUF
Definition: forward.h:43
char * last_reply
Definition: FtpClient.h:66
const SBuf & UrlWith2f(HttpRequest *)
Definition: FtpGateway.cc:2637
static ftpListParts * ftpListParseParts(const char *buf, struct Ftp::GatewayFlags flags)
Definition: FtpGateway.cc:530
int64_t restart_offset
Definition: FtpGateway.cc:114
static FTPSM ftpReadMdtm
Definition: FtpGateway.cc:208
void processHeadResponse()
Definition: FtpGateway.cc:1680
void httpHeaderAddContRange(HttpHeader *, HttpHdrRangeSpec, int64_t)
bool timestampsSet()
Definition: store.cc:1449
GatewayFlags flags
Definition: FtpGateway.cc:122
char * content()
start of the added data
Definition: MemBuf.h:41
static int is_month(const char *buf)
Definition: FtpGateway.cc:506
void putStr(Http::HdrType id, const char *str)
Definition: HttpHeader.cc:1068
static FTPSM ftpFail
Definition: FtpGateway.cc:240
Ftp::StateMethod FTPSM
Definition: FtpGateway.cc:178
char * url
Definition: tcp-banger2.c:114
static FTPSM ftpReadStor
Definition: FtpGateway.cc:235
void memFree(void *, int type)
Free a element allocated by memAllocate()
Definition: old_api.cc:222
void printfReplyBody(const char *fmt,...)
Definition: FtpGateway.cc:2658
void readStor()
Definition: FtpGateway.cc:2049
char * old_request
Definition: FtpClient.h:159
void loginFailed(void)
Definition: FtpGateway.cc:1216
static FTPSM ftpSendMdtm
Definition: FtpGateway.cc:207
const char * mimeGetContentEncoding(const char *fn)
Definition: mime.cc:191
void reset(char const *str)
Definition: String.cc:151
void listenForDataChannel(const Comm::ConnectionPointer &conn)
create a data channel acceptor and start listening.
Definition: FtpGateway.cc:445
char password[MAX_URL]
Definition: FtpGateway.cc:100
int restartable()
Definition: FtpGateway.cc:2099
void Controller::create() STUB void Controller Controller nil
int unsigned int const char *desc STUB void int len
Definition: stub_fd.cc:20
void completedListing(void)
Definition: FtpGateway.cc:2257
void release(const bool shareable=false)
Definition: store.cc:1196
#define PRId64
Definition: types.h:110
char * rfc1738_do_escape(const char *url, int flags)
Definition: rfc1738.c:56
int64_t getCurrentOffset() const
Definition: FtpGateway.cc:149
SBuf & appendf(const char *fmt,...)
Definition: SBuf.cc:239
CtrlChannel ctrl
FTP control channel state.
Definition: FtpClient.h:124
static FTPSM ftpReadPORT
Definition: FtpGateway.cc:216
virtual void haveParsedReplyHeaders()
called when we have final (possibly adapted) reply headers; kids extend
Definition: FtpGateway.cc:2607
int token
Definition: parse.c:163
char * dirpath
Definition: FtpGateway.cc:113
const char * mimeGetIconURL(const char *fn)
Definition: mime.cc:158
void setHeaders(Http::StatusCode status, const char *reason, const char *ctype, int64_t clen, time_t lmt, time_t expires)
Definition: HttpReply.cc:168
#define xisspace(x)
Definition: xis.h:17
static FTPSM ftpSendPORT
Definition: FtpGateway.cc:215
#define CTRL_BUFLEN
Definition: FtpGateway.cc:191
@ scOkay
Definition: StatusCode.h:26
virtual ~Gateway()
Definition: FtpGateway.cc:366
bool mimeGetDownloadOption(const char *fn)
Definition: mime.cc:212
virtual void start()
called by AsyncStart; do not call directly
Definition: FtpGateway.cc:1143
#define rfc1738_escape_part(x)
Definition: rfc1738.h:55
@ ERR_FTP_FORBIDDEN
Definition: err_type.h:54
const char * wordlistAdd(wordlist **list, const char *key)
Definition: wordlist.cc:25
static FTPSM ftpSendStor
Definition: FtpGateway.cc:234
virtual void timeout(const CommTimeoutCbParams &io)
read timeout handler
Definition: FtpClient.cc:871
HttpRequest * request
Definition: FwdState.h:173
void host(const char *src)
Definition: Uri.cc:98
#define MAX_TOKENS
Definition: FtpGateway.cc:527
static FTPSM ftpSendReply
Definition: FtpGateway.cc:237
HttpRequestPointer request
Definition: Client.h:166
struct _request * request(char *urlin)
Definition: tcp-banger2.c:291
static FTPSM ftpReadRetr
Definition: FtpGateway.cc:232
char * old_reply
Definition: FtpClient.h:160
static FTPSM ftpReadPass
Definition: FtpGateway.cc:204
void setCurrentOffset(int64_t offset)
Definition: FtpGateway.cc:148
void switchTimeoutToDataChannel()
Definition: FtpClient.cc:1032
size_type copy(char *dest, size_type n) const
Definition: SBuf.cc:510
void const char * buf
Definition: stub_helper.cc:16
#define SQUIDSBUFPH
Definition: SBuf.h:31
char mimeGetTransferMode(const char *fn)
Definition: mime.cc:205
void PF(int, void *)
Definition: forward.h:18
static FTPSM ftpWriteTransferDone
Definition: FtpGateway.cc:236
class SquidConfig Config
Definition: SquidConfig.cc:12
@ ERR_FTP_UNAVAILABLE
Definition: err_type.h:50
#define REG_NOSUB
Definition: GnuRegex.h:239
static FTPSM ftpGetFile
Definition: FtpGateway.cc:222
bool epsv_all_sent
EPSV ALL has been used. Must abort on failures.
Definition: FtpGateway.cc:58
int regcomp(regex_t *preg, const char *pattern, int cflags)
Definition: GnuRegex.c:4117

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors