Replace the types from sys/types.h and netinet/in.h by their glib.h
[obnox/wireshark/wip.git] / packet-ntp.c
1 /* packet-ntp.c
2  * Routines for NTP packet dissection
3  * Copyright 1999, Nathan Neulinger <nneul@umr.edu>
4  *
5  * $Id: packet-ntp.c,v 1.36 2002/08/02 23:35:55 jmayer Exp $
6  *
7  * Ethereal - Network traffic analyzer
8  * By Gerald Combs <gerald@ethereal.com>
9  * Copyright 1998 Gerald Combs
10  *
11  * Copied from packet-tftp.c
12  * 
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  * 
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  * 
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26  */
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <stdio.h>
33
34 #include <string.h>
35 #include <time.h>
36 #include <math.h>
37 #include <glib.h>
38
39 #ifdef NEED_SNPRINTF_H
40 # include "snprintf.h"
41 #endif
42
43 #include <epan/packet.h>
44 #include <epan/resolv.h>
45 #include "packet-ntp.h"
46
47 /*
48  * Dissecting NTP packets version 3 and 4 (RFC2030, RFC1769, RFC1361,
49  * RFC1305).
50  *
51  * Those packets have simple structure:
52  *                      1                   2                   3
53  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
54  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
55  * |LI | VN  |Mode |    Stratum    |     Poll      |   Precision   |
56  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
57  * |                          Root Delay                           |
58  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
59  * |                       Root Dispersion                         |
60  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
61  * |                    Reference Identifier                       |
62  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
63  * |                   Reference Timestamp (64)                    |
64  * |                                                               |
65  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
66  * |                   Originate Timestamp (64)                    |
67  * |                                                               |
68  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
69  * |                    Receive Timestamp (64)                     |
70  * |                                                               |
71  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72  * |                    Transmit Timestamp (64)                    |
73  * |                                                               |
74  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
75  * |                 Key Identifier (optional) (32)                |
76  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
77  * |                 Message Digest (optional) (128)               |
78  * |                                                               |
79  * |                                                               |
80  * |                                                               |
81  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
82  * NTP timestamps are represented as a 64-bit unsigned fixed-point number,
83  * in seconds relative to 0h on 1 January 1900. The integer part is in the
84  * first 32 bits and the fraction part in the last 32 bits.
85  */
86
87 #define UDP_PORT_NTP    123
88 #define TCP_PORT_NTP    123
89
90 /* Leap indicator, 2bit field is used to warn of a inserted/deleted
91  * second, or to alarm loosed synchronization.
92  */
93 #define NTP_LI_MASK     0xC0
94
95 #define NTP_LI_NONE     0
96 #define NTP_LI_61       1
97 #define NTP_LI_59       2
98 #define NTP_LI_ALARM    3
99
100 static const value_string li_types[] = {
101         { NTP_LI_NONE,  "no warning" },
102         { NTP_LI_61,    "last minute has 61 seconds" },
103         { NTP_LI_59,    "last minute has 59 seconds" },
104         { NTP_LI_ALARM, "alarm condition (clock not synchronized)" },
105         { 0,            NULL}
106 };
107
108 /* Version info, 3bit field informs about NTP version used in particular
109  * packet. According to rfc2030, version info could be only 3 or 4, but I
110  * have noticed packets with 1 or even 6 as version numbers. They are
111  * produced as a result of ntptrace command. Are those packets mailformed
112  * on purpose? I don't know yet, probably some browsing through ntp sources
113  * would help. My solution is to put them as reserved for now.
114  */
115 #define NTP_VN_MASK     0x38
116
117 static const value_string ver_nums[] = {
118         { 0,    "reserved" },
119         { 1,    "reserved" },
120         { 2,    "reserved" },
121         { 3,    "NTP Version 3" },
122         { 4,    "NTP Version 4" },
123         { 5,    "reserved" },
124         { 6,    "reserved" },
125         { 7,    "reserved" },
126         { 0,    NULL}
127 };
128
129 /* Mode, 3bit field representing mode of comunication.
130  */
131 #define NTP_MODE_MASK   7
132
133 #define NTP_MODE_RSV    0
134 #define NTP_MODE_SYMACT 1
135 #define NTP_MODE_SYMPAS 2
136 #define NTP_MODE_CLIENT 3
137 #define NTP_MODE_SERVER 4
138 #define NTP_MODE_BCAST  5
139 #define NTP_MODE_CTRL   6
140 #define NTP_MODE_PRIV   7
141
142 static const value_string mode_types[] = {
143         { NTP_MODE_RSV,         "reserved" },
144         { NTP_MODE_SYMACT,      "symmetric active" },
145         { NTP_MODE_SYMPAS,      "symmetric passive" },
146         { NTP_MODE_CLIENT,      "client" },
147         { NTP_MODE_SERVER,      "server" },
148         { NTP_MODE_BCAST,       "broadcast" },
149         { NTP_MODE_CTRL,        "reserved for NTP control message"},
150         { NTP_MODE_PRIV,        "reserved for private use" },
151         { 0,            NULL}
152 };
153
154 /* According to rfc, primary (stratum-0 and stratum-1) servers should set
155  * their Reference Clock ID (4bytes field) according to following table:
156  */
157 static const struct {
158         char *id;
159         char *data;
160 } primary_sources[] = {
161         { "LOCL",       "uncalibrated local clock" },
162         { "PPS\0",      "atomic clock or other pulse-per-second source" },
163         { "ACTS",       "NIST dialup modem service" },
164         { "USNO",       "USNO modem service" },
165         { "PTB\0",      "PTB (Germany) modem service" },
166         { "TDF\0",      "Allouis (France) Radio 164 kHz" },
167         { "DCF\0",      "Mainflingen (Germany) Radio 77.5 kHz" },
168         { "MSF\0",      "Rugby (UK) Radio 60 kHz" },
169         { "WWV\0",      "Ft. Collins (US) Radio 2.5, 5, 10, 15, 20 MHz" },
170         { "WWVB",       "Boulder (US) Radio 60 kHz" },
171         { "WWVH",       "Kaui Hawaii (US) Radio 2.5, 5, 10, 15 MHz" },
172         { "CHU\0",      "Ottawa (Canada) Radio 3330, 7335, 14670 kHz" },
173         { "LORC",       "LORAN-C radionavigation system" },
174         { "OMEG",       "OMEGA radionavigation system" },
175         { "GPS\0",      "Global Positioning Service" },
176         { "GOES",       "Geostationary Orbit Environment Satellite" },
177         { "DCN\0",      "DCN routing protocol" },
178         { "NIST",       "NIST public modem" },
179         { "TSP\0",      "TSP time protocol" },
180         { "DTS\0",      "Digital Time Service" },
181         { "ATOM",       "Atomic clock (calibrated)" },
182         { "VLF\0",      "VLF radio (OMEGA,, etc.)" },
183         { "IRIG",       "IRIG-B timecode" },
184         { "1PPS",       "External 1 PPS input" },
185         { "FREE",       "(Internal clock)" },
186         { NULL,         NULL}
187 };
188
189 static int proto_ntp = -1;
190 static int hf_ntp_flags = -1;
191 static int hf_ntp_flags_li = -1;
192 static int hf_ntp_flags_vn = -1;
193 static int hf_ntp_flags_mode = -1;
194 static int hf_ntp_stratum = -1;
195 static int hf_ntp_ppoll = -1;
196 static int hf_ntp_precision = -1;
197 static int hf_ntp_rootdelay = -1;
198 static int hf_ntp_rootdispersion = -1;
199 static int hf_ntp_refid = -1;
200 static int hf_ntp_reftime = -1;
201 static int hf_ntp_org = -1;
202 static int hf_ntp_rec = -1;
203 static int hf_ntp_xmt = -1;
204 static int hf_ntp_keyid = -1;
205 static int hf_ntp_mac = -1;
206
207 static gint ett_ntp = -1;
208 static gint ett_ntp_flags = -1;
209
210 /* ntp_fmt_ts - converts NTP timestamp to human readable string.
211  * reftime - 64bit timestamp (IN)
212  * buff - string buffer for result (OUT)
213  * returns pointer to filled buffer.
214  */
215 static char *
216 ntp_fmt_ts(const guint8 *reftime, char* buff)
217 {
218         guint32 tempstmp, tempfrac;
219         time_t temptime;
220         struct tm *bd;
221         double fractime;
222
223         tempstmp = pntohl(&reftime[0]);
224         tempfrac = pntohl(&reftime[4]);
225         if ((tempstmp == 0) && (tempfrac == 0)) {
226                 strcpy (buff, "NULL");
227                 return buff;
228         } else {
229                 temptime = tempstmp - (guint32) NTP_BASETIME;
230                 bd = gmtime(&temptime);
231                 if (bd != NULL) {
232                         fractime = bd->tm_sec + tempfrac / 4294967296.0;
233                         snprintf(buff, NTP_TS_SIZE,
234                                  "%04d-%02d-%02d %02d:%02d:%07.4f UTC",
235                                  bd->tm_year + 1900, bd->tm_mon + 1, bd->tm_mday,
236                                  bd->tm_hour, bd->tm_min, fractime);
237                 } else
238                         strncpy(buff, "Not representable", NTP_TS_SIZE);
239         }
240         return buff;
241 }
242                 
243 /* dissect_ntp - dissects NTP packet data
244  * tvb - tvbuff for packet data (IN)
245  * pinfo - packet info
246  * proto_tree - resolved protocol tree
247  */
248 static void
249 dissect_ntp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
250 {
251         proto_tree      *ntp_tree, *flags_tree;
252         proto_item      *ti, *tf;
253         guint8          flags;
254         guint8          stratum;
255         guint8          ppoll;
256         gint8           precision;
257         double          rootdelay;
258         double          rootdispersion;
259         const guint8    *refid;
260         guint32         refid_addr;
261         const guint8    *reftime;
262         const guint8    *org;
263         const guint8    *rec;
264         const guint8    *xmt;
265         gchar           buff[NTP_TS_SIZE];
266         int             i;
267
268         if (check_col(pinfo->cinfo, COL_PROTOCOL))
269                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "NTP");
270
271         if (check_col(pinfo->cinfo, COL_INFO))
272                 col_set_str(pinfo->cinfo, COL_INFO, "NTP");
273
274         if (tree) {
275                 /* Adding NTP item and subtree */
276                 ti = proto_tree_add_item(tree, proto_ntp, tvb, 0, -1, FALSE);
277                 ntp_tree = proto_item_add_subtree(ti, ett_ntp);
278
279                 flags = tvb_get_guint8(tvb, 0);
280                 tf = proto_tree_add_uint(ntp_tree, hf_ntp_flags, tvb, 0, 1,
281                     flags);
282
283                 /* Adding flag subtree and items */
284                 flags_tree = proto_item_add_subtree(tf, ett_ntp_flags);
285                 proto_tree_add_uint(flags_tree, hf_ntp_flags_li, tvb, 0, 1,
286                                            flags);
287                 proto_tree_add_uint(flags_tree, hf_ntp_flags_vn, tvb, 0, 1,
288                                            flags);
289                 proto_tree_add_uint(flags_tree, hf_ntp_flags_mode, tvb, 0, 1,
290                                            flags);
291
292                 /* Stratum, 1byte field represents distance from primary source
293                  */
294                 stratum = tvb_get_guint8(tvb, 1);
295                 if (stratum == 0) {
296                         strcpy (buff, "Peer Clock Stratum: unspecified or unavailable (%u)");
297                 } else if (stratum == 1) {
298                         strcpy (buff, "Peer Clock Stratum: primary reference (%u)");
299                 } else if ((stratum >= 2) && (stratum <= 15)) {
300                         strcpy (buff, "Peer Clock Stratum: secondary reference (%u)");
301                 } else {
302                         strcpy (buff, "Peer Clock Stratum: reserved: %u");
303                 }
304                 proto_tree_add_uint_format(ntp_tree, hf_ntp_stratum, tvb, 1, 1,
305                                            stratum, buff, stratum);
306                 /* Poll interval, 1byte field indicating the maximum interval
307                  * between successive messages, in seconds to the nearest
308                  * power of two.
309                  */
310                 ppoll = tvb_get_guint8(tvb, 2);
311                 proto_tree_add_uint_format(ntp_tree, hf_ntp_ppoll, tvb, 2, 1,
312                                            ppoll,
313                                            (((ppoll >= 4) && (ppoll <= 16)) ? 
314                                            "Peer Polling Interval: %u (%u sec)" :
315                                            "Peer Polling Interval: invalid (%u)"),
316                                            ppoll,
317                                            1 << ppoll);
318
319                 /* Precision, 1byte field indicating the precision of the
320                  * local clock, in seconds to the nearest power of two.
321                  */
322                 precision = tvb_get_guint8(tvb, 3);
323                 proto_tree_add_uint_format(ntp_tree, hf_ntp_precision, tvb, 3, 1,
324                                            precision,
325                                            "Peer Clock Precision: %8.6f sec",
326                                            pow(2, precision));
327
328                 /* Root Delay is a 32-bit signed fixed-point number indicating
329                  * the total roundtrip delay to the primary reference source,
330                  * in seconds with fraction point between bits 15 and 16.
331                  */
332                 rootdelay = ((gint16)tvb_get_ntohs(tvb, 4)) +
333                                 (tvb_get_ntohs(tvb, 6) / 65536.0);
334                 proto_tree_add_double_format(ntp_tree, hf_ntp_rootdelay, tvb, 4, 4,
335                                            rootdelay,
336                                            "Root Delay: %9.4f sec",
337                                            rootdelay);
338
339                 /* Root Dispersion, 32-bit unsigned fixed-point number indicating
340                  * the nominal error relative to the primary reference source, in
341                  * seconds with fraction point between bits 15 and 16.
342                  */
343                 rootdispersion = ((gint16)tvb_get_ntohs(tvb, 8)) +
344                                         (tvb_get_ntohs(tvb, 10) / 65536.0);
345                 proto_tree_add_double_format(ntp_tree, hf_ntp_rootdispersion, tvb, 8, 4,
346                                            rootdispersion,
347                                            "Clock Dispersion: %9.4f sec",
348                                            rootdispersion);
349
350                 /* Now, there is a problem with secondary servers.  Standards
351                  * asks from stratum-2 - stratum-15 servers to set this to the
352                  * low order 32 bits of the latest transmit timestamp of the
353                  * reference source.
354                  * But, all V3 and V4 servers set this to IP adress of their
355                  * higher level server. My decision was to resolve this address.
356                  */
357                 refid = tvb_get_ptr(tvb, 12, 4);
358                 if (stratum <= 1) {
359                         snprintf (buff, sizeof buff,
360                             "Unindentified reference source '%.4s'",
361                             refid);
362                         for (i = 0; primary_sources[i].id; i++) {
363                                 if (memcmp (refid, primary_sources[i].id,
364                                     4) == 0) {
365                                         strcpy (buff, primary_sources[i].data);
366                                         break;
367                                 }
368                         }
369                 } else {
370                         buff[sizeof(buff) - 1] = '\0';
371                         tvb_memcpy(tvb, (guint8 *)&refid_addr, 12, 4);
372                         strncpy (buff, get_hostname (refid_addr),
373                             sizeof(buff));
374                         if (buff[sizeof(buff) - 1] != '\0')
375                                 strcpy(&buff[sizeof(buff) - 4], "...");
376                 }
377                 proto_tree_add_bytes_format(ntp_tree, hf_ntp_refid, tvb, 12, 4,
378                                            refid,
379                                            "Reference Clock ID: %s", buff);
380
381                 /* Reference Timestamp: This is the time at which the local clock was
382                  * last set or corrected.
383                  */
384                 reftime = tvb_get_ptr(tvb, 16, 8);
385                 proto_tree_add_bytes_format(ntp_tree, hf_ntp_reftime, tvb, 16, 8,
386                                            reftime,
387                                            "Reference Clock Update Time: %s", 
388                                            ntp_fmt_ts(reftime, buff));
389
390                 /* Originate Timestamp: This is the time at which the request departed
391                  * the client for the server.
392                  */
393                 org = tvb_get_ptr(tvb, 24, 8);
394                 proto_tree_add_bytes_format(ntp_tree, hf_ntp_org, tvb, 24, 8,
395                                            org,
396                                            "Originate Time Stamp: %s", 
397                                            ntp_fmt_ts(org, buff));
398                 /* Receive Timestamp: This is the time at which the request arrived at
399                  * the server.
400                  */
401                 rec = tvb_get_ptr(tvb, 32, 8);
402                 proto_tree_add_bytes_format(ntp_tree, hf_ntp_rec, tvb, 32, 8,
403                                            rec,
404                                            "Receive Time Stamp: %s", 
405                                            ntp_fmt_ts(rec, buff));
406                 /* Transmit Timestamp: This is the time at which the reply departed the
407                  * server for the client.
408                  */
409                 xmt = tvb_get_ptr(tvb, 40, 8);
410                 proto_tree_add_bytes_format(ntp_tree, hf_ntp_xmt, tvb, 40, 8,
411                                            xmt,
412                                            "Transmit Time Stamp: %s", 
413                                            ntp_fmt_ts(xmt, buff));
414
415                 /* When the NTP authentication scheme is implemented, the
416                  * Key Identifier and Message Digest fields contain the
417                  * message authentication code (MAC) information defined in
418                  * Appendix C of RFC-1305. Will print this as hex code for now.
419                  */
420                 if ( tvb_reported_length_remaining(tvb, 48) >= 4 )
421                         proto_tree_add_item(ntp_tree, hf_ntp_keyid, tvb, 48, 4,
422                                            FALSE);
423                 if ( tvb_reported_length_remaining(tvb, 52) > 0 )
424                         proto_tree_add_item(ntp_tree, hf_ntp_mac, tvb, 52,
425                                            tvb_reported_length_remaining(tvb, 52),
426                                            FALSE);
427
428         }
429 }
430
431 void
432 proto_register_ntp(void)
433 {
434         static hf_register_info hf[] = {
435                 { &hf_ntp_flags, {      
436                         "Flags", "ntp.flags", FT_UINT8, BASE_HEX, 
437                         NULL, 0, "Flags (Leap/Version/Mode)", HFILL }},
438                 { &hf_ntp_flags_li, {
439                         "Leap Indicator", "ntp.flags.li", FT_UINT8, BASE_DEC,
440                         VALS(li_types), NTP_LI_MASK, "Leap Indicator", HFILL }},
441                 { &hf_ntp_flags_vn, {
442                         "Version number", "ntp.flags.vn", FT_UINT8, BASE_DEC,
443                         VALS(ver_nums), NTP_VN_MASK, "Version number", HFILL }},
444                 { &hf_ntp_flags_mode, {
445                         "Mode", "ntp.flags.mode", FT_UINT8, BASE_DEC,
446                         VALS(mode_types), NTP_MODE_MASK, "Mode", HFILL }},
447                 { &hf_ntp_stratum, {    
448                         "Peer Clock Stratum", "ntp.stratum", FT_UINT8, BASE_DEC,
449                         NULL, 0, "Peer Clock Stratum", HFILL }},
450                 { &hf_ntp_ppoll, {      
451                         "Peer Polling Interval", "ntp.ppoll", FT_UINT8, BASE_DEC, 
452                         NULL, 0, "Peer Polling Interval", HFILL }},
453                 { &hf_ntp_precision, {  
454                         "Peer Clock Precision", "ntp.precision", FT_UINT8, BASE_DEC, 
455                         NULL, 0, "Peer Clock Precision", HFILL }},
456                 { &hf_ntp_rootdelay, {  
457                         "Root Delay", "ntp.rootdelay", FT_DOUBLE, BASE_DEC,
458                         NULL, 0, "Root Delay", HFILL }},
459                 { &hf_ntp_rootdispersion, {     
460                         "Clock Dispersion", "ntp.rootdispersion", FT_DOUBLE, BASE_DEC, 
461                         NULL, 0, "Clock Dispersion", HFILL }},
462                 { &hf_ntp_refid, {      
463                         "Reference Clock ID", "ntp.refid", FT_BYTES, BASE_NONE, 
464                         NULL, 0, "Reference Clock ID", HFILL }},
465                 { &hf_ntp_reftime, {    
466                         "Reference Clock Update Time", "ntp.reftime", FT_BYTES, BASE_NONE, 
467                         NULL, 0, "Reference Clock Update Time", HFILL }},
468                 { &hf_ntp_org, {        
469                         "Originate Time Stamp", "ntp.org", FT_BYTES, BASE_NONE, 
470                         NULL, 0, "Originate Time Stamp", HFILL }},
471                 { &hf_ntp_rec, {        
472                         "Receive Time Stamp", "ntp.rec", FT_BYTES, BASE_NONE, 
473                         NULL, 0, "Receive Time Stamp", HFILL }},
474                 { &hf_ntp_xmt, {        
475                         "Transmit Time Stamp", "ntp.xmt", FT_BYTES, BASE_NONE, 
476                         NULL, 0, "Transmit Time Stamp", HFILL }},
477                 { &hf_ntp_keyid, {      
478                         "Key ID", "ntp.keyid", FT_BYTES, BASE_HEX, 
479                         NULL, 0, "Key ID", HFILL }},
480                 { &hf_ntp_mac, {        
481                         "Message Authentication Code", "ntp.mac", FT_BYTES, BASE_HEX, 
482                         NULL, 0, "Message Authentication Code", HFILL }},
483         };
484         static gint *ett[] = {
485                 &ett_ntp,
486                 &ett_ntp_flags,
487         };
488
489         proto_ntp = proto_register_protocol("Network Time Protocol", "NTP",
490             "ntp");
491         proto_register_field_array(proto_ntp, hf, array_length(hf));
492         proto_register_subtree_array(ett, array_length(ett));
493 }
494
495 void
496 proto_reg_handoff_ntp(void)
497 {
498         dissector_handle_t ntp_handle;
499
500         ntp_handle = create_dissector_handle(dissect_ntp, proto_ntp);
501         dissector_add("udp.port", UDP_PORT_NTP, ntp_handle);
502         dissector_add("tcp.port", TCP_PORT_NTP, ntp_handle);
503 }