Removed trailing whitespaces from .h and .c files using the
[obnox/wireshark/wip.git] / packet-mbtcp.c
1 /* packet-mbtcp.c
2  * Routines for Modbus/TCP dissection
3  * By Riaan Swart <rswart@cs.sun.ac.za>
4  * Copyright 2001, Institute for Applied Computer Science
5  *                                       University of Stellenbosch
6  *
7  * See
8  *
9  *      http://www.modicon.com/openmbus/
10  *
11  * for information on Modbus/TCP.
12  *
13  * $Id: packet-mbtcp.c,v 1.10 2002/08/02 23:35:54 jmayer Exp $
14  *
15  * Ethereal - Network traffic analyzer
16  * By Gerald Combs <gerald@ethereal.com>
17  * Copyright 1998 Gerald Combs
18  * 
19  * This program is free software; you can redistribute it and/or
20  * modify it under the terms of the GNU General Public License
21  * as published by the Free Software Foundation; either version 2
22  * of the License, or (at your option) any later version.
23  * 
24  * This program is distributed in the hope that it will be useful,
25  * but WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  * GNU General Public License for more details.
28  * 
29  * You should have received a copy of the GNU General Public License
30  * along with this program; if not, write to the Free Software
31  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32  */
33
34 /*      TODO:
35  *      Analysis of the payload of the Modbus packet.
36  *              --      Based on the function code in the header, and the fact that the packet is 
37  *                      either a query or a response, the different fields in the payload can be 
38  *                      interpreted and displayed.
39  */
40
41 #ifdef HAVE_CONFIG_H
42 # include "config.h"
43 #endif
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48
49 #include <glib.h>
50
51 #include <epan/packet.h>
52
53 #define DEBUG  
54
55 #define TCP_PORT_MBTCP          502     /* Modbus/TCP located on TCP port 502 */
56
57 /* Modbus protocol function codes */
58 #define read_coils                              1
59 #define read_input_discretes    2
60 #define read_mult_regs                  3
61 #define read_input_regs                 4
62 #define write_coil                              5
63 #define write_single_reg                6
64 #define read_except_stat                7
65 #define diagnostics                             8
66 #define program_484                             9
67 #define poll_484                                        10
68 #define get_comm_event_ctrs     11
69 #define get_comm_event_log              12
70 #define program_584_984                 13
71 #define poll_584_984                            14
72 #define force_mult_coils                15
73 #define write_mult_regs                 16
74 #define report_slave_id                 17
75 #define program_884_u84                 18
76 #define reset_comm_link                 19
77 #define read_genl_ref                   20
78 #define write_genl_ref                  21
79 #define mask_write_reg                  22
80 #define read_write_reg                  23
81 #define read_fifo_queue                 24
82 #define program_ConCept                 40
83 #define firmware_replace                125
84 #define program_584_984_2               126
85 #define report_local_addr_mb    127
86
87 /* Modbus protocol exception codes */
88 #define illegal_function                0x01
89 #define illegal_address                 0x02
90 #define illegal_value                   0x03
91 #define illegal_response                0x04
92 #define acknowledge                             0x05
93 #define slave_busy                              0x06
94 #define negative_ack                            0x07
95 #define memory_err                              0x08
96 #define gateway_unavailable     0x0a
97 #define gateway_trgt_fail               0x0b
98
99 /* return codes of function classifying packets as query/response */
100 #define query_packet                            0
101 #define response_packet                 1
102 #define cannot_classify                 2
103
104 /* Modbus header */
105 typedef struct _modbus_hdr {
106         gchar           unit_id;                        /* unit identifier (previously slave addr) */
107         gchar           function_code; /* Modbus function code */
108 } modbus_hdr;
109
110 /* Modbus/TCP header, containing the Modbus header */
111 typedef struct _mbtcp_hdr {
112         guint16         transaction_id; /* copied by svr, usually 0 */
113         guint16                 protocol_id;            /* always 0 */
114         guint16         len;                                    /* len of data that follows */
115         modbus_hdr      mdbs_hdr;                       /* mdbus hdr directly after mdbs/tcp hdr *
116                                                                                          * in packet */
117 } mbtcp_hdr;
118
119 /* Initialize the protocol and registered fields */
120 static int proto_mbtcp = -1;
121 static int hf_mbtcp_transid = -1;
122 static int hf_mbtcp_protid = -1;
123 static int hf_mbtcp_len = -1;
124 static int hf_mbtcp_unitid = -1;
125 static int hf_mbtcp_functioncode = -1;
126
127 /* Initialize the subtree pointers */
128 static gint ett_mbtcp = -1;
129 static gint ett_modbus_hdr = -1;
130         
131 static int
132 classify_packet(packet_info *pinfo)
133 {
134         /* see if nature of packets can be derived from src/dst ports */
135         /* if so, return as found */
136         if ( ( 502 == pinfo->srcport && 502 != pinfo->destport ) ||
137                   ( 502 != pinfo->srcport && 502 == pinfo->destport ) ) {
138                 /* the slave is receiving queries on port 502 */
139                 if ( 502 == pinfo->srcport )  
140                         return response_packet;
141                 else if ( 502 == pinfo->destport ) 
142                         return query_packet;
143         }
144         /* else, cannot classify */
145         return cannot_classify;
146 }
147
148 /* returns string describing function, as given on p6 of 
149  * "Open Modbus/TCP Specification", release 1 by Andy Swales. */
150 static char *
151 function_string(guint16 func_code)
152 {
153         switch ( func_code ) {
154                 case read_coils:                                return "Read coils";                                                            break;
155                 case read_input_discretes:      return "Read input discretes";                          break;
156                 case read_mult_regs:                    return "Read multiple registers";                       break;
157                 case read_input_regs:           return "Read input registers";                          break;
158                 case write_coil:                                return "Write coil";                                                            break;
159                 case write_single_reg:          return "Write single register";                         break;
160                 case read_except_stat:          return "Read exception status";                         break;
161                 case diagnostics:                               return "Diagnostics";                                                   break;
162                 case program_484:                               return "Program (484)";                                                 break;
163                 case poll_484:                                  return "Poll (484)";                                                            break;
164                 case get_comm_event_ctrs:       return "Get Comm. Event Counters";                      break;
165                 case get_comm_event_log:        return "Get Comm. Event Log";                                   break;
166                 case program_584_984:           return "Program (584/984)";                                     break;
167                 case poll_584_984:                      return "Poll (584/984)";                                                break;
168                 case force_mult_coils:          return "Force Multiple Coils";                          break;
169                 case write_mult_regs:           return "Write Multiple Registers";                      break;
170                 case report_slave_id:           return "Report Slave ID";                                               break;
171                 case program_884_u84:           return "Program 884/u84";                                               break;
172                 case reset_comm_link:           return "Reset Comm. Link (884/u84)";            break;
173                 case read_genl_ref:                     return "Read General Reference";                                break;
174                 case write_genl_ref:                    return "Write General Reference";                       break;
175                 case mask_write_reg:                    return "Mask Write Register";                                   break;
176                 case read_write_reg:                    return "Read Write Register";                                   break;
177                 case read_fifo_queue:           return "Read FIFO Queue";                                               break;
178                 case program_ConCept:           return "Program (ConCept)";                                     break;
179                 case firmware_replace:          return "Firmware replacement";                          break;
180                 case program_584_984_2:         return "Program (584/984)";                                     break;
181                 case report_local_addr_mb:      return "Report local address (Modbus)"; break;
182                 default:                                                        return "Unknown function";                                              break;
183         }
184 }
185 static char *
186 exception_string(guint8 exception_code)
187 {
188         switch( exception_code ) {
189                 case illegal_function:          return "Illegal function";                              break;
190                 case illegal_address:           return "Illegal data address";          break;
191                 case illegal_value:                     return "Illegal data value";                    break;
192                 case illegal_response:          return "Illegal response length";       break;
193                 case acknowledge:                               return "Acknowledge";                                   break;
194                 case slave_busy:                                return "Slave device busy";                     break;
195                 case negative_ack:                      return "Negative acknowledge";          break;
196                 case memory_err:                                return "Memory parity error";                   break;
197                 case gateway_unavailable:       return "Gateway path unavailable";      break;
198                 case gateway_trgt_fail:         return "Gateway target device failed to respond";       break;
199                 default:                                                        return "Unknown exception code";                break;
200         }
201 }
202
203 /* Code to actually dissect the packets */
204 static void
205 dissect_mbtcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
206 {
207 /* Set up structures needed to add the protocol subtree and manage it */
208         mbtcp_hdr       mh;
209         proto_item      *mi, *mf;
210         proto_tree      *mbtcp_tree, *modbus_tree;
211         int                     offset = 0;
212         gint                    packet_end, packet_len;
213         char                    *func_string = "", pkt_type_str[9] = "";
214         char                    err_str[100] = "";
215         int                     packet_type;
216         guint32         packet_num = 0; /* num to uniquely identify different mbtcp 
217                                                                                                  * packets in one TCP packet */
218         guint8          exception_code = 0, exception_returned = 0;
219         
220 /* Make entries in Protocol column on summary display */
221         if (check_col(pinfo->cinfo, COL_PROTOCOL)) 
222                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/TCP");
223
224         if (check_col(pinfo->cinfo, COL_INFO))
225                 col_clear(pinfo->cinfo, COL_INFO);
226
227 /* Make entries in Info column on summary display (updated after building proto tree) */
228         tvb_memcpy(tvb, (guint8 *)&mh, offset, sizeof(mbtcp_hdr));
229         mh.transaction_id                               =       g_ntohs(mh.transaction_id);
230         mh.protocol_id                                  =       g_ntohs(mh.protocol_id);
231         mh.len                                                  =       g_ntohs(mh.len);
232         if ( mh.mdbs_hdr.function_code & 0x80 ) {
233                 mh.mdbs_hdr.function_code ^= 0x80;
234                 exception_returned = 1;
235         }
236         func_string = function_string(mh.mdbs_hdr.function_code);
237         if (check_col(pinfo->cinfo, COL_INFO))
238         {
239                 packet_type = classify_packet(pinfo);
240                 switch ( packet_type ) {
241                         case query_packet :                     strcpy(pkt_type_str, "query");  
242                                                                                                 break;
243                         case response_packet :          strcpy(pkt_type_str, "response");  
244                                                                                                 break;
245                         case cannot_classify :          strcpy(err_str, "Unable to classify as query or response.");
246                                                                                                 strcpy(pkt_type_str, "unknown");
247                                                                                                 break;
248                         default :
249                                                                                                 break;
250                 }
251                 if ( exception_returned )
252                         strcpy(err_str, "Exception returned ");
253                 col_add_fstr(pinfo->cinfo, COL_INFO, 
254                                 "%8s [%2u pkt(s)]: trans: %5u; unit: %3u, func: %3u: %s. %s", 
255                                 pkt_type_str, 1, mh.transaction_id, (unsigned char) mh.mdbs_hdr.unit_id, 
256                                 (unsigned char) mh.mdbs_hdr.function_code, func_string, err_str);
257         }       
258
259         /* build up protocol tree */
260         do {
261         /* Avoids alignment problems on many architectures. */
262                 tvb_memcpy(tvb, (guint8 *)&mh, offset, sizeof(mbtcp_hdr));
263                 mh.transaction_id                               =       g_ntohs(mh.transaction_id);
264                 mh.protocol_id                                  =       g_ntohs(mh.protocol_id);
265                 mh.len                                                  =       g_ntohs(mh.len);
266                         
267                 if ( mh.mdbs_hdr.function_code & 0x80 ) {
268                         tvb_memcpy(tvb, (guint8 *)&exception_code, offset + sizeof(mbtcp_hdr), 1);
269                         mh.mdbs_hdr.function_code ^= 0x80;
270                         exception_returned = 1;
271                 } else 
272                         exception_code = 0;
273                 
274                 packet_type = classify_packet(pinfo);
275                 
276                 /* if a tree exists, perform operations to add fields to it */
277                 if (tree) {
278                         packet_len = sizeof(mbtcp_hdr) - sizeof(modbus_hdr) + mh.len;
279                         mi = proto_tree_add_protocol_format(tree, proto_mbtcp, tvb, offset, 
280                                         packet_len, "Modbus/TCP");
281                         mbtcp_tree = proto_item_add_subtree(mi, ett_mbtcp);
282         
283                         /* Add items to protocol tree */
284                         /* Modbus/TCP */
285                         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_transid, tvb, offset, 2, 
286                                         mh.transaction_id);
287                         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_protid, tvb, offset + 2, 2, 
288                                         mh.protocol_id);
289                         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_len, tvb, offset + 4, 2, 
290                                         mh.len);
291                         /* Modbus */
292                         packet_end = mh.len;
293                         mf = proto_tree_add_text(mbtcp_tree, tvb, offset + 6, packet_end, 
294                                         "Modbus");
295                         modbus_tree = proto_item_add_subtree(mf, ett_modbus_hdr);       
296                         proto_tree_add_item(modbus_tree, hf_mbtcp_unitid, tvb, offset + 6, 1, 
297                                         mh.mdbs_hdr.unit_id);
298                         mi = proto_tree_add_item(modbus_tree, hf_mbtcp_functioncode, tvb, offset + 7, 1, 
299                                         mh.mdbs_hdr.function_code);
300                         func_string = function_string(mh.mdbs_hdr.function_code);
301                         if ( 0 == exception_code ) 
302                                 proto_item_set_text(mi, "function %u:  %s", mh.mdbs_hdr.function_code, 
303                                                 func_string);
304                         else  
305                                 proto_item_set_text(mi, "function %u:  %s.  Exception: %s",     
306                                                 mh.mdbs_hdr.function_code, func_string, exception_string(exception_code)); 
307                         
308                         packet_end = mh.len - 2;
309                         proto_tree_add_text(modbus_tree, tvb, offset + 8, packet_end, 
310                                         "Modbus data");
311                 }
312                 offset = offset + sizeof(mbtcp_hdr) + (mh.len - sizeof(modbus_hdr));
313                 packet_num++;
314         } while ( tvb_reported_length_remaining(tvb, offset) > 0 );
315
316         
317 /* Update entries in Info column on summary display */
318         if (check_col(pinfo->cinfo, COL_INFO))
319         {
320                 switch ( packet_type ) {
321                         case query_packet :                     strcpy(pkt_type_str, "query");  
322                                                                                                 break;
323                         case response_packet :          strcpy(pkt_type_str, "response");  
324                                                                                                 break;
325                         case cannot_classify :          strcpy(err_str, "Unable to classify as query or response.");
326                                                                                                 strcpy(pkt_type_str, "unknown");
327                                                                                                 break;
328                         default :
329                                                                                                 break;
330                 }
331                 if ( exception_returned )
332                         strcpy(err_str, "Exception returned ");
333                 col_add_fstr(pinfo->cinfo, COL_INFO, 
334                                 "%8s [%2u pkt(s)]: trans: %5u; unit: %3u, func: %3u: %s. %s", 
335                                 pkt_type_str, packet_num, mh.transaction_id, (unsigned char) mh.mdbs_hdr.unit_id, 
336                                 (unsigned char) mh.mdbs_hdr.function_code, func_string, err_str); 
337         }
338
339 /* If this protocol has a sub-dissector call it here, see section 1.8 */
340 }
341
342
343 /* Register the protocol with Ethereal */
344
345 /* this format is require because a script is used to build the C function
346    that calls all the protocol registration.
347 */
348
349 void
350 proto_register_modbus(void)
351 {                 
352
353 /* Setup list of header fields  See Section 1.6.1 for details*/
354         static hf_register_info hf[] = {
355                 /* Modbus/TCP header fields */
356                 { &hf_mbtcp_transid,
357                         { "transaction identifier",           "modbus_tcp.trans_id",
358                         FT_UINT16, BASE_DEC, NULL, 0x0,          
359                         "", HFILL }
360                 },
361                 { &hf_mbtcp_protid,
362                         { "protocol identifier",           "modbus_tcp.prot_id",
363                         FT_UINT16, BASE_DEC, NULL, 0x0,          
364                         "", HFILL }
365                 },
366                 { &hf_mbtcp_len,
367                         { "length",           "modbus_tcp.len",
368                         FT_UINT16, BASE_DEC, NULL, 0x0,          
369                         "", HFILL }
370                 },
371                 /* Modbus header fields */
372                 { &hf_mbtcp_unitid,
373                         { "unit identifier",           "modbus_tcp.unit_id",
374                         FT_UINT8, BASE_DEC, NULL, 0x0,          
375                         "", HFILL }
376                 },
377                 { &hf_mbtcp_functioncode,
378                         { "function code ",           "modbus_tcp.func_code",
379                         FT_UINT8, BASE_DEC, NULL, 0x0,          
380                         "", HFILL }
381                 }
382         };
383
384 /* Setup protocol subtree array */
385         static gint *ett[] = {
386                 &ett_mbtcp,
387                 &ett_modbus_hdr
388         };
389
390 /* Register the protocol name and description */
391         proto_mbtcp = proto_register_protocol("Modbus/TCP",
392             "Modbus/TCP", "mbtcp");
393
394 /* Required function calls to register the header fields and subtrees used */
395         proto_register_field_array(proto_mbtcp, hf, array_length(hf));
396         proto_register_subtree_array(ett, array_length(ett));
397 }
398
399
400 /* If this dissector uses sub-dissector registration add a registration routine.
401    This format is required because a script is used to find these routines and
402    create the code that calls these routines.
403  */
404 void
405 proto_reg_handoff_mbtcp(void)
406 {
407         dissector_handle_t mbtcp_handle;
408
409         mbtcp_handle = create_dissector_handle(dissect_mbtcp, proto_mbtcp);
410         dissector_add("tcp.port", TCP_PORT_MBTCP, mbtcp_handle);
411 }