Make various lengths unsigned in "dissect_fhandle_data_unknown()", so
[obnox/wireshark/wip.git] / packet-smtp.c
1 /* packet-smtp.c
2  * Routines for SMTP packet disassembly
3  *
4  * $Id: packet-smtp.c,v 1.34 2003/06/11 18:22:12 guy Exp $
5  *
6  * Copyright (c) 2000 by Richard Sharpe <rsharpe@ns.aus.com>
7  *
8  * Ethereal - Network traffic analyzer
9  * By Gerald Combs <gerald@ethereal.com>
10  * Copyright 1999 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <ctype.h>
34 #include <time.h>
35 #include <glib.h>
36 #include <string.h>
37 #include <epan/packet.h>
38 #include <epan/conversation.h>
39 #include <epan/resolv.h>
40 #include "prefs.h"
41 #include <epan/strutil.h>
42
43 #define TCP_PORT_SMTP 25
44
45 void proto_reg_handoff_smtp(void);
46
47 static int proto_smtp = -1;
48
49 static int hf_smtp_req = -1;
50 static int hf_smtp_rsp = -1;
51 static int hf_smtp_req_command = -1;
52 static int hf_smtp_req_parameter = -1;
53 static int hf_smtp_rsp_code = -1;
54 static int hf_smtp_rsp_parameter = -1;
55
56 static int ett_smtp = -1;
57 static int ett_smtp_cmdresp = -1;
58
59 static int global_smtp_tcp_port = TCP_PORT_SMTP;
60
61 /* desegmentation of SMTP command and response lines */
62 static gboolean smtp_desegment = TRUE;
63
64 /*
65  * A CMD is an SMTP command, MESSAGE is the message portion, and EOM is the
66  * last part of a message
67  */
68
69 #define SMTP_PDU_CMD     0
70 #define SMTP_PDU_MESSAGE 1
71 #define SMTP_PDU_EOM     2
72
73 struct smtp_proto_data {
74   guint16 pdu_type;
75 };
76
77 static int smtp_packet_init_count = 100;
78
79 /*
80  * State information stored with a conversation.
81  */
82 struct smtp_request_val {
83   gboolean reading_data; /* Reading message data, not commands */
84   guint16 crlf_seen;     /* Have we seen a CRLF on the end of a packet */
85 };
86
87 static GMemChunk  *smtp_request_vals = NULL;
88 static GMemChunk  *smtp_packet_infos = NULL;
89
90 static void
91 smtp_init_protocol(void)
92 {
93   if (smtp_request_vals)
94     g_mem_chunk_destroy(smtp_request_vals);
95   if (smtp_packet_infos)
96     g_mem_chunk_destroy(smtp_packet_infos);
97
98   smtp_request_vals = g_mem_chunk_new("smtp_request_vals",
99                                       sizeof(struct smtp_request_val),
100                                       smtp_packet_init_count * sizeof(struct smtp_request_val), G_ALLOC_AND_FREE);
101   smtp_packet_infos = g_mem_chunk_new("smtp_packet_infos",
102                                       sizeof(struct smtp_proto_data),
103                                       smtp_packet_init_count * sizeof(struct smtp_proto_data), G_ALLOC_AND_FREE);
104
105 }
106
107 static void
108 dissect_smtp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
109 {
110     struct smtp_proto_data  *frame_data;
111     proto_tree              *smtp_tree;
112     proto_tree              *cmdresp_tree;
113     proto_item              *ti;
114     int                     offset = 0;
115     int                     request = 0;
116     conversation_t          *conversation;
117     struct smtp_request_val *request_val;
118     const guchar            *line;
119     guint32                 code;
120     int                     linelen;
121     gint                    length_remaining;
122     gboolean                eom_seen = FALSE;
123     gint                    next_offset;
124     gboolean                is_continuation_line;
125     int                     cmdlen;
126
127     /* As there is no guarantee that we will only see frames in the
128      * the SMTP conversation once, and that we will see them in
129      * order - in Ethereal, the user could randomly click on frames
130      * in the conversation in any order in which they choose - we
131      * have to store information with each frame indicating whether
132      * it contains commands or data or an EOM indication.
133      *
134      * XXX - what about frames that contain *both*?  TCP is a
135      * byte-stream protocol, and there are no guarantees that
136      * TCP segment boundaries will correspond to SMTP commands
137      * or EOM indications.
138      *
139      * We only need that for the client->server stream; responses
140      * are easy to manage.
141      *
142      * If we have per frame data, use that, else, we must be on the first
143      * pass, so we figure it out on the first pass.
144      */
145
146     /* Find out what conversation this packet is part of ... but only
147      * if we have no information on this packet, so find the per-frame
148      * info first.
149      */
150
151     /* SMTP messages have a simple format ... */
152
153     request = pinfo -> destport == pinfo -> match_port;
154
155     /*
156      * Get the first line from the buffer.
157      *
158      * Note that "tvb_find_line_end()" will, if it doesn't return
159      * -1, return a value that is not longer than what's in the buffer,
160      * and "tvb_find_line_end()" will always return a value that is not
161      * longer than what's in the buffer, so the "tvb_get_ptr()" call
162      * won't throw an exception.
163      */
164     linelen = tvb_find_line_end(tvb, offset, -1, &next_offset,
165       smtp_desegment && pinfo->can_desegment);
166     if (linelen == -1) {
167       /*
168        * We didn't find a line ending, and we're doing desegmentation;
169        * tell the TCP dissector where the data for this message starts
170        * in the data it handed us, and tell it we need one more byte
171        * (we may need more, but we'll try again if what we get next
172        * isn't enough), and return.
173        */
174       pinfo->desegment_offset = offset;
175       pinfo->desegment_len = 1;
176       return;
177     }
178     line = tvb_get_ptr(tvb, offset, linelen);
179
180     frame_data = p_get_proto_data(pinfo->fd, proto_smtp);
181
182     if (!frame_data) {
183
184       conversation = find_conversation(&pinfo->src, &pinfo->dst, pinfo->ptype,
185                                        pinfo->srcport, pinfo->destport, 0);
186       if (conversation == NULL) { /* No conversation, create one */
187         conversation = conversation_new(&pinfo->src, &pinfo->dst, pinfo->ptype,
188                                         pinfo->srcport, pinfo->destport, 0);
189
190       }
191
192       /*
193        * Is there a request structure attached to this conversation?
194        */
195       request_val = conversation_get_proto_data(conversation, proto_smtp);
196
197       if (!request_val) {
198
199         /*
200          * No - create one and attach it.
201          */
202         request_val = g_mem_chunk_alloc(smtp_request_vals);
203         request_val->reading_data = FALSE;
204         request_val->crlf_seen = 0;
205
206         conversation_add_proto_data(conversation, proto_smtp, request_val);
207
208       }
209
210       /*
211        * Check whether or not this packet is an end of message packet
212        * We should look for CRLF.CRLF and they may be split.
213        * We have to keep in mind that we may see what we want on
214        * two passes through here ...
215        */
216
217       if (request_val->reading_data) {
218
219         /*
220          * The order of these is important ... We want to avoid
221          * cases where there is a CRLF at the end of a packet and a
222          * .CRLF at the begining of the same packet.
223          */
224
225         if ((request_val->crlf_seen && tvb_strneql(tvb, offset, ".\r\n", 3) == 0) ||
226             tvb_strneql(tvb, offset, "\r\n.\r\n", 5) == 0) {
227
228           eom_seen = TRUE;
229
230         }
231
232         length_remaining = tvb_length_remaining(tvb, offset);
233         if (length_remaining == tvb_reported_length_remaining(tvb, offset) &&
234             tvb_strneql(tvb, offset + length_remaining - 2, "\r\n", 2) == 0) {
235
236           request_val->crlf_seen = 1;
237
238         }
239         else {
240
241           request_val->crlf_seen = 0;
242
243         }
244       }
245
246     /*
247      * OK, Check if we have seen a DATA request. We do it here for
248      * simplicity, but we have to be careful below.
249      */
250
251       if (request) {
252
253         frame_data = g_mem_chunk_alloc(smtp_packet_infos);
254
255         if (request_val->reading_data) {
256           /*
257            * This is message data.
258            */
259           if (eom_seen) { /* Seen the EOM */
260             /*
261              * EOM.
262              * Everything that comes after it is commands.
263              *
264              * XXX - what if the EOM isn't at the beginning of
265              * the TCP segment?  It can occur anywhere....
266              */
267             frame_data->pdu_type = SMTP_PDU_EOM;
268             request_val->reading_data = FALSE;
269           } else {
270             /*
271              * Message data with no EOM.
272              */
273             frame_data->pdu_type = SMTP_PDU_MESSAGE;
274           }
275         } else {
276           /*
277            * This is commands - unless the capture started in the
278            * middle of a session, and we're in the middle of data.
279            * To quote RFC 821, "Command codes are four alphabetic
280            * characters"; if we don't see four alphabetic characters
281            * and, if there's anything else in the line, a space, we
282            * assume it's not a command.
283            * (We treat only A-Z and a-z as alphabetic.)
284            */
285 #define ISALPHA(c)      (((c) >= 'A' && (c) <= 'Z') || \
286                          ((c) >= 'a' && (c) <= 'z'))
287           if (linelen >= 4 && ISALPHA(line[0]) && ISALPHA(line[1]) &&
288               ISALPHA(line[2]) && ISALPHA(line[3]) &&
289               (linelen == 4 || line[4] == ' ')) {
290             if (strncasecmp(line, "DATA", 4) == 0) {
291
292               /*
293                * DATA command.
294                * This is a command, but everything that comes after it,
295                * until an EOM, is data.
296                */
297               frame_data->pdu_type = SMTP_PDU_CMD;
298               request_val->reading_data = TRUE;
299
300             } else {
301
302               /*
303                * Regular command.
304                */
305               frame_data->pdu_type = SMTP_PDU_CMD;
306
307             }
308           } else {
309
310             /*
311              * Assume it's message data.
312              */
313
314             frame_data->pdu_type = SMTP_PDU_MESSAGE;
315
316           }
317
318         }
319
320         p_add_proto_data(pinfo->fd, proto_smtp, frame_data);
321
322       }
323     }
324
325     /*
326      * From here, we simply add items to the tree and info to the info
327      * fields ...
328      */
329
330     if (check_col(pinfo->cinfo, COL_PROTOCOL))
331       col_set_str(pinfo->cinfo, COL_PROTOCOL, "SMTP");
332
333     if (check_col(pinfo->cinfo, COL_INFO)) {  /* Add the appropriate type here */
334
335       /*
336        * If it is a request, we have to look things up, otherwise, just
337        * display the right things
338        */
339
340       if (request) {
341
342         /* We must have frame_data here ... */
343
344         switch (frame_data->pdu_type) {
345         case SMTP_PDU_MESSAGE:
346
347           col_set_str(pinfo->cinfo, COL_INFO, "Message Body");
348           break;
349
350         case SMTP_PDU_EOM:
351
352           col_add_fstr(pinfo->cinfo, COL_INFO, "EOM: %s",
353               format_text(line, linelen));
354           break;
355
356         case SMTP_PDU_CMD:
357
358           col_add_fstr(pinfo->cinfo, COL_INFO, "Command: %s",
359               format_text(line, linelen));
360           break;
361
362         }
363
364       }
365       else {
366
367         col_add_fstr(pinfo->cinfo, COL_INFO, "Response: %s",
368             format_text(line, linelen));
369
370       }
371     }
372
373     if (tree) { /* Build the tree info ... */
374
375       ti = proto_tree_add_item(tree, proto_smtp, tvb, offset, -1, FALSE);
376       smtp_tree = proto_item_add_subtree(ti, ett_smtp);
377       if (request) {
378
379         /*
380          * Check out whether or not we can see a command in there ...
381          * What we are looking for is not data_seen and the word DATA
382          * and not eom_seen.
383          *
384          * We will see DATA and request_val->data_seen when we process the
385          * tree view after we have seen a DATA packet when processing
386          * the packet list pane.
387          *
388          * On the first pass, we will not have any info on the packets
389          * On second and subsequent passes, we will.
390          */
391
392         switch (frame_data->pdu_type) {
393
394         case SMTP_PDU_MESSAGE:
395
396           /*
397            * Message body.
398            * Put its lines into the protocol tree, a line at a time.
399            */
400           while (tvb_offset_exists(tvb, offset)) {
401
402             /*
403              * Find the end of the line.
404              */
405             tvb_find_line_end(tvb, offset, -1, &next_offset, FALSE);
406
407             /*
408              * Put this line.
409              */
410             proto_tree_add_text(smtp_tree, tvb, offset, next_offset - offset,
411                 "Message: %s",
412                 tvb_format_text(tvb, offset, next_offset - offset));
413
414             /*
415              * Step to the next line.
416              */
417             offset = next_offset;
418
419           }
420
421           break;
422
423         case SMTP_PDU_EOM:
424
425           /*
426            * End-of-message-body indicator.
427            *
428            * XXX - what about stuff after the first line?
429            * Unlikely, as the client should wait for a response to the
430            * DATA command this terminates before sending another
431            * request, but we should probably handle it.
432            */
433           proto_tree_add_text(smtp_tree, tvb, offset, linelen,
434               "EOM: %s", format_text(line, linelen));
435
436           break;
437
438         case SMTP_PDU_CMD:
439
440           /*
441            * Command.
442            *
443            * XXX - what about stuff after the first line?
444            * Unlikely, as the client should wait for a response to the
445            * previous command before sending another request, but we
446            * should probably handle it.
447            */
448           if (linelen >= 4)
449             cmdlen = 4;
450           else
451             cmdlen = linelen;
452           proto_tree_add_boolean_hidden(smtp_tree, hf_smtp_req, tvb,
453                                         0, 0, TRUE);
454           /*
455            * Put the command line into the protocol tree.
456            */
457           ti = proto_tree_add_text(smtp_tree, tvb, offset, next_offset - offset,
458                 "Command: %s",
459                 tvb_format_text(tvb, offset, next_offset - offset));
460           cmdresp_tree = proto_item_add_subtree(ti, ett_smtp_cmdresp);
461
462           proto_tree_add_item(cmdresp_tree, hf_smtp_req_command, tvb,
463                               offset, cmdlen, FALSE);
464           if (linelen > 5) {
465             proto_tree_add_item(cmdresp_tree, hf_smtp_req_parameter, tvb,
466                                 offset + 5, linelen - 5, FALSE);
467           }
468
469         }
470
471       }
472       else {
473
474         /*
475          * Process the response, a line at a time, until we hit a line
476          * that doesn't have a continuation indication on it.
477          */
478         proto_tree_add_boolean_hidden(smtp_tree, hf_smtp_rsp, tvb,
479                                         0, 0, TRUE);
480
481         while (tvb_offset_exists(tvb, offset)) {
482
483           /*
484            * Find the end of the line.
485            */
486           linelen = tvb_find_line_end(tvb, offset, -1, &next_offset, FALSE);
487
488           /*
489            * Put it into the protocol tree.
490            */
491           ti = proto_tree_add_text(smtp_tree, tvb, offset,
492                                    next_offset - offset, "Response: %s",
493                                    tvb_format_text(tvb, offset,
494                                                    next_offset - offset));
495           cmdresp_tree = proto_item_add_subtree(ti, ett_smtp_cmdresp);
496
497           /*
498            * Is it a continuation line?
499            */
500           is_continuation_line =
501               (linelen >= 4 && tvb_get_guint8(tvb, offset + 3) == '-');
502
503           /*
504            * Put the response code and parameters into the protocol tree.
505            */
506           line = tvb_get_ptr(tvb, offset, linelen);
507           if (linelen >= 3 && isdigit(line[0]) && isdigit(line[1])
508                            && isdigit(line[2])) {
509             /*
510              * We have a 3-digit response code.
511              */
512             code = (line[0] - '0')*100 + (line[1] - '0')*10 + (line[2] - '0');
513             proto_tree_add_uint(cmdresp_tree, hf_smtp_rsp_code, tvb, offset, 3,
514                                 code);
515
516             if (linelen >= 4) {
517               proto_tree_add_item(cmdresp_tree, hf_smtp_rsp_parameter, tvb,
518                                   offset + 4, linelen - 4, FALSE);
519             }
520           }
521
522           /*
523            * Step past this line.
524            */
525           offset = next_offset;
526
527           /*
528            * If it's not a continuation line, quit.
529            */
530           if (!is_continuation_line)
531             break;
532
533         }
534
535       }
536     }
537 }
538
539 /* Register all the bits needed by the filtering engine */
540
541 void
542 proto_register_smtp(void)
543 {
544   static hf_register_info hf[] = {
545     { &hf_smtp_req,
546       { "Request", "smtp.req", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "", HFILL }},
547
548     { &hf_smtp_rsp,
549       { "Response", "smtp.rsp", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "", HFILL }},
550
551     { &hf_smtp_req_command,
552       { "Command", "smtp.req.command", FT_STRING,  BASE_NONE, NULL, 0x0,
553         "", HFILL }},
554
555     { &hf_smtp_req_parameter,
556       { "Request parameter", "smtp.req.parameter", FT_STRING, BASE_NONE, NULL, 0x0,
557         "", HFILL }},
558
559     { &hf_smtp_rsp_code,
560       { "Response code", "smtp.response.code", FT_UINT32, BASE_DEC, NULL, 0x0,
561         "", HFILL }},
562
563     { &hf_smtp_rsp_parameter,
564       { "Response parameter", "smtp.rsp.parameter", FT_STRING, BASE_NONE, NULL, 0x0,
565         "", HFILL }}
566   };
567   static gint *ett[] = {
568     &ett_smtp,
569     &ett_smtp_cmdresp,
570   };
571   module_t *smtp_module;
572
573   /* No Configuration options to register? */
574
575   proto_smtp = proto_register_protocol("Simple Mail Transfer Protocol",
576                                        "SMTP", "smtp");
577
578   proto_register_field_array(proto_smtp, hf, array_length(hf));
579   proto_register_subtree_array(ett, array_length(ett));
580   register_init_routine(&smtp_init_protocol);
581
582   smtp_module = prefs_register_protocol(proto_smtp, NULL);
583   prefs_register_bool_preference(smtp_module, "desegment_lines",
584     "Desegment all SMTP command and response lines spanning multiple TCP segments",
585     "Whether the SMTP dissector should desegment all command and response lines spanning multiple TCP segments",
586     &smtp_desegment);
587 }
588
589 /* The registration hand-off routine */
590 void
591 proto_reg_handoff_smtp(void)
592 {
593   static int smtp_prefs_initialized = FALSE;
594   static dissector_handle_t smtp_handle;
595   static int tcp_port = 0;
596
597   if (!smtp_prefs_initialized) {
598
599     smtp_handle = create_dissector_handle(dissect_smtp, proto_smtp);
600
601     smtp_prefs_initialized = TRUE;
602
603   }
604   else {
605
606     dissector_delete("tcp.port", tcp_port, smtp_handle);
607
608   }
609
610   tcp_port = global_smtp_tcp_port;
611
612   dissector_add("tcp.port", global_smtp_tcp_port, smtp_handle);
613
614 }