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