Start of a PCNFSD dissector as the RPC dissector 150001.
[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.20 2001/09/03 10:33: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     const char              *line;
171     int                     linelen;
172     gboolean                eom_seen = FALSE;
173     gint                    next_offset;
174     gboolean                is_continuation_line;
175     int                     cmdlen;
176
177     /* As there is no guarantee that we will only see frames in the
178      * the SMTP conversation once, and that we will see them in
179      * order - in Ethereal, the user could randomly click on frames
180      * in the conversation in any order in which they choose - we
181      * have to store information with each frame indicating whether
182      * it contains commands or data or an EOM indication.
183      *
184      * XXX - what about frames that contain *both*?  TCP is a
185      * byte-stream protocol, and there are no guarantees that
186      * TCP segment boundaries will correspond to SMTP commands
187      * or EOM indications.
188      *
189      * We only need that for the client->server stream; responses
190      * are easy to manage.
191      *
192      * If we have per frame data, use that, else, we must be on the first 
193      * pass, so we figure it out on the first pass.
194      */
195
196     /* Find out what conversation this packet is part of ... but only
197      * if we have no information on this packet, so find the per-frame 
198      * info first.
199      */
200
201     /* SMTP messages have a simple format ... */
202
203     request = pinfo -> destport == pinfo -> match_port;
204
205     /*
206      * Get the first line from the buffer.
207      *
208      * Note that "tvb_find_line_end()" will return a value that
209      * is not longer than what's in the buffer, so the
210      * "tvb_get_ptr()" call won't throw an exception.
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, pinfo->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, 0);
224
225       }
226
227       /* 
228        * Check for and insert an entry in the request table if does not exist
229        */
230       request_key.conversation = conversation->index;
231
232       request_val = (struct smtp_request_val *)g_hash_table_lookup(smtp_request_hash, &request_key);
233       
234       if (!request_val) { /* Create one */
235
236         new_request_key = g_mem_chunk_alloc(smtp_request_keys);
237         new_request_key->conversation = conversation->index;
238
239         request_val = g_mem_chunk_alloc(smtp_request_vals);
240         request_val->reading_data = FALSE;
241         request_val->crlf_seen = 0;
242
243         g_hash_table_insert(smtp_request_hash, new_request_key, request_val);
244
245       }
246
247       /* 
248        * Check whether or not this packet is an end of message packet
249        * We should look for CRLF.CRLF and they may be split.
250        * We have to keep in mind that we may see what we want on
251        * two passes through here ...
252        */
253
254       if (request_val->reading_data) {
255
256         /*
257          * The order of these is important ... We want to avoid
258          * cases where there is a CRLF at the end of a packet and a 
259          * .CRLF at the begining of the same packet.
260          */
261
262         if ((request_val->crlf_seen && tvb_strneql(tvb, offset, ".\r\n", 3) == 0) ||
263             tvb_strneql(tvb, offset, "\r\n.\r\n", 5) == 0) {
264
265           eom_seen = TRUE;
266
267         }
268
269         if (tvb_strneql(tvb, offset + tvb_length_remaining(tvb, offset) - 2, "\r\n", 2) == 0) {
270
271           request_val->crlf_seen = 1;
272
273         }
274         else {
275
276           request_val->crlf_seen = 0;
277
278         }
279       }
280
281     /*
282      * OK, Check if we have seen a DATA request. We do it here for 
283      * simplicity, but we have to be careful below.
284      */
285
286       if (request) {
287
288         frame_data = g_mem_chunk_alloc(smtp_packet_infos);
289
290         if (request_val->reading_data) {
291           /*
292            * This is message data.
293            */
294           if (eom_seen) { /* Seen the EOM */
295             /*
296              * EOM.
297              * Everything that comes after it is commands.
298              *
299              * XXX - what if the EOM isn't at the beginning of
300              * the TCP segment?  It can occur anywhere....
301              */
302             frame_data->pdu_type = SMTP_PDU_EOM;
303             request_val->reading_data = FALSE;
304           } else {
305             /*
306              * Message data with no EOM.
307              */
308             frame_data->pdu_type = SMTP_PDU_MESSAGE;
309           }
310         } else {
311           /*
312            * This is commands - unless the capture started in the
313            * middle of a session, and we're in the middle of data.
314            * To quote RFC 821, "Command codes are four alphabetic
315            * characters"; if we don't see four alphabetic characters
316            * and, if there's anything else in the line, a space, we
317            * assume it's not a command.
318            * (We treat only A-Z and a-z as alphabetic.)
319            */
320 #define ISALPHA(c)      (((c) >= 'A' && (c) <= 'Z') || \
321                          ((c) >= 'a' && (c) <= 'z'))
322           if (linelen >= 4 && ISALPHA(line[0]) && ISALPHA(line[1]) &&
323               ISALPHA(line[2]) && ISALPHA(line[3]) &&
324               (linelen == 4 || line[4] == ' ')) {
325             if (strncasecmp(line, "DATA", 4) == 0) {
326
327               /*
328                * DATA command.
329                * This is a command, but everything that comes after it,
330                * until an EOM, is data.
331                */
332               frame_data->pdu_type = SMTP_PDU_CMD;
333               request_val->reading_data = TRUE;
334
335             } else {
336
337               /*
338                * Regular command.
339                */
340               frame_data->pdu_type = SMTP_PDU_CMD;
341
342             }
343           } else {
344
345             /*
346              * Assume it's message data.
347              */
348
349             frame_data->pdu_type = SMTP_PDU_MESSAGE;
350
351           }
352
353         }
354
355         p_add_proto_data(pinfo->fd, proto_smtp, frame_data);
356
357       }
358     }
359
360     /* 
361      * From here, we simply add items to the tree and info to the info 
362      * fields ...
363      */
364
365     if (check_col(pinfo->fd, COL_PROTOCOL))
366       col_set_str(pinfo->fd, COL_PROTOCOL, "SMTP");
367
368     if (check_col(pinfo->fd, COL_INFO)) {  /* Add the appropriate type here */
369
370       /*
371        * If it is a request, we have to look things up, otherwise, just
372        * display the right things 
373        */
374
375       if (request) {
376
377         /* We must have frame_data here ... */
378
379         switch (frame_data->pdu_type) {
380         case SMTP_PDU_MESSAGE:
381
382           col_set_str(pinfo->fd, COL_INFO, "Message Body");
383           break;
384
385         case SMTP_PDU_EOM:
386
387           col_add_fstr(pinfo->fd, COL_INFO, "EOM: %s",
388               format_text(line, linelen));
389           break;
390
391         case SMTP_PDU_CMD:
392
393           col_add_fstr(pinfo->fd, COL_INFO, "Command: %s",
394               format_text(line, linelen));
395           break;
396
397         }
398
399       }
400       else {
401
402         col_add_fstr(pinfo->fd, COL_INFO, "Response: %s",
403             format_text(line, linelen));
404
405       }
406     }
407
408     if (tree) { /* Build the tree info ... */
409
410       ti = proto_tree_add_item(tree, proto_smtp, tvb, offset,
411         tvb_length_remaining(tvb, offset), 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, "", HFILL }},
555
556     { &hf_smtp_rsp,
557       { "Response", "smtp.rsp", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "", HFILL }},
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",
567                                        "SMTP", "smtp");
568
569   proto_register_field_array(proto_smtp, hf, array_length(hf));
570   proto_register_subtree_array(ett, array_length(ett));
571   register_init_routine(&smtp_init_protocol);
572
573 }
574
575 /* The registration hand-off routine */
576 void
577 proto_reg_handoff_smtp(void)
578 {
579   static int smtp_prefs_initialized = FALSE;
580   static int tcp_port = 0;
581
582   if (smtp_prefs_initialized) {
583
584     dissector_delete("tcp.port", tcp_port, dissect_smtp);
585
586   }
587   else {
588
589     smtp_prefs_initialized = TRUE;
590
591   }
592
593   tcp_port = global_smtp_tcp_port;
594
595   dissector_add("tcp.port", global_smtp_tcp_port, dissect_smtp, proto_smtp);
596
597 }