Generally use NULL instead of explicitly casting 0 to some pointer type.
[dragonfly.git] / usr.sbin / timed / timedc / cmds.c
1 /*-
2  * Copyright (c) 1985, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#)cmds.c   8.1 (Berkeley) 6/6/93
34  * $FreeBSD: src/usr.sbin/timed/timedc/cmds.c,v 1.6.2.2 2001/08/31 08:02:06 kris Exp $
35  * $DragonFly: src/usr.sbin/timed/timedc/cmds.c,v 1.4 2004/12/18 22:48:14 swildner Exp $
36  */
37
38 #include "timedc.h"
39 #include <sys/file.h>
40
41 #include <netinet/in_systm.h>
42 #include <netinet/ip.h>
43 #include <netinet/ip_icmp.h>
44
45 #include <err.h>
46 #include <stdlib.h>
47 #include <strings.h>
48 #include <unistd.h>
49
50 #define TSPTYPES
51 #include <protocols/timed.h>
52
53 #ifdef sgi
54 #include <bstring.h>
55 #include <sys/clock.h>
56 #else
57 #define SECHR   (60*60)
58 #define SECDAY  (24*SECHR)
59 #endif /* sgi */
60
61 # define DATE_PROTO "udp"
62 # define DATE_PORT "time"
63
64
65 int sock;
66 int sock_raw;
67 char myname[MAXHOSTNAMELEN];
68 struct hostent *hp;
69 struct sockaddr_in server;
70 struct sockaddr_in dayaddr;
71 extern int measure_delta;
72
73 void bytenetorder(struct tsp *);
74 void bytehostorder(struct tsp *);
75
76
77 #define BU (2208988800UL)       /* seconds before UNIX epoch */
78
79
80 /* compute the difference between our date and another machine
81  */
82 static int                              /* difference in days from our time */
83 daydiff(char *hostname)
84 {
85         int i;
86         int trials;
87         struct timeval tout, now;
88         fd_set ready;
89         struct sockaddr from;
90         int fromlen;
91         unsigned long sec;
92
93         /* wait 2 seconds between 10 tries */
94         tout.tv_sec = 2;
95         tout.tv_usec = 0;
96         for (trials = 0; trials < 10; trials++) {
97                 /* ask for the time */
98                 sec = 0;
99                 if (sendto(sock, &sec, sizeof(sec), 0,
100                            (struct sockaddr*)&dayaddr, sizeof(dayaddr)) < 0) {
101                         warn("sendto(sock)");
102                         return 0;
103                 }
104
105                 for (;;) {
106                         FD_ZERO(&ready);
107                         FD_SET(sock, &ready);
108                         i = select(sock+1, &ready, NULL, NULL, &tout);
109                         if (i < 0) {
110                                 if (errno == EINTR)
111                                         continue;
112                                 warn("select(date read)");
113                                 return 0;
114                         }
115                         if (0 == i)
116                                 break;
117
118                         fromlen = sizeof(from);
119                         if (recvfrom(sock,&sec,sizeof(sec),0,
120                                      &from,&fromlen) < 0) {
121                                 warn("recvfrom(date read)");
122                                 return 0;
123                         }
124
125                         sec = ntohl(sec);
126                         if (sec < BU) {
127                                 warnx("%s says it is before 1970: %lu",
128                                         hostname, sec);
129                                 return 0;
130                         }
131                         sec -= BU;
132
133                         gettimeofday(&now, NULL);
134                         return (sec - now.tv_sec);
135                 }
136         }
137
138         /* if we get here, we tried too many times */
139         warnx("%s will not tell us the date", hostname);
140         return 0;
141 }
142
143
144 /*
145  * Clockdiff computes the difference between the time of the machine on
146  * which it is called and the time of the machines given as argument.
147  * The time differences measured by clockdiff are obtained using a sequence
148  * of ICMP TSTAMP messages which are returned to the sender by the IP module
149  * in the remote machine.
150  * In order to compare clocks of machines in different time zones, the time
151  * is transmitted (as a 32-bit value) in milliseconds since midnight UT.
152  * If a hosts uses a different time format, it should set the high order
153  * bit of the 32-bit quantity it transmits.
154  * However, VMS apparently transmits the time in milliseconds since midnight
155  * local time (rather than GMT) without setting the high order bit.
156  * Furthermore, it does not understand daylight-saving time.  This makes
157  * clockdiff behaving inconsistently with hosts running VMS.
158  *
159  * In order to reduce the sensitivity to the variance of message transmission
160  * time, clockdiff sends a sequence of messages.  Yet, measures between
161  * two `distant' hosts can be affected by a small error. The error can,
162  * however, be reduced by increasing the number of messages sent in each
163  * measurement.
164  */
165 void
166 clockdiff(int argc, char *argv[])
167 {
168         int measure_status;
169         extern int measure(u_long, u_long, char *, struct sockaddr_in*, int);
170         int avg_cnt;
171         long avg;
172         struct servent *sp;
173
174         if (argc < 2)  {
175                 printf("usage: timedc clockdiff host ...\n");
176                 return;
177         }
178
179         if (gethostname(myname, sizeof(myname) - 1) < 0)
180                 err(1, "gethostname");
181
182         /* get the address for the date ready */
183         sp = getservbyname(DATE_PORT, DATE_PROTO);
184         if (!sp) {
185                 warnx("%s/%s is an unknown service", DATE_PORT, DATE_PROTO);
186                 dayaddr.sin_port = 0;
187         } else {
188                 dayaddr.sin_port = sp->s_port;
189         }
190
191         while (argc > 1) {
192                 argc--; argv++;
193                 hp = gethostbyname(*argv);
194                 if (hp == NULL) {
195                         warnx("%s: %s", *argv, hstrerror(h_errno));
196                         continue;
197                 }
198
199                 server.sin_family = hp->h_addrtype;
200                 bcopy(hp->h_addr, &server.sin_addr.s_addr, hp->h_length);
201                 for (avg_cnt = 0, avg = 0; avg_cnt < 16; avg_cnt++) {
202                         measure_status = measure(10000,100, *argv, &server, 1);
203                         if (measure_status != GOOD)
204                                 break;
205                         avg += measure_delta;
206                 }
207                 if (measure_status == GOOD)
208                         measure_delta = avg/avg_cnt;
209
210                 switch (measure_status) {
211                 case HOSTDOWN:
212                         printf("%s is down\n", hp->h_name);
213                         continue;
214                 case NONSTDTIME:
215                         printf("%s transmitts a non-standard time format\n",
216                                hp->h_name);
217                         continue;
218                 case UNREACHABLE:
219                         printf("%s is unreachable\n", hp->h_name);
220                         continue;
221                 }
222
223                 /*
224                  * Try to get the date only after using ICMP timestamps to
225                  * get the time.  This is because the date protocol
226                  * is optional.
227                  */
228                 if (dayaddr.sin_port != 0) {
229                         dayaddr.sin_family = hp->h_addrtype;
230                         bcopy(hp->h_addr, &dayaddr.sin_addr.s_addr,
231                               hp->h_length);
232                         avg = daydiff(*argv);
233                         if (avg > SECDAY) {
234                                 printf("time on %s is %ld days ahead %s\n",
235                                        hp->h_name, avg/SECDAY, myname);
236                                 continue;
237                         } else if (avg < -SECDAY) {
238                                 printf("time on %s is %ld days behind %s\n",
239                                        hp->h_name, -avg/SECDAY, myname);
240                                 continue;
241                         }
242                 }
243
244                 if (measure_delta > 0) {
245                         printf("time on %s is %d ms. ahead of time on %s\n",
246                                hp->h_name, measure_delta, myname);
247                 } else if (measure_delta == 0) {
248                         printf("%s and %s have the same time\n",
249                                hp->h_name, myname);
250                 } else {
251                         printf("time on %s is %d ms. behind time on %s\n",
252                                hp->h_name, -measure_delta, myname);
253                 }
254         }
255         return;
256 }
257
258
259 /*
260  * finds location of master timedaemon
261  */
262 void
263 msite(int argc, char *argv[])
264 {
265         int cc;
266         fd_set ready;
267         struct sockaddr_in dest;
268         int i, length;
269         struct sockaddr_in from;
270         struct timeval tout;
271         struct tsp msg;
272         struct servent *srvp;
273         char *tgtname;
274
275         if (argc < 1) {
276                 printf("usage: timedc msite [host ...]\n");
277                 return;
278         }
279
280         srvp = getservbyname("timed", "udp");
281         if (srvp == 0) {
282                 warnx("udp/timed: unknown service");
283                 return;
284         }
285         dest.sin_port = srvp->s_port;
286         dest.sin_family = AF_INET;
287
288         if (gethostname(myname, sizeof(myname) - 1) < 0)
289                 err(1, "gethostname");
290         i = 1;
291         do {
292                 tgtname = (i >= argc) ? myname : argv[i];
293                 hp = gethostbyname(tgtname);
294                 if (hp == 0) {
295                         warnx("%s: %s", tgtname, hstrerror(h_errno));
296                         continue;
297                 }
298                 bcopy(hp->h_addr, &dest.sin_addr.s_addr, hp->h_length);
299
300                 strlcpy(msg.tsp_name, myname, sizeof(msg.tsp_name));
301                 msg.tsp_type = TSP_MSITE;
302                 msg.tsp_vers = TSPVERSION;
303                 bytenetorder(&msg);
304                 if (sendto(sock, &msg, sizeof(struct tsp), 0,
305                            (struct sockaddr*)&dest,
306                            sizeof(struct sockaddr)) < 0) {
307                         warn("sendto");
308                         continue;
309                 }
310
311                 tout.tv_sec = 15;
312                 tout.tv_usec = 0;
313                 FD_ZERO(&ready);
314                 FD_SET(sock, &ready);
315                 if (select(FD_SETSIZE, &ready, NULL, NULL, &tout)) {
316                         length = sizeof(from);
317                         cc = recvfrom(sock, &msg, sizeof(struct tsp), 0,
318                                       (struct sockaddr *)&from, &length);
319                         if (cc < 0) {
320                                 warn("recvfrom");
321                                 continue;
322                         }
323                         /*
324                          * The 4.3BSD protocol spec had a 32-byte tsp_name field, and
325                          * this is still OS-dependent.  Demand that the packet is at
326                          * least long enough to hold a 4.3BSD packet.
327                          */
328                         if (cc < (sizeof(struct tsp) - MAXHOSTNAMELEN + 32)) {
329                                 fprintf(stderr, 
330                                    "short packet (%u/%u bytes) from %s\n",
331                                    cc, sizeof(struct tsp) - MAXHOSTNAMELEN + 32,
332                                    inet_ntoa(from.sin_addr));
333                                 continue;
334                         }
335                         bytehostorder(&msg);
336                         if (msg.tsp_type == TSP_ACK) {
337                                 printf("master timedaemon at %s is %s\n",
338                                        tgtname, msg.tsp_name);
339                         } else {
340                                 if (msg.tsp_type >= TSPTYPENUMBER)
341                                         printf("unknown ack received: %u\n",
342                                                 msg.tsp_type);
343                                 else    
344                                         printf("wrong ack received: %s\n",
345                                                 tsptype[msg.tsp_type]);
346                         }
347                 } else {
348                         printf("communication error with %s\n", tgtname);
349                 }
350         } while (++i < argc);
351 }
352
353 /*
354  * quits timedc
355  */
356 void
357 quit(void)
358 {
359
360         exit(0);
361 }
362
363
364 /*
365  * Causes the election timer to expire on the selected hosts
366  * It sends just one udp message per machine, relying on
367  * reliability of communication channel.
368  */
369 void
370 testing(int argc, char *argv[])
371 {
372         struct servent *srvp;
373         struct sockaddr_in sin;
374         struct tsp msg;
375
376         if (argc < 2)  {
377                 printf("usage: timedc election host1 [host2 ...]\n");
378                 return;
379         }
380
381         srvp = getservbyname("timed", "udp");
382         if (srvp == 0) {
383                 warnx("udp/timed: unknown service");
384                 return;
385         }
386
387         while (argc > 1) {
388                 argc--; argv++;
389                 hp = gethostbyname(*argv);
390                 if (hp == NULL) {
391                         warnx("%s: %s", *argv, hstrerror(h_errno));
392                         argc--; argv++;
393                         continue;
394                 }
395                 sin.sin_port = srvp->s_port;
396                 sin.sin_family = hp->h_addrtype;
397                 bcopy(hp->h_addr, &sin.sin_addr.s_addr, hp->h_length);
398
399                 msg.tsp_type = TSP_TEST;
400                 msg.tsp_vers = TSPVERSION;
401                 if (gethostname(myname, sizeof(myname) - 1) < 0)
402                         err(1, "gethostname");
403                 strlcpy(msg.tsp_name, myname, sizeof(msg.tsp_name));
404                 bytenetorder(&msg);
405                 if (sendto(sock, &msg, sizeof(struct tsp), 0,
406                            (struct sockaddr*)&sin,
407                            sizeof(struct sockaddr)) < 0) {
408                         warn("sendto");
409                 }
410         }
411 }
412
413
414 /*
415  * Enables or disables tracing on local timedaemon
416  */
417 void
418 tracing(int argc, char *argv[])
419 {
420         int onflag;
421         int length;
422         int cc;
423         fd_set ready;
424         struct sockaddr_in dest;
425         struct sockaddr_in from;
426         struct timeval tout;
427         struct tsp msg;
428         struct servent *srvp;
429
430         if (argc != 2) {
431                 printf("usage: timedc trace { on | off }\n");
432                 return;
433         }
434
435         srvp = getservbyname("timed", "udp");
436         if (srvp == 0) {
437                 warnx("udp/timed: unknown service");
438                 return;
439         }
440         dest.sin_port = srvp->s_port;
441         dest.sin_family = AF_INET;
442
443         if (gethostname(myname, sizeof(myname) - 1) < 0)
444                 err(1, "gethostname");
445         hp = gethostbyname(myname);
446         bcopy(hp->h_addr, &dest.sin_addr.s_addr, hp->h_length);
447
448         if (strcmp(argv[1], "on") == 0) {
449                 msg.tsp_type = TSP_TRACEON;
450                 onflag = ON;
451         } else {
452                 msg.tsp_type = TSP_TRACEOFF;
453                 onflag = OFF;
454         }
455
456         strcpy(msg.tsp_name, myname);
457         msg.tsp_vers = TSPVERSION;
458         bytenetorder(&msg);
459         if (sendto(sock, &msg, sizeof(struct tsp), 0,
460                    (struct sockaddr*)&dest, sizeof(struct sockaddr)) < 0) {
461                 warn("sendto");
462                 return;
463         }
464
465         tout.tv_sec = 5;
466         tout.tv_usec = 0;
467         FD_ZERO(&ready);
468         FD_SET(sock, &ready);
469         if (select(FD_SETSIZE, &ready, NULL, NULL, &tout)) {
470                 length = sizeof(from);
471                 cc = recvfrom(sock, &msg, sizeof(struct tsp), 0,
472                               (struct sockaddr *)&from, &length);
473                 if (cc < 0) {
474                         warn("recvfrom");
475                         return;
476                 }
477                 /*
478                  * The 4.3BSD protocol spec had a 32-byte tsp_name field, and
479                  * this is still OS-dependent.  Demand that the packet is at
480                  * least long enough to hold a 4.3BSD packet.
481                  */
482                 if (cc < (sizeof(struct tsp) - MAXHOSTNAMELEN + 32)) {
483                         fprintf(stderr, "short packet (%u/%u bytes) from %s\n",
484                             cc, sizeof(struct tsp) - MAXHOSTNAMELEN + 32,
485                             inet_ntoa(from.sin_addr));
486                         return;
487                 }
488                 bytehostorder(&msg);
489                 if (msg.tsp_type == TSP_ACK)
490                         if (onflag)
491                                 printf("timed tracing enabled\n");
492                         else
493                                 printf("timed tracing disabled\n");
494                 else {
495                         if (msg.tsp_type >= TSPTYPENUMBER)
496                                 printf("unknown ack received: %u\n",
497                                         msg.tsp_type);
498                         else    
499                                 printf("wrong ack received: %s\n",
500                                                 tsptype[msg.tsp_type]);
501                 }
502         } else
503                 printf("communication error\n");
504 }
505
506 int
507 priv_resources(void)
508 {
509         int port;
510         struct sockaddr_in sin;
511
512         sock = socket(AF_INET, SOCK_DGRAM, 0);
513         if (sock < 0) {
514                 warn("opening socket");
515                 return(-1);
516         }
517
518         sin.sin_family = AF_INET;
519         sin.sin_addr.s_addr = 0;
520         for (port = IPPORT_RESERVED - 1; port > IPPORT_RESERVED / 2; port--) {
521                 sin.sin_port = htons((u_short)port);
522                 if (bind(sock, (struct sockaddr*)&sin, sizeof (sin)) >= 0)
523                         break;
524                 if (errno != EADDRINUSE && errno != EADDRNOTAVAIL) {
525                         warn("bind");
526                         close(sock);
527                         return(-1);
528                 }
529         }
530         if (port == IPPORT_RESERVED / 2) {
531                 warnx("all reserved ports in use");
532                 close(sock);
533                 return(-1);
534         }
535
536         sock_raw = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
537         if (sock_raw < 0)  {
538                 warn("opening raw socket");
539                 close(sock);
540                 return(-1);
541         }
542         return(1);
543 }