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 vl = findlistvar(vlist, name);
451 fprintf(stderr, "Variable list full\n");
455 if (NULL == vl->name) {
456 vl->name = estrdup(name);
457 } else if (vl->value != NULL) {
463 vl->value = estrdup(value);
469 * dormvlist - remove variable(s) from the variable list
473 struct varlist *vlist,
483 while (nextvar(&len, &vars, &name, &value)) {
484 vl = findlistvar(vlist, name);
485 if (vl == 0 || vl->name == 0) {
486 (void) fprintf(stderr, "Variable `%s' not found\n",
489 free((void *)(intptr_t)vl->name);
492 for ( ; (vl+1) < (g_varlist + MAXLIST)
493 && (vl+1)->name != 0; vl++) {
494 vl->name = (vl+1)->name;
495 vl->value = (vl+1)->value;
497 vl->name = vl->value = 0;
504 * doclearvlist - clear a variable list
508 struct varlist *vlist
511 register struct varlist *vl;
513 for (vl = vlist; vl < vlist + MAXLIST && vl->name != 0; vl++) {
514 free((void *)(intptr_t)vl->name);
516 if (vl->value != 0) {
525 * makequerydata - form a data buffer to be included with a query
529 struct varlist *vlist,
534 register struct varlist *vl;
535 register char *cp, *cpend;
536 register size_t namelen, valuelen;
537 register size_t totallen;
540 cpend = data + *datalen;
542 for (vl = vlist; vl < vlist + MAXLIST && vl->name != 0; vl++) {
543 namelen = strlen(vl->name);
547 valuelen = strlen(vl->value);
548 totallen = namelen + valuelen + (valuelen != 0) + (cp != data);
549 if (cp + totallen > cpend) {
551 "***Ignoring variables starting with `%s'\n",
558 memcpy(cp, vl->name, (size_t)namelen);
562 memcpy(cp, vl->value, (size_t)valuelen);
566 *datalen = (size_t)(cp - data);
571 * doquerylist - send a message including variables in a list
575 struct varlist *vlist,
584 char data[CTL_MAX_DATA_LEN];
587 datalen = sizeof(data);
588 makequerydata(vlist, &datalen, data);
590 return doquery(op, associd, auth, datalen, data, rstatus, dsize,
596 * doprintvlist - print the variables on a list
600 struct varlist *vlist,
606 if (NULL == vlist->name) {
607 fprintf(fp, "No variables on list\n");
610 for (n = 0; n < MAXLIST && vlist[n].name != NULL; n++) {
611 if (NULL == vlist[n].value)
612 fprintf(fp, "%s\n", vlist[n].name);
614 fprintf(fp, "%s=%s\n", vlist[n].name,
620 * addvars - add variables to the variable list
629 doaddvlist(g_varlist, pcmd->argval[0].string);
634 * rmvars - remove variables from the variable list
643 dormvlist(g_varlist, pcmd->argval[0].string);
648 * clearvars - clear the variable list
657 doclearvlist(g_varlist);
662 * showvars - show variables on the variable list
671 doprintvlist(g_varlist, fp);
676 * dolist - send a request with the given list of variables
680 struct varlist *vlist,
694 * if we're asking for specific variables don't include the
695 * status header line in the output.
700 quiet = (vlist->name != NULL);
702 res = doquerylist(vlist, op, associd, 0, &rstatus, &dsize, &datap);
708 fprintf(fp, "server=%s ", currenthost);
711 fprintf(fp, "No system%s variables returned\n",
712 (type == TYPE_CLOCK) ? " clock" : "");
715 "No information returned for%s association %u\n",
716 (type == TYPE_CLOCK) ? " clock" : "",
722 fprintf(fp, "associd=%u ", associd);
723 printvars(dsize, datap, (int)rstatus, type, quiet, fp);
729 * readlist - send a read variables request with the variables on the list
740 if (pcmd->nargs == 0) {
743 /* HMS: I think we want the u_int32 target here, not the u_long */
744 if (pcmd->argval[0].uval == 0)
746 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
750 type = (0 == associd)
753 dolist(g_varlist, associd, CTL_OP_READVAR, type, fp);
758 * writelist - send a write variables request with the variables on the list
772 if (pcmd->nargs == 0) {
775 /* HMS: Do we really want uval here? */
776 if (pcmd->argval[0].uval == 0)
778 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
782 res = doquerylist(g_varlist, CTL_OP_WRITEVAR, associd, 1, &rstatus,
789 (void) fprintf(fp, "server=%s ", currenthost);
791 (void) fprintf(fp, "done! (no data returned)\n");
793 (void) fprintf(fp,"associd=%u ", associd);
794 printvars(dsize, datap, (int)rstatus,
795 (associd != 0) ? TYPE_PEER : TYPE_SYS, 0, fp);
802 * readvar - send a read variables request with the specified variables
814 struct varlist tmplist[MAXLIST];
818 if (pcmd->nargs == 0 || pcmd->argval[0].uval == 0)
820 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
824 if (pcmd->nargs > 1) {
825 tmpcount = pcmd->nargs - 1;
826 for (u = 0; u < tmpcount; u++)
827 doaddvlist(tmplist, pcmd->argval[1 + u].string);
830 type = (0 == associd)
833 dolist(tmplist, associd, CTL_OP_READVAR, type, fp);
835 doclearvlist(tmplist);
840 * writevar - send a write variables request with the specified variables
854 struct varlist tmplist[MAXLIST];
857 if (pcmd->argval[0].uval == 0)
859 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
863 doaddvlist(tmplist, pcmd->argval[1].string);
865 res = doquerylist(tmplist, CTL_OP_WRITEVAR, associd, 1, &rstatus,
868 doclearvlist(tmplist);
874 fprintf(fp, "server=%s ", currenthost);
876 fprintf(fp, "done! (no data returned)\n");
878 fprintf(fp,"associd=%u ", associd);
879 type = (0 == associd)
882 printvars(dsize, datap, (int)rstatus, type, 0, fp);
889 * clocklist - send a clock variables request with the variables on the list
900 if (pcmd->nargs == 0) {
903 if (pcmd->argval[0].uval == 0)
905 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
909 dolist(g_varlist, associd, CTL_OP_READCLOCK, TYPE_CLOCK, fp);
914 * clockvar - send a clock variables request with the specified variables
923 struct varlist tmplist[MAXLIST];
926 if (pcmd->nargs == 0 || pcmd->argval[0].uval == 0)
928 else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
932 if (pcmd->nargs >= 2)
933 doaddvlist(tmplist, pcmd->argval[1].string);
935 dolist(tmplist, associd, CTL_OP_READCLOCK, TYPE_CLOCK, fp);
937 doclearvlist(tmplist);
942 * findassidrange - verify a range of association ID's
954 int ind[COUNTOF(assids)];
962 assids[0] = checkassocid(assid1);
965 assids[1] = checkassocid(assid2);
969 for (a = 0; a < COUNTOF(assids); a++) {
971 for (i = 0; i < numassoc; i++)
972 if (assoc_cache[i].assid == assids[a])
975 for (a = 0; a < COUNTOF(assids); a++)
978 "***Association ID %u not found in list\n",
983 if (ind[0] < ind[1]) {
996 * mreadlist - send a read variables request for multiple associations
1008 if (!findassidrange(pcmd->argval[0].uval, pcmd->argval[1].uval,
1012 for (i = from; i <= to; i++) {
1015 if (!dolist(g_varlist, assoc_cache[i].assid,
1016 CTL_OP_READVAR, TYPE_PEER, fp))
1024 * mreadvar - send a read variables request for multiple associations
1035 struct varlist tmplist[MAXLIST];
1036 struct varlist *pvars;
1038 if (!findassidrange(pcmd->argval[0].uval, pcmd->argval[1].uval,
1043 if (pcmd->nargs >= 3) {
1044 doaddvlist(tmplist, pcmd->argval[2].string);
1050 for (i = from; i <= to; i++) {
1051 if (!dolist(pvars, assoc_cache[i].assid, CTL_OP_READVAR,
1056 if (pvars == tmplist)
1057 doclearvlist(tmplist);
1064 * dogetassoc - query the host for its list of associations
1077 res = doquery(CTL_OP_READSTAT, 0, 0, 0, (char *)0, &rstatus,
1085 fprintf(fp, "server=%s ", currenthost);
1086 fprintf(fp, "No association ID's returned\n");
1092 fprintf(stderr, "server=%s ", currenthost);
1094 "***Server returned %zu octets, should be multiple of 4\n",
1102 if (numassoc >= assoc_cache_slots) {
1105 pus = (const void *)datap;
1106 assoc_cache[numassoc].assid = ntohs(*pus);
1107 datap += sizeof(*pus);
1108 pus = (const void *)datap;
1109 assoc_cache[numassoc].status = ntohs(*pus);
1110 datap += sizeof(*pus);
1111 dsize -= 2 * sizeof(*pus);
1113 fprintf(stderr, "[%u] ",
1114 assoc_cache[numassoc].assid);
1119 fprintf(stderr, "\n%d associations total\n", numassoc);
1127 * printassoc - print the current list of associations
1143 const char *condition = "";
1144 const char *last_event;
1147 if (numassoc == 0) {
1148 (void) fprintf(fp, "No association ID's in list\n");
1156 "\nind assid status conf reach auth condition last_event cnt\n");
1158 "===========================================================\n");
1159 for (i = 0; i < numassoc; i++) {
1160 statval = (u_char) CTL_PEER_STATVAL(assoc_cache[i].status);
1161 if (!showall && !(statval & (CTL_PST_CONFIG|CTL_PST_REACH)))
1163 event = CTL_PEER_EVENT(assoc_cache[i].status);
1164 event_count = CTL_PEER_NEVNT(assoc_cache[i].status);
1165 if (statval & CTL_PST_CONFIG)
1169 if (statval & CTL_PST_BCAST) {
1171 if (statval & CTL_PST_AUTHENABLE)
1176 if (statval & CTL_PST_REACH)
1180 if (statval & CTL_PST_AUTHENABLE) {
1181 if (statval & CTL_PST_AUTHENTIC)
1189 if (pktversion > NTP_OLDVERSION) {
1190 switch (statval & 0x7) {
1192 case CTL_PST_SEL_REJECT:
1193 condition = "reject";
1196 case CTL_PST_SEL_SANE:
1197 condition = "falsetick";
1200 case CTL_PST_SEL_CORRECT:
1201 condition = "excess";
1204 case CTL_PST_SEL_SELCAND:
1205 condition = "outlier";
1208 case CTL_PST_SEL_SYNCCAND:
1209 condition = "candidate";
1212 case CTL_PST_SEL_EXCESS:
1213 condition = "backup";
1216 case CTL_PST_SEL_SYSPEER:
1217 condition = "sys.peer";
1220 case CTL_PST_SEL_PPS:
1221 condition = "pps.peer";
1225 switch (statval & 0x3) {
1227 case OLD_CTL_PST_SEL_REJECT:
1228 if (!(statval & OLD_CTL_PST_SANE))
1229 condition = "insane";
1230 else if (!(statval & OLD_CTL_PST_DISP))
1231 condition = "hi_disp";
1236 case OLD_CTL_PST_SEL_SELCAND:
1237 condition = "sel_cand";
1240 case OLD_CTL_PST_SEL_SYNCCAND:
1241 condition = "sync_cand";
1244 case OLD_CTL_PST_SEL_SYSPEER:
1245 condition = "sys_peer";
1249 switch (PEER_EVENT|event) {
1252 last_event = "mobilize";
1256 last_event = "demobilize";
1260 last_event = "reachable";
1264 last_event = "unreachable";
1268 last_event = "restart";
1272 last_event = "no_reply";
1276 last_event = "rate_exceeded";
1280 last_event = "access_denied";
1284 last_event = "leap_armed";
1288 last_event = "sys_peer";
1292 last_event = "clock_alarm";
1299 snprintf(buf, sizeof(buf),
1300 "%3d %5u %04x %3.3s %4s %4.4s %9.9s %11s %2lu",
1301 i + 1, assoc_cache[i].assid,
1302 assoc_cache[i].status, conf, reach, auth,
1303 condition, last_event, event_count);
1304 bp = buf + strlen(buf);
1305 while (bp > buf && ' ' == bp[-1])
1308 fprintf(fp, "%s\n", buf);
1314 * associations - get, record and print a list of associations
1329 * lassociations - get, record and print a long list of associations
1344 * passociations - print the association list
1358 * lpassociations - print the long association list
1372 * saveconfig - dump ntp server configuration to server file
1385 if (0 == pcmd->nargs)
1388 res = doquery(CTL_OP_SAVECONFIG, 0, 1,
1389 strlen(pcmd->argval[0].string),
1390 pcmd->argval[0].string, &rstatus, &dsize,
1397 fprintf(fp, "(no response message, curiously)");
1399 fprintf(fp, "%.*s", (int)dsize, datap); /* cast is wobbly */
1405 * radiostatus - print the radio status returned by the server
1419 res = doquery(CTL_OP_READCLOCK, 0, 0, 0, (char *)0, &rstatus,
1426 (void) fprintf(fp, "server=%s ", currenthost);
1428 (void) fprintf(fp, "No radio status string returned\n");
1432 asciize(dsize, datap, fp);
1437 * when - print how long its been since his last packet arrived
1450 else if (reftime->l_ui != 0)
1455 if (ts->l_ui < lasttime->l_ui)
1457 return (ts->l_ui - lasttime->l_ui);
1462 * Pretty-print an interval into the given buffer, in a human-friendly format.
1478 snprintf(buf, cb, "%ld", diff);
1482 diff = (diff + 29) / 60;
1484 snprintf(buf, cb, "%ldm", diff);
1488 diff = (diff + 29) / 60;
1490 snprintf(buf, cb, "%ldh", diff);
1494 diff = (diff + 11) / 24;
1496 snprintf(buf, cb, "%ldd", diff);
1500 /* years are only approximated... */
1501 diff = (long)floor(diff / 365.25 + 0.5);
1502 snprintf(buf, cb, "%ldy", diff);
1516 dummy = SRCADR(sock);
1517 ch = (char)(((dummy&0xf0000000)==0xe0000000) ? 'm' :
1518 ((dummy&0x000000ff)==0x000000ff) ? 'b' :
1519 ((dummy&0xffffffff)==0x7f000001) ? 'l' :
1520 ((dummy&0xffffffe0)==0x00000000) ? '-' :
1524 if (IN6_IS_ADDR_MULTICAST(PSOCK_ADDR6(sock)))
1537 * A list of variables required by the peers command
1539 struct varlist opeervarlist[] = {
1540 { "srcadr", 0 }, /* 0 */
1541 { "dstadr", 0 }, /* 1 */
1542 { "stratum", 0 }, /* 2 */
1543 { "hpoll", 0 }, /* 3 */
1544 { "ppoll", 0 }, /* 4 */
1545 { "reach", 0 }, /* 5 */
1546 { "delay", 0 }, /* 6 */
1547 { "offset", 0 }, /* 7 */
1548 { "jitter", 0 }, /* 8 */
1549 { "dispersion", 0 }, /* 9 */
1550 { "rec", 0 }, /* 10 */
1551 { "reftime", 0 }, /* 11 */
1552 { "srcport", 0 }, /* 12 */
1553 { "hmode", 0 }, /* 13 */
1557 struct varlist peervarlist[] = {
1558 { "srcadr", 0 }, /* 0 */
1559 { "refid", 0 }, /* 1 */
1560 { "stratum", 0 }, /* 2 */
1561 { "hpoll", 0 }, /* 3 */
1562 { "ppoll", 0 }, /* 4 */
1563 { "reach", 0 }, /* 5 */
1564 { "delay", 0 }, /* 6 */
1565 { "offset", 0 }, /* 7 */
1566 { "jitter", 0 }, /* 8 */
1567 { "dispersion", 0 }, /* 9 */
1568 { "rec", 0 }, /* 10 */
1569 { "reftime", 0 }, /* 11 */
1570 { "srcport", 0 }, /* 12 */
1571 { "hmode", 0 }, /* 13 */
1572 { "srchost", 0 }, /* 14 */
1576 struct varlist apeervarlist[] = {
1577 { "srcadr", 0 }, /* 0 */
1578 { "refid", 0 }, /* 1 */
1579 { "assid", 0 }, /* 2 */
1580 { "stratum", 0 }, /* 3 */
1581 { "hpoll", 0 }, /* 4 */
1582 { "ppoll", 0 }, /* 5 */
1583 { "reach", 0 }, /* 6 */
1584 { "delay", 0 }, /* 7 */
1585 { "offset", 0 }, /* 8 */
1586 { "jitter", 0 }, /* 9 */
1587 { "dispersion", 0 }, /* 10 */
1588 { "rec", 0 }, /* 11 */
1589 { "reftime", 0 }, /* 12 */
1590 { "srcport", 0 }, /* 13 */
1591 { "hmode", 0 }, /* 14 */
1592 { "srchost", 0 }, /* 15 */
1598 * Decode an incoming data buffer and print a line in the peer list
1602 struct varlist *pvl,
1621 sockaddr_u dum_store;
1622 sockaddr_u refidadr;
1626 const char *dstadr_refid = "0.0.0.0";
1627 const char *serverlocal;
1642 char whenbuf[8], pollbuf[8];
1643 char clock_name[LENHOSTNAME];
1647 have_srchost = FALSE;
1648 have_dstadr = FALSE;
1649 have_da_rid = FALSE;
1650 have_jitter = FALSE;
1653 clock_name[0] = '\0';
1659 while (nextvar(&datalen, &data, &name, &value)) {
1660 if (!strcmp("srcadr", name) ||
1661 !strcmp("peeradr", name)) {
1662 if (!decodenetnum(value, &srcadr))
1663 fprintf(stderr, "malformed %s=%s\n",
1665 } else if (!strcmp("srchost", name)) {
1666 if (pvl == peervarlist || pvl == apeervarlist) {
1667 len = strlen(value);
1669 (size_t)len < sizeof(clock_name)) {
1673 memcpy(clock_name, value, len);
1674 clock_name[len] = '\0';
1675 have_srchost = TRUE;
1678 } else if (!strcmp("dstadr", name)) {
1679 if (decodenetnum(value, &dum_store)) {
1680 type = decodeaddrtype(&dum_store);
1683 if (pvl == opeervarlist) {
1685 dstadr_refid = trunc_left(stoa(&dstadr), 15);
1688 } else if (!strcmp("hmode", name)) {
1689 decodeint(value, &hmode);
1690 } else if (!strcmp("refid", name)) {
1691 if ( (pvl == peervarlist)
1692 && (drefid == REFID_IPV4)) {
1694 drlen = strlen(value);
1697 } else if (drlen <= 4) {
1699 memcpy(&u32, value, drlen);
1700 dstadr_refid = refid_str(u32, 1);
1701 } else if (decodenetnum(value, &refidadr)) {
1702 if (SOCK_UNSPEC(&refidadr))
1703 dstadr_refid = "0.0.0.0";
1704 else if (ISREFCLOCKADR(&refidadr))
1706 refnumtoa(&refidadr);
1711 have_da_rid = FALSE;
1713 } else if ( (pvl == apeervarlist)
1714 || (pvl == peervarlist)) {
1715 /* no need to check drefid == REFID_HASH */
1717 drlen = strlen(value);
1720 } else if (drlen <= 4) {
1722 memcpy(&u32, value, drlen);
1723 dstadr_refid = refid_str(u32, 1);
1724 //fprintf(stderr, "apeervarlist S1 refid: value=<%s>\n", value);
1725 } else if (decodenetnum(value, &refidadr)) {
1726 if (SOCK_UNSPEC(&refidadr))
1727 dstadr_refid = "0.0.0.0";
1728 else if (ISREFCLOCKADR(&refidadr))
1730 refnumtoa(&refidadr);
1732 char *buf = emalloc(10);
1733 int i = ntohl(refidadr.sa4.sin_addr.s_addr);
1738 //fprintf(stderr, "apeervarlist refid: value=<%x>\n", i);
1740 //fprintf(stderr, "apeervarlist refid: value=<%s>\n", value);
1742 have_da_rid = FALSE;
1745 } else if (!strcmp("stratum", name)) {
1746 decodeuint(value, &stratum);
1747 } else if (!strcmp("hpoll", name)) {
1748 if (decodeint(value, &hpoll) && hpoll < 0)
1749 hpoll = NTP_MINPOLL;
1750 } else if (!strcmp("ppoll", name)) {
1751 if (decodeint(value, &ppoll) && ppoll < 0)
1752 ppoll = NTP_MINPOLL;
1753 } else if (!strcmp("reach", name)) {
1754 decodeuint(value, &reach);
1755 } else if (!strcmp("delay", name)) {
1756 decodetime(value, &estdelay);
1757 } else if (!strcmp("offset", name)) {
1758 decodetime(value, &estoffset);
1759 } else if (!strcmp("jitter", name)) {
1760 if ((pvl == peervarlist || pvl == apeervarlist)
1761 && decodetime(value, &estjitter))
1763 } else if (!strcmp("rootdisp", name) ||
1764 !strcmp("dispersion", name)) {
1765 decodetime(value, &estdisp);
1766 } else if (!strcmp("rec", name)) {
1767 decodets(value, &rec);
1768 } else if (!strcmp("srcport", name) ||
1769 !strcmp("peerport", name)) {
1770 decodeuint(value, &srcport);
1771 } else if (!strcmp("reftime", name)) {
1772 if (!decodets(value, &reftime))
1775 // fprintf(stderr, "UNRECOGNIZED name=%s ", name);
1780 * hmode gives the best guidance for the t column. If the response
1781 * did not include hmode we'll use the old decodeaddrtype() result.
1786 /* broadcastclient or multicastclient */
1790 case MODE_BROADCAST:
1791 /* broadcast or multicast server */
1792 if (IS_MCAST(&srcadr))
1799 if (ISREFCLOCKADR(&srcadr))
1800 type = 'l'; /* local refclock*/
1801 else if (SOCK_UNSPEC(&srcadr))
1802 type = 'p'; /* pool */
1803 else if (IS_MCAST(&srcadr))
1804 type = 'a'; /* manycastclient */
1806 type = 'u'; /* unicast */
1810 type = 's'; /* symmetric active */
1811 break; /* configured */
1814 type = 'S'; /* symmetric passive */
1815 break; /* ephemeral */
1819 * Got everything, format the line
1821 poll_sec = 1 << min(ppoll, hpoll);
1822 if (pktversion > NTP_OLDVERSION)
1823 c = flash3[CTL_PEER_STATVAL(rstatus) & 0x7];
1825 c = flash2[CTL_PEER_STATVAL(rstatus) & 0x3];
1827 if ((pvl == peervarlist || pvl == apeervarlist)
1829 serverlocal = nntohost_col(&dstadr,
1830 (size_t)min(LIB_BUFLENGTH - 1, maxhostlen),
1833 if (currenthostisnum)
1834 serverlocal = trunc_left(currenthost,
1837 serverlocal = currenthost;
1839 fprintf(fp, "%-*s ", (int)maxhostlen, serverlocal);
1841 if (AF_UNSPEC == af || AF(&srcadr) == af) {
1843 strlcpy(clock_name, nntohost(&srcadr),
1844 sizeof(clock_name));
1845 /* wide and long source - space over on next line */
1846 /* allow for host + sp if > 1 and regular tally + source + sp */
1847 if (wideremote && 15 < strlen(clock_name))
1848 fprintf(fp, "%c%s\n%*s", c, clock_name,
1849 ((numhosts > 1) ? (int)maxhostlen + 1 : 0)
1852 fprintf(fp, "%c%-15.15s ", c, clock_name);
1856 drlen = strlen(dstadr_refid);
1857 makeascii(drlen, dstadr_refid, fp);
1859 if (pvl == apeervarlist) {
1862 fprintf(fp, "%-6d", associd);
1864 while (drlen++ < 15)
1868 " %2ld %c %4.4s %4.4s %3lo %7.7s %8.7s %7.7s\n",
1870 prettyinterval(whenbuf, sizeof(whenbuf),
1871 when(&ts, &rec, &reftime)),
1872 prettyinterval(pollbuf, sizeof(pollbuf),
1874 reach, lfptoms(&estdelay, 3),
1875 lfptoms(&estoffset, 3),
1877 ? lfptoms(&estjitter, 3)
1878 : lfptoms(&estdisp, 3));
1887 * dogetpeers - given an association ID, read and print the spreadsheet
1892 struct varlist *pvl,
1904 res = doquerylist(pvl, CTL_OP_READVAR, associd, 0, &rstatus,
1910 res = doquery(CTL_OP_READVAR, associd, 0, 0, NULL, &rstatus,
1919 fprintf(stderr, "server=%s ", currenthost);
1921 "***No information returned for association %u\n",
1926 return doprintpeers(pvl, associd, (int)rstatus, dsize, datap,
1932 * peers - print a peer spreadsheet
1942 char fullname[LENHOSTNAME];
1944 const char * name_or_num;
1947 if (!dogetassoc(fp))
1950 for (u = 0; u < numhosts; u++) {
1951 if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
1952 name_or_num = nntohost(&netnum);
1953 sl = strlen(name_or_num);
1954 maxhostlen = max(maxhostlen, sl);
1958 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
1961 " remote refid st t when poll reach delay offset jitter\n");
1963 for (u = 0; u <= maxhostlen; u++)
1966 "==============================================================================\n");
1968 for (u = 0; u < numassoc; u++) {
1970 !(CTL_PEER_STATVAL(assoc_cache[u].status)
1971 & (CTL_PST_CONFIG|CTL_PST_REACH))) {
1973 fprintf(stderr, "eliding [%d]\n",
1974 (int)assoc_cache[u].assid);
1977 if (!dogetpeers(peervarlist, (int)assoc_cache[u].assid,
1986 * doapeers - print a peer spreadsheet with assocIDs
1996 char fullname[LENHOSTNAME];
1998 const char * name_or_num;
2001 if (!dogetassoc(fp))
2004 for (u = 0; u < numhosts; u++) {
2005 if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
2006 name_or_num = nntohost(&netnum);
2007 sl = strlen(name_or_num);
2008 maxhostlen = max(maxhostlen, sl);
2012 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2015 " remote refid assid st t when poll reach delay offset jitter\n");
2017 for (u = 0; u <= maxhostlen; u++)
2020 "==============================================================================\n");
2022 for (u = 0; u < numassoc; u++) {
2024 !(CTL_PEER_STATVAL(assoc_cache[u].status)
2025 & (CTL_PST_CONFIG|CTL_PST_REACH))) {
2027 fprintf(stderr, "eliding [%d]\n",
2028 (int)assoc_cache[u].assid);
2031 if (!dogetpeers(apeervarlist, (int)assoc_cache[u].assid,
2040 * peers - print a peer spreadsheet
2049 if (drefid == REFID_HASH) {
2054 if (pcmd->nargs == 1) {
2055 if (pcmd->argval->ival == 6)
2066 * apeers - print a peer spreadsheet, with assocIDs
2077 if (pcmd->nargs == 1) {
2078 if (pcmd->argval->ival == 6)
2083 doapeers(0, fp, af);
2088 * lpeers - print a peer spreadsheet including all fuzzball peers
2099 if (pcmd->nargs == 1) {
2100 if (pcmd->argval->ival == 6)
2110 * opeers - print a peer spreadsheet
2120 char fullname[LENHOSTNAME];
2123 if (!dogetassoc(fp))
2126 for (i = 0; i < numhosts; ++i) {
2127 if (getnetnum(chosts[i].name, &netnum, fullname, af))
2128 if (strlen(fullname) > maxhostlen)
2129 maxhostlen = strlen(fullname);
2132 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2135 " remote local st t when poll reach delay offset disp\n");
2137 for (i = 0; i <= maxhostlen; ++i)
2140 "==============================================================================\n");
2142 for (i = 0; i < numassoc; i++) {
2144 !(CTL_PEER_STATVAL(assoc_cache[i].status) &
2145 (CTL_PST_CONFIG | CTL_PST_REACH)))
2147 if (!dogetpeers(opeervarlist, assoc_cache[i].assid, fp, af))
2155 * opeers - print a peer spreadsheet the old way
2166 if (pcmd->nargs == 1) {
2167 if (pcmd->argval->ival == 6)
2172 doopeers(0, fp, af);
2177 * lopeers - print a peer spreadsheet including all fuzzball peers
2188 if (pcmd->nargs == 1) {
2189 if (pcmd->argval->ival == 6)
2194 doopeers(1, fp, af);
2199 * config - send a configuration command to a remote host
2216 cfgcmd = pcmd->argval[0].string;
2222 "Command = %s\n", pcmd->keyword, cfgcmd);
2224 res = doquery(CTL_OP_CONFIGURE, 0, 1,
2225 strlen(cfgcmd), cfgcmd,
2226 &rstatus, &rsize, &rdata);
2231 if (rsize > 0 && '\n' == rdata[rsize - 1])
2234 resp = emalloc(rsize + 1);
2235 memcpy(resp, rdata, rsize);
2239 if (1 == sscanf(resp, "column %d syntax error", &col)
2240 && col >= 0 && (size_t)col <= strlen(cfgcmd) + 1) {
2242 fputs(" *", stdout); /* "ntpq> :config " */
2244 printf("%s\n", cfgcmd);
2245 for (i = 0; i < col; i++)
2247 fputs("^\n", stdout);
2249 printf("%s\n", resp);
2255 * config_from_file - remotely configure an ntpd daemon using the
2256 * specified configuration file
2257 * SK: This function is a kludge at best and is full of bad design
2259 * 1. ntpq uses UDP, which means that there is no guarantee of in-order,
2260 * error-free delivery.
2261 * 2. The maximum length of a packet is constrained, and as a result, the
2262 * maximum length of a line in a configuration file is constrained.
2263 * Longer lines will lead to unpredictable results.
2264 * 3. Since this function is sending a line at a time, we can't update
2265 * the control key through the configuration file (YUCK!!)
2267 * Pearly: There are a few places where 'size_t' is cast to 'int' based
2268 * on the assumption that 'int' can hold the size of the involved
2269 * buffers without overflow.
2283 char config_cmd[MAXLINE];
2292 "Filename = %s\n", pcmd->keyword,
2293 pcmd->argval[0].string);
2295 config_fd = fopen(pcmd->argval[0].string, "r");
2296 if (NULL == config_fd) {
2297 printf("ERROR!! Couldn't open file: %s\n",
2298 pcmd->argval[0].string);
2302 printf("Sending configuration file, one line at a time.\n");
2304 while (fgets(config_cmd, MAXLINE, config_fd) != NULL) {
2305 /* Eliminate comments first. */
2306 cp = strchr(config_cmd, '#');
2307 config_len = (NULL != cp)
2308 ? (size_t)(cp - config_cmd)
2309 : strlen(config_cmd);
2311 /* [Bug 3015] make sure there's no trailing whitespace;
2312 * the fix for [Bug 2853] on the server side forbids
2313 * those. And don't transmit empty lines, as this would
2316 while (config_len != 0 &&
2317 (u_char)config_cmd[config_len-1] <= ' ')
2319 config_cmd[config_len] = '\0';
2322 if (0 == config_len)
2327 res = doquery(CTL_OP_CONFIGURE, 0, 1,
2328 config_len, config_cmd,
2329 &rstatus, &rsize, &rdata);
2330 while (res != 0 && retry_limit--);
2332 printf("Line No: %d query failed: %.*s\n"
2333 "Subsequent lines not sent.\n",
2334 i, (int)config_len, config_cmd);
2339 /* Right-strip the result code string, then output the
2340 * last line executed, with result code. */
2341 while (rsize != 0 && (u_char)rdata[rsize - 1] <= ' ')
2343 printf("Line No: %d %.*s: %.*s\n", i,
2345 (int)config_len, config_cmd);
2347 printf("Done sending file\n");
2358 const char nonce_eq[] = "nonce=";
2366 * Retrieve a nonce specific to this client to demonstrate to
2367 * ntpd that we're capable of receiving responses to our source
2368 * IP address, and thereby unlikely to be forging the source.
2370 qres = doquery(CTL_OP_REQ_NONCE, 0, 0, 0, NULL, &rstatus,
2373 fprintf(stderr, "nonce request failed\n");
2377 if ((size_t)rsize <= sizeof(nonce_eq) - 1 ||
2378 strncmp(rdata, nonce_eq, sizeof(nonce_eq) - 1)) {
2379 fprintf(stderr, "unexpected nonce response format: %.*s\n",
2380 (int)rsize, rdata); /* cast is wobbly */
2383 chars = rsize - (sizeof(nonce_eq) - 1);
2384 if (chars >= (int)cb_nonce)
2386 memcpy(nonce, rdata + sizeof(nonce_eq) - 1, chars);
2387 nonce[chars] = '\0';
2389 ('\r' == nonce[chars - 1] || '\n' == nonce[chars - 1])) {
2391 nonce[chars] = '\0';
2399 * add_mru Add and entry to mru list, hash table, and allocate
2400 * and return a replacement.
2401 * This is a helper for collect_mru_list().
2413 hash = NTP_HASH_ADDR(&add->addr);
2414 /* see if we have it among previously received entries */
2415 for (mon = hash_table[hash]; mon != NULL; mon = mon->hlink)
2416 if (SOCK_EQ(&mon->addr, &add->addr))
2419 if (!L_ISGEQ(&add->first, &mon->first)) {
2421 "add_mru duplicate %s new first ts %08x.%08x precedes prior %08x.%08x\n",
2422 sptoa(&add->addr), add->last.l_ui,
2423 add->last.l_uf, mon->last.l_ui,
2427 UNLINK_DLIST(mon, mlink);
2428 UNLINK_SLIST(unlinked, hash_table[hash], mon, hlink, mru);
2429 INSIST(unlinked == mon);
2431 TRACE(2, ("(updated from %08x.%08x) ", mon->last.l_ui,
2434 LINK_DLIST(mru_list, add, mlink);
2435 LINK_SLIST(hash_table[hash], add, hlink);
2436 TRACE(2, ("add_mru %08x.%08x c %d m %d v %d rest %x first %08x.%08x %s\n",
2437 add->last.l_ui, add->last.l_uf, add->count,
2438 (int)add->mode, (int)add->ver, (u_int)add->rs,
2439 add->first.l_ui, add->first.l_uf, sptoa(&add->addr)));
2440 /* if we didn't update an existing entry, alloc replacement */
2442 mon = emalloc(sizeof(*mon));
2451 /* MGOT macro is specific to collect_mru_list() */
2455 if (MRU_GOT_ALL == got) { \
2457 mon = add_mru(mon); \
2464 mrulist_ctrl_c_hook(void)
2466 mrulist_interrupted = TRUE;
2477 const u_int sleep_msecs = 5;
2478 static int ntpd_row_limit = MRU_ROW_LIMIT;
2479 int c_mru_l_rc; /* this function's return code */
2480 u_char got; /* MRU_GOT_* bits */
2489 char req_buf[CTL_MAX_DATA_LEN];
2502 int si; /* server index in response */
2503 int ci; /* client (our) index for validation */
2504 int ri; /* request index (.# suffix) */
2508 sockaddr_u addr_older;
2510 int have_addr_older;
2511 int have_last_older;
2512 u_int restarted_count;
2517 if (!fetch_nonce(nonce, sizeof(nonce)))
2521 restarted_count = 0;
2523 INIT_DLIST(mru_list, mlink);
2524 cb = NTP_HASH_SIZE * sizeof(*hash_table);
2525 INSIST(NULL == hash_table);
2526 hash_table = emalloc_zero(cb);
2529 list_complete = FALSE;
2535 mon = emalloc_zero(cb);
2538 next_report = time(NULL) + MRU_REPORT_SECS;
2540 limit = min(3 * MAXFRAGS, ntpd_row_limit);
2542 snprintf(req_buf, sizeof(req_buf), "nonce=%s, frags=%d%s",
2543 nonce, frags, parms);
2548 fprintf(stderr, "READ_MRU parms: %s\n", req_buf);
2550 qres = doqueryex(CTL_OP_READ_MRU, 0, 0,
2551 strlen(req_buf), req_buf,
2552 &rstatus, &rsize, &rdata, TRUE);
2554 if (CERR_UNKNOWNVAR == qres && ri > 0) {
2556 * None of the supplied prior entries match, so
2557 * toss them from our list and try again.
2561 "no overlap between %d prior entries and server MRU list\n",
2564 recent = HEAD_DLIST(mru_list, mlink);
2565 INSIST(recent != NULL);
2568 "tossing prior entry %s to resync\n",
2569 sptoa(&recent->addr));
2570 UNLINK_DLIST(recent, mlink);
2571 hash = NTP_HASH_ADDR(&recent->addr);
2572 UNLINK_SLIST(unlinked, hash_table[hash],
2573 recent, hlink, mru);
2574 INSIST(unlinked == recent);
2578 if (NULL == HEAD_DLIST(mru_list, mlink)) {
2580 if (restarted_count > 8) {
2582 "Giving up after 8 restarts from the beginning.\n"
2583 "With high-traffic NTP servers, this can occur if the\n"
2584 "MRU list is limited to less than about 16 seconds' of\n"
2585 "entries. See the 'mru' ntp.conf directive to adjust.\n");
2586 goto cleanup_return;
2590 "---> Restarting from the beginning, retry #%u\n",
2593 } else if (CERR_UNKNOWNVAR == qres) {
2595 "CERR_UNKNOWNVAR from ntpd but no priors given.\n");
2596 goto cleanup_return;
2597 } else if (CERR_BADVALUE == qres) {
2602 "Reverted to row limit from fragments limit.\n");
2604 /* ntpd has lower cap on row limit */
2606 limit = min(limit, ntpd_row_limit);
2609 "Row limit reduced to %d following CERR_BADVALUE.\n",
2612 } else if (ERR_INCOMPLETE == qres ||
2613 ERR_TIMEOUT == qres) {
2615 * Reduce the number of rows/frags requested by
2616 * half to recover from lost response fragments.
2619 frags = max(2, frags / 2);
2622 "Frag limit reduced to %d following incomplete response.\n",
2625 limit = max(2, limit / 2);
2628 "Row limit reduced to %d following incomplete response.\n",
2632 show_error_msg(qres, 0);
2633 goto cleanup_return;
2636 * This is a cheap cop-out implementation of rawmode
2637 * output for mrulist. A better approach would be to
2638 * dump similar output after the list is collected by
2639 * ntpq with a continuous sequence of indexes. This
2640 * cheap approach has indexes resetting to zero for
2641 * each query/response, and duplicates are not
2644 if (!qres && rawmode)
2645 printvars(rsize, rdata, rstatus, TYPE_SYS, 1, stdout);
2647 have_addr_older = FALSE;
2648 have_last_older = FALSE;
2649 while (!qres && nextvar(&rsize, &rdata, &tag, &val)) {
2651 fprintf(stderr, "nextvar gave: %s = %s\n",
2656 if (!strcmp(tag, "addr.older")) {
2657 if (!have_last_older) {
2659 "addr.older %s before last.older\n",
2661 goto cleanup_return;
2663 if (!decodenetnum(val, &addr_older)) {
2665 "addr.older %s garbled\n",
2667 goto cleanup_return;
2669 hash = NTP_HASH_ADDR(&addr_older);
2670 for (recent = hash_table[hash];
2672 recent = recent->hlink)
2677 if (NULL == recent) {
2679 "addr.older %s not in hash table\n",
2681 goto cleanup_return;
2683 if (!L_ISEQU(&last_older,
2686 "last.older %08x.%08x mismatches %08x.%08x expected.\n",
2691 goto cleanup_return;
2693 have_addr_older = TRUE;
2694 } else if (1 != sscanf(tag, "addr.%d", &si)
2697 else if (decodenetnum(val, &mon->addr))
2702 if (!strcmp(tag, "last.older")) {
2703 if ('0' != val[0] ||
2705 !hextolfp(val + 2, &last_older)) {
2707 "last.older %s garbled\n",
2709 goto cleanup_return;
2711 have_last_older = TRUE;
2712 } else if (!strcmp(tag, "last.newest")) {
2715 "last.newest %s before complete row, got = 0x%x\n",
2717 goto cleanup_return;
2721 "last.newest %s before now=\n",
2723 goto cleanup_return;
2725 head = HEAD_DLIST(mru_list, mlink);
2727 if ('0' != val[0] ||
2729 !hextolfp(val + 2, &newest) ||
2733 "last.newest %s mismatches %08x.%08x",
2737 goto cleanup_return;
2740 list_complete = TRUE;
2741 } else if (1 != sscanf(tag, "last.%d", &si) ||
2742 si != ci || '0' != val[0] ||
2744 !hextolfp(val + 2, &mon->last)) {
2749 * allow interrupted retrieval,
2750 * using most recent retrieved
2751 * entry's last seen timestamp
2752 * as the end of operation.
2759 if (1 != sscanf(tag, "first.%d", &si) ||
2760 si != ci || '0' != val[0] ||
2762 !hextolfp(val + 2, &mon->first))
2764 MGOT(MRU_GOT_FIRST);
2768 if (!strcmp(tag, "nonce")) {
2769 strlcpy(nonce, val, sizeof(nonce));
2772 } else if (strcmp(tag, "now") ||
2775 !hextolfp(val + 2, pnow))
2781 if (1 != sscanf(tag, "ct.%d", &si) ||
2783 1 != sscanf(val, "%d", &mon->count)
2786 MGOT(MRU_GOT_COUNT);
2790 if (1 != sscanf(tag, "mv.%d", &si) ||
2792 1 != sscanf(val, "%d", &mv))
2794 mon->mode = PKT_MODE(mv);
2795 mon->ver = PKT_VERSION(mv);
2800 if (1 != sscanf(tag, "rs.%d", &si) ||
2802 1 != sscanf(val, "0x%hx", &mon->rs))
2810 /* ignore unknown tags */
2814 list_complete = TRUE;
2815 if (list_complete) {
2816 INSIST(0 == ri || have_addr_older);
2818 if (mrulist_interrupted) {
2819 printf("mrulist retrieval interrupted by operator.\n"
2820 "Displaying partial client list.\n");
2823 if (list_complete || mrulist_interrupted) {
2825 "\rRetrieved %u unique MRU entries and %u updates.\n",
2826 mru_count, mru_dupes);
2830 if (time(NULL) >= next_report) {
2831 next_report += MRU_REPORT_SECS;
2832 fprintf(stderr, "\r%u (%u updates) ", mru_count,
2838 * Snooze for a bit between queries to let ntpd catch
2839 * up with other duties.
2843 #elif !defined(HAVE_NANOSLEEP)
2844 sleep((sleep_msecs / 1000) + 1);
2847 struct timespec interv = { 0,
2848 1000 * sleep_msecs };
2849 nanosleep(&interv, NULL);
2853 * If there were no errors, increase the number of rows
2854 * to a maximum of 3 * MAXFRAGS (the most packets ntpq
2855 * can handle in one response), on the assumption that
2856 * no less than 3 rows fit in each packet, capped at
2857 * our best guess at the server's row limit.
2861 frags = min(MAXFRAGS, frags + 1);
2863 limit = min3(3 * MAXFRAGS,
2870 * prepare next query with as many address and last-seen
2871 * timestamps as will fit in a single packet.
2874 req_end = req_buf + sizeof(req_buf);
2875 #define REQ_ROOM (req_end - req)
2876 snprintf(req, REQ_ROOM, "nonce=%s, %s=%d%s", nonce,
2886 if (nonce_uses >= 4) {
2887 if (!fetch_nonce(nonce, sizeof(nonce)))
2888 goto cleanup_return;
2893 for (ri = 0, recent = HEAD_DLIST(mru_list, mlink);
2895 ri++, recent = NEXT_DLIST(mru_list, recent, mlink)) {
2897 snprintf(buf, sizeof(buf),
2898 ", addr.%d=%s, last.%d=0x%08x.%08x",
2899 ri, sptoa(&recent->addr), ri,
2900 recent->last.l_ui, recent->last.l_uf);
2901 chars = strlen(buf);
2902 if ((size_t)REQ_ROOM <= chars)
2904 memcpy(req, buf, chars + 1);
2910 goto retain_hash_table;
2925 * qcmp_mru_addr - sort MRU entries by remote address.
2927 * All IPv4 addresses sort before any IPv6, addresses are sorted by
2928 * value within address family.
2936 const mru * const * ppm1 = v1;
2937 const mru * const * ppm2 = v2;
2948 af1 = AF(&pm1->addr);
2949 af2 = AF(&pm2->addr);
2952 return (AF_INET == af1)
2956 cmplen = SIZEOF_INADDR(af1);
2957 addr_off = (AF_INET == af1)
2958 ? offsetof(struct sockaddr_in, sin_addr)
2959 : offsetof(struct sockaddr_in6, sin6_addr);
2961 return memcmp((const char *)&pm1->addr + addr_off,
2962 (const char *)&pm2->addr + addr_off,
2973 return -qcmp_mru_addr(v1, v2);
2978 * qcmp_mru_count - sort MRU entries by times seen (hit count).
2986 const mru * const * ppm1 = v1;
2987 const mru * const * ppm2 = v2;
2994 return (pm1->count < pm2->count)
2996 : ((pm1->count == pm2->count)
3008 return -qcmp_mru_count(v1, v2);
3013 * qcmp_mru_avgint - sort MRU entries by average interval.
3021 const mru * const * ppm1 = v1;
3022 const mru * const * ppm2 = v2;
3032 interval = pm1->last;
3033 L_SUB(&interval, &pm1->first);
3034 LFPTOD(&interval, avg1);
3037 interval = pm2->last;
3038 L_SUB(&interval, &pm2->first);
3039 LFPTOD(&interval, avg2);
3044 else if (avg1 > avg2)
3047 /* secondary sort on lstint - rarely tested */
3048 if (L_ISEQU(&pm1->last, &pm2->last))
3050 else if (L_ISGEQ(&pm1->last, &pm2->last))
3063 return -qcmp_mru_avgint(v1, v2);
3068 * mrulist - ntpq's mrulist command to fetch an arbitrarily large Most
3069 * Recently Used (seen) remote address list from ntpd.
3071 * Similar to ntpdc's monlist command, but not limited to a single
3072 * request/response, and thereby not limited to a few hundred remote
3075 * See ntpd/ntp_control.c read_mru_list() for comments on the way
3076 * CTL_OP_READ_MRU is designed to be used.
3078 * mrulist intentionally differs from monlist in the way the avgint
3079 * column is calculated. monlist includes the time after the last
3080 * packet from the client until the monlist query time in the average,
3081 * while mrulist excludes it. That is, monlist's average interval grows
3082 * over time for remote addresses not heard from in some time, while it
3083 * remains unchanged in mrulist. This also affects the avgint value for
3084 * entries representing a single packet, with identical first and last
3085 * timestamps. mrulist shows 0 avgint, monlist shows a value identical
3090 struct parse * pcmd,
3094 const char mincount_eq[] = "mincount=";
3095 const char resall_eq[] = "resall=";
3096 const char resany_eq[] = "resany=";
3097 const char maxlstint_eq[] = "maxlstint=";
3098 const char laddr_eq[] = "laddr=";
3099 const char sort_eq[] = "sort=";
3100 mru_sort_order order;
3102 char parms_buf[128];
3118 mrulist_interrupted = FALSE;
3119 push_ctrl_c_handler(&mrulist_ctrl_c_hook);
3121 "Ctrl-C will stop MRU retrieval and display partial results.\n");
3124 order = MRUSORT_DEF;
3125 parms_buf[0] = '\0';
3127 for (i = 0; i < pcmd->nargs; i++) {
3128 arg = pcmd->argval[i].string;
3130 cb = strlen(arg) + 1;
3131 if ((!strncmp(resall_eq, arg, sizeof(resall_eq)
3132 - 1) || !strncmp(resany_eq, arg,
3133 sizeof(resany_eq) - 1) || !strncmp(
3134 mincount_eq, arg, sizeof(mincount_eq) - 1)
3135 || !strncmp(laddr_eq, arg, sizeof(laddr_eq)
3136 - 1) || !strncmp(maxlstint_eq, arg,
3137 sizeof(laddr_eq) - 1)) && parms + cb + 2 <=
3138 parms_buf + sizeof(parms_buf)) {
3139 /* these are passed intact to ntpd */
3140 memcpy(parms, ", ", 2);
3142 memcpy(parms, arg, cb);
3144 } else if (!strncmp(sort_eq, arg,
3145 sizeof(sort_eq) - 1)) {
3146 arg += sizeof(sort_eq) - 1;
3148 n < COUNTOF(mru_sort_keywords);
3150 if (!strcmp(mru_sort_keywords[n],
3153 if (n < COUNTOF(mru_sort_keywords))
3155 } else if (!strcmp("limited", arg) ||
3156 !strcmp("kod", arg)) {
3157 /* transform to resany=... */
3158 snprintf(buf, sizeof(buf),
3163 cb = 1 + strlen(buf);
3165 parms_buf + sizeof(parms_buf)) {
3166 memcpy(parms, buf, cb);
3171 "ignoring unrecognized mrulist parameter: %s\n",
3177 if (!collect_mru_list(parms, &now))
3180 /* display the results */
3182 goto cleanup_return;
3184 /* construct an array of entry pointers in default order */
3185 sorted = eallocarray(mru_count, sizeof(*sorted));
3187 if (MRUSORT_R_DEF != order) {
3188 ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3189 INSIST(ppentry < sorted + mru_count);
3194 REV_ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3195 INSIST(ppentry < sorted + mru_count);
3198 REV_ITER_DLIST_END()
3201 if (ppentry - sorted != (int)mru_count) {
3203 "mru_count %u should match MRU list depth %ld.\n",
3204 mru_count, (long)(ppentry - sorted));
3206 goto cleanup_return;
3209 /* re-sort sorted[] if not default or reverse default */
3210 if (MRUSORT_R_DEF < order)
3211 qsort(sorted, mru_count, sizeof(sorted[0]),
3212 mru_qcmp_table[order]);
3214 mrulist_interrupted = FALSE;
3215 printf( "lstint avgint rstr r m v count rport remote address\n"
3216 "==============================================================================\n");
3218 for (ppentry = sorted; ppentry < sorted + mru_count; ppentry++) {
3221 L_SUB(&interval, &recent->last);
3222 LFPTOD(&interval, flstint);
3223 lstint = (int)(flstint + 0.5);
3224 interval = recent->last;
3225 L_SUB(&interval, &recent->first);
3226 LFPTOD(&interval, favgint);
3227 favgint /= recent->count;
3228 avgint = (int)(favgint + 0.5);
3229 fprintf(fp, "%6d %6d %4hx %c %d %d %6d %5u %s\n",
3230 lstint, avgint, recent->rs,
3231 (RES_KOD & recent->rs)
3233 : (RES_LIMITED & recent->rs)
3236 (int)recent->mode, (int)recent->ver,
3237 recent->count, SRCPORT(&recent->addr),
3238 nntohost(&recent->addr));
3241 if (mrulist_interrupted) {
3242 fputs("\n --interrupted--\n", fp);
3250 "--- completed, freeing sorted[] pointers\n");
3257 fprintf(stderr, "... freeing MRU entries\n");
3260 ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3264 fprintf(stderr, "... freeing hash_table[]\n");
3269 INIT_DLIST(mru_list, mlink);
3271 pop_ctrl_c_handler(&mrulist_ctrl_c_hook);
3276 * validate_ifnum - helper for ifstats()
3278 * Ensures rows are received in order and complete.
3288 if (prow->ifnum == ifnum)
3290 if (prow->ifnum + 1 <= ifnum) {
3291 if (*pfields < IFSTATS_FIELDS)
3292 fprintf(fp, "Warning: incomplete row with %d (of %d) fields\n",
3293 *pfields, IFSTATS_FIELDS);
3295 prow->ifnum = ifnum;
3299 "received if index %u, have %d of %d fields for index %u, aborting.\n",
3300 ifnum, *pfields, IFSTATS_FIELDS, prow->ifnum);
3306 * another_ifstats_field - helper for ifstats()
3308 * If all fields for the row have been received, print it.
3311 another_ifstats_field(
3320 /* we understand 12 tags */
3321 if (IFSTATS_FIELDS > *pfields)
3324 " interface name send\n"
3325 " # address/broadcast drop flag ttl mc received sent failed peers uptime\n"
3326 "==============================================================================\n");
3329 "%3u %-24.24s %c %4x %3u %2u %6u %6u %6u %5u %8d\n"
3331 prow->ifnum, prow->name,
3335 prow->flags, prow->ttl, prow->mcast_count,
3336 prow->received, prow->sent, prow->send_errors,
3337 prow->peer_count, prow->uptime, sptoa(&prow->addr));
3338 if (!SOCK_UNSPEC(&prow->bcast))
3339 fprintf(fp, " %s\n", sptoa(&prow->bcast));
3340 ifnum = prow->ifnum;
3342 prow->ifnum = ifnum;
3347 * ifstats - ntpq -c ifstats modeled on ntpdc -c ifstats.
3351 struct parse * pcmd,
3355 const char addr_fmt[] = "addr.%u";
3356 const char bcast_fmt[] = "bcast.%u";
3357 const char en_fmt[] = "en.%u"; /* enabled */
3358 const char flags_fmt[] = "flags.%u";
3359 const char mc_fmt[] = "mc.%u"; /* mcast count */
3360 const char name_fmt[] = "name.%u";
3361 const char pc_fmt[] = "pc.%u"; /* peer count */
3362 const char rx_fmt[] = "rx.%u";
3363 const char tl_fmt[] = "tl.%u"; /* ttl */
3364 const char tx_fmt[] = "tx.%u";
3365 const char txerr_fmt[] = "txerr.%u";
3366 const char up_fmt[] = "up.%u"; /* uptime */
3379 qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, 0, NULL, &rstatus,
3381 if (qres) /* message already displayed */
3385 " interface name send\n"
3386 " # address/broadcast drop flag ttl mc received sent failed peers uptime\n"
3387 "==============================================================================\n");
3393 while (nextvar(&dsize, &datap, &tag, &val)) {
3395 fprintf(stderr, "nextvar gave: %s = %s\n", tag,
3403 if (1 == sscanf(tag, addr_fmt, &ui) &&
3404 decodenetnum(val, &row.addr))
3409 if (1 == sscanf(tag, bcast_fmt, &ui) &&
3411 decodenetnum(val, &row.bcast)))
3416 if (1 == sscanf(tag, en_fmt, &ui) &&
3417 1 == sscanf(val, "%d", &row.enabled))
3422 if (1 == sscanf(tag, flags_fmt, &ui) &&
3423 1 == sscanf(val, "0x%x", &row.flags))
3428 if (1 == sscanf(tag, mc_fmt, &ui) &&
3429 1 == sscanf(val, "%u", &row.mcast_count))
3434 if (1 == sscanf(tag, name_fmt, &ui)) {
3439 len - 2 < sizeof(row.name)) {
3441 memcpy(row.name, val + 1, len);
3442 row.name[len] = '\0';
3449 if (1 == sscanf(tag, pc_fmt, &ui) &&
3450 1 == sscanf(val, "%u", &row.peer_count))
3455 if (1 == sscanf(tag, rx_fmt, &ui) &&
3456 1 == sscanf(val, "%u", &row.received))
3461 if (1 == sscanf(tag, tl_fmt, &ui) &&
3462 1 == sscanf(val, "%u", &row.ttl))
3464 else if (1 == sscanf(tag, tx_fmt, &ui) &&
3465 1 == sscanf(val, "%u", &row.sent))
3467 else if (1 == sscanf(tag, txerr_fmt, &ui) &&
3468 1 == sscanf(val, "%u", &row.send_errors))
3473 if (1 == sscanf(tag, up_fmt, &ui) &&
3474 1 == sscanf(val, "%u", &row.uptime))
3480 /* error out if rows out of order */
3481 validate_ifnum(fp, ui, &fields, &row);
3482 /* if the row is complete, print it */
3483 another_ifstats_field(&fields, &row, fp);
3486 if (fields != IFSTATS_FIELDS)
3487 fprintf(fp, "Warning: incomplete row with %d (of %d) fields\n",
3488 fields, IFSTATS_FIELDS);
3495 * validate_reslist_idx - helper for reslist()
3497 * Ensures rows are received in order and complete.
3500 validate_reslist_idx(
3507 if (prow->idx == idx)
3509 if (prow->idx + 1 == idx) {
3510 if (*pfields < RESLIST_FIELDS)
3511 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3512 *pfields, RESLIST_FIELDS);
3518 "received reslist index %u, have %d of %d fields for index %u, aborting.\n",
3519 idx, *pfields, RESLIST_FIELDS, prow->idx);
3525 * another_reslist_field - helper for reslist()
3527 * If all fields for the row have been received, print it.
3530 another_reslist_field(
3536 char addrmaskstr[128];
3537 int prefix; /* subnet mask as prefix bits count */
3541 /* we understand 4 tags */
3542 if (RESLIST_FIELDS > *pfields)
3545 prefix = sockaddr_masktoprefixlen(&prow->mask);
3547 snprintf(addrmaskstr, sizeof(addrmaskstr), "%s/%d",
3548 stoa(&prow->addr), prefix);
3550 snprintf(addrmaskstr, sizeof(addrmaskstr), "%s %s",
3551 stoa(&prow->addr), stoa(&prow->mask));
3554 " hits addr/prefix or addr mask\n"
3556 "==============================================================================\n");
3561 prow->hits, addrmaskstr, prow->flagstr);
3569 * reslist - ntpq -c reslist modeled on ntpdc -c reslist.
3573 struct parse * pcmd,
3577 const char addr_fmtu[] = "addr.%u";
3578 const char mask_fmtu[] = "mask.%u";
3579 const char hits_fmt[] = "hits.%u";
3580 const char flags_fmt[] = "flags.%u";
3581 const char qdata[] = "addr_restrictions";
3582 const int qdata_chars = COUNTOF(qdata) - 1;
3595 qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, qdata_chars,
3596 qdata, &rstatus, &dsize, &datap);
3597 if (qres) /* message already displayed */
3601 " hits addr/prefix or addr mask\n"
3603 "==============================================================================\n");
3609 while (nextvar(&dsize, &datap, &tag, &val)) {
3611 fprintf(stderr, "nextvar gave: %s = %s\n", tag,
3619 if (1 == sscanf(tag, addr_fmtu, &ui) &&
3620 decodenetnum(val, &row.addr))
3625 if (1 == sscanf(tag, flags_fmt, &ui)) {
3627 row.flagstr[0] = '\0';
3629 } else if ((len = strlen(val)) < sizeof(row.flagstr)) {
3630 memcpy(row.flagstr, val, len);
3631 row.flagstr[len] = '\0';
3634 /* no flags, and still !comprende */
3635 row.flagstr[0] = '\0';
3641 if (1 == sscanf(tag, hits_fmt, &ui) &&
3642 1 == sscanf(val, "%lu", &row.hits))
3647 if (1 == sscanf(tag, mask_fmtu, &ui) &&
3648 decodenetnum(val, &row.mask))
3654 /* error out if rows out of order */
3655 validate_reslist_idx(fp, ui, &fields, &row);
3656 /* if the row is complete, print it */
3657 another_reslist_field(&fields, &row, fp);
3660 if (fields != RESLIST_FIELDS)
3661 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3662 fields, RESLIST_FIELDS);
3669 * collect_display_vdc
3672 collect_display_vdc(
3679 static const char * const suf[2] = { "adr", "port" };
3680 static const char * const leapbits[4] = { "00", "01",
3682 struct varlist vl[MAXLIST];
3698 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3700 if (NTP_ADD != pvdc->type) {
3701 doaddvlist(vl, pvdc->tag);
3703 for (n = 0; n < COUNTOF(suf); n++) {
3704 snprintf(tagbuf, sizeof(tagbuf), "%s%s",
3706 doaddvlist(vl, tagbuf);
3710 qres = doquerylist(vl, CTL_OP_READVAR, as, 0, &rstatus, &rsize,
3714 return; /* error msg already displayed */
3717 * iterate over the response variables filling vdc_table with
3718 * the retrieved values.
3720 while (nextvar(&rsize, &rdata, &tag, &val)) {
3724 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3725 len = strlen(pvdc->tag);
3726 if (strncmp(tag, pvdc->tag, len))
3728 if (NTP_ADD != pvdc->type) {
3729 if ('\0' != tag[len])
3734 for (n = 0; n < COUNTOF(suf); n++) {
3735 if (strcmp(tag + len, suf[n]))
3743 if (NULL == pvdc->tag)
3745 switch (pvdc->type) {
3748 /* strip surrounding double quotes */
3749 if ('"' == val[0]) {
3751 if (len > 0 && '"' == val[len - 1]) {
3752 val[len - 1] = '\0';
3757 case NTP_MODE: /* fallthru */
3759 pvdc->v.str = estrdup(val);
3763 decodets(val, &pvdc->v.lfp);
3767 if (!decodenetnum(val, &pvdc->v.sau))
3768 fprintf(stderr, "malformed %s=%s\n",
3773 if (0 == n) { /* adr */
3774 if (!decodenetnum(val, &pvdc->v.sau))
3776 "malformed %s=%s\n",
3779 if (atouint(val, &ul))
3780 SET_PORT(&pvdc->v.sau,
3792 fprintf(fp, "associd=%u status=%04x %s,\n", as, rstatus,
3793 statustoa(vtype, rstatus));
3796 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3797 switch (pvdc->type) {
3800 if (pvdc->v.str != NULL) {
3801 fprintf(fp, "%s %s\n", pvdc->display,
3808 case NTP_ADD: /* fallthru */
3810 fprintf(fp, "%s %s\n", pvdc->display,
3811 nntohostp(&pvdc->v.sau));
3815 fprintf(fp, "%s %s\n", pvdc->display,
3816 prettydate(&pvdc->v.lfp));
3820 atouint(pvdc->v.str, &ul);
3821 fprintf(fp, "%s %s\n", pvdc->display,
3826 atouint(pvdc->v.str, &ul);
3827 fprintf(fp, "%s %s\n", pvdc->display,
3828 leapbits[ul & 0x3]);
3832 fprintf(stderr, "unexpected vdc type %d for %s\n",
3833 pvdc->type, pvdc->tag);
3841 * sysstats - implements ntpq -c sysstats modeled on ntpdc -c sysstats
3849 static vdc sysstats_vdc[] = {
3850 VDC_INIT("ss_uptime", "uptime: ", NTP_STR),
3851 VDC_INIT("ss_reset", "sysstats reset: ", NTP_STR),
3852 VDC_INIT("ss_received", "packets received: ", NTP_STR),
3853 VDC_INIT("ss_thisver", "current version: ", NTP_STR),
3854 VDC_INIT("ss_oldver", "older version: ", NTP_STR),
3855 VDC_INIT("ss_badformat", "bad length or format: ", NTP_STR),
3856 VDC_INIT("ss_badauth", "authentication failed:", NTP_STR),
3857 VDC_INIT("ss_declined", "declined: ", NTP_STR),
3858 VDC_INIT("ss_restricted", "restricted: ", NTP_STR),
3859 VDC_INIT("ss_limited", "rate limited: ", NTP_STR),
3860 VDC_INIT("ss_kodsent", "KoD responses: ", NTP_STR),
3861 VDC_INIT("ss_processed", "processed for time: ", NTP_STR),
3863 VDC_INIT("ss_lamport", "Lamport violations: ", NTP_STR),
3864 VDC_INIT("ss_tsrounding", "bad timestamp rounding:", NTP_STR),
3866 VDC_INIT(NULL, NULL, 0)
3869 collect_display_vdc(0, sysstats_vdc, FALSE, fp);
3874 * sysinfo - modeled on ntpdc's sysinfo
3882 static vdc sysinfo_vdc[] = {
3883 VDC_INIT("peeradr", "system peer: ", NTP_ADP),
3884 VDC_INIT("peermode", "system peer mode: ", NTP_MODE),
3885 VDC_INIT("leap", "leap indicator: ", NTP_2BIT),
3886 VDC_INIT("stratum", "stratum: ", NTP_STR),
3887 VDC_INIT("precision", "log2 precision: ", NTP_STR),
3888 VDC_INIT("rootdelay", "root delay: ", NTP_STR),
3889 VDC_INIT("rootdisp", "root dispersion: ", NTP_STR),
3890 VDC_INIT("refid", "reference ID: ", NTP_STR),
3891 VDC_INIT("reftime", "reference time: ", NTP_LFP),
3892 VDC_INIT("sys_jitter", "system jitter: ", NTP_STR),
3893 VDC_INIT("clk_jitter", "clock jitter: ", NTP_STR),
3894 VDC_INIT("clk_wander", "clock wander: ", NTP_STR),
3895 VDC_INIT("bcastdelay", "broadcast delay: ", NTP_STR),
3896 VDC_INIT("authdelay", "symm. auth. delay:", NTP_STR),
3897 VDC_INIT(NULL, NULL, 0)
3900 collect_display_vdc(0, sysinfo_vdc, TRUE, fp);
3905 * kerninfo - modeled on ntpdc's kerninfo
3913 static vdc kerninfo_vdc[] = {
3914 VDC_INIT("koffset", "pll offset: ", NTP_STR),
3915 VDC_INIT("kfreq", "pll frequency: ", NTP_STR),
3916 VDC_INIT("kmaxerr", "maximum error: ", NTP_STR),
3917 VDC_INIT("kesterr", "estimated error: ", NTP_STR),
3918 VDC_INIT("kstflags", "kernel status: ", NTP_STR),
3919 VDC_INIT("ktimeconst", "pll time constant: ", NTP_STR),
3920 VDC_INIT("kprecis", "precision: ", NTP_STR),
3921 VDC_INIT("kfreqtol", "frequency tolerance: ", NTP_STR),
3922 VDC_INIT("kppsfreq", "pps frequency: ", NTP_STR),
3923 VDC_INIT("kppsstab", "pps stability: ", NTP_STR),
3924 VDC_INIT("kppsjitter", "pps jitter: ", NTP_STR),
3925 VDC_INIT("kppscalibdur", "calibration interval ", NTP_STR),
3926 VDC_INIT("kppscalibs", "calibration cycles: ", NTP_STR),
3927 VDC_INIT("kppsjitexc", "jitter exceeded: ", NTP_STR),
3928 VDC_INIT("kppsstbexc", "stability exceeded: ", NTP_STR),
3929 VDC_INIT("kppscaliberrs", "calibration errors: ", NTP_STR),
3930 VDC_INIT(NULL, NULL, 0)
3933 collect_display_vdc(0, kerninfo_vdc, TRUE, fp);
3938 * monstats - implements ntpq -c monstats
3946 static vdc monstats_vdc[] = {
3947 VDC_INIT("mru_enabled", "enabled: ", NTP_STR),
3948 VDC_INIT("mru_depth", "addresses: ", NTP_STR),
3949 VDC_INIT("mru_deepest", "peak addresses: ", NTP_STR),
3950 VDC_INIT("mru_maxdepth", "maximum addresses: ", NTP_STR),
3951 VDC_INIT("mru_mindepth", "reclaim above count:", NTP_STR),
3952 VDC_INIT("mru_maxage", "reclaim older than: ", NTP_STR),
3953 VDC_INIT("mru_mem", "kilobytes: ", NTP_STR),
3954 VDC_INIT("mru_maxmem", "maximum kilobytes: ", NTP_STR),
3955 VDC_INIT(NULL, NULL, 0)
3958 collect_display_vdc(0, monstats_vdc, FALSE, fp);
3963 * iostats - ntpq -c iostats - network input and output counters
3971 static vdc iostats_vdc[] = {
3972 VDC_INIT("iostats_reset", "time since reset: ", NTP_STR),
3973 VDC_INIT("total_rbuf", "receive buffers: ", NTP_STR),
3974 VDC_INIT("free_rbuf", "free receive buffers: ", NTP_STR),
3975 VDC_INIT("used_rbuf", "used receive buffers: ", NTP_STR),
3976 VDC_INIT("rbuf_lowater", "low water refills: ", NTP_STR),
3977 VDC_INIT("io_dropped", "dropped packets: ", NTP_STR),
3978 VDC_INIT("io_ignored", "ignored packets: ", NTP_STR),
3979 VDC_INIT("io_received", "received packets: ", NTP_STR),
3980 VDC_INIT("io_sent", "packets sent: ", NTP_STR),
3981 VDC_INIT("io_sendfailed", "packet send failures: ", NTP_STR),
3982 VDC_INIT("io_wakeups", "input wakeups: ", NTP_STR),
3983 VDC_INIT("io_goodwakeups", "useful input wakeups: ", NTP_STR),
3984 VDC_INIT(NULL, NULL, 0)
3987 collect_display_vdc(0, iostats_vdc, FALSE, fp);
3992 * timerstats - ntpq -c timerstats - interval timer counters
4000 static vdc timerstats_vdc[] = {
4001 VDC_INIT("timerstats_reset", "time since reset: ", NTP_STR),
4002 VDC_INIT("timer_overruns", "timer overruns: ", NTP_STR),
4003 VDC_INIT("timer_xmts", "calls to transmit: ", NTP_STR),
4004 VDC_INIT(NULL, NULL, 0)
4007 collect_display_vdc(0, timerstats_vdc, FALSE, fp);
4012 * authinfo - implements ntpq -c authinfo
4020 static vdc authinfo_vdc[] = {
4021 VDC_INIT("authreset", "time since reset:", NTP_STR),
4022 VDC_INIT("authkeys", "stored keys: ", NTP_STR),
4023 VDC_INIT("authfreek", "free keys: ", NTP_STR),
4024 VDC_INIT("authklookups", "key lookups: ", NTP_STR),
4025 VDC_INIT("authknotfound", "keys not found: ", NTP_STR),
4026 VDC_INIT("authkuncached", "uncached keys: ", NTP_STR),
4027 VDC_INIT("authkexpired", "expired keys: ", NTP_STR),
4028 VDC_INIT("authencrypts", "encryptions: ", NTP_STR),
4029 VDC_INIT("authdecrypts", "decryptions: ", NTP_STR),
4030 VDC_INIT(NULL, NULL, 0)
4033 collect_display_vdc(0, authinfo_vdc, FALSE, fp);
4038 * pstats - show statistics for a peer
4046 static vdc pstats_vdc[] = {
4047 VDC_INIT("src", "remote host: ", NTP_ADD),
4048 VDC_INIT("dst", "local address: ", NTP_ADD),
4049 VDC_INIT("timerec", "time last received: ", NTP_STR),
4050 VDC_INIT("timer", "time until next send:", NTP_STR),
4051 VDC_INIT("timereach", "reachability change: ", NTP_STR),
4052 VDC_INIT("sent", "packets sent: ", NTP_STR),
4053 VDC_INIT("received", "packets received: ", NTP_STR),
4054 VDC_INIT("badauth", "bad authentication: ", NTP_STR),
4055 VDC_INIT("bogusorg", "bogus origin: ", NTP_STR),
4056 VDC_INIT("oldpkt", "duplicate: ", NTP_STR),
4057 VDC_INIT("seldisp", "bad dispersion: ", NTP_STR),
4058 VDC_INIT("selbroken", "bad reference time: ", NTP_STR),
4059 VDC_INIT("candidate", "candidate order: ", NTP_STR),
4060 VDC_INIT(NULL, NULL, 0)
4064 associd = checkassocid(pcmd->argval[0].uval);
4068 collect_display_vdc(associd, pstats_vdc, TRUE, fp);