Bump the version to 0.9.10.
[obnox/wireshark/wip.git] / packet-ftp.c
1 /* packet-ftp.c
2  * Routines for ftp packet dissection
3  * Copyright 1999, Richard Sharpe <rsharpe@ns.aus.com>
4  * Copyright 2001, Juan Toledo <toledo@users.sourceforge.net> (Passive FTP)
5  *
6  * $Id: packet-ftp.c,v 1.50 2003/02/25 19:27:19 guy Exp $
7  *
8  * Ethereal - Network traffic analyzer
9  * By Gerald Combs <gerald@ethereal.com>
10  * Copyright 1998 Gerald Combs
11  *
12  * Copied from packet-pop.c
13  *
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27  */
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <ctype.h>
36
37 #include <string.h>
38 #include <glib.h>
39 #include <epan/packet.h>
40 #include <epan/strutil.h>
41 #include <epan/conversation.h>
42
43 static int proto_ftp = -1;
44 static int proto_ftp_data = -1;
45 static int hf_ftp_response = -1;
46 static int hf_ftp_request = -1;
47 static int hf_ftp_request_command = -1;
48 static int hf_ftp_request_arg = -1;
49 static int hf_ftp_response_code = -1;
50 static int hf_ftp_response_arg = -1;
51
52 static gint ett_ftp = -1;
53 static gint ett_ftp_data = -1;
54
55 static dissector_handle_t ftpdata_handle;
56
57 #define TCP_PORT_FTPDATA                20
58 #define TCP_PORT_FTP                    21
59
60 static const value_string response_table[] = {
61         { 110, "Restart marker reply" },
62         { 120, "Service ready in nnn minutes" },
63         { 125, "Data connection already open; transfer starting" },
64         { 150, "File status okay; about to open data connection" },
65         { 200, "Command okay" },
66         { 202, "Command not implemented, superfluous at this site" },
67         { 211, "System status, or system help reply" },
68         { 212, "Directory status" },
69         { 213, "File status" },
70         { 214, "Help message" },
71         { 215, "NAME system type" },
72         { 220, "Service ready for new user" },
73         { 221, "Service closing control connection" },
74         { 225, "Data connection open; no transfer in progress" },
75         { 226, "Closing data connection" },
76         { 227, "Entering Passive Mode" },
77         { 230, "User logged in, proceed" },
78         { 250, "Requested file action okay, completed" },
79         { 257, "PATHNAME created" },
80         { 331, "User name okay, need password" },
81         { 332, "Need account for login" },
82         { 350, "Requested file action pending further information" },
83         { 421, "Service not available, closing control connection" },
84         { 425, "Can't open data connection" },
85         { 426, "Connection closed; transfer aborted" },
86         { 450, "Requested file action not taken" },
87         { 451, "Requested action aborted: local error in processing" },
88         { 452, "Requested action not taken. Insufficient storage space in system" },
89         { 500, "Syntax error, command unrecognized" },
90         { 501, "Syntax error in parameters or arguments" },
91         { 502, "Command not implemented" },
92         { 503, "Bad sequence of commands" },
93         { 504, "Command not implemented for that parameter" },
94         { 530, "Not logged in" },
95         { 532, "Need account for storing files" },
96         { 550, "Requested action not taken: File unavailable" },
97         { 551, "Requested action aborted: page type unknown" },
98         { 552, "Requested file action aborted: Exceeded storage allocation" },
99         { 553, "Requested action not taken: File name not allowed" },
100         { 0,   NULL }
101 };
102                 
103 static void
104 dissect_ftpdata(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
105
106 /*
107  * Handle a response to a PASV command.
108  *
109  * We ignore the IP address in the reply, and use the address from which
110  * the request came.
111  *
112  * XXX - are there cases where they differ?  What if the FTP server is
113  * behind a NAT box, so that the address it puts into the reply isn't
114  * the address at which you should contact it?  Do all NAT boxes detect
115  * FTP PASV replies and rewrite the address?  (I suspect not.)
116  *
117  * RFC 959 doesn't say much about the syntax of the 227 reply.
118  *
119  * A proposal from Dan Bernstein at
120  *
121  *      http://cr.yp.to/ftp/retr.html
122  *
123  * "recommend[s] that clients use the following strategy to parse the
124  * response line: look for the first digit after the initial space; look
125  * for the fourth comma after that digit; read two (possibly negative)
126  * integers, separated by a comma; the TCP port number is p1*256+p2, where
127  * p1 is the first integer modulo 256 and p2 is the second integer modulo
128  * 256."
129  *
130  * wget 1.5.3 looks for a digit, although it doesn't handle negative
131  * integers.
132  *
133  * The FTP code in the source of the cURL library, at
134  *
135  *      http://curl.haxx.se/lxr/source/lib/ftp.c
136  *
137  * says that cURL "now scans for a sequence of six comma-separated numbers
138  * and will take them as IP+port indicators"; it loops, doing "sscanf"s
139  * looking for six numbers separated by commas, stepping the start pointer
140  * in the scanf one character at a time - i.e., it tries rather exhaustively.
141  *
142  * An optimization would be to scan for a digit, and start there, and if
143  * the scanf doesn't find six values, scan for the next digit and try
144  * again; this will probably succeed on the first try.
145  *
146  * The cURL code also says that "found reply-strings include":
147  *
148  *      "227 Entering Passive Mode (127,0,0,1,4,51)"
149  *      "227 Data transfer will passively listen to 127,0,0,1,4,51"
150  *      "227 Entering passive mode. 127,0,0,1,4,51"
151  *
152  * so it appears that you can't assume there are parentheses around
153  * the address and port number.
154  */
155 static void
156 handle_pasv_response(const guchar *line, int linelen, packet_info *pinfo)
157 {
158         char *args;
159         char *p;
160         guchar c;
161         int i;
162         int address[4], port[2];
163         guint16 server_port;
164         conversation_t  *conversation;
165
166         /*
167          * Copy the rest of the line into a null-terminated buffer.
168          */
169         args = g_malloc(linelen + 1);
170         memcpy(args, line, linelen);
171         args[linelen] = '\0';
172         p = args;
173
174         for (;;) {
175                 /*
176                  * Look for a digit.
177                  */
178                 while ((c = *p) != '\0' && !isdigit(c))
179                         p++;
180
181                 if (*p == '\0') {
182                         /*
183                          * We ran out of text without finding anything.
184                          */
185                         break;
186                 }
187
188                 /*
189                  * See if we have six numbers.
190                  */
191                 i = sscanf(p, "%d,%d,%d,%d,%d,%d",
192                     &address[0], &address[1], &address[2], &address[3],
193                     &port[0], &port[1]);
194                 if (i == 6) {
195                         /*
196                          * We have a winner!
197                          * Set up a conversation, to be dissected as FTP data.
198                          */
199                         server_port = ((port[0] & 0xFF)<<8) | (port[1] & 0xFF);
200
201                         /*
202                          * XXX - should this call to "find_conversation()"
203                          * just use "pinfo->src" and "server_port", and
204                          * wildcard everything else?
205                          */
206                         conversation = find_conversation(&pinfo->src,
207                             &pinfo->dst, PT_TCP, server_port, 0, NO_PORT_B);
208                         if (conversation == NULL) {
209                                 /*
210                                  * XXX - should this call to
211                                  * "conversation_new()" just use "pinfo->src"
212                                  * and "server_port", and wildcard everything
213                                  * else?
214                                  *
215                                  * XXX - what if we did find a conversation?
216                                  * As we create it only on the first pass
217                                  * through the packets, if we find one, it's
218                                  * presumably an unrelated conversation.
219                                  * Should we remove the old one from the hash
220                                  * table and put this one in its place?
221                                  * Can the conversaton code handle
222                                  * conversations not in the hash table?
223                                  */
224                                 conversation = conversation_new(&pinfo->src,
225                                     &pinfo->dst, PT_TCP, server_port, 0,
226                                     NO_PORT2);
227                                 conversation_set_dissector(conversation,
228                                     ftpdata_handle);
229                         }
230                         break;
231                 }
232
233                 /*
234                  * Well, that didn't work.  Skip the first number we found,
235                  * and keep trying.
236                  */
237                 while ((c = *p) != '\0' && isdigit(c))
238                         p++;
239         }
240
241         g_free(args);
242 }
243
244 static void
245 dissect_ftp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
246 {
247         gboolean        is_request;
248         proto_tree      *ftp_tree = NULL;
249         proto_item      *ti;
250         gint            offset = 0;
251         const guchar    *line;
252         guint32         code;
253         gchar           code_str[4];
254         gboolean        is_pasv_response = FALSE;
255         gint            next_offset;
256         int             linelen;
257         int             tokenlen;
258         const guchar    *next_token;
259
260         if (pinfo->match_port == pinfo->destport)
261                 is_request = TRUE;
262         else
263                 is_request = FALSE;
264
265         if (check_col(pinfo->cinfo, COL_PROTOCOL))
266                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FTP");
267
268         /*
269          * Find the end of the first line.
270          *
271          * Note that "tvb_find_line_end()" will return a value that is
272          * not longer than what's in the buffer, so the "tvb_get_ptr()"
273          * call won't throw an exception.
274          */
275         linelen = tvb_find_line_end(tvb, offset, -1, &next_offset, FALSE);
276         line = tvb_get_ptr(tvb, offset, linelen);
277
278         if (check_col(pinfo->cinfo, COL_INFO)) {
279                 /*
280                  * Put the first line from the buffer into the summary
281                  * (but leave out the line terminator).
282                  */
283                 col_add_fstr(pinfo->cinfo, COL_INFO, "%s: %s",
284                     is_request ? "Request" : "Response",
285                     format_text(line, linelen));
286         }
287
288         if (tree) {
289                 ti = proto_tree_add_item(tree, proto_ftp, tvb, offset, -1,
290                     FALSE);
291                 ftp_tree = proto_item_add_subtree(ti, ett_ftp);
292
293                 if (is_request) {
294                         proto_tree_add_boolean_hidden(ftp_tree,
295                             hf_ftp_request, tvb, 0, 0, TRUE);
296                         proto_tree_add_boolean_hidden(ftp_tree,
297                             hf_ftp_response, tvb, 0, 0, FALSE);
298                 } else {
299                         proto_tree_add_boolean_hidden(ftp_tree,
300                             hf_ftp_request, tvb, 0, 0, FALSE);
301                         proto_tree_add_boolean_hidden(ftp_tree,
302                             hf_ftp_response, tvb, 0, 0, TRUE);
303                 }
304         }
305
306         if (is_request) {
307                 /*
308                  * Extract the first token, and, if there is a first
309                  * token, add it as the request.
310                  */
311                 tokenlen = get_token_len(line, line + linelen, &next_token);
312                 if (tokenlen != 0) {
313                         if (tree) {
314                                 proto_tree_add_item(ftp_tree,
315                                     hf_ftp_request_command, tvb, offset,
316                                     tokenlen, FALSE);
317                         }
318                 }
319         } else {
320                 /*
321                  * This is a response; the response code is 3 digits,
322                  * followed by a space or hyphen, possibly followed by
323                  * text.
324                  *
325                  * If the line doesn't start with 3 digits, it's part of
326                  * a continuation.
327                  *
328                  * XXX - keep track of state in the first pass, and
329                  * treat non-continuation lines not beginning with digits
330                  * as errors?
331                  */
332                 if (linelen >= 3 && isdigit(line[0]) && isdigit(line[1])
333                     && isdigit(line[2])) {
334                         /*
335                          * One-line reply, or first or last line
336                          * of a multi-line reply.
337                          */
338                         tvb_get_nstringz0(tvb, offset, 3, code_str);
339                         code = strtoul(code_str, NULL, 10);
340                                 
341                         if (tree) {
342                                 proto_tree_add_uint(ftp_tree,
343                                     hf_ftp_response_code, tvb, offset, 3, code);
344                         }
345
346                         /*
347                          * See if it's a passive-mode response.
348                          *
349                          * XXX - check for "229" responses to EPSV
350                          * commands, to handle IPv6, as per RFC 2428?
351                          *
352                          * XXX - does anybody do FOOBAR, as per RFC
353                          * 1639, or has that been supplanted by RFC 2428?
354                          */
355                         if (code == 227)
356                                 is_pasv_response = TRUE;
357
358                         /*
359                          * Skip the 3 digits and, if present, the
360                          * space or hyphen.
361                          */
362                         if (linelen >= 4)
363                                 next_token = line + 4;
364                         else
365                                 next_token = line + linelen;
366                 } else {
367                         /*
368                          * Line doesn't start with 3 digits; assume it's
369                          * a line in the middle of a multi-line reply.
370                          */
371                         next_token = line;
372                 }
373         }
374         offset += next_token - line;
375         linelen -= next_token - line;
376         line = next_token;
377
378         /*
379          * If this is a PASV response, handle it if we haven't
380          * already processed this frame.
381          */
382         if (!pinfo->fd->flags.visited && is_pasv_response) {
383                 if (linelen != 0) {
384                         /*
385                          * We haven't processed this frame, and it contains
386                          * a PASV response; set up a conversation for the
387                          * data.
388                          */
389                         handle_pasv_response(line, linelen, pinfo);
390                 }
391         }
392
393         if (tree) {
394                 /*
395                  * Add the rest of the first line as request or
396                  * reply data.
397                  */
398                 if (linelen != 0) {
399                         if (is_request) {
400                                 proto_tree_add_item(ftp_tree,
401                                     hf_ftp_request_arg, tvb, offset,
402                                     linelen, FALSE);
403                         } else {
404                                 proto_tree_add_item(ftp_tree,
405                                     hf_ftp_response_arg, tvb, offset,
406                                     linelen, FALSE);
407                         }
408                 }
409                 offset = next_offset;
410
411                 /*
412                  * Show the rest of the request or response as text,
413                  * a line at a time.
414                  * XXX - only if there's a continuation indicator?
415                  */
416                 while (tvb_offset_exists(tvb, offset)) {
417                         /*
418                          * Find the end of the line.
419                          */
420                         linelen = tvb_find_line_end(tvb, offset, -1,
421                             &next_offset, FALSE);
422
423                         /*
424                          * Put this line.
425                          */
426                         proto_tree_add_text(ftp_tree, tvb, offset,
427                             next_offset - offset, "%s",
428                             tvb_format_text(tvb, offset, next_offset - offset));
429                         offset = next_offset;
430                 }
431         }
432 }
433
434 static void
435 dissect_ftpdata(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
436 {
437         proto_tree      *ti, *ftp_data_tree;
438         int             data_length;
439
440         if (check_col(pinfo->cinfo, COL_PROTOCOL))
441                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FTP-DATA");
442
443         if (check_col(pinfo->cinfo, COL_INFO)) {
444                 col_add_fstr(pinfo->cinfo, COL_INFO, "FTP Data: %u bytes",
445                     tvb_reported_length(tvb));
446         }
447
448         if (tree) {
449                 data_length = tvb_length(tvb);
450
451                 ti = proto_tree_add_item(tree, proto_ftp_data, tvb, 0, -1,
452                     FALSE);
453                 ftp_data_tree = proto_item_add_subtree(ti, ett_ftp_data);
454
455                 /*
456                  * XXX - if this is binary data, it'll produce
457                  * a *really* long line.
458                  */
459                 proto_tree_add_text(ftp_data_tree, tvb, 0, data_length,
460                     "FTP Data: %s", tvb_format_text(tvb, 0, data_length));
461         }
462 }
463
464 void
465 proto_register_ftp(void)
466 {
467     static hf_register_info hf[] = {
468     { &hf_ftp_response,
469       { "Response",           "ftp.response",
470         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
471         "TRUE if FTP response", HFILL }},
472
473     { &hf_ftp_request,
474       { "Request",            "ftp.request",
475         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
476         "TRUE if FTP request", HFILL }},
477
478     { &hf_ftp_request_command,
479       { "Request command",    "ftp.request.command",
480         FT_STRING,  BASE_NONE, NULL, 0x0,
481         "", HFILL }},
482
483     { &hf_ftp_request_arg,
484       { "Request arg",        "ftp.request.arg",
485         FT_STRING,  BASE_NONE, NULL, 0x0,
486         "", HFILL }},
487
488     { &hf_ftp_response_code,
489       { "Response code",      "ftp.response.code",
490         FT_UINT32,   BASE_DEC, VALS(response_table), 0x0,
491         "", HFILL }},
492
493     { &hf_ftp_response_arg,
494       { "Response arg",      "ftp.response.arg",
495         FT_STRING,  BASE_NONE, NULL, 0x0,
496         "", HFILL }}
497   };
498   static gint *ett[] = {
499     &ett_ftp,
500     &ett_ftp_data,
501   };
502
503   proto_ftp = proto_register_protocol("File Transfer Protocol (FTP)", "FTP",
504                                       "ftp");
505   proto_ftp_data = proto_register_protocol("FTP Data", "FTP-DATA", "ftp-data");
506   proto_register_field_array(proto_ftp, hf, array_length(hf));
507   proto_register_subtree_array(ett, array_length(ett));
508
509   ftpdata_handle = create_dissector_handle(dissect_ftpdata, proto_ftp_data);
510 }
511
512 void
513 proto_reg_handoff_ftp(void)
514 {
515   dissector_handle_t ftpdata_handle, ftp_handle;
516
517   ftpdata_handle = create_dissector_handle(dissect_ftpdata, proto_ftp_data);
518   dissector_add("tcp.port", TCP_PORT_FTPDATA, ftpdata_handle);
519   ftp_handle = create_dissector_handle(dissect_ftp, proto_ftp);
520   dissector_add("tcp.port", TCP_PORT_FTP, ftp_handle);
521 }