]> git.ipfire.org Git - thirdparty/squid.git/blame - src/servers/FtpServer.cc
Renamed http_hdr_type to Http::HdrType, fixed some HdrType-int implicit conversions
[thirdparty/squid.git] / src / servers / FtpServer.cc
CommitLineData
92ae4c86 1/*
bde978a6 2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
bbc27441
AJ
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.
92ae4c86
AR
7 */
8
bbc27441
AJ
9/* DEBUG: section 33 Transfer protocol servers */
10
92ae4c86 11#include "squid.h"
ec69bdb2 12#include "acl/FilledChecklist.h"
1ab04517 13#include "base/CharacterSet.h"
aea65fec 14#include "base/RefCount.h"
92ae4c86 15#include "base/Subscription.h"
27c841f6
AR
16#include "client_side_reply.h"
17#include "client_side_request.h"
92ae4c86
AR
18#include "clientStream.h"
19#include "comm/ConnOpener.h"
20#include "comm/Read.h"
21#include "comm/TcpAcceptor.h"
22#include "comm/Write.h"
92ae4c86
AR
23#include "errorpage.h"
24#include "fd.h"
1ab04517 25#include "ftp/Elements.h"
92ae4c86
AR
26#include "ftp/Parsing.h"
27#include "globals.h"
9bafa70d 28#include "http/one/RequestParser.h"
92ae4c86
AR
29#include "HttpHdrCc.h"
30#include "ip/tools.h"
31#include "ipc/FdNotes.h"
1ab04517 32#include "parser/Tokenizer.h"
92ae4c86
AR
33#include "servers/forward.h"
34#include "servers/FtpServer.h"
35#include "SquidConfig.h"
36#include "StatCounters.h"
37#include "tools.h"
38
1ab04517
AR
39#include <set>
40#include <map>
41
92ae4c86
AR
42CBDATA_NAMESPACED_CLASS_INIT(Ftp, Server);
43
27c841f6
AR
44namespace Ftp
45{
92ae4c86 46static void PrintReply(MemBuf &mb, const HttpReply *reply, const char *const prefix = "");
1ab04517
AR
47static bool SupportedCommand(const SBuf &name);
48static bool CommandHasPathParameter(const SBuf &cmd);
92ae4c86
AR
49};
50
51Ftp::Server::Server(const MasterXaction::Pointer &xact):
f53969cc
SM
52 AsyncJob("Ftp::Server"),
53 ConnStateData(xact),
54 master(new MasterState),
55 uri(),
56 host(),
57 gotEpsvAll(false),
58 onDataAcceptCall(),
59 dataListenConn(),
60 dataConn(),
61 uploadAvailSize(0),
62 listener(),
63 connector(),
64 reader()
92ae4c86 65{
92ae4c86 66 flags.readMore = false; // we need to announce ourselves first
4579a6d0 67 *uploadBuf = 0;
92ae4c86
AR
68}
69
70Ftp::Server::~Server()
71{
72 closeDataConnection();
73}
74
75int
76Ftp::Server::pipelinePrefetchMax() const
77{
78 return 0; // no support for concurrent FTP requests
79}
80
81time_t
82Ftp::Server::idleTimeout() const
83{
84 return Config.Timeout.ftpClientIdle;
85}
86
87void
88Ftp::Server::start()
89{
90 ConnStateData::start();
91
92 if (transparent()) {
93 char buf[MAX_IPSTRLEN];
94 clientConnection->local.toUrl(buf, MAX_IPSTRLEN);
95 host = buf;
1ab04517 96 calcUri(NULL);
e7ce227f 97 debugs(33, 5, "FTP transparent URL: " << uri);
92ae4c86
AR
98 }
99
100 writeEarlyReply(220, "Service ready");
101}
102
103/// schedules another data connection read if needed
104void
105Ftp::Server::maybeReadUploadData()
106{
107 if (reader != NULL)
108 return;
109
110 const size_t availSpace = sizeof(uploadBuf) - uploadAvailSize;
111 if (availSpace <= 0)
112 return;
113
e7ce227f 114 debugs(33, 4, dataConn << ": reading FTP data...");
92ae4c86
AR
115
116 typedef CommCbMemFunT<Server, CommIoCbParams> Dialer;
117 reader = JobCallback(33, 5, Dialer, this, Ftp::Server::readUploadData);
118 comm_read(dataConn, uploadBuf + uploadAvailSize, availSpace,
119 reader);
120}
121
122/// react to the freshly parsed request
123void
124Ftp::Server::doProcessRequest()
125{
126 // zero pipelinePrefetchMax() ensures that there is only parsed request
127 ClientSocketContext::Pointer context = getCurrentContext();
128 Must(context != NULL);
129 Must(getConcurrentRequestCount() == 1);
130
131 ClientHttpRequest *const http = context->http;
132 assert(http != NULL);
92ae4c86 133
eacfca83
AR
134 HttpRequest *const request = http->request;
135 Must(http->storeEntry() || request);
136 const bool mayForward = !http->storeEntry() && handleRequest(request);
92ae4c86
AR
137
138 if (http->storeEntry() != NULL) {
139 debugs(33, 4, "got an immediate response");
92ae4c86
AR
140 clientSetKeepaliveFlag(http);
141 context->pullData();
eacfca83 142 } else if (mayForward) {
92ae4c86
AR
143 debugs(33, 4, "forwarding request to server side");
144 assert(http->storeEntry() == NULL);
9bafa70d 145 clientProcessRequest(this, Http1::RequestParserPointer(), context.getRaw());
92ae4c86
AR
146 } else {
147 debugs(33, 4, "will resume processing later");
148 }
149}
150
151void
ced8def3 152Ftp::Server::processParsedRequest(ClientSocketContext *)
92ae4c86 153{
eacfca83
AR
154 Must(getConcurrentRequestCount() == 1);
155
92ae4c86
AR
156 // Process FTP request asynchronously to make sure FTP
157 // data connection accept callback is fired first.
158 CallJobHere(33, 4, CbcPointer<Server>(this),
159 Ftp::Server, doProcessRequest);
160}
161
162/// imports more upload data from the data connection
163void
164Ftp::Server::readUploadData(const CommIoCbParams &io)
165{
e7ce227f 166 debugs(33, 5, io.conn << " size " << io.size);
92ae4c86
AR
167 Must(reader != NULL);
168 reader = NULL;
169
170 assert(Comm::IsConnOpen(dataConn));
171 assert(io.conn->fd == dataConn->fd);
172
173 if (io.flag == Comm::OK && bodyPipe != NULL) {
174 if (io.size > 0) {
175 kb_incr(&(statCounter.client_http.kbytes_in), io.size);
176
177 char *const current_buf = uploadBuf + uploadAvailSize;
178 if (io.buf != current_buf)
179 memmove(current_buf, io.buf, io.size);
180 uploadAvailSize += io.size;
181 shovelUploadData();
182 } else if (io.size == 0) {
e7ce227f 183 debugs(33, 5, io.conn << " closed");
92ae4c86
AR
184 closeDataConnection();
185 if (uploadAvailSize <= 0)
186 finishDechunkingRequest(true);
187 }
188 } else { // not Comm::Flags::OK or unexpected read
e7ce227f 189 debugs(33, 5, io.conn << " closed");
92ae4c86
AR
190 closeDataConnection();
191 finishDechunkingRequest(false);
192 }
193
194}
195
196/// shovel upload data from the internal buffer to the body pipe if possible
197void
198Ftp::Server::shovelUploadData()
199{
200 assert(bodyPipe != NULL);
201
e7ce227f 202 debugs(33, 5, "handling FTP request data for " << clientConnection);
92ae4c86 203 const size_t putSize = bodyPipe->putMoreData(uploadBuf,
27c841f6 204 uploadAvailSize);
92ae4c86
AR
205 if (putSize > 0) {
206 uploadAvailSize -= putSize;
207 if (uploadAvailSize > 0)
208 memmove(uploadBuf, uploadBuf + putSize, uploadAvailSize);
209 }
210
211 if (Comm::IsConnOpen(dataConn))
212 maybeReadUploadData();
213 else if (uploadAvailSize <= 0)
214 finishDechunkingRequest(true);
215}
216
217void
218Ftp::Server::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
219{
220 shovelUploadData();
221}
222
223void
224Ftp::Server::noteBodyConsumerAborted(BodyPipe::Pointer ptr)
225{
226 ConnStateData::noteBodyConsumerAborted(ptr);
227 closeDataConnection();
228}
229
230/// accept a new FTP control connection and hand it to a dedicated Server
231void
232Ftp::Server::AcceptCtrlConnection(const CommAcceptCbParams &params)
233{
234 MasterXaction::Pointer xact = params.xaction;
235 AnyP::PortCfgPointer s = xact->squidPort;
236
237 // NP: it is possible the port was reconfigured when the call or accept() was queued.
238
239 if (params.flag != Comm::OK) {
240 // Its possible the call was still queued when the client disconnected
e7ce227f 241 debugs(33, 2, s->listenConn << ": FTP accept failure: " << xstrerr(params.xerrno));
92ae4c86
AR
242 return;
243 }
244
e7ce227f 245 debugs(33, 4, params.conn << ": accepted");
92ae4c86
AR
246 fd_note(params.conn->fd, "client ftp connect");
247
248 if (s->tcp_keepalive.enabled)
249 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
250
251 ++incoming_sockets_accepted;
252
253 AsyncJob::Start(new Server(xact));
254}
255
256void
257Ftp::StartListening()
258{
259 for (AnyP::PortCfgPointer s = FtpPortList; s != NULL; s = s->next) {
260 if (MAXTCPLISTENPORTS == NHttpSockets) {
261 debugs(1, DBG_IMPORTANT, "Ignoring ftp_port lines exceeding the" <<
262 " limit of " << MAXTCPLISTENPORTS << " ports.");
263 break;
264 }
265
266 // direct new connections accepted by listenConn to Accept()
267 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
268 RefCount<AcceptCall> subCall = commCbCall(5, 5, "Ftp::Server::AcceptCtrlConnection",
27c841f6 269 CommAcceptCbPtrFun(Ftp::Server::AcceptCtrlConnection,
f53969cc 270 CommAcceptCbParams(NULL)));
92ae4c86
AR
271 clientStartListeningOn(s, subCall, Ipc::fdnFtpSocket);
272 }
273}
274
275void
276Ftp::StopListening()
277{
ecba3352 278 for (AnyP::PortCfgPointer s = FtpPortList; s != NULL; s = s->next) {
92ae4c86
AR
279 if (s->listenConn != NULL) {
280 debugs(1, DBG_IMPORTANT, "Closing FTP port " << s->listenConn->local);
281 s->listenConn->close();
282 s->listenConn = NULL;
283 }
284 }
285}
286
287void
288Ftp::Server::notePeerConnection(Comm::ConnectionPointer conn)
289{
290 // find request
291 ClientSocketContext::Pointer context = getCurrentContext();
292 Must(context != NULL);
293 ClientHttpRequest *const http = context->http;
294 Must(http != NULL);
295 HttpRequest *const request = http->request;
296 Must(request != NULL);
297
298 // this is not an idle connection, so we do not want I/O monitoring
299 const bool monitor = false;
300
301 // make FTP peer connection exclusive to our request
302 pinConnection(conn, request, conn->getPeer(), false, monitor);
303}
304
305void
306Ftp::Server::clientPinnedConnectionClosed(const CommCloseCbParams &io)
307{
308 ConnStateData::clientPinnedConnectionClosed(io);
309
310 // if the server control connection is gone, reset state to login again
e7ce227f
AR
311 resetLogin("control connection closure");
312
43446566
AR
313 // XXX: Reseting is not enough. FtpRelay::sendCommand() will not re-login
314 // because FtpRelay::serverState() is not going to be fssConnected.
92ae4c86
AR
315}
316
e7ce227f
AR
317/// clear client and server login-related state after the old login is gone
318void
319Ftp::Server::resetLogin(const char *reason)
320{
321 debugs(33, 5, "will need to re-login due to " << reason);
aea65fec 322 master->clientReadGreeting = false;
e7ce227f
AR
323 changeState(fssBegin, reason);
324}
325
92ae4c86
AR
326/// computes uri member from host and, if tracked, working dir with file name
327void
1ab04517 328Ftp::Server::calcUri(const SBuf *file)
92ae4c86
AR
329{
330 uri = "ftp://";
331 uri.append(host);
aea65fec
AR
332 if (port->ftp_track_dirs && master->workingDir.length()) {
333 if (master->workingDir[0] != '/')
ab4c5a36 334 uri.append("/", 1);
aea65fec 335 uri.append(master->workingDir);
92ae4c86
AR
336 }
337
1ab04517 338 if (uri[uri.length() - 1] != '/')
ab4c5a36 339 uri.append("/", 1);
92ae4c86
AR
340
341 if (port->ftp_track_dirs && file) {
1ab04517
AR
342 static const CharacterSet Slash("/", "/");
343 Parser::Tokenizer tok(*file);
344 tok.skipAll(Slash);
345 uri.append(tok.remaining());
92ae4c86
AR
346 }
347}
348
349/// Starts waiting for a data connection. Returns listening port.
350/// On errors, responds with an error and returns zero.
351unsigned int
352Ftp::Server::listenForDataConnection()
353{
354 closeDataConnection();
355
356 Comm::ConnectionPointer conn = new Comm::Connection;
357 conn->flags = COMM_NONBLOCKING;
358 conn->local = transparent() ? port->s : clientConnection->local;
359 conn->local.port(0);
1ab04517 360 const char *const note = uri.c_str();
92ae4c86
AR
361 comm_open_listener(SOCK_STREAM, IPPROTO_TCP, conn, note);
362 if (!Comm::IsConnOpen(conn)) {
363 debugs(5, DBG_CRITICAL, "comm_open_listener failed for FTP data: " <<
364 conn->local << " error: " << errno);
365 writeCustomReply(451, "Internal error");
366 return 0;
367 }
368
369 typedef CommCbMemFunT<Server, CommAcceptCbParams> AcceptDialer;
370 typedef AsyncCallT<AcceptDialer> AcceptCall;
371 RefCount<AcceptCall> call = static_cast<AcceptCall*>(JobCallback(5, 5, AcceptDialer, this, Ftp::Server::acceptDataConnection));
372 Subscription::Pointer sub = new CallSubscription<AcceptCall>(call);
373 listener = call.getRaw();
374 dataListenConn = conn;
375 AsyncJob::Start(new Comm::TcpAcceptor(conn, note, sub));
376
377 const unsigned int listeningPort = comm_local_port(conn->fd);
378 conn->local.port(listeningPort);
379 return listeningPort;
380}
381
382void
383Ftp::Server::acceptDataConnection(const CommAcceptCbParams &params)
384{
385 if (params.flag != Comm::OK) {
386 // Its possible the call was still queued when the client disconnected
387 debugs(33, 2, dataListenConn << ": accept "
388 "failure: " << xstrerr(params.xerrno));
389 return;
390 }
391
392 debugs(33, 4, "accepted " << params.conn);
393 fd_note(params.conn->fd, "passive client ftp data");
394 ++incoming_sockets_accepted;
395
396 if (!clientConnection) {
397 debugs(33, 5, "late data connection?");
398 closeDataConnection(); // in case we are still listening
399 params.conn->close();
27c841f6 400 } else if (params.conn->remote != clientConnection->remote) {
92ae4c86
AR
401 debugs(33, 2, "rogue data conn? ctrl: " << clientConnection->remote);
402 params.conn->close();
403 // Some FTP servers close control connection here, but it may make
404 // things worse from DoS p.o.v. and no better from data stealing p.o.v.
405 } else {
406 closeDataConnection();
407 dataConn = params.conn;
408 uploadAvailSize = 0;
409 debugs(33, 7, "ready for data");
410 if (onDataAcceptCall != NULL) {
411 AsyncCall::Pointer call = onDataAcceptCall;
412 onDataAcceptCall = NULL;
413 // If we got an upload request, start reading data from the client.
aea65fec 414 if (master->serverState == fssHandleUploadRequest)
92ae4c86
AR
415 maybeReadUploadData();
416 else
aea65fec 417 Must(master->serverState == fssHandleDataRequest);
92ae4c86
AR
418 MemBuf mb;
419 mb.init();
4391cd15 420 mb.appendf("150 Data connection opened.\r\n");
92ae4c86
AR
421 Comm::Write(clientConnection, &mb, call);
422 }
423 }
424}
425
426void
427Ftp::Server::closeDataConnection()
428{
429 if (listener != NULL) {
430 listener->cancel("no longer needed");
431 listener = NULL;
432 }
433
434 if (Comm::IsConnOpen(dataListenConn)) {
e7ce227f 435 debugs(33, 5, "FTP closing client data listen socket: " <<
92ae4c86
AR
436 *dataListenConn);
437 dataListenConn->close();
438 }
439 dataListenConn = NULL;
440
441 if (reader != NULL) {
442 // Comm::ReadCancel can deal with negative FDs
443 Comm::ReadCancel(dataConn->fd, reader);
444 reader = NULL;
445 }
446
447 if (Comm::IsConnOpen(dataConn)) {
e7ce227f 448 debugs(33, 5, "FTP closing client data connection: " <<
92ae4c86
AR
449 *dataConn);
450 dataConn->close();
451 }
452 dataConn = NULL;
453}
454
455/// Writes FTP [error] response before we fully parsed the FTP request and
456/// created the corresponding HTTP request wrapper for that FTP request.
457void
458Ftp::Server::writeEarlyReply(const int code, const char *msg)
459{
e7ce227f 460 debugs(33, 7, code << ' ' << msg);
92ae4c86
AR
461 assert(99 < code && code < 1000);
462
463 MemBuf mb;
464 mb.init();
4391cd15 465 mb.appendf("%i %s\r\n", code, msg);
92ae4c86
AR
466
467 typedef CommCbMemFunT<Server, CommIoCbParams> Dialer;
468 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, Ftp::Server::wroteEarlyReply);
469 Comm::Write(clientConnection, &mb, call);
470
471 flags.readMore = false;
472
473 // TODO: Create master transaction. Log it in wroteEarlyReply().
474}
475
476void
477Ftp::Server::writeReply(MemBuf &mb)
478{
aea65fec
AR
479 debugs(9, 2, "FTP Client " << clientConnection);
480 debugs(9, 2, "FTP Client REPLY:\n---------\n" << mb.buf <<
92ae4c86
AR
481 "\n----------");
482
483 typedef CommCbMemFunT<Server, CommIoCbParams> Dialer;
484 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, Ftp::Server::wroteReply);
485 Comm::Write(clientConnection, &mb, call);
486}
487
488void
489Ftp::Server::writeCustomReply(const int code, const char *msg, const HttpReply *reply)
490{
e7ce227f 491 debugs(33, 7, code << ' ' << msg);
92ae4c86
AR
492 assert(99 < code && code < 1000);
493
494 const bool sendDetails = reply != NULL &&
789217a2 495 reply->header.has(Http::HdrType::FTP_STATUS) && reply->header.has(Http::HdrType::FTP_REASON);
92ae4c86
AR
496
497 MemBuf mb;
498 mb.init();
499 if (sendDetails) {
4391cd15
AJ
500 mb.appendf("%i-%s\r\n", code, msg);
501 mb.appendf(" Server reply:\r\n");
92ae4c86 502 Ftp::PrintReply(mb, reply, " ");
4391cd15 503 mb.appendf("%i \r\n", code);
92ae4c86 504 } else
4391cd15 505 mb.appendf("%i %s\r\n", code, msg);
92ae4c86
AR
506
507 writeReply(mb);
508}
509
510void
511Ftp::Server::changeState(const ServerState newState, const char *reason)
512{
aea65fec
AR
513 if (master->serverState == newState) {
514 debugs(33, 3, "client state unchanged at " << master->serverState <<
92ae4c86 515 " because " << reason);
aea65fec 516 master->serverState = newState;
92ae4c86 517 } else {
aea65fec 518 debugs(33, 3, "client state was " << master->serverState <<
92ae4c86 519 ", now " << newState << " because " << reason);
aea65fec 520 master->serverState = newState;
92ae4c86
AR
521 }
522}
523
524/// whether the given FTP command has a pathname parameter
525static bool
1ab04517
AR
526Ftp::CommandHasPathParameter(const SBuf &cmd)
527{
528 static std::set<SBuf> PathedCommands;
529 if (!PathedCommands.size()) {
530 PathedCommands.insert(cmdMlst());
531 PathedCommands.insert(cmdMlsd());
532 PathedCommands.insert(cmdStat());
533 PathedCommands.insert(cmdNlst());
534 PathedCommands.insert(cmdList());
535 PathedCommands.insert(cmdMkd());
536 PathedCommands.insert(cmdRmd());
537 PathedCommands.insert(cmdDele());
538 PathedCommands.insert(cmdRnto());
539 PathedCommands.insert(cmdRnfr());
540 PathedCommands.insert(cmdAppe());
541 PathedCommands.insert(cmdStor());
542 PathedCommands.insert(cmdRetr());
543 PathedCommands.insert(cmdSmnt());
544 PathedCommands.insert(cmdCwd());
545 }
546
547 return PathedCommands.find(cmd) != PathedCommands.end();
92ae4c86
AR
548}
549
eacfca83
AR
550/// creates a context filled with an error message for a given early error
551ClientSocketContext *
552Ftp::Server::earlyError(const EarlyErrorKind eek)
553{
554 /* Default values, to be updated by the switch statement below */
555 int scode = 421;
556 const char *reason = "Internal error";
557 const char *errUri = "error:ftp-internal-early-error";
558
559 switch (eek) {
560 case eekHugeRequest:
561 scode = 421;
562 reason = "Huge request";
563 errUri = "error:ftp-huge-request";
564 break;
565
566 case eekMissingLogin:
567 scode = 530;
568 reason = "Must login first";
569 errUri = "error:ftp-must-login-first";
570 break;
571
572 case eekMissingUsername:
573 scode = 501;
574 reason = "Missing username";
575 errUri = "error:ftp-missing-username";
576 break;
577
578 case eekMissingHost:
579 scode = 501;
580 reason = "Missing host";
581 errUri = "error:ftp-missing-host";
582 break;
583
584 case eekUnsupportedCommand:
585 scode = 502;
586 reason = "Unknown or unsupported command";
587 errUri = "error:ftp-unsupported-command";
588 break;
589
590 case eekInvalidUri:
591 scode = 501;
592 reason = "Invalid URI";
593 errUri = "error:ftp-invalid-uri";
594 break;
595
596 case eekMalformedCommand:
597 scode = 421;
598 reason = "Malformed command";
599 errUri = "error:ftp-malformed-command";
600 break;
601
74d4eef6 602 // no default so that a compiler can check that we have covered all cases
eacfca83
AR
603 }
604
605 ClientSocketContext *context = abortRequestParsing(errUri);
606 clientStreamNode *node = context->getClientReplyContext();
607 Must(node);
608 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
3d01c5ab 609 Must(repContext);
eacfca83
AR
610
611 // We cannot relay FTP scode/reason via HTTP-specific ErrorState.
612 // TODO: When/if ErrorState can handle native FTP errors, use it instead.
613 HttpReply *reply = Ftp::HttpReplyWrapper(scode, reason, Http::scBadRequest, -1);
614 repContext->setReplyToReply(reply);
615 return context;
616}
617
92ae4c86 618/// Parses a single FTP request on the control connection.
eacfca83
AR
619/// Returns a new ClientSocketContext on valid requests and all errors.
620/// Returns NULL on incomplete requests that may still succeed given more data.
92ae4c86 621ClientSocketContext *
9bafa70d 622Ftp::Server::parseOneRequest()
92ae4c86 623{
eacfca83
AR
624 flags.readMore = false; // common for all but one case below
625
1ab04517 626 // OWS <command> [ RWS <parameter> ] OWS LF
aea65fec
AR
627
628 // InlineSpaceChars are isspace(3) or RFC 959 Section 3.1.1.5.2, except
629 // for the LF character that we must exclude here (but see FullWhiteSpace).
630 static const char * const InlineSpaceChars = " \f\r\t\v";
631 static const CharacterSet InlineSpace = CharacterSet("Ftp::Inline", InlineSpaceChars);
632 static const CharacterSet FullWhiteSpace = (InlineSpace + CharacterSet::LF).rename("Ftp::FWS");
633 static const CharacterSet CommandChars = FullWhiteSpace.complement("Ftp::Command");
634 static const CharacterSet TailChars = CharacterSet::LF.complement("Ftp::Tail");
92ae4c86 635
1ab04517
AR
636 // This set is used to ignore empty commands without allowing an attacker
637 // to keep us endlessly busy by feeding us whitespace or empty commands.
aea65fec 638 static const CharacterSet &LeadingSpace = FullWhiteSpace;
92ae4c86 639
1ab04517
AR
640 SBuf cmd;
641 SBuf params;
92ae4c86 642
1ab04517 643 Parser::Tokenizer tok(in.buf);
92ae4c86 644
1ab04517 645 (void)tok.skipAll(LeadingSpace); // leading OWS and empty commands
aea65fec 646 const bool parsed = tok.prefix(cmd, CommandChars); // required command
92ae4c86 647
1ab04517 648 // note that the condition below will eat either RWS or trailing OWS
aea65fec 649 if (parsed && tok.skipAll(InlineSpace) && tok.prefix(params, TailChars)) {
1ab04517
AR
650 // now params may include trailing OWS
651 // TODO: Support right-trimming using CharacterSet in Tokenizer instead
aea65fec 652 static const SBuf bufWhiteSpace(InlineSpaceChars);
1ab04517 653 params.trim(bufWhiteSpace, false, true);
92ae4c86
AR
654 }
655
eacfca83
AR
656 // Why limit command line and parameters size? Did not we just parse them?
657 // XXX: Our good old String cannot handle very long strings.
658 const SBuf::size_type tokenMax = min(
74d4eef6
A
659 static_cast<SBuf::size_type>(32*1024), // conservative
660 static_cast<SBuf::size_type>(Config.maxRequestHeaderSize));
eacfca83
AR
661 if (cmd.length() > tokenMax || params.length() > tokenMax) {
662 changeState(fssError, "huge req token");
663 quitAfterError(NULL);
664 return earlyError(eekHugeRequest);
665 }
666
1ab04517 667 // technically, we may skip multiple NLs below, but that is OK
aea65fec 668 if (!parsed || !tok.skipAll(CharacterSet::LF)) { // did not find terminating LF yet
1ab04517
AR
669 // we need more data, but can we buffer more?
670 if (in.buf.length() >= Config.maxRequestHeaderSize) {
671 changeState(fssError, "huge req");
eacfca83
AR
672 quitAfterError(NULL);
673 return earlyError(eekHugeRequest);
1ab04517 674 } else {
eacfca83 675 flags.readMore = true;
1ab04517
AR
676 debugs(33, 5, "Waiting for more, up to " <<
677 (Config.maxRequestHeaderSize - in.buf.length()));
678 return NULL;
679 }
680 }
92ae4c86 681
1ab04517
AR
682 Must(parsed && cmd.length());
683 consumeInput(tok.parsedSize()); // TODO: Would delaying optimize copying?
92ae4c86 684
1ab04517 685 debugs(33, 2, ">>ftp " << cmd << (params.isEmpty() ? "" : " ") << params);
92ae4c86 686
1ab04517 687 cmd.toUpper(); // this should speed up and simplify future comparisons
92ae4c86 688
e7ce227f
AR
689 // interception cases do not need USER to calculate the uri
690 if (!transparent()) {
aea65fec 691 if (!master->clientReadGreeting) {
e7ce227f 692 // the first command must be USER
eacfca83
AR
693 if (!pinning.pinned && cmd != cmdUser())
694 return earlyError(eekMissingLogin);
92ae4c86 695 }
92ae4c86 696
e7ce227f 697 // process USER request now because it sets FTP peer host name
eacfca83
AR
698 if (cmd == cmdUser()) {
699 if (ClientSocketContext *errCtx = handleUserRequest(cmd, params))
700 return errCtx;
701 }
e7ce227f 702 }
92ae4c86 703
eacfca83
AR
704 if (!Ftp::SupportedCommand(cmd))
705 return earlyError(eekUnsupportedCommand);
92ae4c86
AR
706
707 const HttpRequestMethod method =
1ab04517 708 cmd == cmdAppe() || cmd == cmdStor() || cmd == cmdStou() ?
92ae4c86
AR
709 Http::METHOD_PUT : Http::METHOD_GET;
710
aea65fec 711 const SBuf *path = (params.length() && CommandHasPathParameter(cmd)) ?
27c841f6 712 &params : NULL;
1ab04517
AR
713 calcUri(path);
714 char *newUri = xstrdup(uri.c_str());
92ae4c86
AR
715 HttpRequest *const request = HttpRequest::CreateFromUrlAndMethod(newUri, method);
716 if (!request) {
e7ce227f 717 debugs(33, 5, "Invalid FTP URL: " << uri);
1ab04517 718 uri.clear();
92ae4c86 719 safe_free(newUri);
eacfca83 720 return earlyError(eekInvalidUri);
92ae4c86
AR
721 }
722
723 request->flags.ftpNative = true;
9bafa70d 724 request->http_ver = Http::ProtocolVersion(Ftp::ProtocolVersion().major, Ftp::ProtocolVersion().minor);
92ae4c86
AR
725
726 // Our fake Request-URIs are not distinctive enough for caching to work
727 request->flags.cachable = false; // XXX: reset later by maybeCacheable()
728 request->flags.noCache = true;
729
789217a2
FC
730 request->header.putStr(Http::HdrType::FTP_COMMAND, cmd.c_str());
731 request->header.putStr(Http::HdrType::FTP_ARGUMENTS, params.c_str()); // may be ""
92ae4c86 732 if (method == Http::METHOD_PUT) {
789217a2
FC
733 request->header.putStr(Http::HdrType::EXPECT, "100-continue");
734 request->header.putStr(Http::HdrType::TRANSFER_ENCODING, "chunked");
92ae4c86
AR
735 }
736
737 ClientHttpRequest *const http = new ClientHttpRequest(this);
738 http->request = request;
739 HTTPMSGLOCK(http->request);
1ab04517 740 http->req_sz = tok.parsedSize();
92ae4c86
AR
741 http->uri = newUri;
742
743 ClientSocketContext *const result =
744 new ClientSocketContext(clientConnection, http);
745
746 StoreIOBuffer tempBuffer;
747 tempBuffer.data = result->reqbuf;
748 tempBuffer.length = HTTP_REQBUF_SZ;
749
750 ClientStreamData newServer = new clientReplyContext(http);
751 ClientStreamData newClient = result;
752 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
753 clientReplyStatus, newServer, clientSocketRecipient,
754 clientSocketDetach, newClient, tempBuffer);
755
92ae4c86 756 result->flags.parsed_ok = 1;
92ae4c86
AR
757 return result;
758}
759
760void
761Ftp::Server::handleReply(HttpReply *reply, StoreIOBuffer data)
762{
763 // the caller guarantees that we are dealing with the current context only
764 ClientSocketContext::Pointer context = getCurrentContext();
765 assert(context != NULL);
766
767 if (context->http && context->http->al != NULL &&
27c841f6 768 !context->http->al->reply && reply) {
92ae4c86
AR
769 context->http->al->reply = reply;
770 HTTPMSGLOCK(context->http->al->reply);
771 }
772
773 static ReplyHandler handlers[] = {
774 NULL, // fssBegin
775 NULL, // fssConnected
776 &Ftp::Server::handleFeatReply, // fssHandleFeat
777 &Ftp::Server::handlePasvReply, // fssHandlePasv
778 &Ftp::Server::handlePortReply, // fssHandlePort
779 &Ftp::Server::handleDataReply, // fssHandleDataRequest
780 &Ftp::Server::handleUploadReply, // fssHandleUploadRequest
781 &Ftp::Server::handleEprtReply,// fssHandleEprt
782 &Ftp::Server::handleEpsvReply,// fssHandleEpsv
783 NULL, // fssHandleCwd
3cc0f4e7 784 NULL, // fssHandlePass
92ae4c86
AR
785 NULL, // fssHandleCdup
786 &Ftp::Server::handleErrorReply // fssError
787 };
788 const Server &server = dynamic_cast<const Ftp::Server&>(*context->getConn());
aea65fec 789 if (const ReplyHandler handler = handlers[server.master->serverState])
92ae4c86
AR
790 (this->*handler)(reply, data);
791 else
792 writeForwardedReply(reply);
793}
794
795void
aea65fec 796Ftp::Server::handleFeatReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
797{
798 if (getCurrentContext()->http->request->errType != ERR_NONE) {
799 writeCustomReply(502, "Server does not support FEAT", reply);
800 return;
801 }
802
f0174f5b
CT
803 HttpReply::Pointer featReply = Ftp::HttpReplyWrapper(211, "End", Http::scNoContent, 0);
804 HttpHeader const &serverReplyHeader = reply->header;
92ae4c86 805
92ae4c86
AR
806 HttpHeaderPos pos = HttpHeaderInitPos;
807 bool hasEPRT = false;
808 bool hasEPSV = false;
809 int prependSpaces = 1;
f0174f5b 810
789217a2
FC
811 featReply->header.putStr(Http::HdrType::FTP_PRE, "\"211-Features:\"");
812 const int scode = serverReplyHeader.getInt(Http::HdrType::FTP_STATUS);
f0174f5b
CT
813 if (scode == 211) {
814 while (const HttpHeaderEntry *e = serverReplyHeader.getEntry(&pos)) {
789217a2 815 if (e->id == Http::HdrType::FTP_PRE) {
f0174f5b
CT
816 // assume RFC 2389 FEAT response format, quoted by Squid:
817 // <"> SP NAME [SP PARAMS] <">
818 // but accommodate MS servers sending four SPs before NAME
819
820 // command name ends with (SP parameter) or quote
821 static const CharacterSet AfterFeatNameChars("AfterFeatName", " \"");
822 static const CharacterSet FeatNameChars = AfterFeatNameChars.complement("FeatName");
823
824 Parser::Tokenizer tok(SBuf(e->value.termedBuf()));
825 if (!tok.skip('"') || !tok.skip(' '))
826 continue;
827
828 // optional spaces; remember their number to accomodate MS servers
829 prependSpaces = 1 + tok.skipAll(CharacterSet::SP);
830
831 SBuf cmd;
832 if (!tok.prefix(cmd, FeatNameChars))
833 continue;
834 cmd.toUpper();
835
836 if (Ftp::SupportedCommand(cmd)) {
837 featReply->header.addEntry(e->clone());
838 }
839
840 if (cmd == cmdEprt())
841 hasEPRT = true;
842 else if (cmd == cmdEpsv())
843 hasEPSV = true;
844 }
92ae4c86 845 }
f0174f5b 846 } // else we got a FEAT error and will only report Squid-supported features
92ae4c86
AR
847
848 char buf[256];
92ae4c86
AR
849 if (!hasEPRT) {
850 snprintf(buf, sizeof(buf), "\"%*s\"", prependSpaces + 4, "EPRT");
789217a2 851 featReply->header.putStr(Http::HdrType::FTP_PRE, buf);
92ae4c86
AR
852 }
853 if (!hasEPSV) {
854 snprintf(buf, sizeof(buf), "\"%*s\"", prependSpaces + 4, "EPSV");
789217a2 855 featReply->header.putStr(Http::HdrType::FTP_PRE, buf);
92ae4c86
AR
856 }
857
f0174f5b 858 featReply->header.refreshMask();
92ae4c86 859
f0174f5b 860 writeForwardedReply(featReply.getRaw());
92ae4c86
AR
861}
862
863void
aea65fec 864Ftp::Server::handlePasvReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
865{
866 ClientSocketContext::Pointer context = getCurrentContext();
867 assert(context != NULL);
868
869 if (context->http->request->errType != ERR_NONE) {
870 writeCustomReply(502, "Server does not support PASV", reply);
871 return;
872 }
873
874 const unsigned short localPort = listenForDataConnection();
875 if (!localPort)
876 return;
877
878 char addr[MAX_IPSTRLEN];
879 // remote server in interception setups and local address otherwise
880 const Ip::Address &server = transparent() ?
881 clientConnection->local : dataListenConn->local;
882 server.toStr(addr, MAX_IPSTRLEN, AF_INET);
883 addr[MAX_IPSTRLEN - 1] = '\0';
884 for (char *c = addr; *c != '\0'; ++c) {
885 if (*c == '.')
886 *c = ',';
887 }
888
889 // In interception setups, we combine remote server address with a
890 // local port number and hope that traffic will be redirected to us.
891 // Do not use "227 =a,b,c,d,p1,p2" format or omit parens: some nf_ct_ftp
892 // versions block responses that use those alternative syntax rules!
893 MemBuf mb;
894 mb.init();
4391cd15 895 mb.appendf("227 Entering Passive Mode (%s,%i,%i).\r\n",
f680026f
SM
896 addr,
897 static_cast<int>(localPort / 256),
898 static_cast<int>(localPort % 256));
aea65fec 899 debugs(9, 3, Raw("writing", mb.buf, mb.size));
92ae4c86
AR
900 writeReply(mb);
901}
902
903void
aea65fec 904Ftp::Server::handlePortReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
905{
906 if (getCurrentContext()->http->request->errType != ERR_NONE) {
907 writeCustomReply(502, "Server does not support PASV (converted from PORT)", reply);
908 return;
909 }
910
911 writeCustomReply(200, "PORT successfully converted to PASV.");
912
913 // and wait for RETR
914}
915
916void
aea65fec 917Ftp::Server::handleErrorReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
918{
919 if (!pinning.pinned) // we failed to connect to server
1ab04517 920 uri.clear();
92ae4c86
AR
921 // 421: we will close due to fssError
922 writeErrorReply(reply, 421);
923}
924
925void
926Ftp::Server::handleDataReply(const HttpReply *reply, StoreIOBuffer data)
927{
928 if (reply != NULL && reply->sline.status() != Http::scOkay) {
929 writeForwardedReply(reply);
930 if (Comm::IsConnOpen(dataConn)) {
931 debugs(33, 3, "closing " << dataConn << " on KO reply");
932 closeDataConnection();
933 }
934 return;
935 }
936
937 if (!dataConn) {
938 // We got STREAM_COMPLETE (or error) and closed the client data conn.
939 debugs(33, 3, "ignoring FTP srv data response after clt data closure");
940 return;
941 }
942
943 if (!checkDataConnPost()) {
944 writeCustomReply(425, "Data connection is not established.");
945 closeDataConnection();
946 return;
947 }
948
e7ce227f 949 debugs(33, 7, data.length);
92ae4c86
AR
950
951 if (data.length <= 0) {
952 replyDataWritingCheckpoint(); // skip the actual write call
953 return;
954 }
955
956 MemBuf mb;
957 mb.init(data.length + 1, data.length + 1);
958 mb.append(data.data, data.length);
959
960 typedef CommCbMemFunT<Server, CommIoCbParams> Dialer;
961 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, Ftp::Server::wroteReplyData);
962 Comm::Write(dataConn, &mb, call);
963
964 getCurrentContext()->noteSentBodyBytes(data.length);
965}
966
967/// called when we are done writing a chunk of the response data
968void
969Ftp::Server::wroteReplyData(const CommIoCbParams &io)
970{
971 if (io.flag == Comm::ERR_CLOSING)
972 return;
973
974 if (io.flag != Comm::OK) {
aea65fec 975 debugs(33, 3, "FTP reply data writing failed: " << xstrerr(io.xerrno));
92ae4c86
AR
976 closeDataConnection();
977 writeCustomReply(426, "Data connection error; transfer aborted");
978 return;
979 }
980
981 assert(getCurrentContext()->http);
982 getCurrentContext()->http->out.size += io.size;
983 replyDataWritingCheckpoint();
984}
985
986/// ClientStream checks after (actual or skipped) reply data writing
987void
27c841f6
AR
988Ftp::Server::replyDataWritingCheckpoint()
989{
92ae4c86
AR
990 switch (getCurrentContext()->socketState()) {
991 case STREAM_NONE:
992 debugs(33, 3, "Keep going");
993 getCurrentContext()->pullData();
994 return;
995 case STREAM_COMPLETE:
e7ce227f 996 debugs(33, 3, "FTP reply data transfer successfully complete");
92ae4c86
AR
997 writeCustomReply(226, "Transfer complete");
998 break;
999 case STREAM_UNPLANNED_COMPLETE:
e7ce227f 1000 debugs(33, 3, "FTP reply data transfer failed: STREAM_UNPLANNED_COMPLETE");
92ae4c86
AR
1001 writeCustomReply(451, "Server error; transfer aborted");
1002 break;
1003 case STREAM_FAILED:
e7ce227f 1004 debugs(33, 3, "FTP reply data transfer failed: STREAM_FAILED");
92ae4c86
AR
1005 writeCustomReply(451, "Server error; transfer aborted");
1006 break;
1007 default:
1008 fatal("unreachable code");
1009 }
1010
1011 closeDataConnection();
1012}
1013
1014void
aea65fec 1015Ftp::Server::handleUploadReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
1016{
1017 writeForwardedReply(reply);
1018 // note that the client data connection may already be closed by now
1019}
1020
1021void
1022Ftp::Server::writeForwardedReply(const HttpReply *reply)
1023{
1024 assert(reply != NULL);
1025 const HttpHeader &header = reply->header;
789217a2
FC
1026 // adaptation and forwarding errors lack Http::HdrType::FTP_STATUS
1027 if (!header.has(Http::HdrType::FTP_STATUS)) {
92ae4c86
AR
1028 writeForwardedForeign(reply); // will get to Ftp::Server::wroteReply
1029 return;
1030 }
1031
1032 typedef CommCbMemFunT<Server, CommIoCbParams> Dialer;
1033 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, Ftp::Server::wroteReply);
1034 writeForwardedReplyAndCall(reply, call);
1035}
1036
1037void
aea65fec 1038Ftp::Server::handleEprtReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
1039{
1040 if (getCurrentContext()->http->request->errType != ERR_NONE) {
1041 writeCustomReply(502, "Server does not support PASV (converted from EPRT)", reply);
1042 return;
1043 }
1044
1045 writeCustomReply(200, "EPRT successfully converted to PASV.");
1046
1047 // and wait for RETR
1048}
1049
1050void
aea65fec 1051Ftp::Server::handleEpsvReply(const HttpReply *reply, StoreIOBuffer)
92ae4c86
AR
1052{
1053 if (getCurrentContext()->http->request->errType != ERR_NONE) {
1054 writeCustomReply(502, "Cannot connect to server", reply);
1055 return;
1056 }
1057
1058 const unsigned short localPort = listenForDataConnection();
1059 if (!localPort)
1060 return;
1061
aea65fec
AR
1062 // In interception setups, we use a local port number and hope that data
1063 // traffic will be redirected to us.
92ae4c86
AR
1064 MemBuf mb;
1065 mb.init();
4391cd15 1066 mb.appendf("229 Entering Extended Passive Mode (|||%u|)\r\n", localPort);
92ae4c86 1067
aea65fec 1068 debugs(9, 3, Raw("writing", mb.buf, mb.size));
92ae4c86
AR
1069 writeReply(mb);
1070}
1071
1072/// writes FTP error response with given status and reply-derived error details
1073void
1074Ftp::Server::writeErrorReply(const HttpReply *reply, const int scode)
1075{
1076 const HttpRequest *request = getCurrentContext()->http->request;
1077 assert(request);
1078
1079 MemBuf mb;
1080 mb.init();
1081
1082 if (request->errType != ERR_NONE)
4391cd15 1083 mb.appendf("%i-%s\r\n", scode, errorPageName(request->errType));
92ae4c86
AR
1084
1085 if (request->errDetail > 0) {
1086 // XXX: > 0 may not always mean that this is an errno
4391cd15 1087 mb.appendf("%i-Error: (%d) %s\r\n", scode,
f680026f
SM
1088 request->errDetail,
1089 strerror(request->errDetail));
92ae4c86
AR
1090 }
1091
02e1ed26 1092#if USE_ADAPTATION
92ae4c86
AR
1093 // XXX: Remove hard coded names. Use an error page template instead.
1094 const Adaptation::History::Pointer ah = request->adaptHistory();
1095 if (ah != NULL) { // XXX: add adapt::<all_h but use lastMeta here
1096 const String info = ah->allMeta.getByName("X-Response-Info");
1097 const String desc = ah->allMeta.getByName("X-Response-Desc");
1098 if (info.size())
4391cd15 1099 mb.appendf("%i-Information: %s\r\n", scode, info.termedBuf());
92ae4c86 1100 if (desc.size())
4391cd15 1101 mb.appendf("%i-Description: %s\r\n", scode, desc.termedBuf());
92ae4c86 1102 }
02e1ed26 1103#endif
92ae4c86
AR
1104
1105 assert(reply != NULL);
789217a2
FC
1106 const char *reason = reply->header.has(Http::HdrType::FTP_REASON) ?
1107 reply->header.getStr(Http::HdrType::FTP_REASON):
92ae4c86
AR
1108 reply->sline.reason();
1109
4391cd15 1110 mb.appendf("%i %s\r\n", scode, reason); // error terminating line
92ae4c86
AR
1111
1112 // TODO: errorpage.cc should detect FTP client and use
1113 // configurable FTP-friendly error templates which we should
1114 // write to the client "as is" instead of hiding most of the info
1115
1116 writeReply(mb);
1117}
1118
1119/// writes FTP response based on HTTP reply that is not an FTP-response wrapper
eacfca83 1120/// for example, internally-generated Squid "errorpages" end up here (for now)
92ae4c86
AR
1121void
1122Ftp::Server::writeForwardedForeign(const HttpReply *reply)
1123{
1124 changeState(fssConnected, "foreign reply");
1125 closeDataConnection();
1126 // 451: We intend to keep the control connection open.
1127 writeErrorReply(reply, 451);
1128}
1129
1130void
ced8def3 1131Ftp::Server::writeControlMsgAndCall(ClientSocketContext *, HttpReply *reply, AsyncCall::Pointer &call)
92ae4c86
AR
1132{
1133 // the caller guarantees that we are dealing with the current context only
789217a2 1134 // the caller should also make sure reply->header.has(Http::HdrType::FTP_STATUS)
92ae4c86
AR
1135 writeForwardedReplyAndCall(reply, call);
1136}
1137
1138void
1139Ftp::Server::writeForwardedReplyAndCall(const HttpReply *reply, AsyncCall::Pointer &call)
1140{
1141 assert(reply != NULL);
1142 const HttpHeader &header = reply->header;
1143
1144 // without status, the caller must use the writeForwardedForeign() path
789217a2
FC
1145 Must(header.has(Http::HdrType::FTP_STATUS));
1146 Must(header.has(Http::HdrType::FTP_REASON));
1147 const int scode = header.getInt(Http::HdrType::FTP_STATUS);
e7ce227f 1148 debugs(33, 7, "scode: " << scode);
92ae4c86
AR
1149
1150 // Status 125 or 150 implies upload or data request, but we still check
1151 // the state in case the server is buggy.
1152 if ((scode == 125 || scode == 150) &&
aea65fec
AR
1153 (master->serverState == fssHandleUploadRequest ||
1154 master->serverState == fssHandleDataRequest)) {
92ae4c86
AR
1155 if (checkDataConnPost()) {
1156 // If the data connection is ready, start reading data (here)
1157 // and forward the response to client (further below).
1158 debugs(33, 7, "data connection established, start data transfer");
aea65fec 1159 if (master->serverState == fssHandleUploadRequest)
92ae4c86
AR
1160 maybeReadUploadData();
1161 } else {
1162 // If we are waiting to accept the data connection, keep waiting.
1163 if (Comm::IsConnOpen(dataListenConn)) {
1164 debugs(33, 7, "wait for the client to establish a data connection");
1165 onDataAcceptCall = call;
1166 // TODO: Add connect timeout for passive connections listener?
1167 // TODO: Remember server response so that we can forward it?
1168 } else {
1169 // Either the connection was establised and closed after the
1170 // data was transferred OR we failed to establish an active
1171 // data connection and already sent the error to the client.
1172 // In either case, there is nothing more to do.
1173 debugs(33, 7, "done with data OR active connection failed");
1174 }
1175 return;
1176 }
1177 }
1178
1179 MemBuf mb;
1180 mb.init();
1181 Ftp::PrintReply(mb, reply);
1182
aea65fec
AR
1183 debugs(9, 2, "FTP Client " << clientConnection);
1184 debugs(9, 2, "FTP Client REPLY:\n---------\n" << mb.buf <<
92ae4c86
AR
1185 "\n----------");
1186
1187 Comm::Write(clientConnection, &mb, call);
1188}
1189
1190static void
ced8def3 1191Ftp::PrintReply(MemBuf &mb, const HttpReply *reply, const char *const)
92ae4c86
AR
1192{
1193 const HttpHeader &header = reply->header;
1194
1195 HttpHeaderPos pos = HttpHeaderInitPos;
1196 while (const HttpHeaderEntry *e = header.getEntry(&pos)) {
789217a2 1197 if (e->id == Http::HdrType::FTP_PRE) {
92ae4c86
AR
1198 String raw;
1199 if (httpHeaderParseQuotedString(e->value.rawBuf(), e->value.size(), &raw))
4391cd15 1200 mb.appendf("%s\r\n", raw.termedBuf());
92ae4c86
AR
1201 }
1202 }
1203
789217a2
FC
1204 if (header.has(Http::HdrType::FTP_STATUS)) {
1205 const char *reason = header.getStr(Http::HdrType::FTP_REASON);
1206 mb.appendf("%i %s\r\n", header.getInt(Http::HdrType::FTP_STATUS),
f680026f 1207 (reason ? reason : 0));
92ae4c86
AR
1208 }
1209}
1210
1211void
1212Ftp::Server::wroteEarlyReply(const CommIoCbParams &io)
1213{
1214 if (io.flag == Comm::ERR_CLOSING)
1215 return;
1216
1217 if (io.flag != Comm::OK) {
1218 debugs(33, 3, "FTP reply writing failed: " << xstrerr(io.xerrno));
1219 io.conn->close();
1220 return;
1221 }
1222
1223 ClientSocketContext::Pointer context = getCurrentContext();
1224 if (context != NULL && context->http) {
1225 context->http->out.size += io.size;
1226 context->http->out.headers_sz += io.size;
1227 }
1228
1229 flags.readMore = true;
1230 readSomeData();
1231}
1232
1233void
1234Ftp::Server::wroteReply(const CommIoCbParams &io)
1235{
1236 if (io.flag == Comm::ERR_CLOSING)
1237 return;
1238
1239 if (io.flag != Comm::OK) {
1240 debugs(33, 3, "FTP reply writing failed: " << xstrerr(io.xerrno));
1241 io.conn->close();
1242 return;
1243 }
1244
1245 ClientSocketContext::Pointer context = getCurrentContext();
1246 assert(context->http);
1247 context->http->out.size += io.size;
1248 context->http->out.headers_sz += io.size;
1249
aea65fec 1250 if (master->serverState == fssError) {
92ae4c86
AR
1251 debugs(33, 5, "closing on FTP server error");
1252 io.conn->close();
1253 return;
1254 }
1255
1256 const clientStream_status_t socketState = context->socketState();
1257 debugs(33, 5, "FTP client stream state " << socketState);
1258 switch (socketState) {
1259 case STREAM_UNPLANNED_COMPLETE:
1260 case STREAM_FAILED:
27c841f6
AR
1261 io.conn->close();
1262 return;
92ae4c86
AR
1263
1264 case STREAM_NONE:
1265 case STREAM_COMPLETE:
1266 flags.readMore = true;
1267 changeState(fssConnected, "Ftp::Server::wroteReply");
1268 if (in.bodyParser)
1269 finishDechunkingRequest(false);
1270 context->keepaliveNextRequest();
1271 return;
1272 }
1273}
1274
1275bool
eacfca83 1276Ftp::Server::handleRequest(HttpRequest *request)
27c841f6 1277{
eacfca83 1278 debugs(33, 9, request);
92ae4c86
AR
1279 Must(request);
1280
eacfca83 1281 HttpHeader &header = request->header;
789217a2
FC
1282 Must(header.has(Http::HdrType::FTP_COMMAND));
1283 String &cmd = header.findEntry(Http::HdrType::FTP_COMMAND)->value;
1284 Must(header.has(Http::HdrType::FTP_ARGUMENTS));
1285 String &params = header.findEntry(Http::HdrType::FTP_ARGUMENTS)->value;
eacfca83 1286
aea65fec 1287 if (do_debug(9, 2)) {
92ae4c86 1288 MemBuf mb;
92ae4c86 1289 mb.init();
10201568 1290 request->pack(&mb);
92ae4c86 1291
aea65fec
AR
1292 debugs(9, 2, "FTP Client " << clientConnection);
1293 debugs(9, 2, "FTP Client REQUEST:\n---------\n" << mb.buf <<
92ae4c86
AR
1294 "\n----------");
1295 }
1296
1ab04517
AR
1297 // TODO: When HttpHeader uses SBuf, change keys to SBuf
1298 typedef std::map<const std::string, RequestHandler> RequestHandlers;
1299 static RequestHandlers handlers;
1300 if (!handlers.size()) {
1301 handlers["LIST"] = &Ftp::Server::handleDataRequest;
1302 handlers["NLST"] = &Ftp::Server::handleDataRequest;
1303 handlers["MLSD"] = &Ftp::Server::handleDataRequest;
1304 handlers["FEAT"] = &Ftp::Server::handleFeatRequest;
1305 handlers["PASV"] = &Ftp::Server::handlePasvRequest;
1306 handlers["PORT"] = &Ftp::Server::handlePortRequest;
1307 handlers["RETR"] = &Ftp::Server::handleDataRequest;
1308 handlers["EPRT"] = &Ftp::Server::handleEprtRequest;
1309 handlers["EPSV"] = &Ftp::Server::handleEpsvRequest;
1310 handlers["CWD"] = &Ftp::Server::handleCwdRequest;
1311 handlers["PASS"] = &Ftp::Server::handlePassRequest;
1312 handlers["CDUP"] = &Ftp::Server::handleCdupRequest;
1313 }
92ae4c86
AR
1314
1315 RequestHandler handler = NULL;
1316 if (request->method == Http::METHOD_PUT)
1317 handler = &Ftp::Server::handleUploadRequest;
1318 else {
1ab04517
AR
1319 const RequestHandlers::const_iterator hi = handlers.find(cmd.termedBuf());
1320 if (hi != handlers.end())
1321 handler = hi->second;
92ae4c86
AR
1322 }
1323
1ab04517 1324 if (!handler) {
aea65fec 1325 debugs(9, 7, "forwarding " << cmd << " as is, no post-processing");
1ab04517
AR
1326 return true;
1327 }
1328
1329 return (this->*handler)(cmd, params);
92ae4c86
AR
1330}
1331
1332/// Called to parse USER command, which is required to create an HTTP request
eacfca83
AR
1333/// wrapper. W/o request, the errors are handled by returning earlyError().
1334ClientSocketContext *
ced8def3 1335Ftp::Server::handleUserRequest(const SBuf &, SBuf &params)
92ae4c86 1336{
eacfca83
AR
1337 if (params.isEmpty())
1338 return earlyError(eekMissingUsername);
92ae4c86 1339
e7ce227f 1340 // find the [end of] user name
1ab04517 1341 const SBuf::size_type eou = params.rfind('@');
eacfca83
AR
1342 if (eou == SBuf::npos || eou + 1 >= params.length())
1343 return earlyError(eekMissingHost);
92ae4c86 1344
e7ce227f 1345 // Determine the intended destination.
1ab04517 1346 host = params.substr(eou + 1, params.length());
92ae4c86
AR
1347 // If we can parse it as raw IPv6 address, then surround with "[]".
1348 // Otherwise (domain, IPv4, [bracketed] IPv6, garbage, etc), use as is.
1ab04517
AR
1349 if (host.find(':') != SBuf::npos) {
1350 const Ip::Address ipa(host.c_str());
92ae4c86 1351 if (!ipa.isAnyAddr()) {
1ab04517 1352 char ipBuf[MAX_IPSTRLEN];
92ae4c86
AR
1353 ipa.toHostStr(ipBuf, MAX_IPSTRLEN);
1354 host = ipBuf;
1355 }
1356 }
1357
1ab04517
AR
1358 // const SBuf login = params.substr(0, eou);
1359 params.chop(0, eou); // leave just the login part for the peer
1360
1361 SBuf oldUri;
aea65fec 1362 if (master->clientReadGreeting)
92ae4c86
AR
1363 oldUri = uri;
1364
aea65fec 1365 master->workingDir.clear();
1ab04517 1366 calcUri(NULL);
92ae4c86 1367
aea65fec
AR
1368 if (!master->clientReadGreeting) {
1369 debugs(9, 3, "set URI to " << uri);
92ae4c86 1370 } else if (oldUri.caseCmp(uri) == 0) {
aea65fec 1371 debugs(9, 5, "kept URI as " << oldUri);
92ae4c86 1372 } else {
aea65fec 1373 debugs(9, 3, "reset URI from " << oldUri << " to " << uri);
92ae4c86 1374 closeDataConnection();
92ae4c86 1375 unpinConnection(true); // close control connection to peer
e7ce227f 1376 resetLogin("URI reset");
92ae4c86
AR
1377 }
1378
eacfca83 1379 return NULL; // no early errors
92ae4c86
AR
1380}
1381
1382bool
ced8def3 1383Ftp::Server::handleFeatRequest(String &, String &)
92ae4c86 1384{
e7ce227f 1385 changeState(fssHandleFeat, "handleFeatRequest");
92ae4c86
AR
1386 return true;
1387}
1388
1389bool
ced8def3 1390Ftp::Server::handlePasvRequest(String &, String &params)
92ae4c86
AR
1391{
1392 if (gotEpsvAll) {
1393 setReply(500, "Bad PASV command");
1394 return false;
1395 }
1396
1397 if (params.size() > 0) {
1398 setReply(501, "Unexpected parameter");
1399 return false;
1400 }
1401
e7ce227f 1402 changeState(fssHandlePasv, "handlePasvRequest");
92ae4c86
AR
1403 // no need to fake PASV request via setDataCommand() in true PASV case
1404 return true;
1405}
1406
1407/// [Re]initializes dataConn for active data transfers. Does not connect.
1408bool
1409Ftp::Server::createDataConnection(Ip::Address cltAddr)
1410{
1411 assert(clientConnection != NULL);
1412 assert(!clientConnection->remote.isAnyAddr());
1413
1414 if (cltAddr != clientConnection->remote) {
1415 debugs(33, 2, "rogue PORT " << cltAddr << " request? ctrl: " << clientConnection->remote);
1416 // Closing the control connection would not help with attacks because
1417 // the client is evidently able to connect to us. Besides, closing
1418 // makes retrials easier for the client and more damaging to us.
1419 setReply(501, "Prohibited parameter value");
1420 return false;
1421 }
1422
1423 closeDataConnection();
1424
1425 Comm::ConnectionPointer conn = new Comm::Connection();
aea65fec 1426 conn->flags |= COMM_DOBIND;
92ae4c86
AR
1427
1428 // Use local IP address of the control connection as the source address
1429 // of the active data connection, or some clients will refuse to accept.
aea65fec 1430 conn->setAddrs(clientConnection->local, cltAddr);
92ae4c86
AR
1431 // RFC 959 requires active FTP connections to originate from port 20
1432 // but that would preclude us from supporting concurrent transfers! (XXX?)
1433 conn->local.port(0);
1434
aea65fec 1435 debugs(9, 3, "will actively connect from " << conn->local << " to " <<
92ae4c86
AR
1436 conn->remote);
1437
1438 dataConn = conn;
1439 uploadAvailSize = 0;
1440 return true;
1441}
1442
1443bool
ced8def3 1444Ftp::Server::handlePortRequest(String &, String &params)
92ae4c86
AR
1445{
1446 // TODO: Should PORT errors trigger closeDataConnection() cleanup?
1447
1448 if (gotEpsvAll) {
1449 setReply(500, "Rejecting PORT after EPSV ALL");
1450 return false;
1451 }
1452
1453 if (!params.size()) {
1454 setReply(501, "Missing parameter");
1455 return false;
1456 }
1457
1458 Ip::Address cltAddr;
1459 if (!Ftp::ParseIpPort(params.termedBuf(), NULL, cltAddr)) {
1460 setReply(501, "Invalid parameter");
1461 return false;
1462 }
1463
1464 if (!createDataConnection(cltAddr))
1465 return false;
1466
e7ce227f 1467 changeState(fssHandlePort, "handlePortRequest");
92ae4c86
AR
1468 setDataCommand();
1469 return true; // forward our fake PASV request
1470}
1471
1472bool
ced8def3 1473Ftp::Server::handleDataRequest(String &, String &)
92ae4c86
AR
1474{
1475 if (!checkDataConnPre())
1476 return false;
1477
e7ce227f 1478 changeState(fssHandleDataRequest, "handleDataRequest");
92ae4c86
AR
1479
1480 return true;
1481}
1482
1483bool
ced8def3 1484Ftp::Server::handleUploadRequest(String &, String &)
92ae4c86
AR
1485{
1486 if (!checkDataConnPre())
1487 return false;
1488
ec69bdb2
CT
1489 if (Config.accessList.forceRequestBodyContinuation) {
1490 ClientHttpRequest *http = getCurrentContext()->http;
1491 HttpRequest *request = http->request;
1492 ACLFilledChecklist bodyContinuationCheck(Config.accessList.forceRequestBodyContinuation, request, NULL);
1493 if (bodyContinuationCheck.fastCheck() == ACCESS_ALLOWED) {
1494 request->forcedBodyContinuation = true;
1495 if (checkDataConnPost()) {
1496 // Write control Msg
1497 writeEarlyReply(150, "Data connection opened");
1498 maybeReadUploadData();
1499 } else {
1500 // wait for acceptDataConnection but tell it to call wroteEarlyReply
1501 // after writing "150 Data connection opened"
1502 typedef CommCbMemFunT<Server, CommIoCbParams> Dialer;
1503 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, Ftp::Server::wroteEarlyReply);
1504 onDataAcceptCall = call;
1505 }
1506 }
1507 }
1508
e7ce227f 1509 changeState(fssHandleUploadRequest, "handleDataRequest");
92ae4c86
AR
1510
1511 return true;
1512}
1513
1514bool
ced8def3 1515Ftp::Server::handleEprtRequest(String &, String &params)
92ae4c86 1516{
aea65fec 1517 debugs(9, 3, "Process an EPRT " << params);
92ae4c86
AR
1518
1519 if (gotEpsvAll) {
1520 setReply(500, "Rejecting EPRT after EPSV ALL");
1521 return false;
1522 }
1523
1524 if (!params.size()) {
1525 setReply(501, "Missing parameter");
1526 return false;
1527 }
1528
1529 Ip::Address cltAddr;
1530 if (!Ftp::ParseProtoIpPort(params.termedBuf(), cltAddr)) {
1531 setReply(501, "Invalid parameter");
1532 return false;
1533 }
1534
1535 if (!createDataConnection(cltAddr))
1536 return false;
1537
e7ce227f 1538 changeState(fssHandleEprt, "handleEprtRequest");
92ae4c86
AR
1539 setDataCommand();
1540 return true; // forward our fake PASV request
1541}
1542
1543bool
ced8def3 1544Ftp::Server::handleEpsvRequest(String &, String &params)
92ae4c86 1545{
aea65fec 1546 debugs(9, 3, "Process an EPSV command with params: " << params);
92ae4c86
AR
1547 if (params.size() <= 0) {
1548 // treat parameterless EPSV as "use the protocol of the ctrl conn"
1549 } else if (params.caseCmp("ALL") == 0) {
1550 setReply(200, "EPSV ALL ok");
1551 gotEpsvAll = true;
1552 return false;
1553 } else if (params.cmp("2") == 0) {
1554 if (!Ip::EnableIpv6) {
1555 setReply(522, "Network protocol not supported, use (1)");
1556 return false;
1557 }
1558 } else if (params.cmp("1") != 0) {
1559 setReply(501, "Unsupported EPSV parameter");
1560 return false;
1561 }
1562
e7ce227f 1563 changeState(fssHandleEpsv, "handleEpsvRequest");
92ae4c86
AR
1564 setDataCommand();
1565 return true; // forward our fake PASV request
1566}
1567
1568bool
ced8def3 1569Ftp::Server::handleCwdRequest(String &, String &)
92ae4c86 1570{
e7ce227f 1571 changeState(fssHandleCwd, "handleCwdRequest");
92ae4c86
AR
1572 return true;
1573}
1574
1575bool
ced8def3 1576Ftp::Server::handlePassRequest(String &, String &)
92ae4c86 1577{
e7ce227f 1578 changeState(fssHandlePass, "handlePassRequest");
92ae4c86
AR
1579 return true;
1580}
1581
1582bool
ced8def3 1583Ftp::Server::handleCdupRequest(String &, String &)
92ae4c86 1584{
e7ce227f 1585 changeState(fssHandleCdup, "handleCdupRequest");
92ae4c86
AR
1586 return true;
1587}
1588
1589// Convert user PORT, EPRT, PASV, or EPSV data command to Squid PASV command.
1590// Squid FTP client decides what data command to use with peers.
1591void
1592Ftp::Server::setDataCommand()
1593{
1594 ClientHttpRequest *const http = getCurrentContext()->http;
1595 assert(http != NULL);
1596 HttpRequest *const request = http->request;
1597 assert(request != NULL);
1598 HttpHeader &header = request->header;
789217a2
FC
1599 header.delById(Http::HdrType::FTP_COMMAND);
1600 header.putStr(Http::HdrType::FTP_COMMAND, "PASV");
1601 header.delById(Http::HdrType::FTP_ARGUMENTS);
1602 header.putStr(Http::HdrType::FTP_ARGUMENTS, "");
aea65fec 1603 debugs(9, 5, "client data command converted to fake PASV");
92ae4c86
AR
1604}
1605
1606/// check that client data connection is ready for future I/O or at least
1607/// has a chance of becoming ready soon.
1608bool
1609Ftp::Server::checkDataConnPre()
1610{
1611 if (Comm::IsConnOpen(dataConn))
1612 return true;
1613
1614 if (Comm::IsConnOpen(dataListenConn)) {
1615 // We are still waiting for a client to connect to us after PASV.
1616 // Perhaps client's data conn handshake has not reached us yet.
1617 // After we talk to the server, checkDataConnPost() will recheck.
1618 debugs(33, 3, "expecting clt data conn " << dataListenConn);
1619 return true;
1620 }
1621
1622 if (!dataConn || dataConn->remote.isAnyAddr()) {
1623 debugs(33, 5, "missing " << dataConn);
1624 // TODO: use client address and default port instead.
1625 setReply(425, "Use PORT or PASV first");
1626 return false;
1627 }
1628
1629 // active transfer: open a data connection from Squid to client
1630 typedef CommCbMemFunT<Server, CommConnectCbParams> Dialer;
1631 connector = JobCallback(17, 3, Dialer, this, Ftp::Server::connectedForData);
1632 Comm::ConnOpener *cs = new Comm::ConnOpener(dataConn, connector,
27c841f6 1633 Config.Timeout.connect);
92ae4c86
AR
1634 AsyncJob::Start(cs);
1635 return false; // ConnStateData::processFtpRequest waits handleConnectDone
1636}
1637
1638/// Check that client data connection is ready for immediate I/O.
1639bool
1640Ftp::Server::checkDataConnPost() const
1641{
1642 if (!Comm::IsConnOpen(dataConn)) {
1643 debugs(33, 3, "missing client data conn: " << dataConn);
1644 return false;
1645 }
1646 return true;
1647}
1648
1649/// Done establishing a data connection to the user.
1650void
1651Ftp::Server::connectedForData(const CommConnectCbParams &params)
1652{
1653 connector = NULL;
1654
1655 if (params.flag != Comm::OK) {
1656 /* it might have been a timeout with a partially open link */
1657 if (params.conn != NULL)
1658 params.conn->close();
1659 setReply(425, "Cannot open data connection.");
1660 ClientSocketContext::Pointer context = getCurrentContext();
1661 Must(context->http);
1662 Must(context->http->storeEntry() != NULL);
1663 } else {
1664 Must(dataConn == params.conn);
1665 Must(Comm::IsConnOpen(params.conn));
1666 fd_note(params.conn->fd, "active client ftp data");
1667 }
1668
1669 doProcessRequest();
1670}
1671
1672void
1673Ftp::Server::setReply(const int code, const char *msg)
1674{
1675 ClientSocketContext::Pointer context = getCurrentContext();
1676 ClientHttpRequest *const http = context->http;
1677 assert(http != NULL);
1678 assert(http->storeEntry() == NULL);
1679
43446566 1680 HttpReply *const reply = Ftp::HttpReplyWrapper(code, msg, Http::scNoContent, 0);
92ae4c86
AR
1681
1682 setLogUri(http, urlCanonicalClean(http->request));
1683
1684 clientStreamNode *const node = context->getClientReplyContext();
1685 clientReplyContext *const repContext =
1686 dynamic_cast<clientReplyContext *>(node->data.getRaw());
1687 assert(repContext != NULL);
1688
1689 RequestFlags reqFlags;
1690 reqFlags.cachable = false; // force releaseRequest() in storeCreateEntry()
1691 reqFlags.noCache = true;
1692 repContext->createStoreEntry(http->request->method, reqFlags);
1693 http->storeEntry()->replaceHttpReply(reply);
1694}
1695
43446566 1696/// Whether Squid FTP Relay supports a named feature (e.g., a command).
92ae4c86 1697static bool
1ab04517 1698Ftp::SupportedCommand(const SBuf &name)
92ae4c86 1699{
1ab04517 1700 static std::set<SBuf> BlackList;
92ae4c86 1701 if (BlackList.empty()) {
43446566 1702 /* Add FTP commands that Squid cannot relay correctly. */
92ae4c86 1703
43446566
AR
1704 // We probably do not support AUTH TLS.* and AUTH SSL,
1705 // but let's disclaim all AUTH support to KISS, for now.
1ab04517 1706 BlackList.insert(cmdAuth());
92ae4c86
AR
1707 }
1708
1709 // we claim support for all commands that we do not know about
1ab04517 1710 return BlackList.find(name) == BlackList.end();
92ae4c86
AR
1711}
1712