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