4c33b7fce3ed6de7fe3bd8f1f47d14a0dc462b3d
[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.45 2002/07/14 00:40:07 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 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
39 #endif
40
41 #ifdef HAVE_NETINET_IN_H
42 # include <netinet/in.h>
43 #endif
44
45 #include <string.h>
46 #include <glib.h>
47 #include <epan/packet.h>
48 #include <epan/strutil.h>
49 #include <epan/conversation.h>
50
51 static int proto_ftp = -1;
52 static int proto_ftp_data = -1;
53 static int hf_ftp_response = -1;
54 static int hf_ftp_request = -1;
55 static int hf_ftp_request_command = -1;
56 static int hf_ftp_request_arg = -1;
57 static int hf_ftp_response_code = -1;
58 static int hf_ftp_response_arg = -1;
59
60 static gint ett_ftp = -1;
61 static gint ett_ftp_data = -1;
62
63 static dissector_handle_t ftpdata_handle;
64
65 #define TCP_PORT_FTPDATA                20
66 #define TCP_PORT_FTP                    21
67
68 static void
69 dissect_ftpdata(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
70
71 /*
72  * Handle a response to a PASV command.
73  *
74  * We ignore the IP address in the reply, and use the address from which
75  * the request came.
76  *
77  * XXX - are there cases where they differ?  What if the FTP server is
78  * behind a NAT box, so that the address it puts into the reply isn't
79  * the address at which you should contact it?  Do all NAT boxes detect
80  * FTP PASV replies and rewrite the address?  (I suspect not.)
81  *
82  * RFC 959 doesn't say much about the syntax of the 227 reply.
83  *
84  * A proposal from Dan Bernstein at
85  *
86  *      http://cr.yp.to/ftp/retr.html
87  *
88  * "recommend[s] that clients use the following strategy to parse the
89  * response line: look for the first digit after the initial space; look
90  * for the fourth comma after that digit; read two (possibly negative)
91  * integers, separated by a comma; the TCP port number is p1*256+p2, where
92  * p1 is the first integer modulo 256 and p2 is the second integer modulo
93  * 256."
94  *
95  * wget 1.5.3 looks for a digit, although it doesn't handle negative
96  * integers.
97  *
98  * The FTP code in the source of the cURL library, at
99  *
100  *      http://curl.haxx.se/lxr/source/lib/ftp.c
101  *
102  * says that cURL "now scans for a sequence of six comma-separated numbers
103  * and will take them as IP+port indicators"; it loops, doing "sscanf"s
104  * looking for six numbers separated by commas, stepping the start pointer
105  * in the scanf one character at a time - i.e., it tries rather exhaustively.
106  *
107  * An optimization would be to scan for a digit, and start there, and if
108  * the scanf doesn't find six values, scan for the next digit and try
109  * again; this will probably succeed on the first try.
110  *
111  * The cURL code also says that "found reply-strings include":
112  *
113  *      "227 Entering Passive Mode (127,0,0,1,4,51)"
114  *      "227 Data transfer will passively listen to 127,0,0,1,4,51"
115  *      "227 Entering passive mode. 127,0,0,1,4,51"
116  *
117  * so it appears that you can't assume there are parentheses around
118  * the address and port number.
119  */
120 static void
121 handle_pasv_response(const u_char *line, int linelen, packet_info *pinfo)
122 {
123         char *args;
124         char *p;
125         u_char c;
126         int i;
127         int address[4], port[2];
128         guint16 server_port;
129         conversation_t  *conversation;
130
131         /*
132          * Copy the rest of the line into a null-terminated buffer.
133          */
134         args = g_malloc(linelen + 1);
135         memcpy(args, line, linelen);
136         args[linelen] = '\0';
137         p = args;
138
139         for (;;) {
140                 /*
141                  * Look for a digit.
142                  */
143                 while ((c = *p) != '\0' && !isdigit(c))
144                         p++;
145
146                 if (*p == '\0') {
147                         /*
148                          * We ran out of text without finding anything.
149                          */
150                         break;
151                 }
152                         
153                 /*
154                  * See if we have six numbers.
155                  */
156                 i = sscanf(p, "%d,%d,%d,%d,%d,%d",
157                     &address[0], &address[1], &address[2], &address[3],
158                     &port[0], &port[1]);
159                 if (i == 6) {
160                         /*
161                          * We have a winner!
162                          * Set up a conversation, to be dissected as FTP data.
163                          */
164                         server_port = ((port[0] & 0xFF)<<8) | (port[1] & 0xFF);
165
166                         /*
167                          * XXX - should this call to "find_conversation()"
168                          * just use "pinfo->src" and "server_port", and
169                          * wildcard everything else?
170                          */
171                         conversation = find_conversation(&pinfo->src,
172                             &pinfo->dst, PT_TCP, server_port, 0, NO_PORT_B);
173                         if (conversation == NULL) {
174                                 /*
175                                  * XXX - should this call to
176                                  * "conversation_new()" just use "pinfo->src"
177                                  * and "server_port", and wildcard everything
178                                  * else?
179                                  *
180                                  * XXX - what if we did find a conversation?
181                                  * As we create it only on the first pass
182                                  * through the packets, if we find one, it's
183                                  * presumably an unrelated conversation.
184                                  * Should we remove the old one from the hash
185                                  * table and put this one in its place?
186                                  * Can the conversaton code handle
187                                  * conversations not in the hash table?
188                                  */
189                                 conversation = conversation_new(&pinfo->src,
190                                     &pinfo->dst, PT_TCP, server_port, 0,
191                                     NO_PORT2);
192                                 conversation_set_dissector(conversation,
193                                     ftpdata_handle);
194                         }
195                         break;
196                 }
197
198                 /*
199                  * Well, that didn't work.  Skip the first number we found,
200                  * and keep trying.
201                  */
202                 while ((c = *p) != '\0' && isdigit(c))
203                         p++;
204         }
205
206         g_free(args);
207 }       
208
209 static void
210 dissect_ftp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
211 {
212         gboolean        is_request;
213         proto_tree      *ftp_tree = NULL;
214         proto_item      *ti;
215         gint            offset = 0;
216         const u_char    *line;
217         guint8          code;
218         gboolean        is_pasv_response = FALSE;
219         gint            next_offset;
220         int             linelen;
221         int             tokenlen;
222         const u_char    *next_token;
223
224         if (pinfo->match_port == pinfo->destport)
225                 is_request = TRUE;
226         else
227                 is_request = FALSE;
228
229         if (check_col(pinfo->cinfo, COL_PROTOCOL))
230                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FTP");
231
232         /*
233          * Find the end of the first line.
234          *
235          * Note that "tvb_find_line_end()" will return a value that is
236          * not longer than what's in the buffer, so the "tvb_get_ptr()"
237          * call won't throw an exception.
238          */
239         linelen = tvb_find_line_end(tvb, offset, -1, &next_offset);
240         line = tvb_get_ptr(tvb, offset, linelen);
241
242         if (check_col(pinfo->cinfo, COL_INFO)) {
243                 /*
244                  * Put the first line from the buffer into the summary
245                  * (but leave out the line terminator).
246                  */
247                 col_add_fstr(pinfo->cinfo, COL_INFO, "%s: %s",
248                     is_request ? "Request" : "Response",
249                     format_text(line, linelen));
250         }
251    
252         if (tree) {
253                 ti = proto_tree_add_item(tree, proto_ftp, tvb, offset, -1,
254                     FALSE);
255                 ftp_tree = proto_item_add_subtree(ti, ett_ftp);
256
257                 if (is_request) {
258                         proto_tree_add_boolean_hidden(ftp_tree,
259                             hf_ftp_request, tvb, 0, 0, TRUE);
260                         proto_tree_add_boolean_hidden(ftp_tree,
261                             hf_ftp_response, tvb, 0, 0, FALSE);
262                 } else {
263                         proto_tree_add_boolean_hidden(ftp_tree,
264                             hf_ftp_request, tvb, 0, 0, FALSE);
265                         proto_tree_add_boolean_hidden(ftp_tree,
266                             hf_ftp_response, tvb, 0, 0, TRUE);
267                 }
268         }
269
270         if (is_request) {
271                 /*
272                  * Extract the first token, and, if there is a first
273                  * token, add it as the request.
274                  */
275                 tokenlen = get_token_len(line, line + linelen, &next_token);
276                 if (tokenlen != 0) {
277                         if (tree) {
278                                 proto_tree_add_item(ftp_tree,
279                                     hf_ftp_request_command, tvb, offset,
280                                     tokenlen, FALSE);
281                         }
282                 }
283         } else {
284                 /*
285                  * This is a response; the response code is 3 digits,
286                  * followed by a space or hyphen, possibly followed by
287                  * text.
288                  *
289                  * If the line doesn't start with 3 digits, it's part of
290                  * a continuation.
291                  *
292                  * XXX - keep track of state in the first pass, and
293                  * treat non-continuation lines not beginning with digits
294                  * as errors?
295                  */
296                 if (linelen >= 3 && isdigit(line[0]) && isdigit(line[1])
297                     && isdigit(line[2])) {
298                         /*
299                          * One-line reply, or first or last line
300                          * of a multi-line reply.
301                          */
302                         code = (line[0] - '0')*100 + (line[1] - '0')*10
303                             + (line[2] - '0');
304                         if (tree) {
305                                 proto_tree_add_uint(ftp_tree,
306                                     hf_ftp_response_code, tvb, offset, 3, code);
307
308                         }
309
310                         /*
311                          * See if it's a passive-mode response.
312                          *
313                          * XXX - check for "229" responses to EPSV
314                          * commands, to handle IPv6, as per RFC 2428?
315                          *
316                          * XXX - does anybody do FOOBAR, as per RFC
317                          * 1639, or has that been supplanted by RFC 2428?
318                          */
319                         if (code == 227)
320                                 is_pasv_response = TRUE;
321
322                         /*
323                          * Skip the 3 digits and, if present, the
324                          * space or hyphen.
325                          */
326                         if (linelen >= 4)
327                                 next_token = line + 4;
328                         else
329                                 next_token = line + linelen;
330                 } else {
331                         /*
332                          * Line doesn't start with 3 digits; assume it's
333                          * a line in the middle of a multi-line reply.
334                          */
335                         next_token = line;
336                 }
337         }
338         offset += next_token - line;
339         linelen -= next_token - line;
340         line = next_token;
341
342         /*
343          * If this is a PASV response, handle it if we haven't
344          * already processed this frame.
345          */
346         if (!pinfo->fd->flags.visited && is_pasv_response) {
347                 if (linelen != 0) {
348                         /*
349                          * We haven't processed this frame, and it contains
350                          * a PASV response; set up a conversation for the
351                          * data.
352                          */
353                         handle_pasv_response(line, linelen, pinfo);
354                 }
355         }
356
357         if (tree) {
358                 /*
359                  * Add the rest of the first line as request or
360                  * reply data.
361                  */
362                 if (linelen != 0) {
363                         if (is_request) {
364                                 proto_tree_add_item(ftp_tree,
365                                     hf_ftp_request_arg, tvb, offset,
366                                     linelen, FALSE);
367                         } else {
368                                 proto_tree_add_item(ftp_tree,
369                                     hf_ftp_response_arg, tvb, offset,
370                                     linelen, FALSE);
371                         }
372                 }
373                 offset = next_offset;
374
375                 /*
376                  * Show the rest of the request or response as text,
377                  * a line at a time.
378                  * XXX - only if there's a continuation indicator?
379                  */
380                 while (tvb_offset_exists(tvb, offset)) {
381                         /*
382                          * Find the end of the line.
383                          */
384                         linelen = tvb_find_line_end(tvb, offset, -1,
385                             &next_offset);
386
387                         /*
388                          * Put this line.
389                          */
390                         proto_tree_add_text(ftp_tree, tvb, offset,
391                             next_offset - offset, "%s",
392                             tvb_format_text(tvb, offset, next_offset - offset));
393                         offset = next_offset;
394                 }
395         }
396 }
397
398 static void
399 dissect_ftpdata(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
400 {
401         proto_tree      *ti, *ftp_data_tree;
402         int             data_length;
403
404         if (check_col(pinfo->cinfo, COL_PROTOCOL))
405                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FTP-DATA");
406
407         if (check_col(pinfo->cinfo, COL_INFO)) {
408                 col_add_fstr(pinfo->cinfo, COL_INFO, "FTP Data: %u bytes",
409                     tvb_reported_length(tvb));
410         }
411
412         if (tree) {
413                 data_length = tvb_length(tvb);
414
415                 ti = proto_tree_add_item(tree, proto_ftp_data, tvb, 0, -1,
416                     FALSE);
417                 ftp_data_tree = proto_item_add_subtree(ti, ett_ftp_data);
418
419                 /*
420                  * XXX - if this is binary data, it'll produce
421                  * a *really* long line.
422                  */
423                 proto_tree_add_text(ftp_data_tree, tvb, 0, data_length,
424                     "FTP Data: %s", tvb_format_text(tvb, 0, data_length));
425         }
426 }
427
428 void
429 proto_register_ftp(void)
430 {
431     static hf_register_info hf[] = {
432     { &hf_ftp_response,
433       { "Response",           "ftp.response",
434         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
435         "TRUE if FTP response", HFILL }},
436
437     { &hf_ftp_request,
438       { "Request",            "ftp.request",
439         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
440         "TRUE if FTP request", HFILL }},
441
442     { &hf_ftp_request_command,
443       { "Request command",    "ftp.request.command",
444         FT_STRING,  BASE_NONE, NULL, 0x0,
445         "", HFILL }},
446
447     { &hf_ftp_request_arg,
448       { "Request arg",        "ftp.request.arg",
449         FT_STRING,  BASE_NONE, NULL, 0x0,
450         "", HFILL }},
451
452     { &hf_ftp_response_code,
453       { "Response code",      "ftp.response.code",
454         FT_UINT8,   BASE_DEC, NULL, 0x0,
455         "", HFILL }},
456
457     { &hf_ftp_response_arg,
458       { "Response arg",      "ftp.response.arg",
459         FT_STRING,  BASE_NONE, NULL, 0x0,
460         "", HFILL }}
461   };
462   static gint *ett[] = {
463     &ett_ftp,
464     &ett_ftp_data,
465   };
466
467   proto_ftp = proto_register_protocol("File Transfer Protocol (FTP)", "FTP",
468                                       "ftp");
469   proto_ftp_data = proto_register_protocol("FTP Data", "FTP-DATA", "ftp-data");
470   proto_register_field_array(proto_ftp, hf, array_length(hf));
471   proto_register_subtree_array(ett, array_length(ett));
472
473   ftpdata_handle = create_dissector_handle(dissect_ftpdata, proto_ftp_data);
474 }
475
476 void
477 proto_reg_handoff_ftp(void)
478 {
479   dissector_handle_t ftpdata_handle, ftp_handle;
480
481   ftpdata_handle = create_dissector_handle(dissect_ftpdata, proto_ftp_data);
482   dissector_add("tcp.port", TCP_PORT_FTPDATA, ftpdata_handle);
483   ftp_handle = create_dissector_handle(dissect_ftp, proto_ftp);
484   dissector_add("tcp.port", TCP_PORT_FTP, ftp_handle);
485 }