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