2 * ntpq-subs.c - subroutines which are called to perform ntpq commands.
11 #include "ntpq-opts.h"
13 extern char currenthost[];
14 extern int currenthostisnum;
18 * Declarations for command handlers in here
20 static associd_t checkassocid (u_int32);
21 static struct varlist *findlistvar (struct varlist *, char *);
22 static void doaddvlist (struct varlist *, const char *);
23 static void dormvlist (struct varlist *, const char *);
24 static void doclearvlist (struct varlist *);
25 static void makequerydata (struct varlist *, size_t *, char *);
26 static int doquerylist (struct varlist *, int, associd_t, int,
27 u_short *, size_t *, const char **);
28 static void doprintvlist (struct varlist *, FILE *);
29 static void addvars (struct parse *, FILE *);
30 static void rmvars (struct parse *, FILE *);
31 static void clearvars (struct parse *, FILE *);
32 static void showvars (struct parse *, FILE *);
33 static int dolist (struct varlist *, associd_t, int, int,
35 static void readlist (struct parse *, FILE *);
36 static void writelist (struct parse *, FILE *);
37 static void readvar (struct parse *, FILE *);
38 static void writevar (struct parse *, FILE *);
39 static void clocklist (struct parse *, FILE *);
40 static void clockvar (struct parse *, FILE *);
41 static int findassidrange (u_int32, u_int32, int *, int *,
43 static void mreadlist (struct parse *, FILE *);
44 static void mreadvar (struct parse *, FILE *);
45 static void printassoc (int, FILE *);
46 static void associations (struct parse *, FILE *);
47 static void lassociations (struct parse *, FILE *);
48 static void passociations (struct parse *, FILE *);
49 static void lpassociations (struct parse *, FILE *);
52 static void radiostatus (struct parse *, FILE *);
55 static void authinfo (struct parse *, FILE *);
56 static void pstats (struct parse *, FILE *);
57 static long when (l_fp *, l_fp *, l_fp *);
58 static char * prettyinterval (char *, size_t, long);
59 static int doprintpeers (struct varlist *, int, int, size_t, const char *, FILE *, int);
60 static int dogetpeers (struct varlist *, associd_t, FILE *, int);
61 static void dopeers (int, FILE *, int);
62 static void peers (struct parse *, FILE *);
63 static void doapeers (int, FILE *, int);
64 static void apeers (struct parse *, FILE *);
65 static void lpeers (struct parse *, FILE *);
66 static void doopeers (int, FILE *, int);
67 static void opeers (struct parse *, FILE *);
68 static void lopeers (struct parse *, FILE *);
69 static void config (struct parse *, FILE *);
70 static void saveconfig (struct parse *, FILE *);
71 static void config_from_file(struct parse *, FILE *);
72 static void mrulist (struct parse *, FILE *);
73 static void ifstats (struct parse *, FILE *);
74 static void reslist (struct parse *, FILE *);
75 static void sysstats (struct parse *, FILE *);
76 static void sysinfo (struct parse *, FILE *);
77 static void kerninfo (struct parse *, FILE *);
78 static void monstats (struct parse *, FILE *);
79 static void iostats (struct parse *, FILE *);
80 static void timerstats (struct parse *, FILE *);
83 * Commands we understand. Ntpdc imports this.
85 struct xcmd opcmds[] = {
86 { "saveconfig", saveconfig, { NTP_STR, NO, NO, NO },
87 { "filename", "", "", ""},
88 "save ntpd configuration to file, . for current config file"},
89 { "associations", associations, { NO, NO, NO, NO },
91 "print list of association ID's and statuses for the server's peers" },
92 { "passociations", passociations, { NO, NO, NO, NO },
94 "print list of associations returned by last associations command" },
95 { "lassociations", lassociations, { NO, NO, NO, NO },
97 "print list of associations including all client information" },
98 { "lpassociations", lpassociations, { NO, NO, NO, NO },
100 "print last obtained list of associations, including client information" },
101 { "addvars", addvars, { NTP_STR, NO, NO, NO },
102 { "name[=value][,...]", "", "", "" },
103 "add variables to the variable list or change their values" },
104 { "rmvars", rmvars, { NTP_STR, NO, NO, NO },
105 { "name[,...]", "", "", "" },
106 "remove variables from the variable list" },
107 { "clearvars", clearvars, { NO, NO, NO, NO },
109 "remove all variables from the variable list" },
110 { "showvars", showvars, { NO, NO, NO, NO },
112 "print variables on the variable list" },
113 { "readlist", readlist, { OPT|NTP_UINT, NO, NO, NO },
114 { "assocID", "", "", "" },
115 "read the system or peer variables included in the variable list" },
116 { "rl", readlist, { OPT|NTP_UINT, NO, NO, NO },
117 { "assocID", "", "", "" },
118 "read the system or peer variables included in the variable list" },
119 { "writelist", writelist, { OPT|NTP_UINT, NO, NO, NO },
120 { "assocID", "", "", "" },
121 "write the system or peer variables included in the variable list" },
122 { "readvar", readvar, { OPT|NTP_UINT, OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR, },
123 { "assocID", "varname1", "varname2", "varname3" },
124 "read system or peer variables" },
125 { "rv", readvar, { OPT|NTP_UINT, OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR, },
126 { "assocID", "varname1", "varname2", "varname3" },
127 "read system or peer variables" },
128 { "writevar", writevar, { NTP_UINT, NTP_STR, NO, NO },
129 { "assocID", "name=value,[...]", "", "" },
130 "write system or peer variables" },
131 { "mreadlist", mreadlist, { NTP_UINT, NTP_UINT, NO, NO },
132 { "assocIDlow", "assocIDhigh", "", "" },
133 "read the peer variables in the variable list for multiple peers" },
134 { "mrl", mreadlist, { NTP_UINT, NTP_UINT, NO, NO },
135 { "assocIDlow", "assocIDhigh", "", "" },
136 "read the peer variables in the variable list for multiple peers" },
137 { "mreadvar", mreadvar, { NTP_UINT, NTP_UINT, OPT|NTP_STR, NO },
138 { "assocIDlow", "assocIDhigh", "name=value[,...]", "" },
139 "read peer variables from multiple peers" },
140 { "mrv", mreadvar, { NTP_UINT, NTP_UINT, OPT|NTP_STR, NO },
141 { "assocIDlow", "assocIDhigh", "name=value[,...]", "" },
142 "read peer variables from multiple peers" },
143 { "clocklist", clocklist, { OPT|NTP_UINT, NO, NO, NO },
144 { "assocID", "", "", "" },
145 "read the clock variables included in the variable list" },
146 { "cl", clocklist, { OPT|NTP_UINT, NO, NO, NO },
147 { "assocID", "", "", "" },
148 "read the clock variables included in the variable list" },
149 { "clockvar", clockvar, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
150 { "assocID", "name=value[,...]", "", "" },
151 "read clock variables" },
152 { "cv", clockvar, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
153 { "assocID", "name=value[,...]", "", "" },
154 "read clock variables" },
155 { "pstats", pstats, { NTP_UINT, NO, NO, NO },
156 { "assocID", "", "", "" },
157 "show statistics for a peer" },
158 { "peers", peers, { OPT|IP_VERSION, NO, NO, NO },
159 { "-4|-6", "", "", "" },
160 "obtain and print a list of the server's peers [IP version]" },
161 { "apeers", apeers, { OPT|IP_VERSION, NO, NO, NO },
162 { "-4|-6", "", "", "" },
163 "obtain and print a list of the server's peers and their assocIDs [IP version]" },
164 { "lpeers", lpeers, { OPT|IP_VERSION, NO, NO, NO },
165 { "-4|-6", "", "", "" },
166 "obtain and print a list of all peers and clients [IP version]" },
167 { "opeers", opeers, { OPT|IP_VERSION, NO, NO, NO },
168 { "-4|-6", "", "", "" },
169 "print peer list the old way, with dstadr shown rather than refid [IP version]" },
170 { "lopeers", lopeers, { OPT|IP_VERSION, NO, NO, NO },
171 { "-4|-6", "", "", "" },
172 "obtain and print a list of all peers and clients showing dstadr [IP version]" },
173 { ":config", config, { NTP_STR, NO, NO, NO },
174 { "<configuration command line>", "", "", "" },
175 "send a remote configuration command to ntpd" },
176 { "config-from-file", config_from_file, { NTP_STR, NO, NO, NO },
177 { "<configuration filename>", "", "", "" },
178 "configure ntpd using the configuration filename" },
179 { "mrulist", mrulist, { OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR },
180 { "tag=value", "tag=value", "tag=value", "tag=value" },
181 "display the list of most recently seen source addresses, tags mincount=... resall=0x... resany=0x..." },
182 { "ifstats", ifstats, { NO, NO, NO, NO },
184 "show statistics for each local address ntpd is using" },
185 { "reslist", reslist, { NO, NO, NO, NO },
187 "show ntpd access control list" },
188 { "sysinfo", sysinfo, { NO, NO, NO, NO },
190 "display system summary" },
191 { "kerninfo", kerninfo, { NO, NO, NO, NO },
193 "display kernel loop and PPS statistics" },
194 { "sysstats", sysstats, { NO, NO, NO, NO },
196 "display system uptime and packet counts" },
197 { "monstats", monstats, { NO, NO, NO, NO },
199 "display monitor (mrulist) counters and limits" },
200 { "authinfo", authinfo, { NO, NO, NO, NO },
202 "display symmetric authentication counters" },
203 { "iostats", iostats, { NO, NO, NO, NO },
205 "display network input and output counters" },
206 { "timerstats", timerstats, { NO, NO, NO, NO },
208 "display interval timer counters" },
209 { 0, 0, { NO, NO, NO, NO },
210 { "-4|-6", "", "", "" }, "" }
215 * Variable list data space
217 #define MAXLINE 512 /* maximum length of a line */
218 #define MAXLIST 128 /* maximum variables in list */
219 #define LENHOSTNAME 256 /* host name limit */
221 #define MRU_GOT_COUNT 0x1
222 #define MRU_GOT_LAST 0x2
223 #define MRU_GOT_FIRST 0x4
224 #define MRU_GOT_MV 0x8
225 #define MRU_GOT_RS 0x10
226 #define MRU_GOT_ADDR 0x20
227 #define MRU_GOT_ALL (MRU_GOT_COUNT | MRU_GOT_LAST | MRU_GOT_FIRST \
228 | MRU_GOT_MV | MRU_GOT_RS | MRU_GOT_ADDR)
231 * mrulist() depends on MRUSORT_DEF and MRUSORT_RDEF being the first two
233 typedef enum mru_sort_order_tag {
234 MRUSORT_DEF = 0, /* lstint ascending */
235 MRUSORT_R_DEF, /* lstint descending */
236 MRUSORT_AVGINT, /* avgint ascending */
237 MRUSORT_R_AVGINT, /* avgint descending */
238 MRUSORT_ADDR, /* IPv4 asc. then IPv6 asc. */
239 MRUSORT_R_ADDR, /* IPv6 desc. then IPv4 desc. */
240 MRUSORT_COUNT, /* hit count ascending */
241 MRUSORT_R_COUNT, /* hit count descending */
242 MRUSORT_MAX, /* special: count of this enum */
245 const char * const mru_sort_keywords[MRUSORT_MAX] = {
246 "lstint", /* MRUSORT_DEF */
247 "-lstint", /* MRUSORT_R_DEF */
248 "avgint", /* MRUSORT_AVGINT */
249 "-avgint", /* MRUSORT_R_AVGINT */
250 "addr", /* MRUSORT_ADDR */
251 "-addr", /* MRUSORT_R_ADDR */
252 "count", /* MRUSORT_COUNT */
253 "-count", /* MRUSORT_R_COUNT */
256 typedef int (*qsort_cmp)(const void *, const void *);
259 * Old CTL_PST defines for version 2.
261 #define OLD_CTL_PST_CONFIG 0x80
262 #define OLD_CTL_PST_AUTHENABLE 0x40
263 #define OLD_CTL_PST_AUTHENTIC 0x20
264 #define OLD_CTL_PST_REACH 0x10
265 #define OLD_CTL_PST_SANE 0x08
266 #define OLD_CTL_PST_DISP 0x04
268 #define OLD_CTL_PST_SEL_REJECT 0
269 #define OLD_CTL_PST_SEL_SELCAND 1
270 #define OLD_CTL_PST_SEL_SYNCCAND 2
271 #define OLD_CTL_PST_SEL_SYSPEER 3
273 char flash2[] = " .+* "; /* flash decode for version 2 */
274 char flash3[] = " x.-+#*o"; /* flash decode for peer status version 3 */
279 } g_varlist[MAXLIST] = { { 0, 0 } };
282 * Imported from ntpq.c
284 extern int showhostnames;
285 extern int wideremote;
287 extern struct servent *server_entry;
288 extern struct association *assoc_cache;
289 extern u_char pktversion;
291 typedef struct mru_tag mru;
293 mru * hlink; /* next in hash table bucket */
294 DECL_DLIST_LINK(mru, mlink);
304 typedef struct ifstats_row_tag {
320 typedef struct reslist_row_tag {
328 typedef struct var_display_collection_tag {
329 const char * const tag; /* system variable */
330 const char * const display; /* descriptive text */
331 u_char type; /* NTP_STR, etc */
334 sockaddr_u sau; /* NTP_ADD */
335 l_fp lfp; /* NTP_LFP */
336 } v; /* retrieved value */
338 #if !defined(MISSING_C99_STRUCT_INIT)
339 # define VDC_INIT(a, b, c) { .tag = a, .display = b, .type = c }
341 # define VDC_INIT(a, b, c) { a, b, c }
344 * other local function prototypes
346 static int mrulist_ctrl_c_hook(void);
347 static mru * add_mru(mru *);
348 static int collect_mru_list(const char *, l_fp *);
349 static int fetch_nonce(char *, size_t);
350 static int qcmp_mru_avgint(const void *, const void *);
351 static int qcmp_mru_r_avgint(const void *, const void *);
352 static int qcmp_mru_addr(const void *, const void *);
353 static int qcmp_mru_r_addr(const void *, const void *);
354 static int qcmp_mru_count(const void *, const void *);
355 static int qcmp_mru_r_count(const void *, const void *);
356 static void validate_ifnum(FILE *, u_int, int *, ifstats_row *);
357 static void another_ifstats_field(int *, ifstats_row *, FILE *);
358 static void collect_display_vdc(associd_t as, vdc *table,
359 int decodestatus, FILE *fp);
364 static u_int mru_count;
365 static u_int mru_dupes;
366 volatile int mrulist_interrupted;
367 static mru mru_list; /* listhead */
368 static mru ** hash_table;
371 * qsort comparison function table for mrulist(). The first two
372 * entries are NULL because they are handled without qsort().
374 static const qsort_cmp mru_qcmp_table[MRUSORT_MAX] = {
375 NULL, /* MRUSORT_DEF unused */
376 NULL, /* MRUSORT_R_DEF unused */
377 &qcmp_mru_avgint, /* MRUSORT_AVGINT */
378 &qcmp_mru_r_avgint, /* MRUSORT_R_AVGINT */
379 &qcmp_mru_addr, /* MRUSORT_ADDR */
380 &qcmp_mru_r_addr, /* MRUSORT_R_ADDR */
381 &qcmp_mru_count, /* MRUSORT_COUNT */
382 &qcmp_mru_r_count, /* MRUSORT_R_COUNT */
386 * checkassocid - return the association ID, checking to see if it is valid
396 associd = (associd_t)value;
397 if (0 == associd || value != associd) {
400 "***Invalid association ID %lu specified\n",
410 * findlistvar - Look for the named variable in a varlist. If found,
411 * return a pointer to it. Otherwise, if the list has
412 * slots available, return the pointer to the first free
413 * slot, or NULL if it's full.
415 static struct varlist *
417 struct varlist *list,
423 for (vl = list; vl < list + MAXLIST && vl->name != NULL; vl++)
424 if (!strcmp(name, vl->name))
426 if (vl < list + MAXLIST)
434 * doaddvlist - add variable(s) to the variable list
438 struct varlist *vlist,
448 while (nextvar(&len, &vars, &name, &value)) {
449 INSIST(name && value);
450 vl = findlistvar(vlist, name);
452 fprintf(stderr, "Variable list full\n");
456 if (NULL == vl->name) {
457 vl->name = estrdup(name);
458 } else if (vl->value != NULL) {
464 vl->value = estrdup(value);
470 * dormvlist - remove variable(s) from the variable list
474 struct varlist *vlist,
484 while (nextvar(&len, &vars, &name, &value)) {
485 INSIST(name && value);
486 vl = findlistvar(vlist, name);
487 if (vl == 0 || vl->name == 0) {
488 (void) fprintf(stderr, "Variable `%s' not found\n",
491 free((void *)(intptr_t)vl->name);
494 for ( ; (vl+1) < (g_varlist + MAXLIST)
495 && (vl+1)->name != 0; vl++) {
496 vl->name = (vl+1)->name;
497 vl->value = (vl+1)->value;
499 vl->name = vl->value = 0;
506 * doclearvlist - clear a variable list
510 struct varlist *vlist
513 register struct varlist *vl;
515 for (vl = vlist; vl < vlist + MAXLIST && vl->name != 0; vl++) {
516 free((void *)(intptr_t)vl->name);
518 if (vl->value != 0) {
527 * makequerydata - form a data buffer to be included with a query
531 struct varlist *vlist,
536 register struct varlist *vl;
537 register char *cp, *cpend;
538 register size_t namelen, valuelen;
539 register size_t totallen;
542 cpend = data + *datalen;
544 for (vl = vlist; vl < vlist + MAXLIST && vl->name != 0; vl++) {
545 namelen = strlen(vl->name);
549 valuelen = strlen(vl->value);
550 totallen = namelen + valuelen + (valuelen != 0) + (cp != data);
551 if (cp + totallen > cpend) {
553 "***Ignoring variables starting with `%s'\n",
560 memcpy(cp, vl->name, (size_t)namelen);
564 memcpy(cp, vl->value, (size_t)valuelen);
568 *datalen = (size_t)(cp - data);
573 * doquerylist - send a message including variables in a list
577 struct varlist *vlist,
586 char data[CTL_MAX_DATA_LEN];
589 datalen = sizeof(data);
590 makequerydata(vlist, &datalen, data);
592 return doquery(op, associd, auth, datalen, data, rstatus, dsize,
598 * doprintvlist - print the variables on a list
602 struct varlist *vlist,
608 if (NULL == vlist->name) {
609 fprintf(fp, "No variables on list\n");
612 for (n = 0; n < MAXLIST && vlist[n].name != NULL; n++) {
613 if (NULL == vlist[n].value)
614 fprintf(fp, "%s\n", vlist[n].name);
616 fprintf(fp, "%s=%s\n", vlist[n].name,
622 * addvars - add variables to the variable list
631 doaddvlist(g_varlist, pcmd->argval[0].string);
636 * rmvars - remove variables from the variable list
645 dormvlist(g_varlist, pcmd->argval[0].string);
650 * clearvars - clear the variable list
659 doclearvlist(g_varlist);
664 * showvars - show variables on the variable list
673 doprintvlist(g_varlist, fp);
678 * dolist - send a request with the given list of variables
682 struct varlist *vlist,
696 * if we're asking for specific variables don't include the
697 * status header line in the output.
702 quiet = (vlist->name != NULL);
704 res = doquerylist(vlist, op, associd, 0, &rstatus, &dsize, &datap);
710 fprintf(fp, "server=%s ", currenthost);
713 fprintf(fp, "No system%s variables returned\n",
714 (type == TYPE_CLOCK) ? " clock" : "");
717 "No information returned for%s association %u\n",
718 (type == TYPE_CLOCK) ? " clock" : "",
724 fprintf(fp, "associd=%u ", associd);
725 printvars(dsize, datap, (int)rstatus, type, quiet, fp);
731 * readlist - send a read variables request with the variables on the list
742 if (pcmd->nargs == 0) {
745 /* HMS: I think we want the u_int32 target here, not the u_long */
746 if (pcmd->argval[0].uval == 0)
748 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
752 type = (0 == associd)
755 dolist(g_varlist, associd, CTL_OP_READVAR, type, fp);
760 * writelist - send a write variables request with the variables on the list
774 if (pcmd->nargs == 0) {
777 /* HMS: Do we really want uval here? */
778 if (pcmd->argval[0].uval == 0)
780 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
784 res = doquerylist(g_varlist, CTL_OP_WRITEVAR, associd, 1, &rstatus,
791 (void) fprintf(fp, "server=%s ", currenthost);
793 (void) fprintf(fp, "done! (no data returned)\n");
795 (void) fprintf(fp,"associd=%u ", associd);
796 printvars(dsize, datap, (int)rstatus,
797 (associd != 0) ? TYPE_PEER : TYPE_SYS, 0, fp);
804 * readvar - send a read variables request with the specified variables
816 struct varlist tmplist[MAXLIST];
820 if (pcmd->nargs == 0 || pcmd->argval[0].uval == 0)
822 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
826 if (pcmd->nargs > 1) {
827 tmpcount = pcmd->nargs - 1;
828 for (u = 0; u < tmpcount; u++)
829 doaddvlist(tmplist, pcmd->argval[1 + u].string);
832 type = (0 == associd)
835 dolist(tmplist, associd, CTL_OP_READVAR, type, fp);
837 doclearvlist(tmplist);
842 * writevar - send a write variables request with the specified variables
856 struct varlist tmplist[MAXLIST];
859 if (pcmd->argval[0].uval == 0)
861 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
865 doaddvlist(tmplist, pcmd->argval[1].string);
867 res = doquerylist(tmplist, CTL_OP_WRITEVAR, associd, 1, &rstatus,
870 doclearvlist(tmplist);
876 fprintf(fp, "server=%s ", currenthost);
878 fprintf(fp, "done! (no data returned)\n");
880 fprintf(fp,"associd=%u ", associd);
881 type = (0 == associd)
884 printvars(dsize, datap, (int)rstatus, type, 0, fp);
891 * clocklist - send a clock variables request with the variables on the list
902 if (pcmd->nargs == 0) {
905 if (pcmd->argval[0].uval == 0)
907 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
911 dolist(g_varlist, associd, CTL_OP_READCLOCK, TYPE_CLOCK, fp);
916 * clockvar - send a clock variables request with the specified variables
925 struct varlist tmplist[MAXLIST];
928 if (pcmd->nargs == 0 || pcmd->argval[0].uval == 0)
930 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
934 if (pcmd->nargs >= 2)
935 doaddvlist(tmplist, pcmd->argval[1].string);
937 dolist(tmplist, associd, CTL_OP_READCLOCK, TYPE_CLOCK, fp);
939 doclearvlist(tmplist);
944 * findassidrange - verify a range of association ID's
956 int ind[COUNTOF(assids)];
964 assids[0] = checkassocid(assid1);
967 assids[1] = checkassocid(assid2);
971 for (a = 0; a < COUNTOF(assids); a++) {
973 for (i = 0; i < numassoc; i++)
974 if (assoc_cache[i].assid == assids[a])
977 for (a = 0; a < COUNTOF(assids); a++)
980 "***Association ID %u not found in list\n",
985 if (ind[0] < ind[1]) {
998 * mreadlist - send a read variables request for multiple associations
1010 if (!findassidrange(pcmd->argval[0].uval, pcmd->argval[1].uval,
1014 for (i = from; i <= to; i++) {
1017 if (!dolist(g_varlist, assoc_cache[i].assid,
1018 CTL_OP_READVAR, TYPE_PEER, fp))
1026 * mreadvar - send a read variables request for multiple associations
1037 struct varlist tmplist[MAXLIST];
1038 struct varlist *pvars;
1040 if (!findassidrange(pcmd->argval[0].uval, pcmd->argval[1].uval,
1045 if (pcmd->nargs >= 3) {
1046 doaddvlist(tmplist, pcmd->argval[2].string);
1052 for (i = from; i <= to; i++) {
1053 if (!dolist(pvars, assoc_cache[i].assid, CTL_OP_READVAR,
1058 if (pvars == tmplist)
1059 doclearvlist(tmplist);
1066 * dogetassoc - query the host for its list of associations
1079 res = doquery(CTL_OP_READSTAT, 0, 0, 0, (char *)0, &rstatus,
1087 fprintf(fp, "server=%s ", currenthost);
1088 fprintf(fp, "No association ID's returned\n");
1094 fprintf(stderr, "server=%s ", currenthost);
1096 "***Server returned %zu octets, should be multiple of 4\n",
1104 if (numassoc >= assoc_cache_slots) {
1107 pus = (const void *)datap;
1108 assoc_cache[numassoc].assid = ntohs(*pus);
1109 datap += sizeof(*pus);
1110 pus = (const void *)datap;
1111 assoc_cache[numassoc].status = ntohs(*pus);
1112 datap += sizeof(*pus);
1113 dsize -= 2 * sizeof(*pus);
1115 fprintf(stderr, "[%u] ",
1116 assoc_cache[numassoc].assid);
1121 fprintf(stderr, "\n%d associations total\n", numassoc);
1129 * printassoc - print the current list of associations
1145 const char *condition = "";
1146 const char *last_event;
1149 if (numassoc == 0) {
1150 (void) fprintf(fp, "No association ID's in list\n");
1158 "ind assid status conf reach auth condition last_event cnt\n");
1160 "===========================================================\n");
1161 for (i = 0; i < numassoc; i++) {
1162 statval = (u_char) CTL_PEER_STATVAL(assoc_cache[i].status);
1163 if (!showall && !(statval & (CTL_PST_CONFIG|CTL_PST_REACH)))
1165 event = CTL_PEER_EVENT(assoc_cache[i].status);
1166 event_count = CTL_PEER_NEVNT(assoc_cache[i].status);
1167 if (statval & CTL_PST_CONFIG)
1171 if (statval & CTL_PST_BCAST) {
1173 if (statval & CTL_PST_AUTHENABLE)
1178 if (statval & CTL_PST_REACH)
1182 if (statval & CTL_PST_AUTHENABLE) {
1183 if (statval & CTL_PST_AUTHENTIC)
1191 if (pktversion > NTP_OLDVERSION) {
1192 switch (statval & 0x7) {
1194 case CTL_PST_SEL_REJECT:
1195 condition = "reject";
1198 case CTL_PST_SEL_SANE:
1199 condition = "falsetick";
1202 case CTL_PST_SEL_CORRECT:
1203 condition = "excess";
1206 case CTL_PST_SEL_SELCAND:
1207 condition = "outlier";
1210 case CTL_PST_SEL_SYNCCAND:
1211 condition = "candidate";
1214 case CTL_PST_SEL_EXCESS:
1215 condition = "backup";
1218 case CTL_PST_SEL_SYSPEER:
1219 condition = "sys.peer";
1222 case CTL_PST_SEL_PPS:
1223 condition = "pps.peer";
1227 switch (statval & 0x3) {
1229 case OLD_CTL_PST_SEL_REJECT:
1230 if (!(statval & OLD_CTL_PST_SANE))
1231 condition = "insane";
1232 else if (!(statval & OLD_CTL_PST_DISP))
1233 condition = "hi_disp";
1238 case OLD_CTL_PST_SEL_SELCAND:
1239 condition = "sel_cand";
1242 case OLD_CTL_PST_SEL_SYNCCAND:
1243 condition = "sync_cand";
1246 case OLD_CTL_PST_SEL_SYSPEER:
1247 condition = "sys_peer";
1251 switch (PEER_EVENT|event) {
1254 last_event = "mobilize";
1258 last_event = "demobilize";
1262 last_event = "reachable";
1266 last_event = "unreachable";
1270 last_event = "restart";
1274 last_event = "no_reply";
1278 last_event = "rate_exceeded";
1282 last_event = "access_denied";
1286 last_event = "leap_armed";
1290 last_event = "sys_peer";
1294 last_event = "clock_alarm";
1301 snprintf(buf, sizeof(buf),
1302 "%3d %5u %04x %3.3s %4s %4.4s %9.9s %11s %2lu",
1303 i + 1, assoc_cache[i].assid,
1304 assoc_cache[i].status, conf, reach, auth,
1305 condition, last_event, event_count);
1306 bp = buf + strlen(buf);
1307 while (bp > buf && ' ' == bp[-1])
1310 fprintf(fp, "%s\n", buf);
1316 * associations - get, record and print a list of associations
1331 * lassociations - get, record and print a long list of associations
1346 * passociations - print the association list
1360 * lpassociations - print the long association list
1374 * saveconfig - dump ntp server configuration to server file
1387 if (0 == pcmd->nargs)
1390 res = doquery(CTL_OP_SAVECONFIG, 0, 1,
1391 strlen(pcmd->argval[0].string),
1392 pcmd->argval[0].string, &rstatus, &dsize,
1399 fprintf(fp, "(no response message, curiously)");
1401 fprintf(fp, "%.*s", (int)dsize, datap); /* cast is wobbly */
1407 * radiostatus - print the radio status returned by the server
1421 res = doquery(CTL_OP_READCLOCK, 0, 0, 0, (char *)0, &rstatus,
1428 (void) fprintf(fp, "server=%s ", currenthost);
1430 (void) fprintf(fp, "No radio status string returned\n");
1434 asciize(dsize, datap, fp);
1439 * when - print how long its been since his last packet arrived
1452 else if (reftime->l_ui != 0)
1457 if (ts->l_ui < lasttime->l_ui)
1459 return (ts->l_ui - lasttime->l_ui);
1464 * Pretty-print an interval into the given buffer, in a human-friendly format.
1480 snprintf(buf, cb, "%u", (unsigned int)diff);
1484 diff = (diff + 29) / 60;
1486 snprintf(buf, cb, "%um", (unsigned int)diff);
1490 diff = (diff + 29) / 60;
1492 snprintf(buf, cb, "%uh", (unsigned int)diff);
1496 diff = (diff + 11) / 24;
1498 snprintf(buf, cb, "%ud", (unsigned int)diff);
1502 /* years are only approximated... */
1503 diff = (long)floor(diff / 365.25 + 0.5);
1505 snprintf(buf, cb, "%uy", (unsigned int)diff);
1508 /* Ok, this amounts to infinity... */
1509 strlcpy(buf, "INF", cb);
1523 dummy = SRCADR(sock);
1524 ch = (char)(((dummy&0xf0000000)==0xe0000000) ? 'm' :
1525 ((dummy&0x000000ff)==0x000000ff) ? 'b' :
1526 ((dummy&0xffffffff)==0x7f000001) ? 'l' :
1527 ((dummy&0xffffffe0)==0x00000000) ? '-' :
1531 if (IN6_IS_ADDR_MULTICAST(PSOCK_ADDR6(sock)))
1544 * A list of variables required by the peers command
1546 struct varlist opeervarlist[] = {
1547 { "srcadr", 0 }, /* 0 */
1548 { "dstadr", 0 }, /* 1 */
1549 { "stratum", 0 }, /* 2 */
1550 { "hpoll", 0 }, /* 3 */
1551 { "ppoll", 0 }, /* 4 */
1552 { "reach", 0 }, /* 5 */
1553 { "delay", 0 }, /* 6 */
1554 { "offset", 0 }, /* 7 */
1555 { "jitter", 0 }, /* 8 */
1556 { "dispersion", 0 }, /* 9 */
1557 { "rec", 0 }, /* 10 */
1558 { "reftime", 0 }, /* 11 */
1559 { "srcport", 0 }, /* 12 */
1560 { "hmode", 0 }, /* 13 */
1564 struct varlist peervarlist[] = {
1565 { "srcadr", 0 }, /* 0 */
1566 { "refid", 0 }, /* 1 */
1567 { "stratum", 0 }, /* 2 */
1568 { "hpoll", 0 }, /* 3 */
1569 { "ppoll", 0 }, /* 4 */
1570 { "reach", 0 }, /* 5 */
1571 { "delay", 0 }, /* 6 */
1572 { "offset", 0 }, /* 7 */
1573 { "jitter", 0 }, /* 8 */
1574 { "dispersion", 0 }, /* 9 */
1575 { "rec", 0 }, /* 10 */
1576 { "reftime", 0 }, /* 11 */
1577 { "srcport", 0 }, /* 12 */
1578 { "hmode", 0 }, /* 13 */
1579 { "srchost", 0 }, /* 14 */
1583 struct varlist apeervarlist[] = {
1584 { "srcadr", 0 }, /* 0 */
1585 { "refid", 0 }, /* 1 */
1586 { "assid", 0 }, /* 2 */
1587 { "stratum", 0 }, /* 3 */
1588 { "hpoll", 0 }, /* 4 */
1589 { "ppoll", 0 }, /* 5 */
1590 { "reach", 0 }, /* 6 */
1591 { "delay", 0 }, /* 7 */
1592 { "offset", 0 }, /* 8 */
1593 { "jitter", 0 }, /* 9 */
1594 { "dispersion", 0 }, /* 10 */
1595 { "rec", 0 }, /* 11 */
1596 { "reftime", 0 }, /* 12 */
1597 { "srcport", 0 }, /* 13 */
1598 { "hmode", 0 }, /* 14 */
1599 { "srchost", 0 }, /* 15 */
1605 * Decode an incoming data buffer and print a line in the peer list
1609 struct varlist *pvl,
1628 sockaddr_u dum_store;
1629 sockaddr_u refidadr;
1633 const char *dstadr_refid = "0.0.0.0";
1634 const char *serverlocal;
1650 char clock_name[LENHOSTNAME];
1651 char whenbuf[12], pollbuf[12];
1652 /* [Bug 3482] formally whenbuf & pollbuf should be able to hold
1653 * a full signed int. Not that we would use that much string
1658 have_srchost = FALSE;
1659 have_dstadr = FALSE;
1660 have_da_rid = FALSE;
1661 have_jitter = FALSE;
1664 clock_name[0] = '\0';
1670 while (nextvar(&datalen, &data, &name, &value)) {
1671 INSIST(name && value);
1672 if (!strcmp("srcadr", name) ||
1673 !strcmp("peeradr", name)) {
1674 if (!decodenetnum(value, &srcadr))
1675 fprintf(stderr, "malformed %s=%s\n",
1677 } else if (!strcmp("srchost", name)) {
1678 if (pvl == peervarlist || pvl == apeervarlist) {
1679 len = strlen(value);
1681 (size_t)len < sizeof(clock_name)) {
1685 memcpy(clock_name, value, len);
1686 clock_name[len] = '\0';
1687 have_srchost = TRUE;
1690 } else if (!strcmp("dstadr", name)) {
1691 if (decodenetnum(value, &dum_store)) {
1692 type = decodeaddrtype(&dum_store);
1695 if (pvl == opeervarlist) {
1697 dstadr_refid = trunc_left(stoa(&dstadr), 15);
1700 } else if (!strcmp("hmode", name)) {
1701 decodeint(value, &hmode);
1702 } else if (!strcmp("refid", name)) {
1703 if ( (pvl == peervarlist)
1704 && (drefid == REFID_IPV4)) {
1706 drlen = strlen(value);
1709 } else if (drlen <= 4) {
1711 memcpy(&u32, value, drlen);
1712 dstadr_refid = refid_str(u32, 1);
1713 } else if (decodenetnum(value, &refidadr)) {
1714 if (SOCK_UNSPEC(&refidadr))
1715 dstadr_refid = "0.0.0.0";
1716 else if (ISREFCLOCKADR(&refidadr))
1718 refnumtoa(&refidadr);
1723 have_da_rid = FALSE;
1725 } else if ( (pvl == apeervarlist)
1726 || (pvl == peervarlist)) {
1727 /* no need to check drefid == REFID_HASH */
1729 drlen = strlen(value);
1732 } else if (drlen <= 4) {
1734 memcpy(&u32, value, drlen);
1735 dstadr_refid = refid_str(u32, 1);
1736 //fprintf(stderr, "apeervarlist S1 refid: value=<%s>\n", value);
1737 } else if (decodenetnum(value, &refidadr)) {
1738 if (SOCK_UNSPEC(&refidadr))
1739 dstadr_refid = "0.0.0.0";
1740 else if (ISREFCLOCKADR(&refidadr))
1742 refnumtoa(&refidadr);
1744 char *buf = emalloc(10);
1745 int i = ntohl(refidadr.sa4.sin_addr.s_addr);
1750 //fprintf(stderr, "apeervarlist refid: value=<%x>\n", i);
1752 //fprintf(stderr, "apeervarlist refid: value=<%s>\n", value);
1754 have_da_rid = FALSE;
1757 } else if (!strcmp("stratum", name)) {
1758 decodeuint(value, &stratum);
1759 } else if (!strcmp("hpoll", name)) {
1760 if (decodeint(value, &hpoll) && hpoll < 0)
1761 hpoll = NTP_MINPOLL;
1762 } else if (!strcmp("ppoll", name)) {
1763 if (decodeint(value, &ppoll) && ppoll < 0)
1764 ppoll = NTP_MINPOLL;
1765 } else if (!strcmp("reach", name)) {
1766 decodeuint(value, &reach);
1767 } else if (!strcmp("delay", name)) {
1768 decodetime(value, &estdelay);
1769 } else if (!strcmp("offset", name)) {
1770 decodetime(value, &estoffset);
1771 } else if (!strcmp("jitter", name)) {
1772 if ((pvl == peervarlist || pvl == apeervarlist)
1773 && decodetime(value, &estjitter))
1775 } else if (!strcmp("rootdisp", name) ||
1776 !strcmp("dispersion", name)) {
1777 decodetime(value, &estdisp);
1778 } else if (!strcmp("rec", name)) {
1779 decodets(value, &rec);
1780 } else if (!strcmp("srcport", name) ||
1781 !strcmp("peerport", name)) {
1782 decodeuint(value, &srcport);
1783 } else if (!strcmp("reftime", name)) {
1784 if (!decodets(value, &reftime))
1786 } else if (!strcmp("flash", name)) {
1787 decodeuint(value, &flash);
1789 // fprintf(stderr, "UNRECOGNIZED name=%s ", name);
1794 * hmode gives the best guidance for the t column. If the response
1795 * did not include hmode we'll use the old decodeaddrtype() result.
1800 /* broadcastclient or multicastclient */
1804 case MODE_BROADCAST:
1805 /* broadcast or multicast server */
1806 if (IS_MCAST(&srcadr))
1813 if (ISREFCLOCKADR(&srcadr))
1814 type = 'l'; /* local refclock*/
1815 else if (SOCK_UNSPEC(&srcadr))
1816 type = 'p'; /* pool */
1817 else if (IS_MCAST(&srcadr))
1818 type = 'a'; /* manycastclient */
1820 type = 'u'; /* unicast */
1824 type = 's'; /* symmetric active */
1825 break; /* configured */
1828 type = 'S'; /* symmetric passive */
1829 break; /* ephemeral */
1833 * Got everything, format the line
1835 poll_sec = 1 << min(ppoll, hpoll);
1836 if (pktversion > NTP_OLDVERSION)
1837 c = flash3[CTL_PEER_STATVAL(rstatus) & 0x7];
1839 c = flash2[CTL_PEER_STATVAL(rstatus) & 0x3];
1841 if ((pvl == peervarlist || pvl == apeervarlist)
1843 serverlocal = nntohost_col(&dstadr,
1844 (size_t)min(LIB_BUFLENGTH - 1, maxhostlen),
1847 if (currenthostisnum)
1848 serverlocal = trunc_left(currenthost,
1851 serverlocal = currenthost;
1853 fprintf(fp, "%-*s ", (int)maxhostlen, serverlocal);
1855 if (AF_UNSPEC == af || AF(&srcadr) == af) {
1857 strlcpy(clock_name, nntohost(&srcadr),
1858 sizeof(clock_name));
1859 /* wide and long source - space over on next line */
1860 /* allow for host + sp if > 1 and regular tally + source + sp */
1861 if (wideremote && 15 < strlen(clock_name))
1862 fprintf(fp, "%c%s\n%*s", c, clock_name,
1863 ((numhosts > 1) ? (int)maxhostlen + 1 : 0)
1866 fprintf(fp, "%c%-15.15s ", c, clock_name);
1867 if ((flash & TEST12) && (pvl != opeervarlist)) {
1868 drlen = fprintf(fp, "(loop)");
1869 } else if (!have_da_rid) {
1872 drlen = strlen(dstadr_refid);
1873 makeascii(drlen, dstadr_refid, fp);
1875 if (pvl == apeervarlist) {
1878 fprintf(fp, "%-6d", associd);
1880 while (drlen++ < 15)
1884 " %2ld %c %4.4s %4.4s %3lo %7.7s %8.7s %7.7s\n",
1886 prettyinterval(whenbuf, sizeof(whenbuf),
1887 when(&ts, &rec, &reftime)),
1888 prettyinterval(pollbuf, sizeof(pollbuf),
1890 reach, lfptoms(&estdelay, 3),
1891 lfptoms(&estoffset, 3),
1893 ? lfptoms(&estjitter, 3)
1894 : lfptoms(&estdisp, 3));
1903 * dogetpeers - given an association ID, read and print the spreadsheet
1908 struct varlist *pvl,
1920 res = doquerylist(pvl, CTL_OP_READVAR, associd, 0, &rstatus,
1926 res = doquery(CTL_OP_READVAR, associd, 0, 0, NULL, &rstatus,
1935 fprintf(stderr, "server=%s ", currenthost);
1937 "***No information returned for association %u\n",
1942 return doprintpeers(pvl, associd, (int)rstatus, dsize, datap,
1948 * peers - print a peer spreadsheet
1958 char fullname[LENHOSTNAME];
1960 const char * name_or_num;
1963 if (!dogetassoc(fp))
1966 for (u = 0; u < numhosts; u++) {
1967 if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
1968 name_or_num = nntohost(&netnum);
1969 sl = strlen(name_or_num);
1970 maxhostlen = max(maxhostlen, sl);
1974 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
1977 " remote refid st t when poll reach delay offset jitter\n");
1979 for (u = 0; u <= maxhostlen; u++)
1982 "==============================================================================\n");
1984 for (u = 0; u < numassoc; u++) {
1986 !(CTL_PEER_STATVAL(assoc_cache[u].status)
1987 & (CTL_PST_CONFIG|CTL_PST_REACH))) {
1989 fprintf(stderr, "eliding [%d]\n",
1990 (int)assoc_cache[u].assid);
1993 if (!dogetpeers(peervarlist, (int)assoc_cache[u].assid,
2002 * doapeers - print a peer spreadsheet with assocIDs
2012 char fullname[LENHOSTNAME];
2014 const char * name_or_num;
2017 if (!dogetassoc(fp))
2020 for (u = 0; u < numhosts; u++) {
2021 if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
2022 name_or_num = nntohost(&netnum);
2023 sl = strlen(name_or_num);
2024 maxhostlen = max(maxhostlen, sl);
2028 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2031 " remote refid assid st t when poll reach delay offset jitter\n");
2033 for (u = 0; u <= maxhostlen; u++)
2036 "==============================================================================\n");
2038 for (u = 0; u < numassoc; u++) {
2040 !(CTL_PEER_STATVAL(assoc_cache[u].status)
2041 & (CTL_PST_CONFIG|CTL_PST_REACH))) {
2043 fprintf(stderr, "eliding [%d]\n",
2044 (int)assoc_cache[u].assid);
2047 if (!dogetpeers(apeervarlist, (int)assoc_cache[u].assid,
2056 * peers - print a peer spreadsheet
2065 if (drefid == REFID_HASH) {
2070 if (pcmd->nargs == 1) {
2071 if (pcmd->argval->ival == 6)
2082 * apeers - print a peer spreadsheet, with assocIDs
2093 if (pcmd->nargs == 1) {
2094 if (pcmd->argval->ival == 6)
2099 doapeers(0, fp, af);
2104 * lpeers - print a peer spreadsheet including all fuzzball peers
2115 if (pcmd->nargs == 1) {
2116 if (pcmd->argval->ival == 6)
2126 * opeers - print a peer spreadsheet
2136 char fullname[LENHOSTNAME];
2139 if (!dogetassoc(fp))
2142 for (i = 0; i < numhosts; ++i) {
2143 if (getnetnum(chosts[i].name, &netnum, fullname, af))
2144 if (strlen(fullname) > maxhostlen)
2145 maxhostlen = strlen(fullname);
2148 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2151 " remote local st t when poll reach delay offset disp\n");
2153 for (i = 0; i <= maxhostlen; ++i)
2156 "==============================================================================\n");
2158 for (i = 0; i < numassoc; i++) {
2160 !(CTL_PEER_STATVAL(assoc_cache[i].status) &
2161 (CTL_PST_CONFIG | CTL_PST_REACH)))
2163 if (!dogetpeers(opeervarlist, assoc_cache[i].assid, fp, af))
2171 * opeers - print a peer spreadsheet the old way
2182 if (pcmd->nargs == 1) {
2183 if (pcmd->argval->ival == 6)
2188 doopeers(0, fp, af);
2193 * lopeers - print a peer spreadsheet including all fuzzball peers
2204 if (pcmd->nargs == 1) {
2205 if (pcmd->argval->ival == 6)
2210 doopeers(1, fp, af);
2215 * config - send a configuration command to a remote host
2232 cfgcmd = pcmd->argval[0].string;
2238 "Command = %s\n", pcmd->keyword, cfgcmd);
2240 res = doquery(CTL_OP_CONFIGURE, 0, 1,
2241 strlen(cfgcmd), cfgcmd,
2242 &rstatus, &rsize, &rdata);
2247 if (rsize > 0 && '\n' == rdata[rsize - 1])
2250 resp = emalloc(rsize + 1);
2251 memcpy(resp, rdata, rsize);
2255 if (1 == sscanf(resp, "column %d syntax error", &col)
2256 && col >= 0 && (size_t)col <= strlen(cfgcmd) + 1) {
2258 fputs(" *", stdout); /* "ntpq> :config " */
2260 printf("%s\n", cfgcmd);
2261 for (i = 0; i < col; i++)
2263 fputs("^\n", stdout);
2265 printf("%s\n", resp);
2271 * config_from_file - remotely configure an ntpd daemon using the
2272 * specified configuration file
2273 * SK: This function is a kludge at best and is full of bad design
2275 * 1. ntpq uses UDP, which means that there is no guarantee of in-order,
2276 * error-free delivery.
2277 * 2. The maximum length of a packet is constrained, and as a result, the
2278 * maximum length of a line in a configuration file is constrained.
2279 * Longer lines will lead to unpredictable results.
2280 * 3. Since this function is sending a line at a time, we can't update
2281 * the control key through the configuration file (YUCK!!)
2283 * Pearly: There are a few places where 'size_t' is cast to 'int' based
2284 * on the assumption that 'int' can hold the size of the involved
2285 * buffers without overflow.
2299 char config_cmd[MAXLINE];
2308 "Filename = %s\n", pcmd->keyword,
2309 pcmd->argval[0].string);
2311 config_fd = fopen(pcmd->argval[0].string, "r");
2312 if (NULL == config_fd) {
2313 printf("ERROR!! Couldn't open file: %s\n",
2314 pcmd->argval[0].string);
2318 printf("Sending configuration file, one line at a time.\n");
2320 while (fgets(config_cmd, MAXLINE, config_fd) != NULL) {
2321 /* Eliminate comments first. */
2322 cp = strchr(config_cmd, '#');
2323 config_len = (NULL != cp)
2324 ? (size_t)(cp - config_cmd)
2325 : strlen(config_cmd);
2327 /* [Bug 3015] make sure there's no trailing whitespace;
2328 * the fix for [Bug 2853] on the server side forbids
2329 * those. And don't transmit empty lines, as this would
2332 while (config_len != 0 &&
2333 (u_char)config_cmd[config_len-1] <= ' ')
2335 config_cmd[config_len] = '\0';
2338 if (0 == config_len)
2343 res = doquery(CTL_OP_CONFIGURE, 0, 1,
2344 config_len, config_cmd,
2345 &rstatus, &rsize, &rdata);
2346 while (res != 0 && retry_limit--);
2348 printf("Line No: %d query failed: %.*s\n"
2349 "Subsequent lines not sent.\n",
2350 i, (int)config_len, config_cmd);
2355 /* Right-strip the result code string, then output the
2356 * last line executed, with result code. */
2357 while (rsize != 0 && (u_char)rdata[rsize - 1] <= ' ')
2359 printf("Line No: %d %.*s: %.*s\n", i,
2361 (int)config_len, config_cmd);
2363 printf("Done sending file\n");
2374 const char nonce_eq[] = "nonce=";
2382 * Retrieve a nonce specific to this client to demonstrate to
2383 * ntpd that we're capable of receiving responses to our source
2384 * IP address, and thereby unlikely to be forging the source.
2386 qres = doquery(CTL_OP_REQ_NONCE, 0, 0, 0, NULL, &rstatus,
2389 fprintf(stderr, "nonce request failed\n");
2393 if ((size_t)rsize <= sizeof(nonce_eq) - 1 ||
2394 strncmp(rdata, nonce_eq, sizeof(nonce_eq) - 1)) {
2395 fprintf(stderr, "unexpected nonce response format: %.*s\n",
2396 (int)rsize, rdata); /* cast is wobbly */
2399 chars = rsize - (sizeof(nonce_eq) - 1);
2400 if (chars >= cb_nonce)
2402 memcpy(nonce, rdata + sizeof(nonce_eq) - 1, chars);
2403 nonce[chars] = '\0';
2405 ('\r' == nonce[chars - 1] || '\n' == nonce[chars - 1])) {
2407 nonce[chars] = '\0';
2415 * add_mru Add and entry to mru list, hash table, and allocate
2416 * and return a replacement.
2417 * This is a helper for collect_mru_list().
2429 hash = NTP_HASH_ADDR(&add->addr);
2430 /* see if we have it among previously received entries */
2431 for (mon = hash_table[hash]; mon != NULL; mon = mon->hlink)
2432 if (SOCK_EQ(&mon->addr, &add->addr))
2435 if (!L_ISGEQ(&add->first, &mon->first)) {
2437 "add_mru duplicate %s new first ts %08x.%08x precedes prior %08x.%08x\n",
2438 sptoa(&add->addr), add->last.l_ui,
2439 add->last.l_uf, mon->last.l_ui,
2443 UNLINK_DLIST(mon, mlink);
2444 UNLINK_SLIST(unlinked, hash_table[hash], mon, hlink, mru);
2445 INSIST(unlinked == mon);
2447 TRACE(2, ("(updated from %08x.%08x) ", mon->last.l_ui,
2450 LINK_DLIST(mru_list, add, mlink);
2451 LINK_SLIST(hash_table[hash], add, hlink);
2452 TRACE(2, ("add_mru %08x.%08x c %d m %d v %d rest %x first %08x.%08x %s\n",
2453 add->last.l_ui, add->last.l_uf, add->count,
2454 (int)add->mode, (int)add->ver, (u_int)add->rs,
2455 add->first.l_ui, add->first.l_uf, sptoa(&add->addr)));
2456 /* if we didn't update an existing entry, alloc replacement */
2458 mon = emalloc(sizeof(*mon));
2467 /* MGOT macro is specific to collect_mru_list() */
2471 if (MRU_GOT_ALL == got) { \
2473 mon = add_mru(mon); \
2480 mrulist_ctrl_c_hook(void)
2482 mrulist_interrupted = TRUE;
2493 const u_int sleep_msecs = 5;
2494 static int ntpd_row_limit = MRU_ROW_LIMIT;
2495 int c_mru_l_rc; /* this function's return code */
2496 u_char got; /* MRU_GOT_* bits */
2505 char req_buf[CTL_MAX_DATA_LEN];
2518 int si; /* server index in response */
2519 int ci; /* client (our) index for validation */
2520 int ri; /* request index (.# suffix) */
2524 sockaddr_u addr_older;
2526 int have_addr_older;
2527 int have_last_older;
2528 u_int restarted_count;
2533 if (!fetch_nonce(nonce, sizeof(nonce)))
2537 restarted_count = 0;
2539 INIT_DLIST(mru_list, mlink);
2540 cb = NTP_HASH_SIZE * sizeof(*hash_table);
2541 INSIST(NULL == hash_table);
2542 hash_table = emalloc_zero(cb);
2545 list_complete = FALSE;
2551 mon = emalloc_zero(cb);
2554 next_report = time(NULL) + MRU_REPORT_SECS;
2556 limit = min(3 * MAXFRAGS, ntpd_row_limit);
2558 snprintf(req_buf, sizeof(req_buf), "nonce=%s, frags=%d%s",
2559 nonce, frags, parms);
2564 fprintf(stderr, "READ_MRU parms: %s\n", req_buf);
2566 qres = doqueryex(CTL_OP_READ_MRU, 0, 0,
2567 strlen(req_buf), req_buf,
2568 &rstatus, &rsize, &rdata, TRUE);
2570 if (CERR_UNKNOWNVAR == qres && ri > 0) {
2572 * None of the supplied prior entries match, so
2573 * toss them from our list and try again.
2577 "no overlap between %d prior entries and server MRU list\n",
2580 recent = HEAD_DLIST(mru_list, mlink);
2581 INSIST(recent != NULL);
2584 "tossing prior entry %s to resync\n",
2585 sptoa(&recent->addr));
2586 UNLINK_DLIST(recent, mlink);
2587 hash = NTP_HASH_ADDR(&recent->addr);
2588 UNLINK_SLIST(unlinked, hash_table[hash],
2589 recent, hlink, mru);
2590 INSIST(unlinked == recent);
2594 if (NULL == HEAD_DLIST(mru_list, mlink)) {
2596 if (restarted_count > 8) {
2598 "Giving up after 8 restarts from the beginning.\n"
2599 "With high-traffic NTP servers, this can occur if the\n"
2600 "MRU list is limited to less than about 16 seconds' of\n"
2601 "entries. See the 'mru' ntp.conf directive to adjust.\n");
2602 goto cleanup_return;
2606 "---> Restarting from the beginning, retry #%u\n",
2609 } else if (CERR_UNKNOWNVAR == qres) {
2611 "CERR_UNKNOWNVAR from ntpd but no priors given.\n");
2612 goto cleanup_return;
2613 } else if (CERR_BADVALUE == qres) {
2618 "Reverted to row limit from fragments limit.\n");
2620 /* ntpd has lower cap on row limit */
2622 limit = min(limit, ntpd_row_limit);
2625 "Row limit reduced to %d following CERR_BADVALUE.\n",
2628 } else if (ERR_INCOMPLETE == qres ||
2629 ERR_TIMEOUT == qres) {
2631 * Reduce the number of rows/frags requested by
2632 * half to recover from lost response fragments.
2635 frags = max(2, frags / 2);
2638 "Frag limit reduced to %d following incomplete response.\n",
2641 limit = max(2, limit / 2);
2644 "Row limit reduced to %d following incomplete response.\n",
2648 show_error_msg(qres, 0);
2649 goto cleanup_return;
2652 * This is a cheap cop-out implementation of rawmode
2653 * output for mrulist. A better approach would be to
2654 * dump similar output after the list is collected by
2655 * ntpq with a continuous sequence of indexes. This
2656 * cheap approach has indexes resetting to zero for
2657 * each query/response, and duplicates are not
2660 if (!qres && rawmode)
2661 printvars(rsize, rdata, rstatus, TYPE_SYS, 1, stdout);
2663 have_addr_older = FALSE;
2664 have_last_older = FALSE;
2665 while (!qres && nextvar(&rsize, &rdata, &tag, &val)) {
2668 fprintf(stderr, "nextvar gave: %s = %s\n",
2673 if (!strcmp(tag, "addr.older")) {
2674 if (!have_last_older) {
2676 "addr.older %s before last.older\n",
2678 goto cleanup_return;
2680 if (!decodenetnum(val, &addr_older)) {
2682 "addr.older %s garbled\n",
2684 goto cleanup_return;
2686 hash = NTP_HASH_ADDR(&addr_older);
2687 for (recent = hash_table[hash];
2689 recent = recent->hlink)
2694 if (NULL == recent) {
2696 "addr.older %s not in hash table\n",
2698 goto cleanup_return;
2700 if (!L_ISEQU(&last_older,
2703 "last.older %08x.%08x mismatches %08x.%08x expected.\n",
2708 goto cleanup_return;
2710 have_addr_older = TRUE;
2711 } else if (1 != sscanf(tag, "addr.%d", &si)
2714 else if (decodenetnum(val, &mon->addr))
2719 if (!strcmp(tag, "last.older")) {
2720 if ('0' != val[0] ||
2722 !hextolfp(val + 2, &last_older)) {
2724 "last.older %s garbled\n",
2726 goto cleanup_return;
2728 have_last_older = TRUE;
2729 } else if (!strcmp(tag, "last.newest")) {
2732 "last.newest %s before complete row, got = 0x%x\n",
2734 goto cleanup_return;
2738 "last.newest %s before now=\n",
2740 goto cleanup_return;
2742 head = HEAD_DLIST(mru_list, mlink);
2744 if ('0' != val[0] ||
2746 !hextolfp(val + 2, &newest) ||
2750 "last.newest %s mismatches %08x.%08x",
2754 goto cleanup_return;
2757 list_complete = TRUE;
2758 } else if (1 != sscanf(tag, "last.%d", &si) ||
2759 si != ci || '0' != val[0] ||
2761 !hextolfp(val + 2, &mon->last)) {
2766 * allow interrupted retrieval,
2767 * using most recent retrieved
2768 * entry's last seen timestamp
2769 * as the end of operation.
2776 if (1 != sscanf(tag, "first.%d", &si) ||
2777 si != ci || '0' != val[0] ||
2779 !hextolfp(val + 2, &mon->first))
2781 MGOT(MRU_GOT_FIRST);
2785 if (!strcmp(tag, "nonce")) {
2786 strlcpy(nonce, val, sizeof(nonce));
2789 } else if (strcmp(tag, "now") ||
2792 !hextolfp(val + 2, pnow))
2798 if (1 != sscanf(tag, "ct.%d", &si) ||
2800 1 != sscanf(val, "%d", &mon->count)
2803 MGOT(MRU_GOT_COUNT);
2807 if (1 != sscanf(tag, "mv.%d", &si) ||
2809 1 != sscanf(val, "%d", &mv))
2811 mon->mode = PKT_MODE(mv);
2812 mon->ver = PKT_VERSION(mv);
2817 if (1 != sscanf(tag, "rs.%d", &si) ||
2819 1 != sscanf(val, "0x%hx", &mon->rs))
2827 /* ignore unknown tags */
2831 list_complete = TRUE;
2832 if (list_complete) {
2833 INSIST(0 == ri || have_addr_older);
2835 if (mrulist_interrupted) {
2836 printf("mrulist retrieval interrupted by operator.\n"
2837 "Displaying partial client list.\n");
2840 if (list_complete || mrulist_interrupted) {
2842 "\rRetrieved %u unique MRU entries and %u updates.\n",
2843 mru_count, mru_dupes);
2847 if (time(NULL) >= next_report) {
2848 next_report += MRU_REPORT_SECS;
2849 fprintf(stderr, "\r%u (%u updates) ", mru_count,
2855 * Snooze for a bit between queries to let ntpd catch
2856 * up with other duties.
2860 #elif !defined(HAVE_NANOSLEEP)
2861 sleep((sleep_msecs / 1000) + 1);
2864 struct timespec interv = { 0,
2865 1000 * sleep_msecs };
2866 nanosleep(&interv, NULL);
2870 * If there were no errors, increase the number of rows
2871 * to a maximum of 3 * MAXFRAGS (the most packets ntpq
2872 * can handle in one response), on the assumption that
2873 * no less than 3 rows fit in each packet, capped at
2874 * our best guess at the server's row limit.
2878 frags = min(MAXFRAGS, frags + 1);
2880 limit = min3(3 * MAXFRAGS,
2887 * prepare next query with as many address and last-seen
2888 * timestamps as will fit in a single packet.
2891 req_end = req_buf + sizeof(req_buf);
2892 #define REQ_ROOM (req_end - req)
2893 snprintf(req, REQ_ROOM, "nonce=%s, %s=%d%s", nonce,
2903 if (nonce_uses >= 4) {
2904 if (!fetch_nonce(nonce, sizeof(nonce)))
2905 goto cleanup_return;
2910 for (ri = 0, recent = HEAD_DLIST(mru_list, mlink);
2912 ri++, recent = NEXT_DLIST(mru_list, recent, mlink)) {
2914 snprintf(buf, sizeof(buf),
2915 ", addr.%d=%s, last.%d=0x%08x.%08x",
2916 ri, sptoa(&recent->addr), ri,
2917 recent->last.l_ui, recent->last.l_uf);
2918 chars = strlen(buf);
2919 if ((size_t)REQ_ROOM <= chars)
2921 memcpy(req, buf, chars + 1);
2927 goto retain_hash_table;
2942 * qcmp_mru_addr - sort MRU entries by remote address.
2944 * All IPv4 addresses sort before any IPv6, addresses are sorted by
2945 * value within address family.
2953 const mru * const * ppm1 = v1;
2954 const mru * const * ppm2 = v2;
2965 af1 = AF(&pm1->addr);
2966 af2 = AF(&pm2->addr);
2969 return (AF_INET == af1)
2973 cmplen = SIZEOF_INADDR(af1);
2974 addr_off = (AF_INET == af1)
2975 ? offsetof(struct sockaddr_in, sin_addr)
2976 : offsetof(struct sockaddr_in6, sin6_addr);
2978 return memcmp((const char *)&pm1->addr + addr_off,
2979 (const char *)&pm2->addr + addr_off,
2990 return -qcmp_mru_addr(v1, v2);
2995 * qcmp_mru_count - sort MRU entries by times seen (hit count).
3003 const mru * const * ppm1 = v1;
3004 const mru * const * ppm2 = v2;
3011 return (pm1->count < pm2->count)
3013 : ((pm1->count == pm2->count)
3025 return -qcmp_mru_count(v1, v2);
3030 * qcmp_mru_avgint - sort MRU entries by average interval.
3038 const mru * const * ppm1 = v1;
3039 const mru * const * ppm2 = v2;
3049 interval = pm1->last;
3050 L_SUB(&interval, &pm1->first);
3051 LFPTOD(&interval, avg1);
3054 interval = pm2->last;
3055 L_SUB(&interval, &pm2->first);
3056 LFPTOD(&interval, avg2);
3061 else if (avg1 > avg2)
3064 /* secondary sort on lstint - rarely tested */
3065 if (L_ISEQU(&pm1->last, &pm2->last))
3067 else if (L_ISGEQ(&pm1->last, &pm2->last))
3080 return -qcmp_mru_avgint(v1, v2);
3085 * mrulist - ntpq's mrulist command to fetch an arbitrarily large Most
3086 * Recently Used (seen) remote address list from ntpd.
3088 * Similar to ntpdc's monlist command, but not limited to a single
3089 * request/response, and thereby not limited to a few hundred remote
3092 * See ntpd/ntp_control.c read_mru_list() for comments on the way
3093 * CTL_OP_READ_MRU is designed to be used.
3095 * mrulist intentionally differs from monlist in the way the avgint
3096 * column is calculated. monlist includes the time after the last
3097 * packet from the client until the monlist query time in the average,
3098 * while mrulist excludes it. That is, monlist's average interval grows
3099 * over time for remote addresses not heard from in some time, while it
3100 * remains unchanged in mrulist. This also affects the avgint value for
3101 * entries representing a single packet, with identical first and last
3102 * timestamps. mrulist shows 0 avgint, monlist shows a value identical
3107 struct parse * pcmd,
3111 const char mincount_eq[] = "mincount=";
3112 const char resall_eq[] = "resall=";
3113 const char resany_eq[] = "resany=";
3114 const char maxlstint_eq[] = "maxlstint=";
3115 const char laddr_eq[] = "laddr=";
3116 const char sort_eq[] = "sort=";
3117 mru_sort_order order;
3119 char parms_buf[128];
3135 mrulist_interrupted = FALSE;
3136 push_ctrl_c_handler(&mrulist_ctrl_c_hook);
3138 "Ctrl-C will stop MRU retrieval and display partial results.\n");
3141 order = MRUSORT_DEF;
3142 parms_buf[0] = '\0';
3144 for (i = 0; i < pcmd->nargs; i++) {
3145 arg = pcmd->argval[i].string;
3147 cb = strlen(arg) + 1;
3148 if ((!strncmp(resall_eq, arg, sizeof(resall_eq)
3149 - 1) || !strncmp(resany_eq, arg,
3150 sizeof(resany_eq) - 1) || !strncmp(
3151 mincount_eq, arg, sizeof(mincount_eq) - 1)
3152 || !strncmp(laddr_eq, arg, sizeof(laddr_eq)
3153 - 1) || !strncmp(maxlstint_eq, arg,
3154 sizeof(laddr_eq) - 1)) && parms + cb + 2 <=
3155 parms_buf + sizeof(parms_buf)) {
3156 /* these are passed intact to ntpd */
3157 memcpy(parms, ", ", 2);
3159 memcpy(parms, arg, cb);
3161 } else if (!strncmp(sort_eq, arg,
3162 sizeof(sort_eq) - 1)) {
3163 arg += sizeof(sort_eq) - 1;
3165 n < COUNTOF(mru_sort_keywords);
3167 if (!strcmp(mru_sort_keywords[n],
3170 if (n < COUNTOF(mru_sort_keywords))
3172 } else if (!strcmp("limited", arg) ||
3173 !strcmp("kod", arg)) {
3174 /* transform to resany=... */
3175 snprintf(buf, sizeof(buf),
3180 cb = 1 + strlen(buf);
3182 parms_buf + sizeof(parms_buf)) {
3183 memcpy(parms, buf, cb);
3188 "ignoring unrecognized mrulist parameter: %s\n",
3194 if (!collect_mru_list(parms, &now))
3197 /* display the results */
3199 goto cleanup_return;
3201 /* construct an array of entry pointers in default order */
3202 sorted = eallocarray(mru_count, sizeof(*sorted));
3204 if (MRUSORT_R_DEF != order) {
3205 ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3206 INSIST(ppentry < sorted + mru_count);
3211 REV_ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3212 INSIST(ppentry < sorted + mru_count);
3215 REV_ITER_DLIST_END()
3218 if (ppentry - sorted != (int)mru_count) {
3220 "mru_count %u should match MRU list depth %ld.\n",
3221 mru_count, (long)(ppentry - sorted));
3223 goto cleanup_return;
3226 /* re-sort sorted[] if not default or reverse default */
3227 if (MRUSORT_R_DEF < order)
3228 qsort(sorted, mru_count, sizeof(sorted[0]),
3229 mru_qcmp_table[order]);
3231 mrulist_interrupted = FALSE;
3232 printf( "lstint avgint rstr r m v count rport remote address\n"
3233 "==============================================================================\n");
3235 for (ppentry = sorted; ppentry < sorted + mru_count; ppentry++) {
3238 L_SUB(&interval, &recent->last);
3239 LFPTOD(&interval, flstint);
3240 lstint = (int)(flstint + 0.5);
3241 interval = recent->last;
3242 L_SUB(&interval, &recent->first);
3243 LFPTOD(&interval, favgint);
3244 favgint /= recent->count;
3245 avgint = (int)(favgint + 0.5);
3246 fprintf(fp, "%6d %6d %4hx %c %d %d %6d %5u %s\n",
3247 lstint, avgint, recent->rs,
3248 (RES_KOD & recent->rs)
3250 : (RES_LIMITED & recent->rs)
3253 (int)recent->mode, (int)recent->ver,
3254 recent->count, SRCPORT(&recent->addr),
3255 nntohost(&recent->addr));
3258 if (mrulist_interrupted) {
3259 fputs("\n --interrupted--\n", fp);
3267 "--- completed, freeing sorted[] pointers\n");
3274 fprintf(stderr, "... freeing MRU entries\n");
3277 ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3281 fprintf(stderr, "... freeing hash_table[]\n");
3286 INIT_DLIST(mru_list, mlink);
3288 pop_ctrl_c_handler(&mrulist_ctrl_c_hook);
3293 * validate_ifnum - helper for ifstats()
3295 * Ensures rows are received in order and complete.
3305 if (prow->ifnum == ifnum)
3307 if (prow->ifnum + 1 <= ifnum) {
3308 if (*pfields < IFSTATS_FIELDS)
3309 fprintf(fp, "Warning: incomplete row with %d (of %d) fields\n",
3310 *pfields, IFSTATS_FIELDS);
3312 prow->ifnum = ifnum;
3316 "received if index %u, have %d of %d fields for index %u, aborting.\n",
3317 ifnum, *pfields, IFSTATS_FIELDS, prow->ifnum);
3323 * another_ifstats_field - helper for ifstats()
3325 * If all fields for the row have been received, print it.
3328 another_ifstats_field(
3337 /* we understand 12 tags */
3338 if (IFSTATS_FIELDS > *pfields)
3341 " interface name send\n"
3342 " # address/broadcast drop flag ttl mc received sent failed peers uptime\n"
3343 "==============================================================================\n");
3346 "%3u %-24.24s %c %4x %3u %2u %6u %6u %6u %5u %8d\n"
3348 prow->ifnum, prow->name,
3352 prow->flags, prow->ttl, prow->mcast_count,
3353 prow->received, prow->sent, prow->send_errors,
3354 prow->peer_count, prow->uptime, sptoa(&prow->addr));
3355 if (!SOCK_UNSPEC(&prow->bcast))
3356 fprintf(fp, " %s\n", sptoa(&prow->bcast));
3357 ifnum = prow->ifnum;
3359 prow->ifnum = ifnum;
3364 * ifstats - ntpq -c ifstats modeled on ntpdc -c ifstats.
3368 struct parse * pcmd,
3372 const char addr_fmt[] = "addr.%u";
3373 const char bcast_fmt[] = "bcast.%u";
3374 const char en_fmt[] = "en.%u"; /* enabled */
3375 const char flags_fmt[] = "flags.%u";
3376 const char mc_fmt[] = "mc.%u"; /* mcast count */
3377 const char name_fmt[] = "name.%u";
3378 const char pc_fmt[] = "pc.%u"; /* peer count */
3379 const char rx_fmt[] = "rx.%u";
3380 const char tl_fmt[] = "tl.%u"; /* ttl */
3381 const char tx_fmt[] = "tx.%u";
3382 const char txerr_fmt[] = "txerr.%u";
3383 const char up_fmt[] = "up.%u"; /* uptime */
3396 qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, 0, NULL, &rstatus,
3398 if (qres) /* message already displayed */
3402 " interface name send\n"
3403 " # address/broadcast drop flag ttl mc received sent failed peers uptime\n"
3404 "==============================================================================\n");
3410 while (nextvar(&dsize, &datap, &tag, &val)) {
3413 fprintf(stderr, "nextvar gave: %s = %s\n", tag, val);
3418 if (1 == sscanf(tag, addr_fmt, &ui) &&
3419 decodenetnum(val, &row.addr))
3424 if (1 == sscanf(tag, bcast_fmt, &ui) &&
3426 decodenetnum(val, &row.bcast)))
3431 if (1 == sscanf(tag, en_fmt, &ui) &&
3432 1 == sscanf(val, "%d", &row.enabled))
3437 if (1 == sscanf(tag, flags_fmt, &ui) &&
3438 1 == sscanf(val, "0x%x", &row.flags))
3443 if (1 == sscanf(tag, mc_fmt, &ui) &&
3444 1 == sscanf(val, "%u", &row.mcast_count))
3449 if (1 == sscanf(tag, name_fmt, &ui)) {
3453 len - 2 < sizeof(row.name)) {
3455 memcpy(row.name, val + 1, len);
3456 row.name[len] = '\0';
3463 if (1 == sscanf(tag, pc_fmt, &ui) &&
3464 1 == sscanf(val, "%u", &row.peer_count))
3469 if (1 == sscanf(tag, rx_fmt, &ui) &&
3470 1 == sscanf(val, "%u", &row.received))
3475 if (1 == sscanf(tag, tl_fmt, &ui) &&
3476 1 == sscanf(val, "%u", &row.ttl))
3478 else if (1 == sscanf(tag, tx_fmt, &ui) &&
3479 1 == sscanf(val, "%u", &row.sent))
3481 else if (1 == sscanf(tag, txerr_fmt, &ui) &&
3482 1 == sscanf(val, "%u", &row.send_errors))
3487 if (1 == sscanf(tag, up_fmt, &ui) &&
3488 1 == sscanf(val, "%u", &row.uptime))
3494 /* error out if rows out of order */
3495 validate_ifnum(fp, ui, &fields, &row);
3496 /* if the row is complete, print it */
3497 another_ifstats_field(&fields, &row, fp);
3500 if (fields != IFSTATS_FIELDS)
3501 fprintf(fp, "Warning: incomplete row with %d (of %d) fields\n",
3502 fields, IFSTATS_FIELDS);
3509 * validate_reslist_idx - helper for reslist()
3511 * Ensures rows are received in order and complete.
3514 validate_reslist_idx(
3521 if (prow->idx == idx)
3523 if (prow->idx + 1 == idx) {
3524 if (*pfields < RESLIST_FIELDS)
3525 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3526 *pfields, RESLIST_FIELDS);
3532 "received reslist index %u, have %d of %d fields for index %u, aborting.\n",
3533 idx, *pfields, RESLIST_FIELDS, prow->idx);
3539 * another_reslist_field - helper for reslist()
3541 * If all fields for the row have been received, print it.
3544 another_reslist_field(
3550 char addrmaskstr[128];
3551 int prefix; /* subnet mask as prefix bits count */
3555 /* we understand 4 tags */
3556 if (RESLIST_FIELDS > *pfields)
3559 prefix = sockaddr_masktoprefixlen(&prow->mask);
3561 snprintf(addrmaskstr, sizeof(addrmaskstr), "%s/%d",
3562 stoa(&prow->addr), prefix);
3564 snprintf(addrmaskstr, sizeof(addrmaskstr), "%s %s",
3565 stoa(&prow->addr), stoa(&prow->mask));
3568 " hits addr/prefix or addr mask\n"
3570 "==============================================================================\n");
3575 prow->hits, addrmaskstr, prow->flagstr);
3583 * reslist - ntpq -c reslist modeled on ntpdc -c reslist.
3587 struct parse * pcmd,
3591 const char addr_fmtu[] = "addr.%u";
3592 const char mask_fmtu[] = "mask.%u";
3593 const char hits_fmt[] = "hits.%u";
3594 const char flags_fmt[] = "flags.%u";
3595 const char qdata[] = "addr_restrictions";
3596 const int qdata_chars = COUNTOF(qdata) - 1;
3609 qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, qdata_chars,
3610 qdata, &rstatus, &dsize, &datap);
3611 if (qres) /* message already displayed */
3615 " hits addr/prefix or addr mask\n"
3617 "==============================================================================\n");
3623 while (nextvar(&dsize, &datap, &tag, &val)) {
3626 fprintf(stderr, "nextvar gave: %s = %s\n", tag, val);
3631 if (1 == sscanf(tag, addr_fmtu, &ui) &&
3632 decodenetnum(val, &row.addr))
3637 if (1 == sscanf(tag, flags_fmt, &ui)) {
3639 row.flagstr[0] = '\0';
3641 } else if ((len = strlen(val)) < sizeof(row.flagstr)) {
3642 memcpy(row.flagstr, val, len);
3643 row.flagstr[len] = '\0';
3646 /* no flags, and still !comprende */
3647 row.flagstr[0] = '\0';
3653 if (1 == sscanf(tag, hits_fmt, &ui) &&
3654 1 == sscanf(val, "%lu", &row.hits))
3659 if (1 == sscanf(tag, mask_fmtu, &ui) &&
3660 decodenetnum(val, &row.mask))
3666 /* error out if rows out of order */
3667 validate_reslist_idx(fp, ui, &fields, &row);
3668 /* if the row is complete, print it */
3669 another_reslist_field(&fields, &row, fp);
3672 if (fields != RESLIST_FIELDS)
3673 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3674 fields, RESLIST_FIELDS);
3681 * collect_display_vdc
3684 collect_display_vdc(
3691 static const char * const suf[2] = { "adr", "port" };
3692 static const char * const leapbits[4] = { "00", "01",
3694 struct varlist vl[MAXLIST];
3710 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3712 if (NTP_ADD != pvdc->type) {
3713 doaddvlist(vl, pvdc->tag);
3715 for (n = 0; n < COUNTOF(suf); n++) {
3716 snprintf(tagbuf, sizeof(tagbuf), "%s%s",
3718 doaddvlist(vl, tagbuf);
3722 qres = doquerylist(vl, CTL_OP_READVAR, as, 0, &rstatus, &rsize,
3726 return; /* error msg already displayed */
3729 * iterate over the response variables filling vdc_table with
3730 * the retrieved values.
3732 while (nextvar(&rsize, &rdata, &tag, &val)) {
3735 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3736 len = strlen(pvdc->tag);
3737 if (strncmp(tag, pvdc->tag, len))
3739 if (NTP_ADD != pvdc->type) {
3740 if ('\0' != tag[len])
3745 for (n = 0; n < COUNTOF(suf); n++) {
3746 if (strcmp(tag + len, suf[n]))
3754 if (NULL == pvdc->tag)
3756 switch (pvdc->type) {
3759 /* strip surrounding double quotes */
3760 if ('"' == val[0]) {
3762 if (len > 0 && '"' == val[len - 1]) {
3763 val[len - 1] = '\0';
3768 case NTP_MODE: /* fallthru */
3770 pvdc->v.str = estrdup(val);
3774 decodets(val, &pvdc->v.lfp);
3778 if (!decodenetnum(val, &pvdc->v.sau))
3779 fprintf(stderr, "malformed %s=%s\n",
3784 if (0 == n) { /* adr */
3785 if (!decodenetnum(val, &pvdc->v.sau))
3787 "malformed %s=%s\n",
3790 if (atouint(val, &ul))
3791 SET_PORT(&pvdc->v.sau,
3803 fprintf(fp, "associd=%u status=%04x %s,\n", as, rstatus,
3804 statustoa(vtype, rstatus));
3807 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3808 switch (pvdc->type) {
3811 if (pvdc->v.str != NULL) {
3812 fprintf(fp, "%s %s\n", pvdc->display,
3819 case NTP_ADD: /* fallthru */
3821 fprintf(fp, "%s %s\n", pvdc->display,
3822 nntohostp(&pvdc->v.sau));
3826 fprintf(fp, "%s %s\n", pvdc->display,
3827 prettydate(&pvdc->v.lfp));
3831 atouint(pvdc->v.str, &ul);
3832 fprintf(fp, "%s %s\n", pvdc->display,
3837 atouint(pvdc->v.str, &ul);
3838 fprintf(fp, "%s %s\n", pvdc->display,
3839 leapbits[ul & 0x3]);
3843 fprintf(stderr, "unexpected vdc type %d for %s\n",
3844 pvdc->type, pvdc->tag);
3852 * sysstats - implements ntpq -c sysstats modeled on ntpdc -c sysstats
3860 static vdc sysstats_vdc[] = {
3861 VDC_INIT("ss_uptime", "uptime: ", NTP_STR),
3862 VDC_INIT("ss_reset", "sysstats reset: ", NTP_STR),
3863 VDC_INIT("ss_received", "packets received: ", NTP_STR),
3864 VDC_INIT("ss_thisver", "current version: ", NTP_STR),
3865 VDC_INIT("ss_oldver", "older version: ", NTP_STR),
3866 VDC_INIT("ss_badformat", "bad length or format: ", NTP_STR),
3867 VDC_INIT("ss_badauth", "authentication failed:", NTP_STR),
3868 VDC_INIT("ss_declined", "declined: ", NTP_STR),
3869 VDC_INIT("ss_restricted", "restricted: ", NTP_STR),
3870 VDC_INIT("ss_limited", "rate limited: ", NTP_STR),
3871 VDC_INIT("ss_kodsent", "KoD responses: ", NTP_STR),
3872 VDC_INIT("ss_processed", "processed for time: ", NTP_STR),
3874 VDC_INIT("ss_lamport", "Lamport violations: ", NTP_STR),
3875 VDC_INIT("ss_tsrounding", "bad timestamp rounding:", NTP_STR),
3877 VDC_INIT(NULL, NULL, 0)
3880 collect_display_vdc(0, sysstats_vdc, FALSE, fp);
3885 * sysinfo - modeled on ntpdc's sysinfo
3893 static vdc sysinfo_vdc[] = {
3894 VDC_INIT("peeradr", "system peer: ", NTP_ADP),
3895 VDC_INIT("peermode", "system peer mode: ", NTP_MODE),
3896 VDC_INIT("leap", "leap indicator: ", NTP_2BIT),
3897 VDC_INIT("stratum", "stratum: ", NTP_STR),
3898 VDC_INIT("precision", "log2 precision: ", NTP_STR),
3899 VDC_INIT("rootdelay", "root delay: ", NTP_STR),
3900 VDC_INIT("rootdisp", "root dispersion: ", NTP_STR),
3901 VDC_INIT("refid", "reference ID: ", NTP_STR),
3902 VDC_INIT("reftime", "reference time: ", NTP_LFP),
3903 VDC_INIT("sys_jitter", "system jitter: ", NTP_STR),
3904 VDC_INIT("clk_jitter", "clock jitter: ", NTP_STR),
3905 VDC_INIT("clk_wander", "clock wander: ", NTP_STR),
3906 VDC_INIT("bcastdelay", "broadcast delay: ", NTP_STR),
3907 VDC_INIT("authdelay", "symm. auth. delay:", NTP_STR),
3908 VDC_INIT(NULL, NULL, 0)
3911 collect_display_vdc(0, sysinfo_vdc, TRUE, fp);
3916 * kerninfo - modeled on ntpdc's kerninfo
3924 static vdc kerninfo_vdc[] = {
3925 VDC_INIT("koffset", "pll offset: ", NTP_STR),
3926 VDC_INIT("kfreq", "pll frequency: ", NTP_STR),
3927 VDC_INIT("kmaxerr", "maximum error: ", NTP_STR),
3928 VDC_INIT("kesterr", "estimated error: ", NTP_STR),
3929 VDC_INIT("kstflags", "kernel status: ", NTP_STR),
3930 VDC_INIT("ktimeconst", "pll time constant: ", NTP_STR),
3931 VDC_INIT("kprecis", "precision: ", NTP_STR),
3932 VDC_INIT("kfreqtol", "frequency tolerance: ", NTP_STR),
3933 VDC_INIT("kppsfreq", "pps frequency: ", NTP_STR),
3934 VDC_INIT("kppsstab", "pps stability: ", NTP_STR),
3935 VDC_INIT("kppsjitter", "pps jitter: ", NTP_STR),
3936 VDC_INIT("kppscalibdur", "calibration interval ", NTP_STR),
3937 VDC_INIT("kppscalibs", "calibration cycles: ", NTP_STR),
3938 VDC_INIT("kppsjitexc", "jitter exceeded: ", NTP_STR),
3939 VDC_INIT("kppsstbexc", "stability exceeded: ", NTP_STR),
3940 VDC_INIT("kppscaliberrs", "calibration errors: ", NTP_STR),
3941 VDC_INIT(NULL, NULL, 0)
3944 collect_display_vdc(0, kerninfo_vdc, TRUE, fp);
3949 * monstats - implements ntpq -c monstats
3957 static vdc monstats_vdc[] = {
3958 VDC_INIT("mru_enabled", "enabled: ", NTP_STR),
3959 VDC_INIT("mru_depth", "addresses: ", NTP_STR),
3960 VDC_INIT("mru_deepest", "peak addresses: ", NTP_STR),
3961 VDC_INIT("mru_maxdepth", "maximum addresses: ", NTP_STR),
3962 VDC_INIT("mru_mindepth", "reclaim above count:", NTP_STR),
3963 VDC_INIT("mru_maxage", "reclaim older than: ", NTP_STR),
3964 VDC_INIT("mru_mem", "kilobytes: ", NTP_STR),
3965 VDC_INIT("mru_maxmem", "maximum kilobytes: ", NTP_STR),
3966 VDC_INIT(NULL, NULL, 0)
3969 collect_display_vdc(0, monstats_vdc, FALSE, fp);
3974 * iostats - ntpq -c iostats - network input and output counters
3982 static vdc iostats_vdc[] = {
3983 VDC_INIT("iostats_reset", "time since reset: ", NTP_STR),
3984 VDC_INIT("total_rbuf", "receive buffers: ", NTP_STR),
3985 VDC_INIT("free_rbuf", "free receive buffers: ", NTP_STR),
3986 VDC_INIT("used_rbuf", "used receive buffers: ", NTP_STR),
3987 VDC_INIT("rbuf_lowater", "low water refills: ", NTP_STR),
3988 VDC_INIT("io_dropped", "dropped packets: ", NTP_STR),
3989 VDC_INIT("io_ignored", "ignored packets: ", NTP_STR),
3990 VDC_INIT("io_received", "received packets: ", NTP_STR),
3991 VDC_INIT("io_sent", "packets sent: ", NTP_STR),
3992 VDC_INIT("io_sendfailed", "packet send failures: ", NTP_STR),
3993 VDC_INIT("io_wakeups", "input wakeups: ", NTP_STR),
3994 VDC_INIT("io_goodwakeups", "useful input wakeups: ", NTP_STR),
3995 VDC_INIT(NULL, NULL, 0)
3998 collect_display_vdc(0, iostats_vdc, FALSE, fp);
4003 * timerstats - ntpq -c timerstats - interval timer counters
4011 static vdc timerstats_vdc[] = {
4012 VDC_INIT("timerstats_reset", "time since reset: ", NTP_STR),
4013 VDC_INIT("timer_overruns", "timer overruns: ", NTP_STR),
4014 VDC_INIT("timer_xmts", "calls to transmit: ", NTP_STR),
4015 VDC_INIT(NULL, NULL, 0)
4018 collect_display_vdc(0, timerstats_vdc, FALSE, fp);
4023 * authinfo - implements ntpq -c authinfo
4031 static vdc authinfo_vdc[] = {
4032 VDC_INIT("authreset", "time since reset:", NTP_STR),
4033 VDC_INIT("authkeys", "stored keys: ", NTP_STR),
4034 VDC_INIT("authfreek", "free keys: ", NTP_STR),
4035 VDC_INIT("authklookups", "key lookups: ", NTP_STR),
4036 VDC_INIT("authknotfound", "keys not found: ", NTP_STR),
4037 VDC_INIT("authkuncached", "uncached keys: ", NTP_STR),
4038 VDC_INIT("authkexpired", "expired keys: ", NTP_STR),
4039 VDC_INIT("authencrypts", "encryptions: ", NTP_STR),
4040 VDC_INIT("authdecrypts", "decryptions: ", NTP_STR),
4041 VDC_INIT(NULL, NULL, 0)
4044 collect_display_vdc(0, authinfo_vdc, FALSE, fp);
4049 * pstats - show statistics for a peer
4057 static vdc pstats_vdc[] = {
4058 VDC_INIT("src", "remote host: ", NTP_ADD),
4059 VDC_INIT("dst", "local address: ", NTP_ADD),
4060 VDC_INIT("timerec", "time last received: ", NTP_STR),
4061 VDC_INIT("timer", "time until next send:", NTP_STR),
4062 VDC_INIT("timereach", "reachability change: ", NTP_STR),
4063 VDC_INIT("sent", "packets sent: ", NTP_STR),
4064 VDC_INIT("received", "packets received: ", NTP_STR),
4065 VDC_INIT("badauth", "bad authentication: ", NTP_STR),
4066 VDC_INIT("bogusorg", "bogus origin: ", NTP_STR),
4067 VDC_INIT("oldpkt", "duplicate: ", NTP_STR),
4068 VDC_INIT("seldisp", "bad dispersion: ", NTP_STR),
4069 VDC_INIT("selbroken", "bad reference time: ", NTP_STR),
4070 VDC_INIT("candidate", "candidate order: ", NTP_STR),
4071 VDC_INIT(NULL, NULL, 0)
4075 associd = checkassocid(pcmd->argval[0].uval);
4079 collect_display_vdc(associd, pstats_vdc, TRUE, fp);