Initial support for writing NetXRay 2.x (Windows Sniffer) format
[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.26 2002/04/14 23:04:04 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 #ifdef HAVE_SYS_TYPES_H
32 # include <sys/types.h>
33 #endif
34
35 #ifdef HAVE_NETINET_IN_H
36 #include <netinet/in.h>
37 #endif
38
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <glib.h>
44 #include <string.h>
45 #include <epan/packet.h>
46 #include <epan/conversation.h>
47 #include <epan/resolv.h>
48 #include "prefs.h"
49 #include <epan/strutil.h>
50
51 #define TCP_PORT_SMTP 25
52
53 void proto_reg_handoff_smtp(void);
54
55 static int proto_smtp = -1;
56
57 static int hf_smtp_req = -1;
58 static int hf_smtp_rsp = -1;
59
60 static int ett_smtp = -1;
61
62 static int global_smtp_tcp_port = TCP_PORT_SMTP;
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_item              *ti;
113     int                     offset = 0;
114     int                     request = 0;
115     conversation_t          *conversation;
116     struct smtp_request_val *request_val;
117     const char              *line;
118     int                     linelen;
119     gboolean                eom_seen = FALSE;
120     gint                    next_offset;
121     gboolean                is_continuation_line;
122     int                     cmdlen;
123
124     /* As there is no guarantee that we will only see frames in the
125      * the SMTP conversation once, and that we will see them in
126      * order - in Ethereal, the user could randomly click on frames
127      * in the conversation in any order in which they choose - we
128      * have to store information with each frame indicating whether
129      * it contains commands or data or an EOM indication.
130      *
131      * XXX - what about frames that contain *both*?  TCP is a
132      * byte-stream protocol, and there are no guarantees that
133      * TCP segment boundaries will correspond to SMTP commands
134      * or EOM indications.
135      *
136      * We only need that for the client->server stream; responses
137      * are easy to manage.
138      *
139      * If we have per frame data, use that, else, we must be on the first 
140      * pass, so we figure it out on the first pass.
141      */
142
143     /* Find out what conversation this packet is part of ... but only
144      * if we have no information on this packet, so find the per-frame 
145      * info first.
146      */
147
148     /* SMTP messages have a simple format ... */
149
150     request = pinfo -> destport == pinfo -> match_port;
151
152     /*
153      * Get the first line from the buffer.
154      *
155      * Note that "tvb_find_line_end()" will return a value that
156      * is not longer than what's in the buffer, so the
157      * "tvb_get_ptr()" call won't throw an exception.
158      */
159     linelen = tvb_find_line_end(tvb, offset, -1, &next_offset);
160     line = tvb_get_ptr(tvb, offset, linelen);
161
162     frame_data = p_get_proto_data(pinfo->fd, proto_smtp);
163
164     if (!frame_data) {
165
166       conversation = find_conversation(&pinfo->src, &pinfo->dst, pinfo->ptype,
167                                        pinfo->srcport, pinfo->destport, 0);
168       if (conversation == NULL) { /* No conversation, create one */
169         conversation = conversation_new(&pinfo->src, &pinfo->dst, pinfo->ptype,
170                                         pinfo->srcport, pinfo->destport, 0);
171
172       }
173
174       /*
175        * Is there a request structure attached to this conversation?
176        */
177       request_val = conversation_get_proto_data(conversation, proto_smtp);
178
179       if (!request_val) {
180
181         /*
182          * No - create one and attach it.
183          */
184         request_val = g_mem_chunk_alloc(smtp_request_vals);
185         request_val->reading_data = FALSE;
186         request_val->crlf_seen = 0;
187
188         conversation_add_proto_data(conversation, proto_smtp, request_val);
189
190       }
191
192       /* 
193        * Check whether or not this packet is an end of message packet
194        * We should look for CRLF.CRLF and they may be split.
195        * We have to keep in mind that we may see what we want on
196        * two passes through here ...
197        */
198
199       if (request_val->reading_data) {
200
201         /*
202          * The order of these is important ... We want to avoid
203          * cases where there is a CRLF at the end of a packet and a 
204          * .CRLF at the begining of the same packet.
205          */
206
207         if ((request_val->crlf_seen && tvb_strneql(tvb, offset, ".\r\n", 3) == 0) ||
208             tvb_strneql(tvb, offset, "\r\n.\r\n", 5) == 0) {
209
210           eom_seen = TRUE;
211
212         }
213
214         if (tvb_strneql(tvb, offset + tvb_length_remaining(tvb, offset) - 2, "\r\n", 2) == 0) {
215
216           request_val->crlf_seen = 1;
217
218         }
219         else {
220
221           request_val->crlf_seen = 0;
222
223         }
224       }
225
226     /*
227      * OK, Check if we have seen a DATA request. We do it here for 
228      * simplicity, but we have to be careful below.
229      */
230
231       if (request) {
232
233         frame_data = g_mem_chunk_alloc(smtp_packet_infos);
234
235         if (request_val->reading_data) {
236           /*
237            * This is message data.
238            */
239           if (eom_seen) { /* Seen the EOM */
240             /*
241              * EOM.
242              * Everything that comes after it is commands.
243              *
244              * XXX - what if the EOM isn't at the beginning of
245              * the TCP segment?  It can occur anywhere....
246              */
247             frame_data->pdu_type = SMTP_PDU_EOM;
248             request_val->reading_data = FALSE;
249           } else {
250             /*
251              * Message data with no EOM.
252              */
253             frame_data->pdu_type = SMTP_PDU_MESSAGE;
254           }
255         } else {
256           /*
257            * This is commands - unless the capture started in the
258            * middle of a session, and we're in the middle of data.
259            * To quote RFC 821, "Command codes are four alphabetic
260            * characters"; if we don't see four alphabetic characters
261            * and, if there's anything else in the line, a space, we
262            * assume it's not a command.
263            * (We treat only A-Z and a-z as alphabetic.)
264            */
265 #define ISALPHA(c)      (((c) >= 'A' && (c) <= 'Z') || \
266                          ((c) >= 'a' && (c) <= 'z'))
267           if (linelen >= 4 && ISALPHA(line[0]) && ISALPHA(line[1]) &&
268               ISALPHA(line[2]) && ISALPHA(line[3]) &&
269               (linelen == 4 || line[4] == ' ')) {
270             if (strncasecmp(line, "DATA", 4) == 0) {
271
272               /*
273                * DATA command.
274                * This is a command, but everything that comes after it,
275                * until an EOM, is data.
276                */
277               frame_data->pdu_type = SMTP_PDU_CMD;
278               request_val->reading_data = TRUE;
279
280             } else {
281
282               /*
283                * Regular command.
284                */
285               frame_data->pdu_type = SMTP_PDU_CMD;
286
287             }
288           } else {
289
290             /*
291              * Assume it's message data.
292              */
293
294             frame_data->pdu_type = SMTP_PDU_MESSAGE;
295
296           }
297
298         }
299
300         p_add_proto_data(pinfo->fd, proto_smtp, frame_data);
301
302       }
303     }
304
305     /* 
306      * From here, we simply add items to the tree and info to the info 
307      * fields ...
308      */
309
310     if (check_col(pinfo->cinfo, COL_PROTOCOL))
311       col_set_str(pinfo->cinfo, COL_PROTOCOL, "SMTP");
312
313     if (check_col(pinfo->cinfo, COL_INFO)) {  /* Add the appropriate type here */
314
315       /*
316        * If it is a request, we have to look things up, otherwise, just
317        * display the right things 
318        */
319
320       if (request) {
321
322         /* We must have frame_data here ... */
323
324         switch (frame_data->pdu_type) {
325         case SMTP_PDU_MESSAGE:
326
327           col_set_str(pinfo->cinfo, COL_INFO, "Message Body");
328           break;
329
330         case SMTP_PDU_EOM:
331
332           col_add_fstr(pinfo->cinfo, COL_INFO, "EOM: %s",
333               format_text(line, linelen));
334           break;
335
336         case SMTP_PDU_CMD:
337
338           col_add_fstr(pinfo->cinfo, COL_INFO, "Command: %s",
339               format_text(line, linelen));
340           break;
341
342         }
343
344       }
345       else {
346
347         col_add_fstr(pinfo->cinfo, COL_INFO, "Response: %s",
348             format_text(line, linelen));
349
350       }
351     }
352
353     if (tree) { /* Build the tree info ... */
354
355       ti = proto_tree_add_item(tree, proto_smtp, tvb, offset, -1, FALSE);
356       smtp_tree = proto_item_add_subtree(ti, ett_smtp);
357       proto_tree_add_boolean_hidden(smtp_tree, (request ? hf_smtp_req : hf_smtp_rsp),
358                                     tvb, offset, 4, TRUE);
359       if (request) {
360
361         /* 
362          * Check out whether or not we can see a command in there ...
363          * What we are looking for is not data_seen and the word DATA
364          * and not eom_seen.
365          *
366          * We will see DATA and request_val->data_seen when we process the
367          * tree view after we have seen a DATA packet when processing
368          * the packet list pane.
369          *
370          * On the first pass, we will not have any info on the packets
371          * On second and subsequent passes, we will.
372          */
373
374         switch (frame_data->pdu_type) {
375
376         case SMTP_PDU_MESSAGE:
377
378           /*
379            * Message body.
380            * Put its lines into the protocol tree, a line at a time.
381            */
382           while (tvb_offset_exists(tvb, offset)) {
383
384             /*
385              * Find the end of the line.
386              */
387             tvb_find_line_end(tvb, offset, -1, &next_offset);
388
389             /*
390              * Put this line.
391              */
392             proto_tree_add_text(smtp_tree, tvb, offset, next_offset - offset,
393                 "Message: %s",
394                 tvb_format_text(tvb, offset, next_offset - offset));
395
396             /*
397              * Step to the next line.
398              */
399             offset = next_offset;
400
401           }
402
403           break;
404
405         case SMTP_PDU_EOM:
406
407           /*
408            * End-of-message-body indicator.
409            *
410            * XXX - what about stuff after the first line?
411            * Unlikely, as the client should wait for a response to the
412            * DATA command this terminates before sending another
413            * request, but we should probably handle it.
414            */
415           proto_tree_add_text(smtp_tree, tvb, offset, linelen,
416               "EOM: %s", format_text(line, linelen));
417
418           break;
419
420         case SMTP_PDU_CMD:
421
422           /*
423            * Command.
424            *
425            * XXX - what about stuff after the first line?
426            * Unlikely, as the client should wait for a response to the
427            * previous command before sending another request, but we
428            * should probably handle it.
429            */
430           if (linelen >= 4)
431             cmdlen = 4;
432           else
433             cmdlen = linelen;
434           proto_tree_add_text(smtp_tree, tvb, offset, cmdlen,
435               "Command: %s", format_text(line, cmdlen));
436           if (linelen > 5) {
437             proto_tree_add_text(smtp_tree, tvb, offset + 5, linelen - 5,
438                 "Parameter: %s", format_text(line + 5, linelen - 5));
439           }
440
441         }
442
443       }
444       else {
445
446         /*
447          * Process the response, a line at a time, until we hit a line
448          * that doesn't have a continuation indication on it.
449          */
450
451         while (tvb_offset_exists(tvb, offset)) {
452
453           /*
454            * Find the end of the line.
455            */
456           linelen = tvb_find_line_end(tvb, offset, -1, &next_offset);
457
458           /*
459            * Is it a continuation line?
460            */
461           is_continuation_line =
462               (linelen >= 4 && tvb_get_guint8(tvb, offset + 3) == '-');
463
464           /*
465            * Put it into the protocol tree.
466            */
467           proto_tree_add_text(smtp_tree, tvb, offset, 3,
468               "Response: %s", tvb_format_text(tvb, offset, 3));
469           if (linelen >= 4) {
470             proto_tree_add_text(smtp_tree, tvb, offset + 4, linelen - 4,
471                 "Parameter: %s", tvb_format_text(tvb, offset + 4, linelen - 4));
472           }
473
474           /*
475            * Step past this line.
476            */
477           offset = next_offset;
478
479           /*
480            * If it's not a continuation line, quit.
481            */
482           if (!is_continuation_line)
483             break;
484
485         }
486         
487       }
488     }
489 }
490
491 /* Register all the bits needed by the filtering engine */
492
493 void
494 proto_register_smtp(void)
495 {
496   static hf_register_info hf[] = {
497     { &hf_smtp_req,
498       { "Request", "smtp.req", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "", HFILL }},
499
500     { &hf_smtp_rsp,
501       { "Response", "smtp.rsp", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "", HFILL }},
502   };
503   static gint *ett[] = {
504     &ett_smtp
505   };
506   /*module_t *smtp_module = NULL; */  /* Not yet used */
507
508   /* No Configuration options to register? */
509
510   proto_smtp = proto_register_protocol("Simple Mail Transfer Protocol",
511                                        "SMTP", "smtp");
512
513   proto_register_field_array(proto_smtp, hf, array_length(hf));
514   proto_register_subtree_array(ett, array_length(ett));
515   register_init_routine(&smtp_init_protocol);
516
517 }
518
519 /* The registration hand-off routine */
520 void
521 proto_reg_handoff_smtp(void)
522 {
523   static int smtp_prefs_initialized = FALSE;
524   static dissector_handle_t smtp_handle;
525   static int tcp_port = 0;
526
527   if (!smtp_prefs_initialized) {
528
529     smtp_handle = create_dissector_handle(dissect_smtp, proto_smtp);
530
531     smtp_prefs_initialized = TRUE;
532
533   }
534   else {
535
536     dissector_delete("tcp.port", tcp_port, smtp_handle);
537
538   }
539
540   tcp_port = global_smtp_tcp_port;
541
542   dissector_add("tcp.port", global_smtp_tcp_port, smtp_handle);
543
544 }