1 #!/local/bin/perl -w--*-perl-*-
3 ;# ntploopstat,v 3.1 1993/07/06 01:09:11 jbj Exp
5 ;# Poll NTP server using NTP mode 7 loopinfo request.
6 ;# Log info and timestamp to file for processing by ntploopwatch.
10 ;# Rainer Pruy Friedrich-Alexander Universitaet Erlangen-Nuernberg
12 ;#################################################################
14 ;# The format written to the logfile is the same as used by xntpd
15 ;# for the loopstats file.
16 ;# This script however allows to gather loop filter statistics from
17 ;# remote servers where you do not have access to the loopstats logfile.
19 ;# Please note: Communication delays affect the accuracy of the
20 ;# timestamps recorded. Effects from these delays will probably
21 ;# not show up, as timestamps are recorded to the second only.
22 ;# (Should have implemented &gettimeofday()..)
25 $0 =~ s!^.*/([^/]+)$!\1!; # beautify script name
27 $ntpserver = 'localhost'; # default host to poll
28 $delay = 60; # default sampling rate
29 ;# keep it shorter than minpoll (=64)
33 ;# handle bug in early ctime distributions
34 $ENV{'TZ'} = 'MET' unless defined($ENV{'TZ'}) || $] > 4.010;
36 if (defined(@ctime'MoY))
38 *MonthName = *ctime'MoY;
42 @MonthName = ('Jan','Feb','Mar','Apr','May','Jun',
43 'Jul','Aug','Sep','Oct','Nov','Dec');
46 ;# this routine can be redefined to point to syslog if necessary
49 return unless $verbose;
55 ;#############################################################
57 ;# process command line
61 $0 [-d<delay>] [-t<timeout>] [-l <logfile>] [-v] [ntpserver]
66 /^-v(\d*)$/ && ($verbose=($1 eq '') ? 1 : $1,1) && next;
69 ($1 ne '') && ($delay = $1,1) && next;
70 @ARGV || die("$0: delay value missing after -d\n$usage");
72 ($delay >= 0) || die("$0: bad delay value \"$delay\"\n$usage");
77 @ARGV || die("$0: logfile missing after -l\n$usage");
81 /^-t(\d*(\.\d*)?)$/ &&
83 ($1 ne '') && ($timeout = $1,1) && next;
84 @ARGV || die("$0: timeout value missing after -t\n$usage\n");
87 die("$0: bad timeout value \"$timeout\"\n$usage");
91 /^-/ && die("$0: unknown option \"$_\"\n$usage");
93 ;# any other argument is server to poll
100 warn("unexpected arguments: ".join(" ",@ARGV).".\n");
101 die("$0: too many servers specified\n$usage");
104 ;# logfile defaults to include server name
105 ;# The name of the current month is appended and
106 ;# the file is opened and closed for each sample.
108 $logfile = "loopstats:$ntpserver." unless defined($logfile);
109 $timeout = 12.0 unless defined($timeout); # wait $timeout seconds for reply
111 $MAX_FAIL = 60; # give up after $MAX_FAIL failed polls
116 if (eval 'require "syscall.ph";')
118 if (defined(&SYS_gettimeofday))
121 ;# gettimeofday(struct timeval *tp,struct timezone *tzp)
122 ;# syntax for gettimeofday syscall
123 ;# tzp = NULL -> undef
125 eval 'sub time { local($tz) = pack("LL",0,0);
126 (&msg("gettimeofday failed: $!\n"),
128 unless syscall(&SYS_gettimeofday,$tz,undef) == 0;
129 local($s,$us) = unpack("LL",$tz);
130 return $s + $us/1000000; }';
135 die("$0: gettimeofday failed: $@.\n") if defined($@) && $@;
136 die("$0: gettimeofday inconsistency time=$t1,gettimeofday=$t2,time=$t2\n")
137 if (int($t1) != int($t2) && int($t3) != int($t2));
138 &msg("Using gettimeofday for timestamps\n");
142 warn("No gettimeofday syscall found - using time builtin for timestamps\n");
143 eval 'sub time { return time; }';
148 warn("No syscall.ph file found - using time builtin for timestamps\n");
149 eval 'sub time { return time; }';
153 ;#------------------+
154 ;# from ntp_request.h
155 ;#------------------+
157 ;# NTP mode 7 packet format:
158 ;# Byte 1: ResponseBit MoreBit Version(3bit) Mode(3bit)==7
159 ;# Byte 2: AuthBit Sequence # - 0 - 127 see MoreBit
160 ;# Byte 3: Implementation #
161 ;# Byte 4: Request Code
163 ;# Short 1: Err(3bit) NumItems(12bit)
164 ;# Short 2: MBZ(3bit)=0 DataItemSize(12bit)
166 ;# if AuthBit is set:
175 ;# request packet for REQ_LOOP_INFO:
176 ;# B1: RB=0 MB=0 V=2 M=7
178 ;# B3: I# = IMPL_XNTPD
179 ;# B4: RC = REQ_LOOP_INFO
182 ;# data: 32 byte 0 padding
183 ;# 8byte timestamp if encryption, 0 padding otherwise
185 pack("CCCC nn x32 x8", 0x17, 0, $IMPL_XNTPD, $REQ_LOOP_INFO, 0, 0);
187 ;# ignore any auth data in packets
188 $loopinfo_response_size =
189 1+1+1+1+2+2 # header size like request pkt
190 + 8 # l_fp last_offset
191 + 8 # l_fp drift_comp
192 + 4 # u_long compliance
193 + 4 # u_long watchdog_timer
195 $loopinfo_response_fmt = "C4n2N2N2NN";
196 $loopinfo_response_fmt_v2 = "C4n2N2N2N2N";
199 ;# prepare connection to server
202 ;# workaround for broken socket.ph on dynix_ptx
203 eval 'sub INTEL {1;}' unless defined(&INTEL);
204 eval 'sub ATT {1;}' unless defined(&ATT);
206 require "sys/socket.ph";
208 require 'netinet/in.ph';
210 ;# if you do not have netinet/in.ph enable the following lines
211 ;#eval 'sub INADDR_ANY { 0x00000000; }' unless defined(&INADDR_ANY);
212 ;#eval 'sub IPPRORO_UDP { 17; }' unless defined(&IPPROTO_UDP);
214 if ($ntpserver =~ /^((0x?)?\w+)\.((0x?)?\w+)\.((0x?)?\w+)\.((0x?)?\w+)$/)
216 local($a,$b,$c,$d) = ($1,$3,$5,$7);
217 $a = oct($a) if defined($2);
218 $b = oct($b) if defined($4);
219 $c = oct($c) if defined($6);
220 $d = oct($d) if defined($8);
221 $server_addr = pack("C4", $a,$b,$c,$d);
224 = (gethostbyaddr($server_addr,&AF_INET))[$[] || $ntpserver;
228 ($server_mainname,$server_addr)
229 = (gethostbyname($ntpserver))[$[,$[+4];
231 die("$0: host \"$ntpserver\" is unknown\n")
232 unless defined($server_addr);
234 &msg ("Address of server \"$ntpserver\" is \"%d.%d.%d.%d\"\n",
235 unpack("C4",$server_addr));
237 $proto_udp = (getprotobyname('udp'))[$[+2] || &IPPROTO_UDP;
240 (getservbyname('ntp','udp'))[$[+2] ||
241 (warn "Could not get port number for service \"ntp/udp\" using 123\n"),
245 0 && &SOCK_DGRAM; # satisfy perl -w ...
246 socket(S, &AF_INET, &SOCK_DGRAM, $proto_udp) ||
247 die("Cannot open socket: $!\n");
249 bind(S, pack("S n N x8", &AF_INET, 0, &INADDR_ANY)) ||
250 die("Cannot bind: $!\n");
252 ($my_port, $my_addr) = (unpack("S n a4 x8",getsockname(S)))[$[+1,$[+2];
254 &msg("Listening at address %d.%d.%d.%d port %d\n",
255 unpack("C4",$my_addr), $my_port);
257 $server_inaddr = pack("Sna4x8", &AF_INET, $ntp_port, $server_addr);
259 ;############################################################
264 ;# wait til next sample time
273 &msg("Sending request $stime...\n");
275 $ret = send(S,$loopinfo_reqpkt,0,$server_inaddr);
277 if (! defined($ret) || $ret < length($loopinfo_reqpkt))
279 warn("$0: send failed ret=($ret): $!\n");
284 &msg("Waiting for reply...\n");
286 $mask = ""; vec($mask,fileno(S),1) = 1;
287 $ret = select($mask,undef,undef,$timeout);
291 warn("$0: select failed: $!\n");
297 warn("$0: request to $ntpserver timed out ($timeout seconds)\n");
298 ;# do not count this event as failure
299 ;# it usually this happens due to dropped udp packets on noisy and
300 ;# havily loaded lines, so just try again;
305 &msg("Receiving reply...\n");
307 $len = 520; # max size of a mode 7 packet
308 $reply = ""; # just make it defined for -w
309 $ret = recv(S,$reply,$len,0);
313 warn("$0: recv failed: $!\n");
319 &msg("Received at\t$etime\n");
321 ;#$time = ($stime + $etime) / 2; # symmetric delay assumed
322 $time = $etime; # the above assumption breaks for X25
323 ;# so taking etime makes timestamps be a
324 ;# little late, but keeps them increasing
327 &msg(sprintf("Reply from %d.%d.%d.%d took %f seconds\n",
328 (unpack("SnC4",$ret))[$[+2 .. $[+5], ($etime - $stime)));
330 if ($len < $loopinfo_response_size)
332 warn("$0: short packet ($len bytes) received ($loopinfo_response_size bytes expected\n");
337 ($b1,$b2,$b3,$b4,$s1,$s2,
338 $offset_i,$offset_f,$drift_i,$drift_f,$compl,$watchdog)
339 = unpack($loopinfo_response_fmt,$reply);
342 if (($s1 >> 12) != 0) # error !
344 die("$0: got error reply ".($s1>>12)."\n");
346 if (($b1 != 0x97 && $b1 != 0x9f) || # Reply NotMore V=2 M=7
347 ($b2 != 0 && $b2 != 0x80) || # S=0 Auth no/yes
348 $b3 != $IMPL_XNTPD || # ! IMPL_XNTPD
349 $b4 != $REQ_LOOP_INFO || # Ehh.. not loopinfo reply ?
351 ($s2 != 24 && $s2 != 28) #
354 warn("$0: Bad/unexpected reply from server:\n");
355 warn(" \"".unpack("H*",$reply)."\"\n");
356 warn(" ".sprintf("b1=%x b2=%x b3=%x b4=%x s1=%d s2=%d\n",
357 $b1,$b2,$b3,$b4,$s1,$s2));
363 ;# seems to be a version 2 xntpd
364 ($b1,$b2,$b3,$b4,$s1,$s2,
365 $offset_i,$offset_f,$drift_i,$drift_f,$compl_i,$compl_f,$watchdog)
366 = unpack($loopinfo_response_fmt_v2,$reply);
367 $compl = &lfptoa($compl_i, $compl_f);
372 $offset = &lfptoa($offset_i, $offset_f);
373 $drift = &lfptoa($drift_i, $drift_f);
375 &log($time,$offset,$drift,$compl) && ($fail = 0);;
379 die("$0: Too many failures - terminating\n") if $fail > $MAX_FAIL;
380 &msg("Sleeping " . ($lostpacket ? ($delay / 2) : $delay) . " seconds...\n");
382 sleep($lostpacket ? ($delay / 2) : $delay);
388 local($time,$offs,$freq,$cmpl) = @_;
390 local($fname,$suff) = ($logfile);
393 ;# silently drop sample if distance to last sample is too low
394 if (defined($lasttime) && ($lasttime + 2) >= $time)
396 &msg("Dropped packet - old sample\n");
400 ;# $suff determines which samples end up in the same file
401 ;# could have used $year (;-) or WeekOfYear, DayOfYear,....
402 ;# Change it to your suit...
404 ($d,$m,$y) = (localtime($time))[$[+3 .. $[+5];
405 $suff = sprintf("%04d%02d%02d",$y+1900,$m+1,$d);
407 if (!open(LOG,">>$fname"))
409 warn("$0: open($fname) failed: $!\n");
416 ;# MJD seconds offset drift compliance
417 printf LOG ("%d %.3lf %.8lf %.7lf %d\n",
418 int($time/86400)+$MJD_1970,
419 $time - int($time/86400) * 86400,
427 ;# see ntp_fp.h to understand this
444 $i += 1; # 2s complement
447 ;#print "NEG: $i $f\n";
451 ;#print "POS: $i $f\n";
453 ;# unlike xntpd I have perl do the dirty work.
454 ;# Using floats here may affect precision, but
455 ;# currently these bits aren't significant anyway
456 return $sign * ($i + $f/2**32);