From Michael Mann via https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=6697
[metze/wireshark/wip.git] / epan / dissectors / packet-mbtcp.c
1 /* packet-mbtcp.c
2  * Routines for Modbus/TCP and Modbus/UDP 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.modbus.org/
10  *
11  * for information on Modbus/TCP.
12  *
13  * Updated to v1.1b of the Modbus Application Protocol specification
14  *   Michael Mann * Copyright 2011
15  *
16  * $Id$
17  *
18  * Wireshark - Network traffic analyzer
19  * By Gerald Combs <gerald@wireshark.org>
20  * Copyright 1998 Gerald Combs
21  *
22  * This program is free software; you can redistribute it and/or
23  * modify it under the terms of the GNU General Public License
24  * as published by the Free Software Foundation; either version 2
25  * of the License, or (at your option) any later version.
26  *
27  * This program is distributed in the hope that it will be useful,
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30  * GNU General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public License
33  * along with this program; if not, write to the Free Software
34  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35  */
36
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40
41 #include <epan/packet.h>
42 #include "packet-tcp.h"
43 #include "packet-mbtcp.h"
44
45 /* Initialize the protocol and registered fields */
46 static int proto_mbtcp = -1;
47 static int proto_modbus = -1;
48 static int hf_mbtcp_transid = -1;
49 static int hf_mbtcp_protid = -1;
50 static int hf_mbtcp_len = -1;
51 static int hf_mbtcp_unitid = -1;
52 static int hf_mbtcp_functioncode = -1;
53 static int hf_modbus_reference = -1;
54 static int hf_modbus_lreference = -1;
55 static int hf_modbus_reftype = -1;
56 static int hf_modbus_readref = -1;
57 static int hf_modbus_writeref = -1;
58 static int hf_modbus_wordcnt = -1;
59 static int hf_modbus_readwordcnt = -1;
60 static int hf_modbus_writewordcnt = -1;
61 static int hf_modbus_bytecnt = -1;
62 static int hf_modbus_lbytecnt = -1;
63 static int hf_modbus_bitcnt = -1;
64 static int hf_modbus_exceptioncode = -1;
65 static int hf_modbus_diag_sf = -1;
66 static int hf_modbus_status = -1;
67 static int hf_modbus_event_count = -1;
68 static int hf_modbus_message_count = -1;
69 static int hf_modbus_event_recv_comm_err = -1;
70 static int hf_modbus_event_recv_char_over = -1;
71 static int hf_modbus_event_recv_lo_mode = -1;
72 static int hf_modbus_event_recv_broadcast = -1;
73 static int hf_modbus_event_send_read_ex = -1;
74 static int hf_modbus_event_send_slave_abort_ex = -1;
75 static int hf_modbus_event_send_slave_busy_ex = -1;
76 static int hf_modbus_event_send_slave_nak_ex = -1;
77 static int hf_modbus_event_send_write_timeout = -1;
78 static int hf_modbus_event_send_lo_mode = -1;
79 static int hf_modbus_andmask = -1;
80 static int hf_modbus_ormask = -1;
81 static int hf_modbus_data = -1;
82 static int hf_modbus_mei = -1;
83 static int hf_modbus_read_device_id = -1;
84 static int hf_modbus_object_id = -1;
85 static int hf_modbus_num_objects = -1;
86 static int hf_modbus_list_object_len = -1;
87 static int hf_modbus_conformity_level = -1;
88 static int hf_modbus_more_follows = -1;
89 static int hf_modbus_next_object_id = -1;
90 static int hf_modbus_object_str_value = -1;
91
92 /* Initialize the subtree pointers */
93 static gint ett_mbtcp = -1;
94 static gint ett_modbus_hdr = -1;
95 static gint ett_group_hdr = -1;
96 static gint ett_events = -1;
97 static gint ett_events_recv = -1;
98 static gint ett_events_send = -1;
99 static gint ett_device_id_objects = -1;
100 static gint ett_device_id_object_items = -1;
101
102 static dissector_table_t   mbtcp_dissector_table;
103 static dissector_table_t   modbus_dissector_table;
104 static dissector_handle_t  modbus_handle;
105
106 static gboolean mbtcp_desegment = TRUE;
107
108 static int
109 classify_packet(packet_info *pinfo)
110 {
111     /* see if nature of packets can be derived from src/dst ports */
112     /* if so, return as found */
113     if (( pinfo->srcport == PORT_MBTCP ) && ( pinfo->destport != PORT_MBTCP ))
114         return RESPONSE_PACKET;
115     if (( pinfo->srcport != PORT_MBTCP ) && ( pinfo->destport == PORT_MBTCP ))
116         return QUERY_PACKET;
117
118     /* else, cannot classify */
119     return CANNOT_CLASSIFY;
120 }
121
122 /* Translate function to string, as given on p6 of
123  * "Open Modbus/TCP Specification", release 1 by Andy Swales.
124  */
125 static const value_string function_code_vals[] = {
126     { READ_COILS,             "Read coils" },
127     { READ_INPUT_DISCRETES,   "Read input discretes" },
128     { READ_MULT_REGS,         "Read multiple registers" },
129     { READ_INPUT_REGS,        "Read input registers" },
130     { WRITE_COIL,             "Write coil" },
131     { WRITE_SINGLE_REG,       "Write single register" },
132     { READ_EXCEPT_STAT,       "Read exception status" },
133     { DIAGNOSTICS,            "Diagnostics" },
134     { GET_COMM_EVENT_CTRS,    "Get Comm. Event Counters" },
135     { GET_COMM_EVENT_LOG,     "Get Comm. Event Log" },
136     { WRITE_MULT_COILS,       "Write Multiple Coils" },
137     { WRITE_MULT_REGS,        "Write Multiple Registers" },
138     { REPORT_SLAVE_ID,        "Report Slave ID" },
139     { READ_FILE_RECORD,       "Read File Record" },
140     { WRITE_FILE_RECORD,      "Write File Record" },
141     { MASK_WRITE_REG,         "Mask Write Register" },
142     { READ_WRITE_REG,         "Read Write Register" },
143     { READ_FIFO_QUEUE,        "Read FIFO Queue" },
144     { ENCAP_INTERFACE_TRANSP, "Encapsulated Interface Transport" },
145     { 0,                      NULL }
146 };
147
148 /* Translate exception code to string */
149 static const value_string exception_code_vals[] = {
150     { ILLEGAL_FUNCTION,    "Illegal function" },
151     { ILLEGAL_ADDRESS,     "Illegal data address" },
152     { ILLEGAL_VALUE,       "Illegal data value" },
153     { SLAVE_FAILURE,       "Slave device failure" },
154     { ACKNOWLEDGE,         "Acknowledge" },
155     { SLAVE_BUSY,          "Slave device busy" },
156     { MEMORY_ERR,          "Memory parity error" },
157     { GATEWAY_UNAVAILABLE, "Gateway path unavailable" },
158     { GATEWAY_TRGT_FAIL,   "Gateway target device failed to respond" },
159     { 0,                    NULL }
160 };
161
162 /* Translate Modbus Encapsulation Interface (MEI) code to string */
163 static const value_string encap_interface_code_vals[] = {
164     { CANOPEN_REQ_RESP, "CANopen Request/Response " },
165     { READ_DEVICE_ID,   "Read Device Identification" },
166     { 0,                NULL }
167 };
168
169 /* Translate Modbus Diagnostic subfunction code to string */
170 static const value_string diagnostic_code_vals[] = {
171     { RETURN_QUERY_DATA,                "Return Query Data" },
172     { RESTART_COMMUNICATION_OPTION,     "Restart Communications Option" },
173     { RETURN_DIAGNOSTIC_REGISTER,       "Return Diagnostic Register" },
174     { CHANGE_ASCII_INPUT_DELIMITER,     "Change ASCII Input Delimiter" },
175     { FORCE_LISTEN_ONLY_MODE,           "Force Listen Only Mode" },
176     { CLEAR_COUNTERS_AND_DIAG_REG,      "Clear Counters and Diagnostic Register" },
177     { RETURN_BUS_MESSAGE_COUNT,         "Return Bus Message Count" },
178     { RETURN_BUS_COMM_ERROR_COUNT,      "Return Bus Communication Error Count" },
179     { RETURN_BUS_EXCEPTION_ERROR_COUNT, "Return Bus Exception Error Count" },
180     { RETURN_SLAVE_MESSAGE_COUNT,       "Return Slave Message Count" },
181     { RETURN_SLAVE_NO_RESPONSE_COUNT,   "Return Slave No Response Count" },
182     { RETURN_SLAVE_NAK_COUNT,           "Return Slave NAK Count" },
183     { RETURN_SLAVE_BUSY_COUNT,          "Return Slave Busy Count" },
184     { RETURN_BUS_CHAR_OVERRUN_COUNT,    "Return Bus Character Overrun Count" },
185     { CLEAR_OVERRUN_COUNTER_AND_FLAG,   "Clear Overrun Counter and Flag" },
186     { 0,                                NULL }
187 };
188
189 /* Translate read device code to string */
190 static const value_string read_device_id_vals[] = {
191     { 1,        "Basic Device Identification" },
192     { 2,        "Regular Device Identification"  },
193     { 3,        "Extended Device Identification"  },
194     { 4,        "Specific Identification Object"  },
195
196     { 0,        NULL             }
197 };
198
199 /* Translate read device code to string */
200 static const value_string object_id_vals[] = {
201     { 0,        "VendorName" },
202     { 1,        "ProductCode" },
203     { 2,        "MajorMinorRevision"  },
204     { 3,        "VendorURL"  },
205     { 4,        "ProductName"  },
206     { 5,        "ModelName"  },
207     { 6,        "UserApplicationName"  },
208
209     { 0,        NULL             }
210 };
211
212 static const value_string conformity_level_vals[] = {
213     { 0x01,     "Basic Device Identification (stream)" },
214     { 0x02,     "Regular Device Identification (stream)"  },
215     { 0x03,     "Extended Device Identification (stream)"  },
216     { 0x81,     "Basic Device Identification (stream and individual)" },
217     { 0x82,     "Regular Device Identification (stream and individual)"  },
218     { 0x83,     "Extended Device Identification (stream and individual)"  },
219
220     { 0,        NULL             }
221 };
222
223 /* Code to actually dissect the packets */
224 static void
225 dissect_mbtcp_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
226 {
227 /* Set up structures needed to add the protocol subtree and manage it */
228     proto_item    *mi;
229     proto_tree    *mbtcp_tree;
230     int           offset, packet_type;
231     tvbuff_t      *next_tvb;
232     const char    *func_string = "";
233     const char    *pkt_type_str = "";
234     const char    *err_str = "";
235     guint16       transaction_id, protocol_id, len;
236     guint8        unit_id, function_code, exception_code, subfunction_code;
237     void          *p_save_proto_data;
238
239     /* Make entries in Protocol column on summary display */
240     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/TCP");
241     col_clear(pinfo->cinfo, COL_INFO);
242
243     transaction_id = tvb_get_ntohs(tvb, 0);
244     protocol_id = tvb_get_ntohs(tvb, 2);
245     len = tvb_get_ntohs(tvb, 4);
246
247     unit_id = tvb_get_guint8(tvb, 6);
248     function_code = tvb_get_guint8(tvb, 7) & 0x7F;
249
250     /* Make entries in Info column on summary display */
251     offset = 0;
252
253     /* Find exception - last bit set in function code */
254     if (tvb_get_guint8(tvb, 7) & 0x80) {
255         exception_code = tvb_get_guint8(tvb, offset + 8);
256     }
257     else {
258         exception_code = 0;
259     }
260
261     if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0))  {
262         func_string = val_to_str(tvb_get_guint8(tvb, offset + 8), encap_interface_code_vals, "Encapsulated Interface Transport");
263         subfunction_code = 1;
264     }
265     else if ((function_code == DIAGNOSTICS) && (exception_code == 0))  {
266         func_string = val_to_str(tvb_get_ntohs(tvb, offset + 8), diagnostic_code_vals, "Diagnostics");
267         subfunction_code = 1;
268     }
269     else {
270         func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
271         subfunction_code = 0;
272     }
273
274     /* "Request" or "Response" */
275     packet_type = classify_packet(pinfo);
276
277     if (check_col(pinfo->cinfo, COL_INFO))
278     {
279         switch ( packet_type ) {
280             case QUERY_PACKET :
281                 pkt_type_str="query";
282                 break;
283             case RESPONSE_PACKET :     
284                 pkt_type_str="response";
285                 break;
286             case CANNOT_CLASSIFY :
287                 err_str="Unable to classify as query or response.";
288                 pkt_type_str="unknown";
289                 break;
290             default :
291                 break;
292         }
293         if ( exception_code != 0 )
294             err_str="Exception returned ";
295
296         if (subfunction_code == 0) {
297             if (strlen(err_str) > 0) {
298                 col_add_fstr(pinfo->cinfo, COL_INFO,
299                       "%8s: trans: %5u; unit: %3u, func: %3u: %s. %s",
300                       pkt_type_str, transaction_id, unit_id,
301                       function_code, func_string, err_str);
302             }
303             else {
304                 col_add_fstr(pinfo->cinfo, COL_INFO,
305                       "%8s: trans: %5u; unit: %3u, func: %3u: %s",
306                       pkt_type_str, transaction_id, unit_id,
307                       function_code, func_string);
308             }
309         }
310         else {
311             if (strlen(err_str) > 0) {
312                 col_add_fstr(pinfo->cinfo, COL_INFO,
313                       "%8s: trans: %5u; unit: %3u, func: %3u/%3u: %s. %s",
314                       pkt_type_str, transaction_id, unit_id,
315                       function_code, subfunction_code, func_string, err_str);
316             }
317             else {
318                 col_add_fstr(pinfo->cinfo, COL_INFO,
319                       "%8s: trans: %5u; unit: %3u, func: %3u/%3u: %s",
320                       pkt_type_str, transaction_id, unit_id,
321                       function_code, subfunction_code, func_string);
322             }
323         }
324     }
325
326     /* if a tree exists, perform operations to add fields to it */
327     if (tree) 
328     {
329         mi = proto_tree_add_protocol_format(tree, proto_mbtcp, tvb, offset,
330                 len+6, "Modbus/TCP");
331         mbtcp_tree = proto_item_add_subtree(mi, ett_mbtcp);
332
333         /* Add items to protocol tree specific to Modbus/TCP */
334         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_transid, tvb, offset, 2, transaction_id);
335         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_protid, tvb, offset + 2, 2, protocol_id);
336         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_len, tvb, offset + 4, 2, len);
337         proto_tree_add_uint(mbtcp_tree, hf_mbtcp_unitid, tvb, offset + 6, 1, unit_id);
338
339         /* dissect the Modbus PDU */
340         next_tvb = tvb_new_subset( tvb, offset+7, len-1, len-1);
341
342         /* keep packet context */
343         p_save_proto_data = p_get_proto_data( pinfo->fd, proto_mbtcp );
344         p_remove_proto_data(pinfo->fd, proto_mbtcp);
345         p_add_proto_data(pinfo->fd, proto_mbtcp, GINT_TO_POINTER(packet_type));
346
347         /* Show the undissected payload */
348         if( tvb_length_remaining(tvb, offset) > 0 )
349             call_dissector(modbus_handle, next_tvb, pinfo, tree);
350
351         p_remove_proto_data(pinfo->fd, proto_mbtcp);
352         p_add_proto_data(pinfo->fd, proto_mbtcp, p_save_proto_data);
353     }
354 }
355
356 static guint
357 get_mbtcp_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset)
358 {
359     guint16 plen;
360
361     /*
362      * Get the length of the data from the encapsulation header.
363      */
364     plen = tvb_get_ntohs(tvb, offset + 4);
365
366     /*
367      * That length doesn't include the encapsulation header itself;
368      * add that in.
369      */
370     return plen + 6;
371 }
372
373 static int
374 dissect_mbtcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
375 {
376     /* Make sure there's at least enough data to determine its a Modbus packet */
377     if (!tvb_bytes_exist(tvb, 0, 8))
378         return 0;
379
380     /* check that it actually looks like Modbus/TCP */
381     /* protocol id == 0 */
382     if(tvb_get_ntohs(tvb, 2) != 0 ){
383         return 0;
384     }
385     /* length is at least 2 (unit_id + function_code) */
386     if(tvb_get_ntohs(tvb, 4) < 2 ){
387         return 0;
388     }
389
390     /* build up protocol tree and iterate over multiple packets */
391     tcp_dissect_pdus(tvb, pinfo, tree, mbtcp_desegment, 6,
392                      get_mbtcp_pdu_len, dissect_mbtcp_pdu);
393
394     return tvb_length(tvb);
395 }
396
397 static int
398 dissect_mbudp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
399 {
400     /* Make sure there's at least enough data to determine its a Modbus packet */
401     if (!tvb_bytes_exist(tvb, 0, 8))
402         return 0;
403
404     /* check that it actually looks like Modbus/UDP */
405     /* protocol id == 0 */
406     if(tvb_get_ntohs(tvb, 2) != 0 ){
407         return 0;
408     }
409     /* length is at least 2 (unit_id + function_code) */
410     if(tvb_get_ntohs(tvb, 4) < 2 ){
411         return 0;
412     }
413
414     /* dissect the PDU */
415     dissect_mbtcp_pdu(tvb, pinfo, tree);
416
417     return tvb_length(tvb);
418 }
419
420 /* Code to allow special handling of mbtcp data */
421 static void
422 dissect_mbtcp_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 function_code, gint payload_start, gint payload_len)
423 {
424     gint reported_len;
425     tvbuff_t *next_tvb;
426
427     reported_len = tvb_reported_length_remaining(tvb, payload_start);
428
429         if ( payload_start < 0 || ( payload_len + payload_start ) == 0 )
430                 return;
431
432         if ( payload_len != reported_len ) {
433         proto_tree_add_bytes_format(tree, hf_modbus_data, tvb, payload_start, payload_len, NULL, "Data");
434         return;
435     }
436
437     next_tvb = tvb_new_subset(tvb, payload_start, payload_len, reported_len);
438
439     switch ( function_code ) {
440         default:
441             if ( ! dissector_try_string(mbtcp_dissector_table, "data", next_tvb, pinfo, tree) )
442                 proto_tree_add_bytes_format(tree, hf_modbus_data, tvb, payload_start, payload_len, NULL, "Data");
443             break;
444     }
445 }
446
447 /* Code to actually dissect the packets */
448 static int
449 dissect_modbus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
450 {
451     proto_tree    *modbus_tree, *group_tree, *event_tree, 
452                   *event_item_tree, *device_objects_tree,
453                   *device_objects_item_tree;
454     proto_item    *mi, *mf, *me, *mei, *doe, *doie;
455     int           offset, group_offset, packet_type, temp_data;
456     const char    *func_string = "";
457     gint          payload_start, payload_len, event_index,
458                   i, byte_cnt, len, num_objects, object_index,
459                   object_len;
460     guint32       group_byte_cnt, group_word_cnt;
461     guint8        function_code, exception_code, mei_code, event_code, object_type;
462     guint16       diagnostic_code;
463     guint8        *object_str;
464
465     /* Don't need to do anything if there's no tree */
466     if (tree == NULL)
467         return tvb_length(tvb);
468
469     len = tvb_length_remaining(tvb, 0);
470     function_code = tvb_get_guint8(tvb, 0) & 0x7F;
471
472     /* Find exception - last bit set in function code */
473     if (tvb_get_guint8(tvb, 0) & 0x80 ) {
474         exception_code = tvb_get_guint8(tvb, 1);
475     }
476     else {
477         exception_code = 0;
478     }
479
480     /* "Request" or "Response" */
481     packet_type = GPOINTER_TO_INT(p_get_proto_data( pinfo->fd, proto_mbtcp ));
482
483     /* Make entries in Info column on summary display */
484     offset = 0;
485
486     /* Add items to protocol tree specific to Modbus generic */
487     mf = proto_tree_add_text(tree, tvb, offset, len, "Modbus");
488     modbus_tree = proto_item_add_subtree(mf, ett_modbus_hdr);
489     mi = proto_tree_add_uint(modbus_tree, hf_mbtcp_functioncode, tvb, offset, 1,
490                              function_code);
491
492     /** detail payload as a function of exception/function code */
493     func_string = val_to_str(function_code, function_code_vals, "Unknown function");
494
495     payload_start = offset + 1;
496     payload_len = len - 1;
497     if (exception_code != 0) {
498         proto_item_set_text(mi, "function %u:  %s.  Exception: %s",
499                             function_code,
500                             func_string,
501                             val_to_str(exception_code,
502                                        exception_code_vals,
503                                        "Unknown exception code (%u)"));
504         proto_tree_add_uint(modbus_tree, hf_modbus_exceptioncode, tvb, payload_start, 1,
505                             exception_code);
506     }
507     else {
508         proto_item_set_text(mi, "function %u:  %s", function_code,
509                             func_string);
510         switch (function_code) {
511
512             case READ_COILS:
513             case READ_INPUT_DISCRETES:
514                 if (packet_type == QUERY_PACKET) {
515                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
516                     proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
517                 }
518                 else if (packet_type == RESPONSE_PACKET) {
519                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
520                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
521                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt);
522                 }
523                 break;
524
525             case READ_MULT_REGS:
526             case READ_INPUT_REGS:
527                 if (packet_type == QUERY_PACKET) {
528                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
529                     proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
530                 }
531                 else if (packet_type == RESPONSE_PACKET) {
532                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
533                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
534                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt);
535                 }
536                 break;
537
538             case WRITE_COIL:
539                 if (packet_type == QUERY_PACKET) {
540                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
541                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1);
542                     proto_tree_add_text(modbus_tree, tvb, payload_start + 3, 1, "Padding");
543                 }
544                 else if (packet_type == RESPONSE_PACKET) {
545                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
546                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1);
547                     proto_tree_add_text(modbus_tree, tvb, payload_start + 3, 1, "Padding");
548                 }
549                 break;
550
551             case WRITE_SINGLE_REG:
552                 if (packet_type == QUERY_PACKET) {
553                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
554                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2);
555                 }
556                 else if (packet_type == RESPONSE_PACKET) {
557                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
558                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2);
559                 }
560                 break;
561
562             case READ_EXCEPT_STAT:
563                 if (packet_type == RESPONSE_PACKET)
564                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start, 1);
565                 break;
566
567             case DIAGNOSTICS:
568                 if ((packet_type == QUERY_PACKET) || (packet_type == RESPONSE_PACKET)) {
569                     diagnostic_code = tvb_get_ntohs(tvb, payload_start);
570                     proto_tree_add_uint(modbus_tree, hf_modbus_diag_sf, tvb, payload_start, 2, diagnostic_code);
571                     switch(diagnostic_code)
572                     {
573                         case RETURN_QUERY_DATA:
574                             if (packet_type == QUERY_PACKET) {
575                                 if (payload_len > 2)
576                                     proto_tree_add_text(modbus_tree, tvb, payload_start+2, payload_len-2, "Request Data");
577                             }
578                             else if (packet_type == RESPONSE_PACKET) {
579                                 if (payload_len > 2)
580                                     proto_tree_add_text(modbus_tree, tvb, payload_start+2, payload_len-2, "Echo Data");
581                             }
582                             break;
583                         case RESTART_COMMUNICATION_OPTION:
584                             temp_data = tvb_get_ntohs(tvb, payload_start+2);
585                             if (temp_data == 0) {
586                                 proto_tree_add_text(modbus_tree, tvb, payload_start+2, 2, "Leave Log");
587                             }
588                             else if (temp_data == 0xFF) {
589                                 proto_tree_add_text(modbus_tree, tvb, payload_start+2, 2, "Clear Log");
590                             }
591                             else {
592                                 proto_tree_add_text(modbus_tree, tvb, payload_start+2, 2, "Unknown");
593                             }
594                             break;
595                         case RETURN_DIAGNOSTIC_REGISTER:
596                             if (packet_type == QUERY_PACKET) {
597                                 if (payload_len > 2)
598                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
599                             }
600                             else if (packet_type == RESPONSE_PACKET) {
601                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
602                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Diagnostic Register Contents 0x%04x", temp_data );
603                             }
604                             break;
605                         case CHANGE_ASCII_INPUT_DELIMITER:
606                             temp_data = tvb_get_guint8(tvb, payload_start+2);
607                             proto_tree_add_text( modbus_tree, tvb, payload_start+2, 1, "CHAR 0x%02x", temp_data );
608                             break;
609                         case RETURN_BUS_MESSAGE_COUNT:
610                             if (packet_type == QUERY_PACKET) {
611                                 if (payload_len > 2)
612                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
613                             }
614                             else if (packet_type == RESPONSE_PACKET) {
615                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
616                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Total Message Count %d", temp_data );
617                             }
618                             break;
619                         case RETURN_BUS_COMM_ERROR_COUNT:
620                             if (packet_type == QUERY_PACKET) {
621                                 if (payload_len > 2)
622                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
623                             }
624                             else if (packet_type == RESPONSE_PACKET) {
625                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
626                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "CRC Error Count %d", temp_data );
627                             }
628                             break;
629                         case RETURN_BUS_EXCEPTION_ERROR_COUNT:
630                             if (packet_type == QUERY_PACKET) {
631                                 if (payload_len > 2)
632                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
633                             }
634                             else if (packet_type == RESPONSE_PACKET) {
635                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
636                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Exception Error Count %d", temp_data );
637                             }
638                             break;
639                         case RETURN_SLAVE_MESSAGE_COUNT:
640                             if (packet_type == QUERY_PACKET) {
641                                 if (payload_len > 2)
642                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
643                             }
644                             else if (packet_type == RESPONSE_PACKET) {
645                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
646                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Slave Message Count %d", temp_data );
647                             }
648                             break;
649                         case RETURN_SLAVE_NO_RESPONSE_COUNT:
650                             if (packet_type == QUERY_PACKET) {
651                                 if (payload_len > 2)
652                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
653                             }
654                             else if (packet_type == RESPONSE_PACKET) {
655                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
656                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Slave No Response Count %d", temp_data );
657                             }
658                             break;
659                         case RETURN_SLAVE_NAK_COUNT:
660                             if (packet_type == QUERY_PACKET) {
661                                 if (payload_len > 2)
662                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
663                             }
664                             else if (packet_type == RESPONSE_PACKET) {
665                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
666                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Slave NAK Count %d", temp_data );
667                             }
668                             break;
669                         case RETURN_SLAVE_BUSY_COUNT:
670                             if (packet_type == QUERY_PACKET) {
671                                 if (payload_len > 2)
672                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
673                             }
674                             else if (packet_type == RESPONSE_PACKET) {
675                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
676                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Slave Device Busy Count %d", temp_data );
677                             }
678                             break;
679                         case RETURN_BUS_CHAR_OVERRUN_COUNT:
680                             if (packet_type == QUERY_PACKET) {
681                                 if (payload_len > 2)
682                                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
683                             }
684                             else if (packet_type == RESPONSE_PACKET) {
685                                 temp_data = tvb_get_ntohs(tvb, payload_start+2);
686                                 proto_tree_add_text( modbus_tree, tvb, payload_start+2, 2, "Slave Character Overrun Count %d", temp_data );
687                             }
688                             break;
689                         case CLEAR_OVERRUN_COUNTER_AND_FLAG:
690                         case FORCE_LISTEN_ONLY_MODE:
691                         case CLEAR_COUNTERS_AND_DIAG_REG:
692                         default:
693                             if (payload_len > 2)
694                                 dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2);
695                             break;
696                     }
697                 }
698                 break;
699
700             case GET_COMM_EVENT_CTRS:
701                 if (packet_type == RESPONSE_PACKET) {
702                     proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start, 2, ENC_BIG_ENDIAN);
703                     proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
704                 }
705                 break;
706
707             case GET_COMM_EVENT_LOG:
708                 if (packet_type == RESPONSE_PACKET) {
709                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
710                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
711                     proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start+1, 2, ENC_BIG_ENDIAN);
712                     proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+3, 2, ENC_BIG_ENDIAN);
713                     proto_tree_add_item(modbus_tree, hf_modbus_message_count, tvb, payload_start+5, 2, ENC_BIG_ENDIAN);
714                     if (byte_cnt-6 > 0) {
715                         byte_cnt -= 6;
716                         event_index = 0;
717                         me = proto_tree_add_text(modbus_tree, tvb, payload_start+7, byte_cnt, "Events");
718                         event_tree = proto_item_add_subtree(me, ett_events);
719                         while (byte_cnt > 0) {
720                             event_code = tvb_get_guint8(tvb, payload_start+7+event_index);
721                             if (event_code == 0) {
722                                 proto_tree_add_text(event_tree, tvb, payload_start+7+event_index, 1, "Initiated Communication Restart");
723                             }
724                             else if (event_code == 4) {
725                                 proto_tree_add_text(event_tree, tvb, payload_start+7+event_index, 1, "Entered Listen Only Mode");
726                             }
727                             else if (event_code & REMOTE_DEVICE_RECV_EVENT_MASK) {
728                                 mei = proto_tree_add_text(event_tree, tvb, payload_start+7+event_index, 1, "Receive Event: 0x%02X", event_code);
729                                 event_item_tree = proto_item_add_subtree(mei, ett_events_recv);
730
731                                 /* add subtrees to describe each event bit */
732                                 proto_tree_add_item(event_item_tree, hf_modbus_event_recv_comm_err,
733                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
734                                 proto_tree_add_item(event_item_tree, hf_modbus_event_recv_char_over,
735                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
736                                 proto_tree_add_item(event_item_tree, hf_modbus_event_recv_lo_mode,
737                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
738                                 proto_tree_add_item(event_item_tree, hf_modbus_event_recv_broadcast,
739                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
740                             }
741                             else if ((event_code & REMOTE_DEVICE_SEND_EVENT_MASK) == REMOTE_DEVICE_SEND_EVENT_VALUE) {
742                                 mei = proto_tree_add_text(event_tree, tvb, payload_start+7+event_index, 1, "Send Event: 0x%02X", event_code);
743                                 event_item_tree = proto_item_add_subtree(mei, ett_events_send);
744
745                                 /* add subtrees to describe each event bit */
746                                 proto_tree_add_item(event_item_tree, hf_modbus_event_send_read_ex,
747                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
748                                 proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_abort_ex,
749                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
750                                 proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_busy_ex,
751                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
752                                 proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_nak_ex,
753                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
754                                 proto_tree_add_item(event_item_tree, hf_modbus_event_send_write_timeout,
755                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
756                                 proto_tree_add_item(event_item_tree, hf_modbus_event_send_lo_mode,
757                                   tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
758                             }
759                             else {
760                                 proto_tree_add_text(event_tree, tvb, payload_start+7+event_index, 1, "Unknown Event");
761                             }
762
763                             byte_cnt--;
764                             event_index++;
765                         }
766                     }
767                 }
768                 break;
769
770             case WRITE_MULT_COILS:
771                 if (packet_type == QUERY_PACKET) {
772                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
773                     proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
774                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
775                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1,
776                             byte_cnt);
777                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt);
778                 }
779                 else if (packet_type == RESPONSE_PACKET) {
780                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
781                     proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
782                 }
783                 break;
784
785             case WRITE_MULT_REGS:
786                 if (packet_type == QUERY_PACKET) {
787                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
788                     proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
789                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
790                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1,
791                             byte_cnt);
792                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt);
793                 }
794                 else if (packet_type == RESPONSE_PACKET) {
795                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
796                     proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
797                 }
798                 break;
799
800             case READ_FILE_RECORD:
801                 if (packet_type == QUERY_PACKET) {
802                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
803                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
804                             byte_cnt);
805
806                     /* add subtrees to describe each group of packet */
807                     group_offset = payload_start + 1;
808                     for (i = 0; i < byte_cnt / 7; i++) {
809                         mi = proto_tree_add_text( modbus_tree, tvb, group_offset, 7,
810                                 "Group %u", i);
811                         group_tree = proto_item_add_subtree(mi, ett_group_hdr);
812                         proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
813                         proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
814                         proto_tree_add_item(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, ENC_BIG_ENDIAN);
815                         group_offset += 7;
816                     }
817                 }
818                 else if (packet_type == RESPONSE_PACKET) {
819                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
820                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
821                             byte_cnt);
822
823                     /* add subtrees to describe each group of packet */
824                     group_offset = payload_start + 1;
825                     i = 0;
826                     while (byte_cnt > 0) {
827                         group_byte_cnt = (guint32)tvb_get_guint8(tvb, group_offset);
828                         mi = proto_tree_add_text( modbus_tree, tvb, group_offset, group_byte_cnt + 1,
829                                 "Group %u", i);
830                         group_tree = proto_item_add_subtree(mi, ett_group_hdr);
831                         proto_tree_add_uint(group_tree, hf_modbus_bytecnt, tvb, group_offset, 1,
832                                 group_byte_cnt);
833                         proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset + 1, 1, ENC_BIG_ENDIAN);
834                         dissect_mbtcp_data(tvb, pinfo, group_tree, function_code, group_offset + 2, group_byte_cnt - 1);
835                         group_offset += (group_byte_cnt + 1);
836                         byte_cnt -= (group_byte_cnt + 1);
837                         i++;
838                     }
839                 }
840                 break;
841
842             case WRITE_FILE_RECORD:
843                 if ((packet_type == QUERY_PACKET) || (packet_type == RESPONSE_PACKET)) {
844                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
845                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
846                             byte_cnt);
847
848                     /* add subtrees to describe each group of packet */
849                     group_offset = payload_start + 1;
850                     i = 0;
851                     while (byte_cnt > 0) {
852                         group_word_cnt = tvb_get_ntohs(tvb, group_offset + 5);
853                         group_byte_cnt = (2 * group_word_cnt) + 7;
854                         mi = proto_tree_add_text( modbus_tree, tvb, group_offset,
855                                 group_byte_cnt, "Group %u", i);
856                         group_tree = proto_item_add_subtree(mi, ett_group_hdr);
857                         proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
858                         proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
859                         proto_tree_add_uint(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2,
860                                 group_word_cnt);
861                         dissect_mbtcp_data(tvb, pinfo, group_tree, function_code, group_offset + 7, group_byte_cnt - 7);
862                         group_offset += group_byte_cnt;
863                         byte_cnt -= group_byte_cnt;
864                         i++;
865                     }
866                 }
867                 break;
868
869             case MASK_WRITE_REG:
870                 if ((packet_type == QUERY_PACKET) || (packet_type == RESPONSE_PACKET)) {
871                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
872                     proto_tree_add_item(modbus_tree, hf_modbus_andmask, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
873                     proto_tree_add_item(modbus_tree, hf_modbus_ormask, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
874                 }
875                 break;
876
877             case READ_WRITE_REG:
878                 if (packet_type == QUERY_PACKET) {
879                     proto_tree_add_item(modbus_tree, hf_modbus_readref, tvb, payload_start, 2, ENC_BIG_ENDIAN);
880                     proto_tree_add_item(modbus_tree, hf_modbus_readwordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
881                     proto_tree_add_item(modbus_tree, hf_modbus_writeref, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
882                     proto_tree_add_item(modbus_tree, hf_modbus_writewordcnt, tvb, payload_start + 6, 2, ENC_BIG_ENDIAN);
883                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 8);
884                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 8, 1,
885                             byte_cnt);
886                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 9, byte_cnt);
887                 }
888                 else if (packet_type == RESPONSE_PACKET) {
889                     byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
890                     proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
891                             byte_cnt);
892                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt);
893                 }
894                 break;
895
896             case READ_FIFO_QUEUE:
897                 if (packet_type == QUERY_PACKET)
898                     proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
899                 else if (packet_type == RESPONSE_PACKET) {
900                     byte_cnt = (guint32)tvb_get_ntohs(tvb, payload_start);
901                     proto_tree_add_uint(modbus_tree, hf_modbus_lbytecnt, tvb, payload_start, 2,
902                             byte_cnt);
903                     proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
904                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start + 4, byte_cnt - 2);
905                 }
906                 break;
907
908             case ENCAP_INTERFACE_TRANSP:
909                 if (packet_type == QUERY_PACKET) {
910                     proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
911                     mei_code = tvb_get_guint8(tvb, payload_start);
912                     switch (mei_code)
913                     {
914                         case READ_DEVICE_ID:
915                             proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
916                             proto_tree_add_item(modbus_tree, hf_modbus_object_id, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
917                             break;
918
919                         case CANOPEN_REQ_RESP:
920                             /* CANopen protocol not part of the Modbus/TCP specification */
921                         default:
922                             if (payload_len > 1)
923                                 dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1);
924                                 break;
925                     }
926                 }
927                 else if (packet_type == RESPONSE_PACKET) {
928                     proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
929                     mei_code = tvb_get_guint8(tvb, payload_start);
930                     switch (mei_code)
931                     {
932                         case READ_DEVICE_ID:
933                             proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
934                             proto_tree_add_item(modbus_tree, hf_modbus_conformity_level, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
935                             proto_tree_add_item(modbus_tree, hf_modbus_more_follows, tvb, payload_start+3, 1, ENC_BIG_ENDIAN);
936                             proto_tree_add_item(modbus_tree, hf_modbus_next_object_id, tvb, payload_start+4, 1, ENC_BIG_ENDIAN);
937                             num_objects = tvb_get_guint8(tvb, payload_start+5);
938                             proto_tree_add_uint(modbus_tree, hf_modbus_num_objects, tvb, payload_start+5, 1, num_objects);
939                             doe = proto_tree_add_text(modbus_tree, tvb, payload_start+6, payload_len-6, "Objects");
940
941                             object_index = 0;
942                             for (i = 1; i <= num_objects; i++)
943                             {
944                                 device_objects_tree = proto_item_add_subtree(doe, ett_device_id_objects);
945                      
946                                 /* add each "object item" as its own subtree */
947
948                                 /* compute length of object */
949                                 object_type = tvb_get_guint8(tvb, payload_start+6+object_index);
950                                 object_len = tvb_get_guint8(tvb, payload_start+6+object_index+1);
951
952                                 doie = proto_tree_add_text(device_objects_tree, tvb, payload_start+6+object_index, 2+object_len, "Object #%d", i);
953                                 device_objects_item_tree = proto_item_add_subtree(doie, ett_device_id_object_items);
954
955                                 proto_tree_add_item(device_objects_item_tree, hf_modbus_object_id, tvb, payload_start+6+object_index, 1, ENC_BIG_ENDIAN);
956                                 object_index++;
957
958                                 proto_tree_add_uint(device_objects_item_tree, hf_modbus_list_object_len, tvb, payload_start+6+object_index, 1, object_len);
959                                 object_index++;
960
961                                 if (object_type < 7)
962                                 {
963                                     object_str = tvb_get_string(tvb, payload_start+6+object_index, object_len);
964                                     proto_tree_add_string(device_objects_item_tree, hf_modbus_object_str_value, tvb, payload_start+6+object_index, object_len, object_str);
965                                     g_free(object_str);
966                                 }
967                                 else
968                                 {
969                                     if (object_len > 0)
970                                         proto_tree_add_text(device_objects_item_tree, tvb, payload_start+6+object_index, object_len, "Object Value");
971                                 }
972                                 object_index += object_len;
973                             }
974                             break;
975
976                         case CANOPEN_REQ_RESP:
977                             /* CANopen protocol not part of the Modbus/TCP specification */
978                         default:
979                             if (payload_len > 1)
980                                 dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1);
981                                 break;
982                     }
983                 }
984                 break;
985
986             case REPORT_SLAVE_ID:
987             default:
988                 if (payload_len > 0)
989                     dissect_mbtcp_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len);
990                 break;
991         }
992     }
993
994     return tvb_length(tvb);
995 }
996
997
998 /* Register the protocol with Wireshark */
999
1000 void
1001 proto_register_modbus(void)
1002 {
1003
1004 /* Setup list of header fields  See Section 1.6.1 for details*/
1005     static hf_register_info hf[] = {
1006         /* Modbus/TCP header fields */
1007         { &hf_mbtcp_transid,
1008             { "transaction identifier",            "mbtcp.trans_id",
1009             FT_UINT16, BASE_DEC, NULL, 0x0,
1010             NULL, HFILL }
1011         },
1012         { &hf_mbtcp_protid,
1013             { "protocol identifier",            "mbtcp.prot_id",
1014             FT_UINT16, BASE_DEC, NULL, 0x0,
1015             NULL, HFILL }
1016         },
1017         { &hf_mbtcp_len,
1018             { "length",                    "mbtcp.len",
1019             FT_UINT16, BASE_DEC, NULL, 0x0,
1020             NULL, HFILL }
1021         },
1022         /* Modbus header fields */
1023         { &hf_mbtcp_unitid,
1024             { "unit identifier",                "mbtcp.modbus.unit_id",
1025             FT_UINT8, BASE_DEC, NULL, 0x0,
1026             NULL, HFILL }
1027         },
1028         { &hf_mbtcp_functioncode,
1029             { "function code",                "mbtcp.modbus.func_code",
1030             FT_UINT8, BASE_DEC, VALS(function_code_vals), 0x0,
1031             NULL, HFILL }
1032         },
1033         { &hf_modbus_reference,
1034             { "reference number",                "mbtcp.modbus.reference_num",
1035             FT_UINT16, BASE_DEC, NULL, 0x0,
1036             NULL, HFILL }
1037         },
1038         { &hf_modbus_lreference,
1039             { "reference number (32 bit)",            "mbtcp.modbus.reference_num_32",
1040             FT_UINT32, BASE_DEC, NULL, 0x0,
1041             NULL, HFILL }
1042         },
1043         { &hf_modbus_reftype,
1044             { "reference type",                "mbtcp.modbus.reference_type",
1045             FT_UINT8, BASE_DEC, NULL, 0x0,
1046             NULL, HFILL }
1047         },
1048         { &hf_modbus_readref,
1049             { "read reference number",            "mbtcp.modbus.read_reference_num",
1050             FT_UINT16, BASE_DEC, NULL, 0x0,
1051             NULL, HFILL }
1052         },
1053         { &hf_modbus_writeref,
1054             { "write reference number",            "mbtcp.modbus.write_reference_num",
1055             FT_UINT16, BASE_DEC, NULL, 0x0,
1056             NULL, HFILL }
1057         },
1058         { &hf_modbus_wordcnt,
1059             { "word count",                    "mbtcp.modbus.word_cnt",
1060             FT_UINT16, BASE_DEC, NULL, 0x0,
1061             NULL, HFILL }
1062         },
1063         { &hf_modbus_readwordcnt,
1064             { "read word count",                "mbtcp.modbus.read_word_cnt",
1065             FT_UINT16, BASE_DEC, NULL, 0x0,
1066             NULL, HFILL }
1067         },
1068         { &hf_modbus_writewordcnt,
1069             { "write word count",                "mbtcp.modbus.write_word_cnt",
1070             FT_UINT16, BASE_DEC, NULL, 0x0,
1071             NULL, HFILL }
1072         },
1073         { &hf_modbus_bitcnt,
1074             { "bit count",                    "mbtcp.modbus.bit_cnt",
1075             FT_UINT16, BASE_DEC, NULL, 0x0,
1076             NULL, HFILL }
1077         },
1078         { &hf_modbus_bytecnt,
1079             { "byte count",                    "mbtcp.modbus.byte_cnt",
1080             FT_UINT8, BASE_DEC, NULL, 0x0,
1081             NULL, HFILL }
1082         },
1083         { &hf_modbus_lbytecnt,
1084             { "byte count (16-bit)",            "mbtcp.modbus.byte_cnt_16",
1085             FT_UINT8, BASE_DEC, NULL, 0x0,
1086             NULL, HFILL }
1087         },
1088         { &hf_modbus_exceptioncode,
1089             { "exception code",                "mbtcp.modbus.exception_code",
1090             FT_UINT8, BASE_DEC, VALS(exception_code_vals), 0x0,
1091             NULL, HFILL }
1092         },
1093         { &hf_modbus_diag_sf,
1094             { "diagnostic code",                    "mbtcp.modbus.diagnostic_code",
1095             FT_UINT16, BASE_DEC, VALS(diagnostic_code_vals), 0x0,
1096             NULL, HFILL }
1097         },
1098         { &hf_modbus_status,
1099             { "status",                             "mbtcp.modbus.ev_status",
1100             FT_UINT16, BASE_HEX, NULL, 0x0,
1101             NULL, HFILL }
1102         },
1103         { &hf_modbus_event_count,
1104             { "event count",                    "mbtcp.modbus.ev_count",
1105             FT_UINT16, BASE_DEC, NULL, 0x0,
1106             NULL, HFILL }
1107         },
1108         { &hf_modbus_message_count,
1109             { "message count",               "mbtcp.modbus.ev_msg_count",
1110             FT_UINT16, BASE_DEC, NULL, 0x0,
1111             NULL, HFILL }
1112         },
1113         { &hf_modbus_event_recv_comm_err,
1114             { "Communication Error",               "mbtcp.modbus.ev_recv_comm_err",
1115             FT_UINT8, BASE_DEC, NULL, 0x02,
1116             NULL, HFILL }
1117         },
1118         { &hf_modbus_event_recv_char_over,
1119             { "Character Overrun",               "mbtcp.modbus.ev_recv_char_over",
1120             FT_UINT8, BASE_DEC, NULL, 0x10,
1121             NULL, HFILL }
1122         },
1123         { &hf_modbus_event_recv_lo_mode,
1124             { "Currently in Listen Only Mode",   "mbtcp.modbus.ev_recv_lo_mode",
1125             FT_UINT8, BASE_DEC, NULL, 0x20,
1126             NULL, HFILL }
1127         },
1128         { &hf_modbus_event_recv_broadcast,
1129             { "Broadcast Received",               "mbtcp.modbus.ev_recv_broadcast",
1130             FT_UINT8, BASE_DEC, NULL, 0x40,
1131             NULL, HFILL }
1132         },
1133         { &hf_modbus_event_send_read_ex,
1134             { "Read Exception Sent",               "mbtcp.modbus.ev_send_read_ex",
1135             FT_UINT8, BASE_DEC, NULL, 0x01,
1136             NULL, HFILL }
1137         },
1138         { &hf_modbus_event_send_slave_abort_ex,
1139             { "Slave Abort Exception Sent",               "mbtcp.modbus.ev_send_slave_abort_ex",
1140             FT_UINT8, BASE_DEC, NULL, 0x02,
1141             NULL, HFILL }
1142         },
1143         { &hf_modbus_event_send_slave_busy_ex,
1144             { "Slave Busy Exception Sent",               "mbtcp.modbus.ev_send_slave_busy_ex",
1145             FT_UINT8, BASE_DEC, NULL, 0x04,
1146             NULL, HFILL }
1147         },
1148         { &hf_modbus_event_send_slave_nak_ex,
1149             { "Slave Program NAK Exception Sent",               "mbtcp.modbus.ev_send_slave_nak_ex",
1150             FT_UINT8, BASE_DEC, NULL, 0x08,
1151             NULL, HFILL }
1152         },
1153         { &hf_modbus_event_send_write_timeout,
1154             { "Write Timeout Error Occurred",               "mbtcp.modbus.ev_send_write_timeout",
1155             FT_UINT8, BASE_DEC, NULL, 0x10,
1156             NULL, HFILL }
1157         },
1158         { &hf_modbus_event_send_lo_mode,
1159             { "Currently in Listen Only Mode",               "mbtcp.modbus.ev_send_lo_mode",
1160             FT_UINT8, BASE_DEC, NULL, 0x20,
1161             NULL, HFILL }
1162         },
1163         { &hf_modbus_andmask,
1164             { "AND mask",                    "mbtcp.modbus.and_mask",
1165             FT_UINT16, BASE_HEX, NULL, 0x0,
1166             NULL, HFILL }
1167         },
1168         { &hf_modbus_ormask,
1169             { "OR mask",                    "mbtcp.modbus.or_mask",
1170             FT_UINT16, BASE_HEX, NULL, 0x0,
1171             NULL, HFILL }
1172         },
1173         { &hf_modbus_data,
1174             { "Data",                        "mbtcp.modbus.data",
1175             FT_BYTES,  BASE_NONE, NULL,    0x0, NULL, HFILL }
1176         },
1177         { &hf_modbus_mei,
1178             { "MEI type",                        "mbtcp.modbus.mei",
1179             FT_UINT8, BASE_DEC, VALS(encap_interface_code_vals), 0x0,
1180             NULL, HFILL }
1181         },
1182         { &hf_modbus_read_device_id,
1183             { "Read Device ID",                "mbtcp.modbus.read_device_id",
1184             FT_UINT8, BASE_DEC, VALS(read_device_id_vals), 0x0,
1185             NULL, HFILL }
1186         },
1187         { &hf_modbus_object_id,
1188             { "Object ID",                        "mbtcp.modbus.object_id",
1189             FT_UINT8, BASE_DEC, VALS(object_id_vals), 0x0,
1190             NULL, HFILL }
1191         },
1192         { &hf_modbus_num_objects,
1193             { "Number of Objects",                        "mbtcp.modbus.num_objects",
1194             FT_UINT8, BASE_DEC, NULL, 0x0,
1195             NULL, HFILL }
1196         },
1197         { &hf_modbus_list_object_len,
1198             { "Object length",                        "mbtcp.modbus.objects_len",
1199             FT_UINT8, BASE_DEC, NULL, 0x0,
1200             NULL, HFILL }
1201         },
1202         { &hf_modbus_conformity_level,
1203             { "Conformity Level",                        "mbtcp.modbus.conformity_level",
1204             FT_UINT8, BASE_HEX, VALS(conformity_level_vals), 0x0,
1205             NULL, HFILL }
1206         },
1207         { &hf_modbus_more_follows,
1208             { "More Follows",                        "mbtcp.modbus.more_follows",
1209             FT_UINT8, BASE_HEX, NULL, 0x0,
1210             NULL, HFILL }
1211         },
1212         { &hf_modbus_next_object_id,
1213             { "Next Object ID",                        "mbtcp.modbus.next_object_id",
1214             FT_UINT8, BASE_DEC, NULL, 0x0,
1215             NULL, HFILL }
1216         },
1217         { &hf_modbus_object_str_value,
1218             { "Object String Value",                        "mbtcp.modbus.object_str_value",
1219             FT_STRING, BASE_NONE, NULL, 0x0,
1220             NULL, HFILL }
1221         }
1222     };
1223
1224     /* Setup protocol subtree array */
1225     static gint *ett[] = {
1226         &ett_mbtcp,
1227         &ett_modbus_hdr,
1228         &ett_group_hdr,
1229         &ett_events,
1230         &ett_events_recv,
1231         &ett_events_send,
1232         &ett_device_id_objects,
1233         &ett_device_id_object_items
1234     };
1235
1236     /* Register the protocol name and description */
1237     proto_mbtcp = proto_register_protocol("Modbus/TCP", "Modbus/TCP", "mbtcp");
1238     proto_modbus = proto_register_protocol("Modbus", "Modbus", "modbus");
1239
1240     /* Registering protocol to be called by another dissector */
1241     new_register_dissector("mbtcp", dissect_mbtcp, proto_mbtcp);
1242     new_register_dissector("modbus", dissect_modbus, proto_modbus);
1243
1244     /* Registering subdissectors table */
1245     mbtcp_dissector_table = register_dissector_table("mbtcp.modbus.data", "Modbus/TCP Data", FT_STRING, BASE_NONE);
1246     modbus_dissector_table = register_dissector_table("mbtcp.prot_id", "protocol identifier", FT_UINT16, BASE_DEC);
1247
1248     /* Required function calls to register the header fields and subtrees used */
1249     proto_register_field_array(proto_mbtcp, hf, array_length(hf));
1250     proto_register_subtree_array(ett, array_length(ett));
1251 }
1252
1253
1254 /* If this dissector uses sub-dissector registration add a registration routine.
1255    This format is required because a script is used to find these routines and
1256    create the code that calls these routines.
1257  */
1258 void
1259 proto_reg_handoff_mbtcp(void)
1260 {
1261     dissector_handle_t mbtcp_handle, mbudp_handle;
1262
1263     mbtcp_handle = new_create_dissector_handle(dissect_mbtcp, proto_mbtcp);
1264     dissector_add_uint("tcp.port", PORT_MBTCP, mbtcp_handle);
1265
1266     mbudp_handle = new_create_dissector_handle(dissect_mbudp, proto_mbtcp);
1267     dissector_add_uint("udp.port", PORT_MBTCP, mbudp_handle);
1268
1269     modbus_handle = new_create_dissector_handle(dissect_modbus, proto_modbus);
1270     dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
1271 }