Add prefs_get_uint_value and prefs_get_range_value
[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 http://www.modbus.org/ for information on Modbus/TCP.
8  *
9  * Updated to v1.1b of the Modbus Application Protocol specification
10  *   Michael Mann * Copyright 2011
11  *
12  *****************************************************************************************************
13  * A brief explanation of the distinction between Modbus/TCP and Modbus RTU over TCP:
14  *
15  * Consider a Modbus poll message: Unit 01, Scan Holding Register Address 0 for 30 Registers
16  *
17  * The Modbus/TCP message structure will follow the pattern below:
18  * 00 00 00 00 00 06 01 03 00 00 00 1E
19  * AA AA BB BB CC CC DD EE FF FF GG GG
20  *
21  * A = 16-bit Transaction Identifier (typically increments, or is locked at zero)
22  * B = 16-bit Protocol Identifier (typically zero)
23  * C = 16-bit Length of data payload following (and inclusive of) the length byte
24  * D = 8-bit Unit / Slave ID
25  * E = 8-bit Modbus Function Code
26  * F = 16-bit Reference Number / Register Base Address
27  * G = 16-bit Word Count / Number of Registers to scan
28  *
29  * A identical Modbus RTU (or Modbus RTU over TCP) message will overlay partially with the msg above
30  * and contain 16-bit CRC at the end:
31  * 00 00 00 00 00 06 01 03 00 00 00 1E -- -- (Modbus/TCP message, repeated from above)
32  * -- -- -- -- -- -- 01 03 00 00 00 1E C5 C2 (Modbus RTU over TCP message, includes 16-bit CRC footer)
33  * AA AA BB BB CC CC DD EE FF FF GG GG HH HH
34  *
35  * A = Not present in Modbus RTU message
36  * B = Not present in Modbus RTU message
37  * C = Not present in Modbus RTU message
38  * D = 8-bit Unit / Slave ID
39  * E = 8-bit Modbus Function Code
40  * F = 16-bit Reference Number / Register Base Address
41  * G = 16-bit Word Count / Number of Registers to scan
42  * H = 16-bit CRC
43  *
44  *****************************************************************************************************
45  * Wireshark - Network traffic analyzer
46  * By Gerald Combs <gerald@wireshark.org>
47  * Copyright 1998 Gerald Combs
48  *
49  * This program is free software; you can redistribute it and/or
50  * modify it under the terms of the GNU General Public License
51  * as published by the Free Software Foundation; either version 2
52  * of the License, or (at your option) any later version.
53  *
54  * This program is distributed in the hope that it will be useful,
55  * but WITHOUT ANY WARRANTY; without even the implied warranty of
56  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
57  * GNU General Public License for more details.
58  *
59  * You should have received a copy of the GNU General Public License
60  * along with this program; if not, write to the Free Software
61  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
62  */
63
64 #include "config.h"
65
66 #include <epan/packet.h>
67 #include "packet-tcp.h"
68 #include "packet-mbtcp.h"
69 #include <epan/prefs.h>
70 #include <epan/expert.h>
71 #include <epan/crc16-tvb.h> /* For CRC verification */
72 #include <epan/proto_data.h>
73
74 void proto_register_modbus(void);
75 void proto_reg_handoff_mbtcp(void);
76 void proto_reg_handoff_mbrtu(void);
77
78 /* Initialize the protocol and registered fields */
79 static int proto_mbtcp = -1;
80 static int proto_mbudp = -1;
81 static int proto_mbrtu = -1;
82 static int proto_modbus = -1;
83 static int hf_mbtcp_transid = -1;
84 static int hf_mbtcp_protid = -1;
85 static int hf_mbtcp_len = -1;
86 static int hf_mbtcp_unitid = -1;
87 static int hf_modbus_request_frame = -1;
88 static int hf_modbus_functioncode = -1;
89 static int hf_modbus_reference = -1;
90 static int hf_modbus_padding = -1;
91 static int hf_modbus_lreference = -1;
92 static int hf_modbus_reftype = -1;
93 static int hf_modbus_readref = -1;
94 static int hf_modbus_writeref = -1;
95 static int hf_modbus_wordcnt = -1;
96 static int hf_modbus_readwordcnt = -1;
97 static int hf_modbus_writewordcnt = -1;
98 static int hf_modbus_bytecnt = -1;
99 static int hf_modbus_lbytecnt = -1;
100 static int hf_modbus_bitcnt = -1;
101 static int hf_modbus_exceptioncode = -1;
102 static int hf_modbus_diag_sf = -1;
103 static int hf_modbus_diag_return_query_data_request = -1;
104 static int hf_modbus_diag_return_query_data_echo = -1;
105 static int hf_modbus_diag_restart_communication_option = -1;
106 static int hf_modbus_diag_return_diag_register = -1;
107 static int hf_modbus_diag_ascii_input_delimiter = -1;
108 static int hf_modbus_diag_clear_ctr_diag_reg = -1;
109 static int hf_modbus_diag_return_bus_message_count = -1;
110 static int hf_modbus_diag_return_bus_comm_error_count = -1;
111 static int hf_modbus_diag_return_bus_exception_error_count = -1;
112 static int hf_modbus_diag_return_slave_message_count = -1;
113 static int hf_modbus_diag_return_no_slave_response_count = -1;
114 static int hf_modbus_diag_return_slave_nak_count = -1;
115 static int hf_modbus_diag_return_slave_busy_count = -1;
116 static int hf_modbus_diag_return_bus_char_overrun_count = -1;
117 static int hf_modbus_status = -1;
118 static int hf_modbus_event = -1;
119 static int hf_modbus_event_count = -1;
120 static int hf_modbus_message_count = -1;
121 static int hf_modbus_event_recv_comm_err = -1;
122 static int hf_modbus_event_recv_char_over = -1;
123 static int hf_modbus_event_recv_lo_mode = -1;
124 static int hf_modbus_event_recv_broadcast = -1;
125 static int hf_modbus_event_send_read_ex = -1;
126 static int hf_modbus_event_send_slave_abort_ex = -1;
127 static int hf_modbus_event_send_slave_busy_ex = -1;
128 static int hf_modbus_event_send_slave_nak_ex = -1;
129 static int hf_modbus_event_send_write_timeout = -1;
130 static int hf_modbus_event_send_lo_mode = -1;
131 static int hf_modbus_andmask = -1;
132 static int hf_modbus_ormask = -1;
133 static int hf_modbus_data = -1;
134 static int hf_modbus_mei = -1;
135 static int hf_modbus_read_device_id = -1;
136 static int hf_modbus_object_id = -1;
137 static int hf_modbus_num_objects = -1;
138 static int hf_modbus_list_object_len = -1;
139 static int hf_modbus_conformity_level = -1;
140 static int hf_modbus_more_follows = -1;
141 static int hf_modbus_next_object_id = -1;
142 static int hf_modbus_object_str_value = -1;
143 static int hf_modbus_object_value = -1;
144 static int hf_modbus_reg16 = -1;
145 static int hf_modbus_reg32 = -1;
146 static int hf_mbrtu_unitid = -1;
147 static int hf_mbrtu_crc16 = -1;
148 static int hf_mbrtu_crc16_status = -1;
149
150 /* Initialize the subtree pointers */
151 static gint ett_mbtcp = -1;
152 static gint ett_mbrtu = -1;
153 static gint ett_modbus_hdr = -1;
154 static gint ett_group_hdr = -1;
155 static gint ett_events = -1;
156 static gint ett_events_recv = -1;
157 static gint ett_events_send = -1;
158 static gint ett_device_id_objects = -1;
159 static gint ett_device_id_object_items = -1;
160
161 static expert_field ei_mbrtu_crc16_incorrect = EI_INIT;
162 static expert_field ei_modbus_data_decode = EI_INIT;
163 static expert_field ei_mbtcp_cannot_classify = EI_INIT;
164
165 static dissector_handle_t modbus_handle;
166 static dissector_handle_t mbtcp_handle;
167 static dissector_handle_t mbudp_handle;
168 static dissector_handle_t mbrtu_handle;
169
170 static dissector_table_t   modbus_data_dissector_table;
171 static dissector_table_t   modbus_dissector_table;
172
173
174 /* Globals for Modbus/TCP Preferences */
175 static gboolean mbtcp_desegment = TRUE;
176 static guint global_mbus_tcp_port = PORT_MBTCP; /* Port 502, by default */
177 static guint global_mbus_udp_port = PORT_MBTCP; /* Port 502, by default */
178
179 /* Globals for Modbus RTU over TCP Preferences */
180 static gboolean mbrtu_desegment = TRUE;
181 static guint global_mbus_tcp_rtu_port = PORT_MBRTU; /* 0, by default        */
182 static guint global_mbus_udp_rtu_port = PORT_MBRTU; /* 0, by default        */
183 static gboolean mbrtu_crc = FALSE;
184
185 /* Globals for Modbus Preferences */
186 static gint global_mbus_register_format = MODBUS_PREF_REGISTER_FORMAT_UINT16;
187
188 static int
189 classify_mbtcp_packet(packet_info *pinfo, guint port)
190 {
191     /* see if nature of packets can be derived from src/dst ports */
192     /* if so, return as found */
193     /*                        */
194     /* XXX Update Oct 2012 - It can be difficult to determine if a packet is a query or response; some way to track  */
195     /* the Modbus/TCP transaction ID for each pair of messages would allow for detection based on a new seq. number. */
196     /* Otherwise, we can stick with this method; a configurable port option has been added to allow for usage of     */
197     /* user ports either than the default of 502.                                                                    */
198     if (( pinfo->srcport == port ) && ( pinfo->destport != port ))
199         return RESPONSE_PACKET;
200     if (( pinfo->srcport != port ) && ( pinfo->destport == port ))
201         return QUERY_PACKET;
202
203     /* else, cannot classify */
204     return CANNOT_CLASSIFY;
205 }
206
207 static int
208 classify_mbrtu_packet(packet_info *pinfo, tvbuff_t *tvb, guint port)
209 {
210     guint8 func, len;
211
212     func = tvb_get_guint8(tvb, 1);
213     len = tvb_reported_length(tvb);
214
215     /* see if nature of packets can be derived from src/dst ports */
216     /* if so, return as found */
217     if (( pinfo->srcport == port ) && ( pinfo->destport != port ))
218         return RESPONSE_PACKET;
219     if (( pinfo->srcport != port ) && ( pinfo->destport == port ))
220         return QUERY_PACKET;
221
222
223     /* We may not have an Ethernet header or unique ports. */
224     /* Dig into these a little deeper to try to guess the message type */
225
226     /* The 'exception' bit is set, so this is a response */
227     if (func & 0x80) {
228         return RESPONSE_PACKET;
229     }
230     switch (func) {
231         case READ_COILS:
232         case READ_DISCRETE_INPUTS:
233             /* Only possible to get a response message of 8 bytes with Discrete or Coils */
234             if (len == 8) {
235                 /* If this is, in fact, a response then the data byte count will be 3 */
236                 /* This will correctly identify all messages except for those that are discrete or coil polls */
237                 /* where the base address range happens to have 0x03 in the upper 16-bit address register     */
238                 if (tvb_get_guint8(tvb, 2) == 3) {
239                     return RESPONSE_PACKET;
240                 }
241                 else {
242                     return QUERY_PACKET;
243                 }
244             }
245             else {
246                 return RESPONSE_PACKET;
247             }
248             break;
249
250         case READ_HOLDING_REGS:
251         case READ_INPUT_REGS:
252         case WRITE_SINGLE_COIL:
253         case WRITE_SINGLE_REG:
254             if (len == 8) {
255                 return QUERY_PACKET;
256             }
257             else {
258                 return RESPONSE_PACKET;
259             }
260             break;
261
262         case WRITE_MULT_REGS:
263         case WRITE_MULT_COILS:
264             if (len == 8) {
265                 return RESPONSE_PACKET;
266             }
267             else {
268                 return QUERY_PACKET;
269             }
270             break;
271     }
272
273
274     /* else, cannot classify */
275     return CANNOT_CLASSIFY;
276 }
277
278 /* Translate function to string, as given on p6 of
279  * "Open Modbus/TCP Specification", release 1 by Andy Swales.
280  */
281 static const value_string function_code_vals[] = {
282     { READ_COILS,             "Read Coils" },
283     { READ_DISCRETE_INPUTS,   "Read Discrete Inputs" },
284     { READ_HOLDING_REGS,      "Read Holding Registers" },
285     { READ_INPUT_REGS,        "Read Input Registers" },
286     { WRITE_SINGLE_COIL,      "Write Single Coil" },
287     { WRITE_SINGLE_REG,       "Write Single Register" },
288     { READ_EXCEPT_STAT,       "Read Exception Status" },
289     { DIAGNOSTICS,            "Diagnostics" },
290     { GET_COMM_EVENT_CTRS,    "Get Comm. Event Counters" },
291     { GET_COMM_EVENT_LOG,     "Get Comm. Event Log" },
292     { WRITE_MULT_COILS,       "Write Multiple Coils" },
293     { WRITE_MULT_REGS,        "Write Multiple Registers" },
294     { REPORT_SLAVE_ID,        "Report Slave ID" },
295     { READ_FILE_RECORD,       "Read File Record" },
296     { WRITE_FILE_RECORD,      "Write File Record" },
297     { MASK_WRITE_REG,         "Mask Write Register" },
298     { READ_WRITE_REG,         "Read Write Register" },
299     { READ_FIFO_QUEUE,        "Read FIFO Queue" },
300     { ENCAP_INTERFACE_TRANSP, "Encapsulated Interface Transport" },
301     { UNITY_SCHNEIDER,        "Unity (Schneider)" },
302     { 0,                      NULL }
303 };
304
305 /* Translate exception code to string */
306 static const value_string exception_code_vals[] = {
307     { ILLEGAL_FUNCTION,    "Illegal function" },
308     { ILLEGAL_ADDRESS,     "Illegal data address" },
309     { ILLEGAL_VALUE,       "Illegal data value" },
310     { SLAVE_FAILURE,       "Slave device failure" },
311     { ACKNOWLEDGE,         "Acknowledge" },
312     { SLAVE_BUSY,          "Slave device busy" },
313     { MEMORY_ERR,          "Memory parity error" },
314     { GATEWAY_UNAVAILABLE, "Gateway path unavailable" },
315     { GATEWAY_TRGT_FAIL,   "Gateway target device failed to respond" },
316     { 0,                    NULL }
317 };
318
319 /* Translate Modbus Encapsulation Interface (MEI) code to string */
320 static const value_string encap_interface_code_vals[] = {
321     { CANOPEN_REQ_RESP, "CANopen Request/Response " },
322     { READ_DEVICE_ID,   "Read Device Identification" },
323     { 0,                NULL }
324 };
325
326 /* Translate Modbus Diagnostic subfunction code to string */
327 static const value_string diagnostic_code_vals[] = {
328     { RETURN_QUERY_DATA,                "Return Query Data" },
329     { RESTART_COMMUNICATION_OPTION,     "Restart Communications Option" },
330     { RETURN_DIAGNOSTIC_REGISTER,       "Return Diagnostic Register" },
331     { CHANGE_ASCII_INPUT_DELIMITER,     "Change ASCII Input Delimiter" },
332     { FORCE_LISTEN_ONLY_MODE,           "Force Listen Only Mode" },
333     { CLEAR_COUNTERS_AND_DIAG_REG,      "Clear Counters and Diagnostic Register" },
334     { RETURN_BUS_MESSAGE_COUNT,         "Return Bus Message Count" },
335     { RETURN_BUS_COMM_ERROR_COUNT,      "Return Bus Communication Error Count" },
336     { RETURN_BUS_EXCEPTION_ERROR_COUNT, "Return Bus Exception Error Count" },
337     { RETURN_SLAVE_MESSAGE_COUNT,       "Return Slave Message Count" },
338     { RETURN_SLAVE_NO_RESPONSE_COUNT,   "Return Slave No Response Count" },
339     { RETURN_SLAVE_NAK_COUNT,           "Return Slave NAK Count" },
340     { RETURN_SLAVE_BUSY_COUNT,          "Return Slave Busy Count" },
341     { RETURN_BUS_CHAR_OVERRUN_COUNT,    "Return Bus Character Overrun Count" },
342     { CLEAR_OVERRUN_COUNTER_AND_FLAG,   "Clear Overrun Counter and Flag" },
343     { 0,                                NULL }
344 };
345
346 static const value_string diagnostic_restart_communication_option_vals[] = {
347     { 0,        "Leave Log" },
348     { 0xFF,     "Clear Log" },
349     { 0,        NULL }
350 };
351
352 /* Translate read device code to string */
353 static const value_string read_device_id_vals[] = {
354     { 1,        "Basic Device Identification" },
355     { 2,        "Regular Device Identification"  },
356     { 3,        "Extended Device Identification"  },
357     { 4,        "Specific Identification Object"  },
358
359     { 0,        NULL             }
360 };
361
362 /* Translate read device code to string */
363 static const value_string object_id_vals[] = {
364     { 0,        "VendorName" },
365     { 1,        "ProductCode" },
366     { 2,        "MajorMinorRevision"  },
367     { 3,        "VendorURL"  },
368     { 4,        "ProductName"  },
369     { 5,        "ModelName"  },
370     { 6,        "UserApplicationName"  },
371
372     { 0,        NULL             }
373 };
374
375 static const value_string conformity_level_vals[] = {
376     { 0x01,     "Basic Device Identification (stream)" },
377     { 0x02,     "Regular Device Identification (stream)"  },
378     { 0x03,     "Extended Device Identification (stream)"  },
379     { 0x81,     "Basic Device Identification (stream and individual)" },
380     { 0x82,     "Regular Device Identification (stream and individual)"  },
381     { 0x83,     "Extended Device Identification (stream and individual)"  },
382
383     { 0,        NULL             }
384 };
385
386 static const enum_val_t mbus_register_format[] = {
387   { "UINT16     ", "UINT16     ",  MODBUS_PREF_REGISTER_FORMAT_UINT16  },
388   { "INT16      ", "INT16      ",  MODBUS_PREF_REGISTER_FORMAT_INT16   },
389   { "UINT32     ", "UINT32     ",  MODBUS_PREF_REGISTER_FORMAT_UINT32  },
390   { "INT32      ", "INT32      ",  MODBUS_PREF_REGISTER_FORMAT_INT32  },
391   { "IEEE FLT   ", "IEEE FLT   ",  MODBUS_PREF_REGISTER_FORMAT_IEEE_FLOAT  },
392   { "MODICON FLT", "MODICON FLT",  MODBUS_PREF_REGISTER_FORMAT_MODICON_FLOAT  },
393   { NULL, NULL, 0 }
394 };
395
396 /* Code to dissect Modbus/TCP packets */
397 static int
398 dissect_mbtcp_pdu_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int proto, guint port)
399 {
400 /* Set up structures needed to add the protocol subtree and manage it */
401     proto_item    *mi;
402     proto_tree    *mbtcp_tree;
403     int           offset, packet_type;
404     tvbuff_t      *next_tvb;
405     const char    *func_string = "";
406     const char    *pkt_type_str = "";
407     const char    *err_str = "";
408     guint16       transaction_id, protocol_id, len;
409     guint8        unit_id, function_code, exception_code, subfunction_code;
410
411     transaction_id = tvb_get_ntohs(tvb, 0);
412     protocol_id = tvb_get_ntohs(tvb, 2);
413     len = tvb_get_ntohs(tvb, 4);
414
415     unit_id = tvb_get_guint8(tvb, 6);
416     function_code = tvb_get_guint8(tvb, 7) & 0x7F;
417
418     offset = 0;
419
420     /* "Request" or "Response" */
421     packet_type = classify_mbtcp_packet(pinfo, port);
422
423     switch ( packet_type ) {
424         case QUERY_PACKET :
425             pkt_type_str="Query";
426             break;
427         case RESPONSE_PACKET :
428             pkt_type_str="Response";
429             break;
430         case CANNOT_CLASSIFY :
431             err_str="Unable to classify as query or response.";
432             pkt_type_str="unknown";
433             break;
434         default :
435             break;
436     }
437
438     /* Find exception - last bit set in function code */
439     if (tvb_get_guint8(tvb, 7) & 0x80) {
440         exception_code = tvb_get_guint8(tvb, offset + 8);
441     }
442     else {
443         exception_code = 0;
444     }
445
446     if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0))  {
447         func_string = val_to_str_const(tvb_get_guint8(tvb, offset + 8), encap_interface_code_vals, "Encapsulated Interface Transport");
448         subfunction_code = 1;
449     }
450     else if ((function_code == DIAGNOSTICS) && (exception_code == 0))  {
451         func_string = val_to_str_const(tvb_get_ntohs(tvb, offset + 8), diagnostic_code_vals, "Diagnostics");
452         subfunction_code = 1;
453     }
454     else {
455         func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
456         subfunction_code = 0;
457     }
458
459     if ( exception_code != 0 )
460         err_str="Exception returned ";
461
462     /* Make entries in Info column on summary display */
463     if (subfunction_code == 0) {
464         if (strlen(err_str) > 0) {
465             col_add_fstr(pinfo->cinfo, COL_INFO,
466                     "%8s: Trans: %5u; Unit: %3u, Func: %3u: %s. %s",
467                     pkt_type_str, transaction_id, unit_id,
468                     function_code, func_string, err_str);
469         }
470         else {
471             col_add_fstr(pinfo->cinfo, COL_INFO,
472                     "%8s: Trans: %5u; Unit: %3u, Func: %3u: %s",
473                     pkt_type_str, transaction_id, unit_id,
474                     function_code, func_string);
475         }
476     }
477     else {
478         if (strlen(err_str) > 0) {
479             col_add_fstr(pinfo->cinfo, COL_INFO,
480                     "%8s: Trans: %5u; Unit: %3u, Func: %3u/%3u: %s. %s",
481                     pkt_type_str, transaction_id, unit_id,
482                     function_code, subfunction_code, func_string, err_str);
483         }
484         else {
485             col_add_fstr(pinfo->cinfo, COL_INFO,
486                     "%8s: Trans: %5u; Unit: %3u, Func: %3u/%3u: %s",
487                     pkt_type_str, transaction_id, unit_id,
488                     function_code, subfunction_code, func_string);
489         }
490     }
491
492     /* Create protocol tree */
493     mi = proto_tree_add_item(tree, proto, tvb, offset, len+6, ENC_NA);
494     mbtcp_tree = proto_item_add_subtree(mi, ett_mbtcp);
495
496     if (packet_type == CANNOT_CLASSIFY)
497         expert_add_info(pinfo, mi, &ei_mbtcp_cannot_classify);
498
499     /* Add items to protocol tree specific to Modbus/TCP */
500     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_transid, tvb, offset, 2, transaction_id);
501     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_protid, tvb, offset + 2, 2, protocol_id);
502     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_len, tvb, offset + 4, 2, len);
503     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_unitid, tvb, offset + 6, 1, unit_id);
504
505     /* dissect the Modbus PDU */
506     next_tvb = tvb_new_subset_length( tvb, offset+7, len-1);
507
508     /* Continue with dissection of Modbus data payload following Modbus/TCP frame */
509     if( tvb_reported_length_remaining(tvb, offset) > 0 )
510         call_dissector_with_data(modbus_handle, next_tvb, pinfo, tree, &packet_type);
511
512     return tvb_captured_length(tvb);
513 }
514
515 static int
516 dissect_mbtcp_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
517 {
518     /* Make entries in Protocol column on summary display */
519     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/TCP");
520     col_clear(pinfo->cinfo, COL_INFO);
521
522     return dissect_mbtcp_pdu_common(tvb, pinfo, tree, proto_mbtcp, global_mbus_tcp_port);
523 }
524
525 /* Code to dissect Modbus RTU */
526 static int
527 dissect_mbrtu_pdu_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint port)
528 {
529 /* Set up structures needed to add the protocol subtree and manage it */
530     proto_item    *mi;
531     proto_tree    *mbrtu_tree;
532     int           offset, packet_type;
533     tvbuff_t      *next_tvb;
534     const char    *func_string = "";
535     const char    *pkt_type_str = "";
536     const char    *err_str = "";
537     guint16       len, calc_crc16;
538     guint8        unit_id, function_code, exception_code, subfunction_code;
539
540     /* Make entries in Protocol column on summary display */
541     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus RTU");
542     col_clear(pinfo->cinfo, COL_INFO);
543
544     len = tvb_reported_length(tvb);
545
546     unit_id = tvb_get_guint8(tvb, 0);
547     function_code = tvb_get_guint8(tvb, 1) & 0x7F;
548
549     offset = 0;
550
551     /* "Request" or "Response" */
552     packet_type = classify_mbrtu_packet(pinfo, tvb, port);
553
554     switch ( packet_type ) {
555         case QUERY_PACKET :
556             pkt_type_str="Query";
557             break;
558         case RESPONSE_PACKET :
559             pkt_type_str="Response";
560             break;
561         case CANNOT_CLASSIFY :
562             err_str="Unable to classify as query or response.";
563             pkt_type_str="unknown";
564             break;
565         default :
566             break;
567     }
568
569     /* Find exception - last bit set in function code */
570     if (tvb_get_guint8(tvb, 1) & 0x80) {
571         exception_code = tvb_get_guint8(tvb, offset + 2);
572     }
573     else {
574         exception_code = 0;
575     }
576
577     if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0))  {
578         func_string = val_to_str_const(tvb_get_guint8(tvb, offset + 2), encap_interface_code_vals, "Encapsulated Interface Transport");
579         subfunction_code = 1;
580     }
581     else if ((function_code == DIAGNOSTICS) && (exception_code == 0))  {
582         func_string = val_to_str_const(tvb_get_ntohs(tvb, offset + 2), diagnostic_code_vals, "Diagnostics");
583         subfunction_code = 1;
584     }
585     else {
586         func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
587         subfunction_code = 0;
588     }
589
590     if ( exception_code != 0 )
591         err_str="Exception returned ";
592
593     /* Make entries in Info column on summary display */
594     if (subfunction_code == 0) {
595         if (strlen(err_str) > 0) {
596             col_add_fstr(pinfo->cinfo, COL_INFO,
597                     "%8s: Unit: %3u, Func: %3u: %s. %s",
598                     pkt_type_str, unit_id,
599                     function_code, func_string, err_str);
600         }
601         else {
602             col_add_fstr(pinfo->cinfo, COL_INFO,
603                     "%8s: Unit: %3u, Func: %3u: %s",
604                     pkt_type_str, unit_id,
605                     function_code, func_string);
606         }
607     }
608     else {
609         if (strlen(err_str) > 0) {
610             col_add_fstr(pinfo->cinfo, COL_INFO,
611                     "%8s: Unit: %3u, Func: %3u/%3u: %s. %s",
612                     pkt_type_str, unit_id,
613                     function_code, subfunction_code, func_string, err_str);
614         }
615         else {
616             col_add_fstr(pinfo->cinfo, COL_INFO,
617                     "%8s: Unit: %3u, Func: %3u/%3u: %s",
618                     pkt_type_str, unit_id,
619                     function_code, subfunction_code, func_string);
620         }
621     }
622
623     /* Create protocol tree */
624     mi = proto_tree_add_protocol_format(tree, proto_mbrtu, tvb, offset,
625             len, "Modbus RTU");
626     mbrtu_tree = proto_item_add_subtree(mi, ett_mbrtu);
627
628     /* Add items to protocol tree specific to Modbus RTU */
629     proto_tree_add_uint(mbrtu_tree, hf_mbrtu_unitid, tvb, offset, 1, unit_id);
630
631     /* CRC validation */
632     if (mbrtu_crc)
633     {
634         calc_crc16 = crc16_plain_tvb_offset_seed(tvb, offset, len-2, 0xFFFF);
635         proto_tree_add_checksum(mbrtu_tree, tvb, len-2, hf_mbrtu_crc16, hf_mbrtu_crc16_status, &ei_mbrtu_crc16_incorrect, pinfo, g_htons(calc_crc16), ENC_BIG_ENDIAN, PROTO_CHECKSUM_VERIFY);
636     }
637     else
638     {
639         proto_tree_add_checksum(mbrtu_tree, tvb, len-2, hf_mbrtu_crc16, hf_mbrtu_crc16_status, &ei_mbrtu_crc16_incorrect, pinfo, 0, ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);
640     }
641
642     /* when determining payload length, make sure to ignore the unit ID header & CRC-16 footer bytes */
643     len = len - 3;
644
645     /* dissect the Modbus PDU                      */
646     next_tvb = tvb_new_subset_length( tvb, offset+1, len);
647
648     /* Continue with dissection of Modbus data payload following Modbus RTU frame */
649     if( tvb_reported_length_remaining(tvb, offset) > 0 )
650         call_dissector_with_data(modbus_handle, next_tvb, pinfo, tree, &packet_type);
651
652     return tvb_captured_length(tvb);
653 }
654
655 /* Code to dissect Modbus RTU over TCP packets */
656 static int
657 dissect_mbrtu_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
658 {
659     return dissect_mbrtu_pdu_common(tvb, pinfo, tree, global_mbus_tcp_rtu_port);
660 }
661
662 /* Return length of Modbus/TCP message */
663 static guint
664 get_mbtcp_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset, void *data _U_)
665 {
666     guint16 plen;
667
668     /*
669      * Get the length of the data from the encapsulation header.
670      */
671     plen = tvb_get_ntohs(tvb, offset + 4);
672
673     /*
674      * That length doesn't include the encapsulation header itself;
675      * add that in.
676      */
677     return plen + 6;
678 }
679
680 /* Return length of Modbus RTU over TCP message */
681 static guint
682 get_mbrtu_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb,
683                   int offset _U_, void *data _U_)
684 {
685     int packet_type;
686     guint8 function_code;
687
688     function_code = tvb_get_guint8(tvb, 1);
689
690     /* Modbus RTU requests do not contain a length field but they are typically a consistent size.
691        Responses do contain a usable 'length' byte at offset 2
692        XXX - Note that only some function codes are supported by this lookup function;
693              the rest can be added as pcap examples are made available */
694
695     /* Determine "Query" or "Response" */
696     packet_type = classify_mbrtu_packet(pinfo, tvb, global_mbus_tcp_rtu_port);
697
698     switch ( packet_type ) {
699         case QUERY_PACKET :
700             switch (function_code) {
701                 case READ_COILS:   /* Query messages of these types are always 8 bytes */
702                 case READ_DISCRETE_INPUTS:
703                 case READ_HOLDING_REGS:
704                 case READ_INPUT_REGS:
705                 case WRITE_SINGLE_COIL:
706                 case WRITE_SINGLE_REG:
707                     return 8;
708                     break;
709                 case WRITE_MULT_REGS:
710                 case WRITE_MULT_COILS:
711                     return tvb_get_guint8(tvb, 6) + 9; /* Reported size does not include 2 header, 4 FC15/16-specific, 1 size byte or 2 CRC16 bytes */
712                     break;
713                 default :
714                     return tvb_captured_length(tvb);  /* Fall back on tvb length */
715                     break;
716             }
717         case RESPONSE_PACKET :
718             /* The 'exception' bit is set, so this is a 5-byte response */
719             if (function_code & 0x80) {
720                 return 5;
721             }
722
723             switch (function_code) {
724                 case READ_COILS:
725                 case READ_DISCRETE_INPUTS:
726                 case READ_HOLDING_REGS:
727                 case READ_INPUT_REGS:
728                 case WRITE_SINGLE_COIL:
729                 case WRITE_SINGLE_REG:
730                     return tvb_get_guint8(tvb, 2) + 5;  /* Reported size does not include 2 header, 1 size byte, 2 CRC16 bytes */
731                     break;
732                 case WRITE_MULT_REGS:  /* Response messages of FC15/16 are always 8 bytes */
733                 case WRITE_MULT_COILS:
734                     return 8;
735                     break;
736                 default :
737                     return tvb_captured_length(tvb);  /* Fall back on tvb length */
738                     break;
739             }
740         case CANNOT_CLASSIFY :
741         default :
742             return tvb_captured_length(tvb);  /* Fall back on tvb length */
743             break;
744     }
745
746 }
747
748
749 /* Code to dissect Modbus/TCP messages */
750 static int
751 dissect_mbtcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
752 {
753
754     /* Make sure there's at least enough data to determine it's a Modbus TCP packet */
755     if (!tvb_bytes_exist(tvb, 0, 8))
756         return 0;
757
758     /* check that it actually looks like Modbus/TCP */
759     /* protocol id == 0 */
760     if(tvb_get_ntohs(tvb, 2) != 0 ){
761         return 0;
762     }
763     /* length is at least 2 (unit_id + function_code) */
764     if(tvb_get_ntohs(tvb, 4) < 2 ){
765         return 0;
766     }
767
768     /* build up protocol tree and iterate over multiple packets */
769     tcp_dissect_pdus(tvb, pinfo, tree, mbtcp_desegment, 6,
770                      get_mbtcp_pdu_len, dissect_mbtcp_pdu, data);
771
772     return tvb_captured_length(tvb);
773 }
774
775 static int
776 dissect_mbudp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
777 {
778
779     /* Make sure there's at least enough data to determine it's a Modbus UDP packet */
780     if (!tvb_bytes_exist(tvb, 0, 8))
781         return 0;
782
783     /* check that it actually looks like Modbus/TCP */
784     /* protocol id == 0 */
785     if(tvb_get_ntohs(tvb, 2) != 0 ){
786         return 0;
787     }
788     /* length is at least 2 (unit_id + function_code) */
789     if(tvb_get_ntohs(tvb, 4) < 2 ){
790         return 0;
791     }
792
793     /* Make entries in Protocol column on summary display */
794     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/UDP");
795     col_clear(pinfo->cinfo, COL_INFO);
796
797     return dissect_mbtcp_pdu_common(tvb, pinfo, tree, proto_mbudp, global_mbus_udp_port);
798 }
799
800 /* Code to dissect Modbus RTU over TCP messages */
801 static int
802 dissect_mbrtu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
803 {
804
805     /* Make sure there's at least enough data to determine it's a Modbus packet */
806     /* 5 bytes is the smallest possible valid message (exception response) */
807     if (!tvb_bytes_exist(tvb, 0, 5))
808         return 0;
809
810     /* For Modbus RTU mode, confirm that the first byte is a valid address (non-zero), */
811     /* so we can eliminate false-posititves on Modbus TCP messages loaded as RTU       */
812     if(tvb_get_guint8(tvb, 0) == 0 )
813         return 0;
814
815     /* build up protocol tree and iterate over multiple packets */
816     tcp_dissect_pdus(tvb, pinfo, tree, mbrtu_desegment, 5,
817                      get_mbrtu_pdu_len, dissect_mbrtu_pdu, data);
818
819     return tvb_captured_length(tvb);
820 }
821
822 static int
823 dissect_mbrtu_udp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
824 {
825
826     /* Make sure there's at least enough data to determine it's a Modbus packet */
827     /* 5 bytes is the smallest possible valid message (exception response) */
828     if (tvb_reported_length(tvb) < 5)
829         return 0;
830
831     return dissect_mbrtu_pdu_common(tvb, pinfo, tree, global_mbus_udp_rtu_port);
832 }
833
834
835 /* Code to allow further dissection of Modbus data payload */
836 /* Common to both Modbus/TCP and Modbus RTU dissectors     */
837 static void
838 dissect_modbus_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 function_code,
839                     gint payload_start, gint payload_len, gint register_format, guint16 reg_base)
840 {
841     gint reported_len, data_offset;
842     gint16  data16s;
843     gint32  data32s;
844     guint16 data16, modflt_lo, modflt_hi, reg_num=reg_base;
845     guint32 data32, modflt_comb;
846     gfloat data_float, modfloat;
847     proto_item    *register_item = NULL;
848     tvbuff_t *next_tvb;
849
850     reported_len = tvb_reported_length_remaining(tvb, payload_start);
851     data_offset = 0;
852
853     if ( payload_start < 0 || ( payload_len + payload_start ) == 0 )
854         return;
855
856     /* If calculated length from remaining tvb data != bytes in packet, do not attempt to decode      */
857     if ( payload_len != reported_len ) {
858         proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, reported_len, ENC_NA);
859         return;
860     }
861
862     /* If data type of payload is Holding or Input registers */
863     /* AND */
864     /* if payload length is not a multiple of 4, don't attempt to decode anything in 32-bit format */
865     if ((function_code == READ_HOLDING_REGS) || (function_code == READ_INPUT_REGS) || (function_code == WRITE_MULT_REGS)) {
866         if ((payload_len % 4 != 0) && ( (register_format == MODBUS_PREF_REGISTER_FORMAT_UINT32) ||
867             (register_format == MODBUS_PREF_REGISTER_FORMAT_IEEE_FLOAT) ||
868             (register_format == MODBUS_PREF_REGISTER_FORMAT_MODICON_FLOAT) ) ) {
869             register_item = proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, payload_len, ENC_NA);
870             expert_add_info(pinfo, register_item, &ei_modbus_data_decode);
871             return;
872         }
873     }
874
875     /* Build a new tvb containing just the data payload   */
876     next_tvb = tvb_new_subset(tvb, payload_start, payload_len, reported_len);
877
878     switch ( function_code ) {
879
880         case READ_HOLDING_REGS:
881         case READ_INPUT_REGS:
882         case WRITE_MULT_REGS:
883             while (data_offset < payload_len) {
884                 /* Use "Preferences" options to determine decoding format of register data, as no format is implied by the protocol itself. */
885                 /* Based on a standard register size of 16-bits, use decoding format preference to step through each register and display  */
886                 /* it in an appropriate fashion. */
887                 switch (register_format) {
888                     case MODBUS_PREF_REGISTER_FORMAT_UINT16: /* Standard-size unsigned integer 16-bit register */
889                         data16 = tvb_get_ntohs(next_tvb, data_offset);
890                         proto_tree_add_uint_format(tree, hf_modbus_reg16, next_tvb, data_offset, 2, reg_num,
891                                                     "Register %u (UINT16): %u", reg_num, data16);
892                         data_offset += 2;
893                         reg_num += 1;
894                         break;
895                     case MODBUS_PREF_REGISTER_FORMAT_INT16: /* Standard-size signed integer 16-bit register */
896                         data16s = tvb_get_ntohs(next_tvb, data_offset);
897                         proto_tree_add_uint_format(tree, hf_modbus_reg16, next_tvb, data_offset, 2, reg_num,
898                                                     "Register %u (INT16): %d", reg_num, data16s);
899                         data_offset += 2;
900                         reg_num += 1;
901                         break;
902                     case MODBUS_PREF_REGISTER_FORMAT_UINT32: /* Double-size unsigned integer 2 x 16-bit registers */
903                         data32 = tvb_get_ntohl(next_tvb, data_offset);
904                         proto_tree_add_uint_format(tree, hf_modbus_reg32, next_tvb, data_offset, 4, reg_num,
905                                                     "Register %u (UINT32): %u", reg_num, data32);
906                         data_offset += 4;
907                         reg_num += 2;
908                         break;
909                     case MODBUS_PREF_REGISTER_FORMAT_INT32: /* Double-size signed integer 2 x 16-bit registers */
910                         data32s = tvb_get_ntohl(next_tvb, data_offset);
911                         proto_tree_add_uint_format(tree, hf_modbus_reg32, next_tvb, data_offset, 4, reg_num,
912                                                     "Register %u (INT32): %d", reg_num, data32s);
913                         data_offset += 4;
914                         reg_num += 2;
915                         break;
916                     case MODBUS_PREF_REGISTER_FORMAT_IEEE_FLOAT: /* IEEE Floating Point, 2 x 16-bit registers */
917                         data_float = tvb_get_ntohieee_float(next_tvb, data_offset);
918
919                         proto_tree_add_uint_format(tree, hf_modbus_reg32, next_tvb, data_offset, 4, reg_num,
920                                                     "Register %u (IEEE Float): %f", reg_num, data_float);
921                         data_offset += 4;
922                         reg_num += 2;
923                         break;
924                     case MODBUS_PREF_REGISTER_FORMAT_MODICON_FLOAT: /* Modicon Floating Point (word-swap), 2 x 16-bit registers */
925                         /* Modicon-style Floating Point values are stored in reverse-word order.                     */
926                         /* ie: a standard IEEE float value 59.991459 is equal to 0x426ff741                          */
927                         /*     while the Modicon equivalent to this value is 0xf741426f                              */
928                         /* To re-assemble a proper IEEE float, we must retrieve the 2 x 16-bit words, bit-shift the  */
929                         /* "hi" component by 16-bits and then OR them together into a combined 32-bit int.           */
930                         /* Following that operation, use some memcpy magic to copy the 4 raw data bytes from the     */
931                         /* 32-bit integer into a standard float.  Not sure if there is a cleaner way possible using  */
932                         /* the Wireshark libraries, but this seems to work OK.                                        */
933
934                         modflt_lo = tvb_get_ntohs(next_tvb, data_offset);
935                         modflt_hi = tvb_get_ntohs(next_tvb, data_offset+2);
936                         modflt_comb = (guint32)(modflt_hi<<16) | modflt_lo;
937                         memcpy(&modfloat, &modflt_comb, 4);
938
939                         proto_tree_add_uint_format(tree, hf_modbus_reg32, next_tvb, data_offset, 4, reg_num,
940                                                     "Register %u (Modicon Float): %f", reg_num, modfloat);
941                         data_offset += 4;
942                         reg_num += 2;
943                         break;
944                     default:
945                         /* Avoid any chance of an infinite loop */
946                         data_offset = payload_len;
947                         break;
948                     } /* register format switch */
949
950                 } /* while loop */
951
952                 break;
953
954         default:
955             if ( ! dissector_try_string(modbus_data_dissector_table, "data", next_tvb, pinfo, tree, NULL) )
956                 proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, payload_len, ENC_NA);
957             break;
958         }
959 }
960
961 /* Code to dissect Modbus request message */
962 static int
963 dissect_modbus_request(tvbuff_t *tvb, packet_info *pinfo, proto_tree *modbus_tree, guint8 function_code, gint payload_start, gint payload_len)
964 {
965     proto_tree    *group_tree;
966     gint          byte_cnt, group_offset, ii;
967     gint          register_format = MODBUS_PREF_REGISTER_FORMAT_UINT16;  /* Default value for register formatting.. */
968     guint8        mei_code;
969     guint16       reg_base=0, diagnostic_code;
970     guint32       group_byte_cnt, group_word_cnt;
971
972     modbus_conversation   *conv;
973
974     /* See if we have any context */
975     conv = (modbus_conversation *)p_get_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0);
976
977     if (conv) {
978         register_format = conv->register_format;
979     }
980
981     switch (function_code) {
982
983         case READ_COILS:
984         case READ_DISCRETE_INPUTS:
985             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
986             proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
987             break;
988
989         case READ_HOLDING_REGS:
990         case READ_INPUT_REGS:
991             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
992             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
993             break;
994
995         case WRITE_SINGLE_COIL:
996             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
997             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1, register_format, reg_base);
998             proto_tree_add_item(modbus_tree, hf_modbus_padding, tvb, payload_start + 3, 1, ENC_NA);
999             break;
1000
1001         case WRITE_SINGLE_REG:
1002             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1003             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2, register_format, reg_base);
1004             break;
1005
1006         case READ_EXCEPT_STAT:
1007             /* Do Nothing  */
1008             break;
1009
1010         case DIAGNOSTICS:
1011             diagnostic_code = tvb_get_ntohs(tvb, payload_start);
1012             proto_tree_add_uint(modbus_tree, hf_modbus_diag_sf, tvb, payload_start, 2, diagnostic_code);
1013             switch(diagnostic_code)
1014             {
1015                 case RETURN_QUERY_DATA:
1016                     if (payload_len > 2)
1017                         proto_tree_add_item(modbus_tree, hf_modbus_diag_return_query_data_request, tvb, payload_start+2, payload_len-2, ENC_NA);
1018                     break;
1019                 case RESTART_COMMUNICATION_OPTION:
1020                     proto_tree_add_item(modbus_tree, hf_modbus_diag_restart_communication_option, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1021                     break;
1022                 case CHANGE_ASCII_INPUT_DELIMITER:
1023                     proto_tree_add_item(modbus_tree, hf_modbus_diag_ascii_input_delimiter, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1024                     break;
1025                 case RETURN_DIAGNOSTIC_REGISTER:           /* 00 00 Data Field */
1026                 case FORCE_LISTEN_ONLY_MODE:               /* 00 00 Data Field */
1027                 case CLEAR_COUNTERS_AND_DIAG_REG:          /* 00 00 Data Field */
1028                 case RETURN_BUS_MESSAGE_COUNT:             /* 00 00 Data Field */
1029                 case RETURN_BUS_COMM_ERROR_COUNT:          /* 00 00 Data Field */
1030                 case RETURN_BUS_EXCEPTION_ERROR_COUNT:     /* 00 00 Data Field */
1031                 case RETURN_SLAVE_MESSAGE_COUNT:           /* 00 00 Data Field */
1032                 case RETURN_SLAVE_NO_RESPONSE_COUNT:       /* 00 00 Data Field */
1033                 case RETURN_SLAVE_NAK_COUNT:               /* 00 00 Data Field */
1034                 case RETURN_SLAVE_BUSY_COUNT:              /* 00 00 Data Field */
1035                 case RETURN_BUS_CHAR_OVERRUN_COUNT:        /* 00 00 Data Field */
1036                 case CLEAR_OVERRUN_COUNTER_AND_FLAG:
1037                 default:
1038                     if (payload_len > 2)
1039                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format, reg_base);
1040                     break;
1041             }
1042             break;
1043         case WRITE_MULT_COILS:
1044             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1045             proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1046             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
1047             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1, byte_cnt);
1048             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt, register_format, reg_base);
1049             break;
1050
1051         case WRITE_MULT_REGS:
1052             reg_base = tvb_get_ntohs(tvb, payload_start);
1053             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1054             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1055             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
1056             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1, byte_cnt);
1057             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt, register_format, reg_base);
1058             break;
1059
1060         case READ_FILE_RECORD:
1061             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1062             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
1063                     byte_cnt);
1064
1065             /* add subtrees to describe each group of packet */
1066             group_offset = payload_start + 1;
1067             for (ii = 0; ii < byte_cnt / 7; ii++) {
1068                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset, 7,
1069                         ett_group_hdr, NULL, "Group %u", ii);
1070                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
1071                 proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
1072                 proto_tree_add_item(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, ENC_BIG_ENDIAN);
1073                 group_offset += 7;
1074             }
1075             break;
1076
1077         case WRITE_FILE_RECORD:
1078             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1079             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1080
1081             /* add subtrees to describe each group of packet */
1082             group_offset = payload_start + 1;
1083             ii = 0;
1084             while (byte_cnt > 0) {
1085                 group_word_cnt = tvb_get_ntohs(tvb, group_offset + 5);
1086                 group_byte_cnt = (2 * group_word_cnt) + 7;
1087                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset,
1088                         group_byte_cnt, ett_group_hdr, NULL, "Group %u", ii);
1089                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
1090                 proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
1091                 proto_tree_add_uint(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, group_word_cnt);
1092                 dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 7, group_byte_cnt - 7, register_format, reg_base);
1093                 group_offset += group_byte_cnt;
1094                 byte_cnt -= group_byte_cnt;
1095                 ii++;
1096             }
1097             break;
1098
1099         case MASK_WRITE_REG:
1100             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1101             proto_tree_add_item(modbus_tree, hf_modbus_andmask, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1102             proto_tree_add_item(modbus_tree, hf_modbus_ormask, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
1103             break;
1104
1105         case READ_WRITE_REG:
1106             proto_tree_add_item(modbus_tree, hf_modbus_readref, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1107             proto_tree_add_item(modbus_tree, hf_modbus_readwordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1108             proto_tree_add_item(modbus_tree, hf_modbus_writeref, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
1109             proto_tree_add_item(modbus_tree, hf_modbus_writewordcnt, tvb, payload_start + 6, 2, ENC_BIG_ENDIAN);
1110             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 8);
1111             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 8, 1, byte_cnt);
1112             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 9, byte_cnt, register_format, reg_base);
1113             break;
1114
1115         case READ_FIFO_QUEUE:
1116             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1117             break;
1118
1119         case ENCAP_INTERFACE_TRANSP:
1120             proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
1121             mei_code = tvb_get_guint8(tvb, payload_start);
1122             switch (mei_code)
1123             {
1124                 case READ_DEVICE_ID:
1125                     proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
1126                     proto_tree_add_item(modbus_tree, hf_modbus_object_id, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1127                     break;
1128
1129                 case CANOPEN_REQ_RESP:
1130                     /* CANopen protocol not part of the Modbus/TCP specification */
1131                 default:
1132                     if (payload_len > 1)
1133                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1, register_format, reg_base);
1134                     break;
1135             }
1136
1137             break;
1138
1139         case REPORT_SLAVE_ID:
1140         default:
1141             if (payload_len > 0)
1142                 dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, register_format, reg_base);
1143             break;
1144
1145     } /* Function Code */
1146
1147     return tvb_captured_length(tvb);
1148 }
1149
1150 /* Code to dissect Modbus Response message */
1151 static int
1152 dissect_modbus_response(tvbuff_t *tvb, packet_info *pinfo, proto_tree *modbus_tree, guint8 function_code, gint payload_start, gint payload_len)
1153 {
1154
1155     proto_tree    *group_tree, *event_tree, *event_item_tree, *device_objects_tree, *device_objects_item_tree;
1156     proto_item    *mei;
1157     gint          byte_cnt, group_offset, event_index, object_index, object_len, num_objects, ii;
1158     gint          register_format = MODBUS_PREF_REGISTER_FORMAT_UINT16;  /* Default value for register formatting.. */
1159     guint8        object_type, mei_code, event_code;
1160     guint16       reg_base=0, diagnostic_code;
1161     guint32       group_byte_cnt, group_word_cnt;
1162
1163     /* Conversation tracking */
1164     proto_item            *request_frame_item;
1165     modbus_conversation   *conv;
1166     guint8                req_function_code;
1167     guint32               req_frame_num;
1168     gboolean              request_found = FALSE;
1169     modbus_request_info_t *request_data;
1170
1171     /* See if we have any context */
1172     conv = (modbus_conversation *)p_get_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0);
1173
1174     if (conv) {
1175
1176         wmem_list_frame_t *frame = wmem_list_head(conv->modbus_request_frame_data);
1177         /* Step backward through all logged instances of request frames, looking for a request frame number that
1178            occurred immediately prior to current frame number that has a matching function code */
1179         while (frame && !request_found) {
1180             request_data = (modbus_request_info_t *)wmem_list_frame_data(frame);
1181             req_frame_num = request_data->fnum;
1182             req_function_code = request_data->function_code;
1183             if ((pinfo->num > req_frame_num) && (req_function_code == function_code)) {
1184                 request_frame_item = proto_tree_add_uint(modbus_tree, hf_modbus_request_frame, tvb, 0, 0, req_frame_num);
1185                 reg_base = request_data->base_address;
1186                 PROTO_ITEM_SET_GENERATED(request_frame_item);
1187                 request_found = TRUE;
1188             }
1189             frame = wmem_list_frame_next(frame);
1190         }
1191
1192         register_format = conv->register_format;
1193     } /* conv */
1194
1195     switch (function_code) {
1196
1197         case READ_COILS:
1198         case READ_DISCRETE_INPUTS:
1199             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1200             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1201             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, register_format, reg_base);
1202             break;
1203
1204         case READ_HOLDING_REGS:
1205         case READ_INPUT_REGS:
1206             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1207             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1208             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, register_format, reg_base);
1209             break;
1210
1211         case WRITE_SINGLE_COIL:
1212             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1213             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1, register_format, reg_base);
1214             proto_tree_add_item(modbus_tree, hf_modbus_padding, tvb, payload_start + 3, 1, ENC_NA);
1215             break;
1216
1217         case WRITE_SINGLE_REG:
1218             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1219             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2, register_format, reg_base);
1220             break;
1221
1222         case READ_EXCEPT_STAT:
1223             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, 1, register_format, reg_base);
1224             break;
1225
1226         case DIAGNOSTICS:
1227             diagnostic_code = tvb_get_ntohs(tvb, payload_start);
1228             proto_tree_add_uint(modbus_tree, hf_modbus_diag_sf, tvb, payload_start, 2, diagnostic_code);
1229             switch(diagnostic_code)
1230             {
1231                 case RETURN_QUERY_DATA: /* Echo of Request */
1232                     if (payload_len > 2)
1233                         proto_tree_add_item(modbus_tree, hf_modbus_diag_return_query_data_echo, tvb, payload_start+2, payload_len-2, ENC_NA);
1234                     break;
1235                 case RESTART_COMMUNICATION_OPTION:  /* Echo of Request */
1236                     proto_tree_add_item(modbus_tree, hf_modbus_diag_restart_communication_option, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1237                     break;
1238                 case RETURN_DIAGNOSTIC_REGISTER:
1239                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_diag_register, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1240                     break;
1241                 case CHANGE_ASCII_INPUT_DELIMITER:   /* XXX - Do we expect this to ever be a response? */
1242                     proto_tree_add_item(modbus_tree, hf_modbus_diag_ascii_input_delimiter, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1243                     break;
1244                 case CLEAR_COUNTERS_AND_DIAG_REG:   /* Echo of Request */
1245                     proto_tree_add_item(modbus_tree, hf_modbus_diag_clear_ctr_diag_reg, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1246                     break;
1247                 case RETURN_BUS_MESSAGE_COUNT:
1248                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_message_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1249                     break;
1250                 case RETURN_BUS_COMM_ERROR_COUNT:
1251                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_comm_error_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1252                     break;
1253                 case RETURN_BUS_EXCEPTION_ERROR_COUNT:
1254                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_exception_error_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1255                     break;
1256                 case RETURN_SLAVE_MESSAGE_COUNT:
1257                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_message_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1258                     break;
1259                 case RETURN_SLAVE_NO_RESPONSE_COUNT:
1260                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_no_slave_response_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1261                     break;
1262                 case RETURN_SLAVE_NAK_COUNT:
1263                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_nak_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1264                     break;
1265                 case RETURN_SLAVE_BUSY_COUNT:
1266                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_busy_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1267                     break;
1268                 case RETURN_BUS_CHAR_OVERRUN_COUNT:
1269                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_char_overrun_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1270                     break;
1271                 case CLEAR_OVERRUN_COUNTER_AND_FLAG:        /* Echo of Request */
1272                 case FORCE_LISTEN_ONLY_MODE:                /* No response anticipated */
1273                 default:
1274                     if (payload_len > 2)
1275                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, register_format, reg_base);
1276                     break;
1277             } /* diagnostic_code */
1278             break;
1279
1280         case GET_COMM_EVENT_CTRS:
1281             proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1282             proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1283             break;
1284
1285         case GET_COMM_EVENT_LOG:
1286             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1287             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1288             proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start+1, 2, ENC_BIG_ENDIAN);
1289             proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+3, 2, ENC_BIG_ENDIAN);
1290             proto_tree_add_item(modbus_tree, hf_modbus_message_count, tvb, payload_start+5, 2, ENC_BIG_ENDIAN);
1291             if (byte_cnt-6 > 0) {
1292                 byte_cnt -= 6;
1293                 event_index = 0;
1294                 event_tree = proto_tree_add_subtree(modbus_tree, tvb, payload_start+7, byte_cnt, ett_events, NULL, "Events");
1295                 while (byte_cnt > 0) {
1296                     event_code = tvb_get_guint8(tvb, payload_start+7+event_index);
1297                     if (event_code == 0) {
1298                         proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Initiated Communication Restart");
1299                     }
1300                     else if (event_code == 4) {
1301                         proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Entered Listen Only Mode");
1302                     }
1303                     else if (event_code & REMOTE_DEVICE_RECV_EVENT_MASK) {
1304                         mei = proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1,
1305                                     event_code, "Receive Event: 0x%02X", event_code);
1306                         event_item_tree = proto_item_add_subtree(mei, ett_events_recv);
1307
1308                         /* add subtrees to describe each event bit */
1309                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_comm_err,
1310                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1311                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_char_over,
1312                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1313                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_lo_mode,
1314                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1315                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_broadcast,
1316                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1317                     }
1318                     else if ((event_code & REMOTE_DEVICE_SEND_EVENT_MASK) == REMOTE_DEVICE_SEND_EVENT_VALUE) {
1319                         mei = proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1,
1320                                     event_code, "Send Event: 0x%02X", event_code);
1321                         event_item_tree = proto_item_add_subtree(mei, ett_events_send);
1322
1323                         /* add subtrees to describe each event bit */
1324                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_read_ex,
1325                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1326                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_abort_ex,
1327                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1328                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_busy_ex,
1329                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1330                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_nak_ex,
1331                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1332                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_write_timeout,
1333                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1334                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_lo_mode,
1335                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1336                     }
1337                     else {
1338                         proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Unknown Event");
1339                     }
1340
1341                     byte_cnt--;
1342                     event_index++;
1343                 }
1344             }
1345             break;
1346
1347         case WRITE_MULT_COILS:
1348             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1349             proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1350             break;
1351
1352         case WRITE_MULT_REGS:
1353             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1354             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1355             break;
1356
1357         case READ_FILE_RECORD:
1358             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1359             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
1360                     byte_cnt);
1361
1362             /* add subtrees to describe each group of packet */
1363             group_offset = payload_start + 1;
1364             ii = 0;
1365             while (byte_cnt > 0) {
1366                 group_byte_cnt = (guint32)tvb_get_guint8(tvb, group_offset);
1367                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset, group_byte_cnt + 1,
1368                         ett_group_hdr, NULL, "Group %u", ii);
1369                 proto_tree_add_uint(group_tree, hf_modbus_bytecnt, tvb, group_offset, 1,
1370                         group_byte_cnt);
1371                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset + 1, 1, ENC_BIG_ENDIAN);
1372                 dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 2, group_byte_cnt - 1, register_format, reg_base);
1373                 group_offset += (group_byte_cnt + 1);
1374                 byte_cnt -= (group_byte_cnt + 1);
1375                 ii++;
1376             }
1377             break;
1378
1379         case WRITE_FILE_RECORD:   /* Normal response is echo of request */
1380             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1381             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1382
1383             /* add subtrees to describe each group of packet */
1384             group_offset = payload_start + 1;
1385             ii = 0;
1386             while (byte_cnt > 0) {
1387                 group_word_cnt = tvb_get_ntohs(tvb, group_offset + 5);
1388                 group_byte_cnt = (2 * group_word_cnt) + 7;
1389                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset,
1390                         group_byte_cnt, ett_group_hdr, NULL, "Group %u", ii);
1391                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
1392                 proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
1393                 proto_tree_add_uint(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, group_word_cnt);
1394                 dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 7, group_byte_cnt - 7, register_format, reg_base);
1395                 group_offset += group_byte_cnt;
1396                 byte_cnt -= group_byte_cnt;
1397                 ii++;
1398             }
1399             break;
1400
1401         case MASK_WRITE_REG:      /* Normal response is echo of request */
1402             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1403             proto_tree_add_item(modbus_tree, hf_modbus_andmask, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1404             proto_tree_add_item(modbus_tree, hf_modbus_ormask, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
1405             break;
1406
1407         case READ_WRITE_REG:
1408             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1409             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1410             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, register_format, reg_base);
1411             break;
1412
1413         case READ_FIFO_QUEUE:
1414             byte_cnt = (guint32)tvb_get_ntohs(tvb, payload_start);
1415             proto_tree_add_uint(modbus_tree, hf_modbus_lbytecnt, tvb, payload_start, 2, byte_cnt);
1416             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1417             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 4, byte_cnt - 2, register_format, reg_base);
1418             break;
1419
1420         case ENCAP_INTERFACE_TRANSP:
1421             proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
1422             mei_code = tvb_get_guint8(tvb, payload_start);
1423             switch (mei_code)
1424             {
1425                 case READ_DEVICE_ID:
1426                     proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
1427                     proto_tree_add_item(modbus_tree, hf_modbus_conformity_level, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1428                     proto_tree_add_item(modbus_tree, hf_modbus_more_follows, tvb, payload_start+3, 1, ENC_BIG_ENDIAN);
1429                     proto_tree_add_item(modbus_tree, hf_modbus_next_object_id, tvb, payload_start+4, 1, ENC_BIG_ENDIAN);
1430                     num_objects = tvb_get_guint8(tvb, payload_start+5);
1431                     proto_tree_add_uint(modbus_tree, hf_modbus_num_objects, tvb, payload_start+5, 1, num_objects);
1432                     device_objects_tree = proto_tree_add_subtree(modbus_tree, tvb, payload_start+6, payload_len-6,
1433                                                                     ett_device_id_objects, NULL, "Objects");
1434
1435                     object_index = 0;
1436                     for (ii = 0; ii < num_objects; ii++)
1437                     {
1438                         /* add each "object item" as its own subtree */
1439
1440                         /* compute length of object */
1441                         object_type = tvb_get_guint8(tvb, payload_start+6+object_index);
1442                         object_len = tvb_get_guint8(tvb, payload_start+6+object_index+1);
1443
1444                         device_objects_item_tree = proto_tree_add_subtree_format(device_objects_tree, tvb, payload_start+6+object_index, 2+object_len,
1445                                                     ett_device_id_object_items, NULL, "Object #%d", ii+1);
1446
1447                         proto_tree_add_item(device_objects_item_tree, hf_modbus_object_id, tvb, payload_start+6+object_index, 1, ENC_BIG_ENDIAN);
1448                         object_index++;
1449
1450                         proto_tree_add_uint(device_objects_item_tree, hf_modbus_list_object_len, tvb, payload_start+6+object_index, 1, object_len);
1451                         object_index++;
1452
1453                         if (object_type < 7)
1454                         {
1455                             proto_tree_add_item(device_objects_item_tree, hf_modbus_object_str_value, tvb, payload_start+6+object_index, object_len, ENC_ASCII|ENC_NA);
1456                         }
1457                         else
1458                         {
1459                             if (object_len > 0)
1460                                 proto_tree_add_item(device_objects_item_tree, hf_modbus_object_value, tvb, payload_start+6+object_index, object_len, ENC_NA);
1461                         }
1462                         object_index += object_len;
1463                     } /* for ii */
1464                     break;
1465
1466                 case CANOPEN_REQ_RESP:
1467                     /* CANopen protocol not part of the Modbus/TCP specification */
1468                 default:
1469                     if (payload_len > 1)
1470                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1, register_format, reg_base);
1471                     break;
1472             } /* mei_code */
1473             break;
1474
1475         case REPORT_SLAVE_ID:
1476         default:
1477             if (payload_len > 0)
1478                 dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, register_format, reg_base);
1479             break;
1480
1481     } /* function code */
1482
1483     return tvb_captured_length(tvb);
1484 }
1485
1486
1487 /* Dissect the Modbus Payload.  Called from either Modbus/TCP or Modbus RTU Dissector */
1488 static int
1489 dissect_modbus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
1490 {
1491     proto_tree    *modbus_tree;
1492     proto_item    *mi;
1493     int           offset = 0;
1494     int*          packet_type = (int*)data;
1495     gint          payload_start, payload_len, len;
1496     guint8        function_code, exception_code;
1497
1498     /* Reject the packet if data passed from the mbrtu or mbtcp dissector is NULL */
1499     if (packet_type == NULL)
1500         return 0;
1501
1502     len = tvb_captured_length(tvb);
1503
1504     /* If the packet is zero-length, we should not attempt to dissect any further */
1505     if (len == 0)
1506         return 0;
1507
1508     /* Add items to protocol tree specific to Modbus */
1509     mi = proto_tree_add_protocol_format(tree, proto_modbus, tvb, offset, len, "Modbus");
1510     modbus_tree = proto_item_add_subtree(mi, ett_modbus_hdr);
1511
1512     function_code = tvb_get_guint8(tvb, offset) & 0x7F;
1513     proto_tree_add_item(modbus_tree, hf_modbus_functioncode, tvb, offset, 1, ENC_BIG_ENDIAN);
1514
1515     /* Conversation support */
1516     if (!pinfo->fd->flags.visited) {
1517         conversation_t       *conversation = NULL;
1518         modbus_conversation  *modbus_conv_data = NULL;
1519
1520         /* Find a conversation, create a new if no one exists */
1521         conversation = find_or_create_conversation(pinfo);
1522         modbus_conv_data = (modbus_conversation *)conversation_get_proto_data(conversation, proto_modbus);
1523
1524         if (modbus_conv_data == NULL){
1525            modbus_conv_data = wmem_new(wmem_file_scope(), modbus_conversation);
1526            modbus_conv_data->modbus_request_frame_data = wmem_list_new(wmem_file_scope());
1527            modbus_conv_data->register_format = global_mbus_register_format;
1528            conversation_add_proto_data(conversation, proto_modbus, (void *)modbus_conv_data);
1529         }
1530
1531         p_add_proto_data(wmem_file_scope(), pinfo, proto_modbus, 0, modbus_conv_data);
1532
1533         if (*packet_type == QUERY_PACKET) {
1534             /*create the modbus_request frame. It holds the request information.*/
1535             modbus_request_info_t    *frame_ptr = wmem_new(wmem_file_scope(), modbus_request_info_t);
1536
1537             /* load information into the modbus request frame */
1538             frame_ptr->fnum = pinfo->num;
1539             frame_ptr->function_code = function_code;
1540             frame_ptr->base_address = tvb_get_ntohs(tvb, 1);
1541             frame_ptr->num_reg = tvb_get_ntohs(tvb, 3);
1542
1543             wmem_list_prepend(modbus_conv_data->modbus_request_frame_data, frame_ptr);
1544         }
1545
1546     } /* !visited */
1547
1548     /* Find exception - last bit set in function code */
1549     if (tvb_get_guint8(tvb, offset) & 0x80 ) {
1550         exception_code = tvb_get_guint8(tvb, offset+1);
1551     }
1552     else {
1553         exception_code = 0;
1554     }
1555
1556     payload_start = offset + 1;
1557     payload_len = len - 1;
1558
1559     if (exception_code != 0) {
1560         proto_item_set_text(mi, "Function %u:  %s.  Exception: %s",
1561                             function_code,
1562                             val_to_str_const(function_code, function_code_vals, "Unknown Function"),
1563                             val_to_str(exception_code,
1564                                        exception_code_vals,
1565                                        "Unknown Exception Code (%u)"));
1566         proto_tree_add_uint(modbus_tree, hf_modbus_exceptioncode, tvb, payload_start, 1,
1567                             exception_code);
1568     }
1569     else {
1570
1571         /* Follow different dissection path depending on whether packet is query or response */
1572         if (*packet_type == QUERY_PACKET) {
1573             dissect_modbus_request(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len);
1574         }
1575         else if (*packet_type == RESPONSE_PACKET) {
1576             dissect_modbus_response(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len);
1577         }
1578
1579     }
1580
1581     return tvb_captured_length(tvb);
1582 }
1583
1584 static void
1585 apply_mbtcp_prefs(void)
1586 {
1587     /* Modbus/RTU uses the port preference to determine request/response */
1588     global_mbus_tcp_port = prefs_get_uint_value("mbtcp", "tcp.port");
1589     global_mbus_udp_port = prefs_get_uint_value("mbudp", "udp.port");
1590 }
1591
1592 static void
1593 apply_mbrtu_prefs(void)
1594 {
1595     /* Modbus/RTU uses the port preference to determine request/response */
1596     global_mbus_tcp_rtu_port = prefs_get_uint_value("mbrtu", "tcp.port");
1597     global_mbus_udp_rtu_port = prefs_get_uint_value("mbrtu", "udp.port");
1598 }
1599
1600 /* Register the protocol with Wireshark */
1601 void
1602 proto_register_modbus(void)
1603 {
1604     /* Modbus/TCP header fields */
1605     static hf_register_info mbtcp_hf[] = {
1606         { &hf_mbtcp_transid,
1607             { "Transaction Identifier", "mbtcp.trans_id",
1608             FT_UINT16, BASE_DEC, NULL, 0x0,
1609             NULL, HFILL }
1610         },
1611         { &hf_mbtcp_protid,
1612             { "Protocol Identifier", "mbtcp.prot_id",
1613             FT_UINT16, BASE_DEC, NULL, 0x0,
1614             NULL, HFILL }
1615         },
1616         { &hf_mbtcp_len,
1617             { "Length", "mbtcp.len",
1618             FT_UINT16, BASE_DEC, NULL, 0x0,
1619             NULL, HFILL }
1620         },
1621         { &hf_mbtcp_unitid,
1622             { "Unit Identifier", "mbtcp.unit_id",
1623             FT_UINT8, BASE_DEC, NULL, 0x0,
1624             NULL, HFILL }
1625         },
1626     };
1627
1628     static ei_register_info mbtcp_ei[] = {
1629         { &ei_mbtcp_cannot_classify,
1630           { "mbtcp.cannot_classify", PI_PROTOCOL, PI_WARN,
1631             "Cannot classify packet type. Try setting Modbus/TCP Port preference to this destination or source port", EXPFILL }
1632         },
1633     };
1634
1635     /* Modbus RTU header fields */
1636     static hf_register_info mbrtu_hf[] = {
1637         { &hf_mbrtu_unitid,
1638             { "Unit ID", "mbrtu.unit_id",
1639             FT_UINT8, BASE_DEC, NULL, 0x0,
1640             NULL, HFILL }
1641         },
1642         { &hf_mbrtu_crc16,
1643             { "CRC-16", "mbrtu.crc16",
1644             FT_UINT16, BASE_HEX, NULL, 0x0,
1645             NULL, HFILL }
1646         },
1647         { &hf_mbrtu_crc16_status,
1648             { "CRC-16 Status", "mbrtu.crc16.status",
1649             FT_UINT8, BASE_NONE, VALS(proto_checksum_vals), 0x0,
1650             NULL, HFILL }
1651         },
1652     };
1653
1654     static ei_register_info mbrtu_ei[] = {
1655         { &ei_mbrtu_crc16_incorrect,
1656           { "mbrtu.crc16.incorrect", PI_CHECKSUM, PI_WARN,
1657             "Incorrect CRC", EXPFILL }
1658         },
1659     };
1660
1661     /* Modbus header fields */
1662     static hf_register_info hf[] = {
1663         { &hf_modbus_request_frame,
1664             { "Request Frame", "modbus.request_frame",
1665             FT_FRAMENUM, BASE_NONE,
1666             NULL, 0x0,
1667             NULL, HFILL }
1668         },
1669         { &hf_modbus_functioncode,
1670             { "Function Code", "modbus.func_code",
1671             FT_UINT8, BASE_DEC, VALS(function_code_vals), 0x7F,
1672             NULL, HFILL }
1673         },
1674         { &hf_modbus_reference,
1675             { "Reference Number", "modbus.reference_num",
1676             FT_UINT16, BASE_DEC, NULL, 0x0,
1677             NULL, HFILL }
1678         },
1679         { &hf_modbus_padding,
1680             { "Padding", "modbus.padding",
1681             FT_UINT8, BASE_HEX, NULL, 0x0,
1682             NULL, HFILL }
1683         },
1684         { &hf_modbus_lreference,
1685             { "Reference Number (32 bit)", "modbus.reference_num_32",
1686             FT_UINT32, BASE_DEC, NULL, 0x0,
1687             NULL, HFILL }
1688         },
1689         { &hf_modbus_reftype,
1690             { "Reference Type", "modbus.reference_type",
1691             FT_UINT8, BASE_DEC, NULL, 0x0,
1692             NULL, HFILL }
1693         },
1694         { &hf_modbus_readref,
1695             { "Read Reference Number", "modbus.read_reference_num",
1696             FT_UINT16, BASE_DEC, NULL, 0x0,
1697             NULL, HFILL }
1698         },
1699         { &hf_modbus_writeref,
1700             { "Write Reference Number", "modbus.write_reference_num",
1701             FT_UINT16, BASE_DEC, NULL, 0x0,
1702             NULL, HFILL }
1703         },
1704         { &hf_modbus_wordcnt,
1705             { "Word Count", "modbus.word_cnt",
1706             FT_UINT16, BASE_DEC, NULL, 0x0,
1707             NULL, HFILL }
1708         },
1709         { &hf_modbus_readwordcnt,
1710             { "Read Word Count", "modbus.read_word_cnt",
1711             FT_UINT16, BASE_DEC, NULL, 0x0,
1712             NULL, HFILL }
1713         },
1714         { &hf_modbus_writewordcnt,
1715             { "Write Word Count", "modbus.write_word_cnt",
1716             FT_UINT16, BASE_DEC, NULL, 0x0,
1717             NULL, HFILL }
1718         },
1719         { &hf_modbus_bitcnt,
1720             { "Bit Count", "modbus.bit_cnt",
1721             FT_UINT16, BASE_DEC, NULL, 0x0,
1722             NULL, HFILL }
1723         },
1724         { &hf_modbus_bytecnt,
1725             { "Byte Count", "modbus.byte_cnt",
1726             FT_UINT8, BASE_DEC, NULL, 0x0,
1727             NULL, HFILL }
1728         },
1729         { &hf_modbus_lbytecnt,
1730             { "Byte Count (16-bit)", "modbus.byte_cnt_16",
1731             FT_UINT8, BASE_DEC, NULL, 0x0,
1732             NULL, HFILL }
1733         },
1734         { &hf_modbus_exceptioncode,
1735             { "Exception Code", "modbus.exception_code",
1736             FT_UINT8, BASE_DEC, VALS(exception_code_vals), 0x0,
1737             NULL, HFILL }
1738         },
1739         { &hf_modbus_diag_sf,
1740             { "Diagnostic Code", "modbus.diagnostic_code",
1741             FT_UINT16, BASE_DEC, VALS(diagnostic_code_vals), 0x0,
1742             NULL, HFILL }
1743         },
1744         { &hf_modbus_diag_return_query_data_request,
1745             { "Request Data", "modbus.diagnostic.return_query_data.request",
1746             FT_BYTES, BASE_NONE, NULL, 0x0,
1747             NULL, HFILL }
1748         },
1749         { &hf_modbus_diag_return_query_data_echo,
1750             { "Echo Data", "modbus.diagnostic.return_query_data.echo",
1751             FT_BYTES, BASE_NONE, NULL, 0x0,
1752             NULL, HFILL }
1753         },
1754         { &hf_modbus_diag_restart_communication_option,
1755             { "Restart Communication Option", "modbus.diagnostic.restart_communication_option",
1756             FT_UINT16, BASE_HEX, VALS(diagnostic_restart_communication_option_vals), 0x0,
1757             NULL, HFILL }
1758         },
1759         { &hf_modbus_diag_return_diag_register,
1760             { "Diagnostic Register Contents", "modbus.diagnostic.return_diag_register",
1761             FT_UINT16, BASE_HEX, NULL, 0x0,
1762             NULL, HFILL }
1763         },
1764         { &hf_modbus_diag_ascii_input_delimiter,
1765             { "CHAR", "modbus.diagnostic.ascii_input_delimiter",
1766             FT_UINT8, BASE_HEX, NULL, 0x0,
1767             NULL, HFILL }
1768         },
1769         { &hf_modbus_diag_clear_ctr_diag_reg,
1770             { "Clear Counters & Diag Register Echo", "modbus.diagnostic.clear_ctr_diag_reg",
1771             FT_UINT16, BASE_DEC, NULL, 0x0,
1772             NULL, HFILL }
1773         },
1774         { &hf_modbus_diag_return_bus_message_count,
1775             { "Total Message Count", "modbus.diagnostic.bus_message_count",
1776             FT_UINT16, BASE_DEC, NULL, 0x0,
1777             NULL, HFILL }
1778         },
1779         { &hf_modbus_diag_return_bus_comm_error_count,
1780             { "CRC Error Count", "modbus.diagnostic.bus_comm_error_count",
1781             FT_UINT16, BASE_DEC, NULL, 0x0,
1782             NULL, HFILL }
1783         },
1784         { &hf_modbus_diag_return_bus_exception_error_count,
1785             { "Exception Error Count", "modbus.diagnostic.bus_exception_error_count",
1786             FT_UINT16, BASE_DEC, NULL, 0x0,
1787             NULL, HFILL }
1788         },
1789         { &hf_modbus_diag_return_slave_message_count,
1790             { "Slave Message Count", "modbus.diagnostic.slave_message_count",
1791             FT_UINT16, BASE_DEC, NULL, 0x0,
1792             NULL, HFILL }
1793         },
1794         { &hf_modbus_diag_return_no_slave_response_count,
1795             { "Slave No Response Count", "modbus.diagnostic.no_slave_response_count",
1796             FT_UINT16, BASE_DEC, NULL, 0x0,
1797             NULL, HFILL }
1798         },
1799         { &hf_modbus_diag_return_slave_nak_count,
1800             { "Slave NAK Count", "modbus.diagnostic.slave_nak_count",
1801             FT_UINT16, BASE_DEC, NULL, 0x0,
1802             NULL, HFILL }
1803         },
1804         { &hf_modbus_diag_return_slave_busy_count,
1805             { "Slave Device Busy Count", "modbus.diagnostic.slave_busy_count",
1806             FT_UINT16, BASE_DEC, NULL, 0x0,
1807             NULL, HFILL }
1808         },
1809         { &hf_modbus_diag_return_bus_char_overrun_count,
1810             { "Slave Character Overrun Count", "modbus.diagnostic.bus_char_overrun_count",
1811             FT_UINT16, BASE_DEC, NULL, 0x0,
1812             NULL, HFILL }
1813         },
1814         { &hf_modbus_status,
1815             { "Status", "modbus.ev_status",
1816             FT_UINT16, BASE_HEX, NULL, 0x0,
1817             NULL, HFILL }
1818         },
1819         { &hf_modbus_event,
1820             { "Event", "modbus.event",
1821             FT_UINT8, BASE_DEC, NULL, 0x0,
1822             NULL, HFILL }
1823         },
1824         { &hf_modbus_event_count,
1825             { "Event Count", "modbus.ev_count",
1826             FT_UINT16, BASE_DEC, NULL, 0x0,
1827             NULL, HFILL }
1828         },
1829         { &hf_modbus_message_count,
1830             { "Message Count", "modbus.ev_msg_count",
1831             FT_UINT16, BASE_DEC, NULL, 0x0,
1832             NULL, HFILL }
1833         },
1834         { &hf_modbus_event_recv_comm_err,
1835             { "Communication Error", "modbus.ev_recv_comm_err",
1836             FT_UINT8, BASE_DEC, NULL, 0x02,
1837             NULL, HFILL }
1838         },
1839         { &hf_modbus_event_recv_char_over,
1840             { "Character Overrun", "modbus.ev_recv_char_over",
1841             FT_UINT8, BASE_DEC, NULL, 0x10,
1842             NULL, HFILL }
1843         },
1844         { &hf_modbus_event_recv_lo_mode,
1845             { "Currently in Listen Only Mode", "modbus.ev_recv_lo_mode",
1846             FT_UINT8, BASE_DEC, NULL, 0x20,
1847             NULL, HFILL }
1848         },
1849         { &hf_modbus_event_recv_broadcast,
1850             { "Broadcast Received", "modbus.ev_recv_broadcast",
1851             FT_UINT8, BASE_DEC, NULL, 0x40,
1852             NULL, HFILL }
1853         },
1854         { &hf_modbus_event_send_read_ex,
1855             { "Read Exception Sent", "modbus.ev_send_read_ex",
1856             FT_UINT8, BASE_DEC, NULL, 0x01,
1857             NULL, HFILL }
1858         },
1859         { &hf_modbus_event_send_slave_abort_ex,
1860             { "Slave Abort Exception Sent", "modbus.ev_send_slave_abort_ex",
1861             FT_UINT8, BASE_DEC, NULL, 0x02,
1862             NULL, HFILL }
1863         },
1864         { &hf_modbus_event_send_slave_busy_ex,
1865             { "Slave Busy Exception Sent", "modbus.ev_send_slave_busy_ex",
1866             FT_UINT8, BASE_DEC, NULL, 0x04,
1867             NULL, HFILL }
1868         },
1869         { &hf_modbus_event_send_slave_nak_ex,
1870             { "Slave Program NAK Exception Sent", "modbus.ev_send_slave_nak_ex",
1871             FT_UINT8, BASE_DEC, NULL, 0x08,
1872             NULL, HFILL }
1873         },
1874         { &hf_modbus_event_send_write_timeout,
1875             { "Write Timeout Error Occurred", "modbus.ev_send_write_timeout",
1876             FT_UINT8, BASE_DEC, NULL, 0x10,
1877             NULL, HFILL }
1878         },
1879         { &hf_modbus_event_send_lo_mode,
1880             { "Currently in Listen Only Mode", "modbus.ev_send_lo_mode",
1881             FT_UINT8, BASE_DEC, NULL, 0x20,
1882             NULL, HFILL }
1883         },
1884         { &hf_modbus_andmask,
1885             { "AND mask", "modbus.and_mask",
1886             FT_UINT16, BASE_HEX, NULL, 0x0,
1887             NULL, HFILL }
1888         },
1889         { &hf_modbus_ormask,
1890             { "OR mask", "modbus.or_mask",
1891             FT_UINT16, BASE_HEX, NULL, 0x0,
1892             NULL, HFILL }
1893         },
1894         { &hf_modbus_data,
1895             { "Data",  "modbus.data",
1896             FT_BYTES,  BASE_NONE, NULL,    0x0, NULL, HFILL }
1897         },
1898         { &hf_modbus_mei,
1899             { "MEI type", "modbus.mei",
1900             FT_UINT8, BASE_DEC, VALS(encap_interface_code_vals), 0x0,
1901             NULL, HFILL }
1902         },
1903         { &hf_modbus_read_device_id,
1904             { "Read Device ID", "modbus.read_device_id",
1905             FT_UINT8, BASE_DEC, VALS(read_device_id_vals), 0x0,
1906             NULL, HFILL }
1907         },
1908         { &hf_modbus_object_id,
1909             { "Object ID", "modbus.object_id",
1910             FT_UINT8, BASE_DEC, VALS(object_id_vals), 0x0,
1911             NULL, HFILL }
1912         },
1913         { &hf_modbus_num_objects,
1914             { "Number of Objects", "modbus.num_objects",
1915             FT_UINT8, BASE_DEC, NULL, 0x0,
1916             NULL, HFILL }
1917         },
1918         { &hf_modbus_list_object_len,
1919             { "Object length", "modbus.objects_len",
1920             FT_UINT8, BASE_DEC, NULL, 0x0,
1921             NULL, HFILL }
1922         },
1923         { &hf_modbus_conformity_level,
1924             { "Conformity Level", "modbus.conformity_level",
1925             FT_UINT8, BASE_HEX, VALS(conformity_level_vals), 0x0,
1926             NULL, HFILL }
1927         },
1928         { &hf_modbus_more_follows,
1929             { "More Follows", "modbus.more_follows",
1930             FT_UINT8, BASE_HEX, NULL, 0x0,
1931             NULL, HFILL }
1932         },
1933         { &hf_modbus_next_object_id,
1934             { "Next Object ID", "modbus.next_object_id",
1935             FT_UINT8, BASE_DEC, NULL, 0x0,
1936             NULL, HFILL }
1937         },
1938         { &hf_modbus_object_str_value,
1939             { "Object String Value", "modbus.object_str_value",
1940             FT_STRING, BASE_NONE, NULL, 0x0,
1941             NULL, HFILL }
1942         },
1943         { &hf_modbus_object_value,
1944             { "Object Value", "modbus.object_value",
1945             FT_BYTES, BASE_NONE, NULL, 0x0,
1946             NULL, HFILL }
1947         },
1948         { &hf_modbus_reg16,
1949             { "Register Value (16-bit)", "modbus.reg16",
1950             FT_UINT16, BASE_DEC, NULL, 0x0,
1951             NULL, HFILL }
1952         },
1953         { &hf_modbus_reg32,
1954             { "Register Value (32-bit)", "modbus.reg32",
1955             FT_UINT32, BASE_DEC, NULL, 0x0,
1956             NULL, HFILL }
1957         },
1958     };
1959
1960     /* Setup protocol subtree array */
1961     static gint *ett[] = {
1962         &ett_mbtcp,
1963         &ett_mbrtu,
1964         &ett_modbus_hdr,
1965         &ett_group_hdr,
1966         &ett_events,
1967         &ett_events_recv,
1968         &ett_events_send,
1969         &ett_device_id_objects,
1970         &ett_device_id_object_items
1971     };
1972
1973     static ei_register_info ei[] = {
1974         { &ei_modbus_data_decode,
1975           { "modbus.data.decode", PI_PROTOCOL, PI_WARN,
1976             "Invalid decoding options, register data not a multiple of 4!", EXPFILL }
1977         },
1978     };
1979     module_t *mbtcp_module;
1980     module_t *mbrtu_module;
1981     module_t *modbus_module;
1982     expert_module_t* expert_mbtcp;
1983     expert_module_t* expert_mbrtu;
1984     expert_module_t* expert_modbus;
1985
1986     /* Register the protocol name and description */
1987     proto_mbtcp = proto_register_protocol("Modbus/TCP", "Modbus/TCP", "mbtcp");
1988     proto_mbudp = proto_register_protocol("Modbus/UDP", "Modbus/UDP", "mbudp");
1989     proto_mbrtu = proto_register_protocol("Modbus RTU", "Modbus RTU", "mbrtu");
1990     proto_modbus = proto_register_protocol("Modbus", "Modbus", "modbus");
1991
1992     /* Registering protocol to be called by another dissector */
1993     modbus_handle = register_dissector("modbus", dissect_modbus, proto_modbus);
1994     mbtcp_handle = register_dissector("mbtcp", dissect_mbtcp, proto_mbtcp);
1995     mbrtu_handle = register_dissector("mbrtu", dissect_mbrtu, proto_mbrtu);
1996     mbudp_handle = register_dissector("mbudp", dissect_mbudp, proto_mbudp);
1997
1998     /* Registering subdissectors table */
1999     modbus_data_dissector_table = register_dissector_table("modbus.data", "Modbus Data", proto_modbus, FT_STRING, BASE_NONE);
2000     modbus_dissector_table = register_dissector_table("mbtcp.prot_id", "Modbus/TCP protocol identifier", proto_mbtcp, FT_UINT16, BASE_DEC);
2001
2002     /* Required function calls to register the header fields and subtrees used */
2003     proto_register_field_array(proto_mbtcp, mbtcp_hf, array_length(mbtcp_hf));
2004     proto_register_field_array(proto_mbrtu, mbrtu_hf, array_length(mbrtu_hf));
2005     proto_register_field_array(proto_modbus, hf, array_length(hf));
2006     proto_register_subtree_array(ett, array_length(ett));
2007     expert_mbtcp = expert_register_protocol(proto_mbtcp);
2008     expert_register_field_array(expert_mbtcp, mbtcp_ei, array_length(mbtcp_ei));
2009     expert_mbrtu = expert_register_protocol(proto_mbrtu);
2010     expert_register_field_array(expert_mbrtu, mbrtu_ei, array_length(mbrtu_ei));
2011     expert_modbus = expert_register_protocol(proto_modbus);
2012     expert_register_field_array(expert_modbus, ei, array_length(ei));
2013
2014
2015     /* Register required preferences for Modbus Protocol variants */
2016     mbtcp_module = prefs_register_protocol(proto_mbtcp, apply_mbtcp_prefs);
2017     mbrtu_module = prefs_register_protocol(proto_mbrtu, apply_mbrtu_prefs);
2018     modbus_module = prefs_register_protocol(proto_modbus, NULL);
2019
2020     /* Modbus RTU Preference - Desegment, defaults to TRUE for TCP desegmentation */
2021     prefs_register_bool_preference(mbtcp_module, "desegment",
2022                                   "Desegment all Modbus RTU packets spanning multiple TCP segments",
2023                                   "Whether the Modbus RTU dissector should desegment all messages spanning multiple TCP segments",
2024                                   &mbtcp_desegment);
2025
2026     /* Modbus RTU Preference - Desegment, defaults to TRUE for TCP desegmentation */
2027     prefs_register_bool_preference(mbrtu_module, "desegment",
2028                                   "Desegment all Modbus RTU packets spanning multiple TCP segments",
2029                                   "Whether the Modbus RTU dissector should desegment all messages spanning multiple TCP segments",
2030                                   &mbrtu_desegment);
2031
2032     /* Modbus RTU Preference - CRC verification, defaults to FALSE (no verification)*/
2033     prefs_register_bool_preference(mbrtu_module, "crc_verification",
2034                                   "Validate CRC",
2035                                   "Whether to validate the CRC",
2036                                   &mbrtu_crc);
2037
2038     /* Modbus Preference - Holding/Input Register format, this allows for deeper dissection of response data */
2039     prefs_register_enum_preference(modbus_module, "mbus_register_format",
2040                                     "Holding/Input Register Format",
2041                                     "Register Format",
2042                                     &global_mbus_register_format,
2043                                     mbus_register_format,
2044                                     TRUE);
2045
2046     /* Obsolete Preferences */
2047     prefs_register_obsolete_preference(mbtcp_module, "mbus_register_addr_type");
2048     prefs_register_obsolete_preference(mbtcp_module, "mbus_register_format");
2049     prefs_register_obsolete_preference(mbrtu_module, "mbus_register_addr_type");
2050     prefs_register_obsolete_preference(mbrtu_module, "mbus_register_format");
2051
2052 }
2053
2054
2055 /* If this dissector uses sub-dissector registration add a registration routine.
2056    This format is required because a script is used to find these routines and
2057    create the code that calls these routines.
2058  */
2059 void
2060 proto_reg_handoff_mbtcp(void)
2061 {
2062     dissector_add_uint_with_preference("tcp.port", PORT_MBTCP, mbtcp_handle);
2063     dissector_add_uint_with_preference("udp.port", PORT_MBTCP, mbudp_handle);
2064
2065     dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
2066
2067 }
2068
2069 void
2070 proto_reg_handoff_mbrtu(void)
2071 {
2072     dissector_handle_t mbrtu_udp_handle = create_dissector_handle(dissect_mbrtu_udp, proto_mbrtu);
2073
2074     /* Make sure to use Modbus RTU Preferences field to determine default TCP port */
2075     dissector_add_for_decode_as_with_preference("udp.port", mbrtu_udp_handle);
2076     dissector_add_for_decode_as_with_preference("tcp.port", mbrtu_handle);
2077
2078     dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
2079     dissector_add_for_decode_as("rtacser.data", mbrtu_handle);
2080     dissector_add_for_decode_as("usb.device", mbrtu_handle);
2081     dissector_add_for_decode_as("usb.product", mbrtu_handle);
2082     dissector_add_for_decode_as("usb.protocol", mbrtu_handle);
2083
2084 }
2085
2086 /*
2087  * Editor modelines
2088  *
2089  * Local Variables:
2090  * c-basic-offset: 4
2091  * tab-width: 8
2092  * indent-tabs-mode: nil
2093  * End:
2094  *
2095  * ex: set shiftwidth=4 tabstop=8 expandtab:
2096  * :indentSize=4:tabSize=8:noTabs=true:
2097  */