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 return (ts->l_ui - lasttime->l_ui);
1460 * Pretty-print an interval into the given buffer, in a human-friendly format.
1476 snprintf(buf, cb, "%ld", diff);
1480 diff = (diff + 29) / 60;
1482 snprintf(buf, cb, "%ldm", diff);
1486 diff = (diff + 29) / 60;
1488 snprintf(buf, cb, "%ldh", diff);
1492 diff = (diff + 11) / 24;
1493 snprintf(buf, cb, "%ldd", diff);
1507 dummy = SRCADR(sock);
1508 ch = (char)(((dummy&0xf0000000)==0xe0000000) ? 'm' :
1509 ((dummy&0x000000ff)==0x000000ff) ? 'b' :
1510 ((dummy&0xffffffff)==0x7f000001) ? 'l' :
1511 ((dummy&0xffffffe0)==0x00000000) ? '-' :
1515 if (IN6_IS_ADDR_MULTICAST(PSOCK_ADDR6(sock)))
1528 * A list of variables required by the peers command
1530 struct varlist opeervarlist[] = {
1531 { "srcadr", 0 }, /* 0 */
1532 { "dstadr", 0 }, /* 1 */
1533 { "stratum", 0 }, /* 2 */
1534 { "hpoll", 0 }, /* 3 */
1535 { "ppoll", 0 }, /* 4 */
1536 { "reach", 0 }, /* 5 */
1537 { "delay", 0 }, /* 6 */
1538 { "offset", 0 }, /* 7 */
1539 { "jitter", 0 }, /* 8 */
1540 { "dispersion", 0 }, /* 9 */
1541 { "rec", 0 }, /* 10 */
1542 { "reftime", 0 }, /* 11 */
1543 { "srcport", 0 }, /* 12 */
1544 { "hmode", 0 }, /* 13 */
1548 struct varlist peervarlist[] = {
1549 { "srcadr", 0 }, /* 0 */
1550 { "refid", 0 }, /* 1 */
1551 { "stratum", 0 }, /* 2 */
1552 { "hpoll", 0 }, /* 3 */
1553 { "ppoll", 0 }, /* 4 */
1554 { "reach", 0 }, /* 5 */
1555 { "delay", 0 }, /* 6 */
1556 { "offset", 0 }, /* 7 */
1557 { "jitter", 0 }, /* 8 */
1558 { "dispersion", 0 }, /* 9 */
1559 { "rec", 0 }, /* 10 */
1560 { "reftime", 0 }, /* 11 */
1561 { "srcport", 0 }, /* 12 */
1562 { "hmode", 0 }, /* 13 */
1563 { "srchost", 0 }, /* 14 */
1567 struct varlist apeervarlist[] = {
1568 { "srcadr", 0 }, /* 0 */
1569 { "refid", 0 }, /* 1 */
1570 { "assid", 0 }, /* 2 */
1571 { "stratum", 0 }, /* 3 */
1572 { "hpoll", 0 }, /* 4 */
1573 { "ppoll", 0 }, /* 5 */
1574 { "reach", 0 }, /* 6 */
1575 { "delay", 0 }, /* 7 */
1576 { "offset", 0 }, /* 8 */
1577 { "jitter", 0 }, /* 9 */
1578 { "dispersion", 0 }, /* 10 */
1579 { "rec", 0 }, /* 11 */
1580 { "reftime", 0 }, /* 12 */
1581 { "srcport", 0 }, /* 13 */
1582 { "hmode", 0 }, /* 14 */
1583 { "srchost", 0 }, /* 15 */
1589 * Decode an incoming data buffer and print a line in the peer list
1593 struct varlist *pvl,
1612 sockaddr_u dum_store;
1613 sockaddr_u refidadr;
1617 const char *dstadr_refid = "0.0.0.0";
1618 const char *serverlocal;
1633 char whenbuf[8], pollbuf[8];
1634 char clock_name[LENHOSTNAME];
1638 have_srchost = FALSE;
1639 have_dstadr = FALSE;
1640 have_da_rid = FALSE;
1641 have_jitter = FALSE;
1644 clock_name[0] = '\0';
1650 while (nextvar(&datalen, &data, &name, &value)) {
1651 if (!strcmp("srcadr", name) ||
1652 !strcmp("peeradr", name)) {
1653 if (!decodenetnum(value, &srcadr))
1654 fprintf(stderr, "malformed %s=%s\n",
1656 } else if (!strcmp("srchost", name)) {
1657 if (pvl == peervarlist || pvl == apeervarlist) {
1658 len = strlen(value);
1660 (size_t)len < sizeof(clock_name)) {
1664 memcpy(clock_name, value, len);
1665 clock_name[len] = '\0';
1666 have_srchost = TRUE;
1669 } else if (!strcmp("dstadr", name)) {
1670 if (decodenetnum(value, &dum_store)) {
1671 type = decodeaddrtype(&dum_store);
1674 if (pvl == opeervarlist) {
1676 dstadr_refid = trunc_left(stoa(&dstadr), 15);
1679 } else if (!strcmp("hmode", name)) {
1680 decodeint(value, &hmode);
1681 } else if (!strcmp("refid", name)) {
1682 if ( (pvl == peervarlist)
1683 && (drefid == REFID_IPV4)) {
1685 drlen = strlen(value);
1688 } else if (drlen <= 4) {
1690 memcpy(&u32, value, drlen);
1691 dstadr_refid = refid_str(u32, 1);
1692 } else if (decodenetnum(value, &refidadr)) {
1693 if (SOCK_UNSPEC(&refidadr))
1694 dstadr_refid = "0.0.0.0";
1695 else if (ISREFCLOCKADR(&refidadr))
1697 refnumtoa(&refidadr);
1702 have_da_rid = FALSE;
1704 } else if ( (pvl == apeervarlist)
1705 || (pvl == peervarlist)) {
1706 /* no need to check drefid == REFID_HASH */
1708 drlen = strlen(value);
1711 } else if (drlen <= 4) {
1713 memcpy(&u32, value, drlen);
1714 dstadr_refid = refid_str(u32, 1);
1715 //fprintf(stderr, "apeervarlist S1 refid: value=<%s>\n", value);
1716 } else if (decodenetnum(value, &refidadr)) {
1717 if (SOCK_UNSPEC(&refidadr))
1718 dstadr_refid = "0.0.0.0";
1719 else if (ISREFCLOCKADR(&refidadr))
1721 refnumtoa(&refidadr);
1723 char *buf = emalloc(10);
1724 int i = ntohl(refidadr.sa4.sin_addr.s_addr);
1729 //fprintf(stderr, "apeervarlist refid: value=<%x>\n", i);
1731 //fprintf(stderr, "apeervarlist refid: value=<%s>\n", value);
1733 have_da_rid = FALSE;
1736 } else if (!strcmp("stratum", name)) {
1737 decodeuint(value, &stratum);
1738 } else if (!strcmp("hpoll", name)) {
1739 if (decodeint(value, &hpoll) && hpoll < 0)
1740 hpoll = NTP_MINPOLL;
1741 } else if (!strcmp("ppoll", name)) {
1742 if (decodeint(value, &ppoll) && ppoll < 0)
1743 ppoll = NTP_MINPOLL;
1744 } else if (!strcmp("reach", name)) {
1745 decodeuint(value, &reach);
1746 } else if (!strcmp("delay", name)) {
1747 decodetime(value, &estdelay);
1748 } else if (!strcmp("offset", name)) {
1749 decodetime(value, &estoffset);
1750 } else if (!strcmp("jitter", name)) {
1751 if ((pvl == peervarlist || pvl == apeervarlist)
1752 && decodetime(value, &estjitter))
1754 } else if (!strcmp("rootdisp", name) ||
1755 !strcmp("dispersion", name)) {
1756 decodetime(value, &estdisp);
1757 } else if (!strcmp("rec", name)) {
1758 decodets(value, &rec);
1759 } else if (!strcmp("srcport", name) ||
1760 !strcmp("peerport", name)) {
1761 decodeuint(value, &srcport);
1762 } else if (!strcmp("reftime", name)) {
1763 if (!decodets(value, &reftime))
1766 // fprintf(stderr, "UNRECOGNIZED name=%s ", name);
1771 * hmode gives the best guidance for the t column. If the response
1772 * did not include hmode we'll use the old decodeaddrtype() result.
1777 /* broadcastclient or multicastclient */
1781 case MODE_BROADCAST:
1782 /* broadcast or multicast server */
1783 if (IS_MCAST(&srcadr))
1790 if (ISREFCLOCKADR(&srcadr))
1791 type = 'l'; /* local refclock*/
1792 else if (SOCK_UNSPEC(&srcadr))
1793 type = 'p'; /* pool */
1794 else if (IS_MCAST(&srcadr))
1795 type = 'a'; /* manycastclient */
1797 type = 'u'; /* unicast */
1801 type = 's'; /* symmetric active */
1802 break; /* configured */
1805 type = 'S'; /* symmetric passive */
1806 break; /* ephemeral */
1810 * Got everything, format the line
1812 poll_sec = 1 << min(ppoll, hpoll);
1813 if (pktversion > NTP_OLDVERSION)
1814 c = flash3[CTL_PEER_STATVAL(rstatus) & 0x7];
1816 c = flash2[CTL_PEER_STATVAL(rstatus) & 0x3];
1818 if ((pvl == peervarlist || pvl == apeervarlist)
1820 serverlocal = nntohost_col(&dstadr,
1821 (size_t)min(LIB_BUFLENGTH - 1, maxhostlen),
1824 if (currenthostisnum)
1825 serverlocal = trunc_left(currenthost,
1828 serverlocal = currenthost;
1830 fprintf(fp, "%-*s ", (int)maxhostlen, serverlocal);
1832 if (AF_UNSPEC == af || AF(&srcadr) == af) {
1834 strlcpy(clock_name, nntohost(&srcadr),
1835 sizeof(clock_name));
1836 if (wideremote && 15 < strlen(clock_name))
1837 fprintf(fp, "%c%s\n ", c, clock_name);
1839 fprintf(fp, "%c%-15.15s ", c, clock_name);
1843 drlen = strlen(dstadr_refid);
1844 makeascii(drlen, dstadr_refid, fp);
1846 if (pvl == apeervarlist) {
1849 fprintf(fp, "%-6d", associd);
1851 while (drlen++ < 15)
1855 " %2ld %c %4.4s %4.4s %3lo %7.7s %8.7s %7.7s\n",
1857 prettyinterval(whenbuf, sizeof(whenbuf),
1858 when(&ts, &rec, &reftime)),
1859 prettyinterval(pollbuf, sizeof(pollbuf),
1861 reach, lfptoms(&estdelay, 3),
1862 lfptoms(&estoffset, 3),
1864 ? lfptoms(&estjitter, 3)
1865 : lfptoms(&estdisp, 3));
1874 * dogetpeers - given an association ID, read and print the spreadsheet
1879 struct varlist *pvl,
1891 res = doquerylist(pvl, CTL_OP_READVAR, associd, 0, &rstatus,
1897 res = doquery(CTL_OP_READVAR, associd, 0, 0, NULL, &rstatus,
1906 fprintf(stderr, "server=%s ", currenthost);
1908 "***No information returned for association %u\n",
1913 return doprintpeers(pvl, associd, (int)rstatus, dsize, datap,
1919 * peers - print a peer spreadsheet
1929 char fullname[LENHOSTNAME];
1931 const char * name_or_num;
1934 if (!dogetassoc(fp))
1937 for (u = 0; u < numhosts; u++) {
1938 if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
1939 name_or_num = nntohost(&netnum);
1940 sl = strlen(name_or_num);
1941 maxhostlen = max(maxhostlen, sl);
1945 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
1948 " remote refid st t when poll reach delay offset jitter\n");
1950 for (u = 0; u <= maxhostlen; u++)
1953 "==============================================================================\n");
1955 for (u = 0; u < numassoc; u++) {
1957 !(CTL_PEER_STATVAL(assoc_cache[u].status)
1958 & (CTL_PST_CONFIG|CTL_PST_REACH))) {
1960 fprintf(stderr, "eliding [%d]\n",
1961 (int)assoc_cache[u].assid);
1964 if (!dogetpeers(peervarlist, (int)assoc_cache[u].assid,
1973 * doapeers - print a peer spreadsheet with assocIDs
1983 char fullname[LENHOSTNAME];
1985 const char * name_or_num;
1988 if (!dogetassoc(fp))
1991 for (u = 0; u < numhosts; u++) {
1992 if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
1993 name_or_num = nntohost(&netnum);
1994 sl = strlen(name_or_num);
1995 maxhostlen = max(maxhostlen, sl);
1999 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2002 " remote refid assid st t when poll reach delay offset jitter\n");
2004 for (u = 0; u <= maxhostlen; u++)
2007 "==============================================================================\n");
2009 for (u = 0; u < numassoc; u++) {
2011 !(CTL_PEER_STATVAL(assoc_cache[u].status)
2012 & (CTL_PST_CONFIG|CTL_PST_REACH))) {
2014 fprintf(stderr, "eliding [%d]\n",
2015 (int)assoc_cache[u].assid);
2018 if (!dogetpeers(apeervarlist, (int)assoc_cache[u].assid,
2027 * peers - print a peer spreadsheet
2036 if (drefid == REFID_HASH) {
2041 if (pcmd->nargs == 1) {
2042 if (pcmd->argval->ival == 6)
2053 * apeers - print a peer spreadsheet, with assocIDs
2064 if (pcmd->nargs == 1) {
2065 if (pcmd->argval->ival == 6)
2070 doapeers(0, fp, af);
2075 * lpeers - print a peer spreadsheet including all fuzzball peers
2086 if (pcmd->nargs == 1) {
2087 if (pcmd->argval->ival == 6)
2097 * opeers - print a peer spreadsheet
2107 char fullname[LENHOSTNAME];
2110 if (!dogetassoc(fp))
2113 for (i = 0; i < numhosts; ++i) {
2114 if (getnetnum(chosts[i].name, &netnum, fullname, af))
2115 if (strlen(fullname) > maxhostlen)
2116 maxhostlen = strlen(fullname);
2119 fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2122 " remote local st t when poll reach delay offset disp\n");
2124 for (i = 0; i <= maxhostlen; ++i)
2127 "==============================================================================\n");
2129 for (i = 0; i < numassoc; i++) {
2131 !(CTL_PEER_STATVAL(assoc_cache[i].status) &
2132 (CTL_PST_CONFIG | CTL_PST_REACH)))
2134 if (!dogetpeers(opeervarlist, assoc_cache[i].assid, fp, af))
2142 * opeers - print a peer spreadsheet the old way
2153 if (pcmd->nargs == 1) {
2154 if (pcmd->argval->ival == 6)
2159 doopeers(0, fp, af);
2164 * lopeers - print a peer spreadsheet including all fuzzball peers
2175 if (pcmd->nargs == 1) {
2176 if (pcmd->argval->ival == 6)
2181 doopeers(1, fp, af);
2186 * config - send a configuration command to a remote host
2203 cfgcmd = pcmd->argval[0].string;
2209 "Command = %s\n", pcmd->keyword, cfgcmd);
2211 res = doquery(CTL_OP_CONFIGURE, 0, 1,
2212 strlen(cfgcmd), cfgcmd,
2213 &rstatus, &rsize, &rdata);
2218 if (rsize > 0 && '\n' == rdata[rsize - 1])
2221 resp = emalloc(rsize + 1);
2222 memcpy(resp, rdata, rsize);
2226 if (1 == sscanf(resp, "column %d syntax error", &col)
2227 && col >= 0 && (size_t)col <= strlen(cfgcmd) + 1) {
2229 printf("______"); /* "ntpq> " */
2230 printf("________"); /* ":config " */
2232 printf("%s\n", cfgcmd);
2233 for (i = 1; i < col; i++)
2237 printf("%s\n", resp);
2243 * config_from_file - remotely configure an ntpd daemon using the
2244 * specified configuration file
2245 * SK: This function is a kludge at best and is full of bad design
2247 * 1. ntpq uses UDP, which means that there is no guarantee of in-order,
2248 * error-free delivery.
2249 * 2. The maximum length of a packet is constrained, and as a result, the
2250 * maximum length of a line in a configuration file is constrained.
2251 * Longer lines will lead to unpredictable results.
2252 * 3. Since this function is sending a line at a time, we can't update
2253 * the control key through the configuration file (YUCK!!)
2255 * Pearly: There are a few places where 'size_t' is cast to 'int' based
2256 * on the assumption that 'int' can hold the size of the involved
2257 * buffers without overflow.
2271 char config_cmd[MAXLINE];
2280 "Filename = %s\n", pcmd->keyword,
2281 pcmd->argval[0].string);
2283 config_fd = fopen(pcmd->argval[0].string, "r");
2284 if (NULL == config_fd) {
2285 printf("ERROR!! Couldn't open file: %s\n",
2286 pcmd->argval[0].string);
2290 printf("Sending configuration file, one line at a time.\n");
2292 while (fgets(config_cmd, MAXLINE, config_fd) != NULL) {
2293 /* Eliminate comments first. */
2294 cp = strchr(config_cmd, '#');
2295 config_len = (NULL != cp)
2296 ? (size_t)(cp - config_cmd)
2297 : strlen(config_cmd);
2299 /* [Bug 3015] make sure there's no trailing whitespace;
2300 * the fix for [Bug 2853] on the server side forbids
2301 * those. And don't transmit empty lines, as this would
2304 while (config_len != 0 &&
2305 (u_char)config_cmd[config_len-1] <= ' ')
2307 config_cmd[config_len] = '\0';
2310 if (0 == config_len)
2315 res = doquery(CTL_OP_CONFIGURE, 0, 1,
2316 config_len, config_cmd,
2317 &rstatus, &rsize, &rdata);
2318 while (res != 0 && retry_limit--);
2320 printf("Line No: %d query failed: %.*s\n"
2321 "Subsequent lines not sent.\n",
2322 i, (int)config_len, config_cmd);
2327 /* Right-strip the result code string, then output the
2328 * last line executed, with result code. */
2329 while (rsize != 0 && (u_char)rdata[rsize - 1] <= ' ')
2331 printf("Line No: %d %.*s: %.*s\n", i,
2333 (int)config_len, config_cmd);
2335 printf("Done sending file\n");
2346 const char nonce_eq[] = "nonce=";
2354 * Retrieve a nonce specific to this client to demonstrate to
2355 * ntpd that we're capable of receiving responses to our source
2356 * IP address, and thereby unlikely to be forging the source.
2358 qres = doquery(CTL_OP_REQ_NONCE, 0, 0, 0, NULL, &rstatus,
2361 fprintf(stderr, "nonce request failed\n");
2365 if ((size_t)rsize <= sizeof(nonce_eq) - 1 ||
2366 strncmp(rdata, nonce_eq, sizeof(nonce_eq) - 1)) {
2367 fprintf(stderr, "unexpected nonce response format: %.*s\n",
2368 (int)rsize, rdata); /* cast is wobbly */
2371 chars = rsize - (sizeof(nonce_eq) - 1);
2372 if (chars >= (int)cb_nonce)
2374 memcpy(nonce, rdata + sizeof(nonce_eq) - 1, chars);
2375 nonce[chars] = '\0';
2377 ('\r' == nonce[chars - 1] || '\n' == nonce[chars - 1])) {
2379 nonce[chars] = '\0';
2387 * add_mru Add and entry to mru list, hash table, and allocate
2388 * and return a replacement.
2389 * This is a helper for collect_mru_list().
2401 hash = NTP_HASH_ADDR(&add->addr);
2402 /* see if we have it among previously received entries */
2403 for (mon = hash_table[hash]; mon != NULL; mon = mon->hlink)
2404 if (SOCK_EQ(&mon->addr, &add->addr))
2407 if (!L_ISGEQ(&add->first, &mon->first)) {
2409 "add_mru duplicate %s new first ts %08x.%08x precedes prior %08x.%08x\n",
2410 sptoa(&add->addr), add->last.l_ui,
2411 add->last.l_uf, mon->last.l_ui,
2415 UNLINK_DLIST(mon, mlink);
2416 UNLINK_SLIST(unlinked, hash_table[hash], mon, hlink, mru);
2417 INSIST(unlinked == mon);
2419 TRACE(2, ("(updated from %08x.%08x) ", mon->last.l_ui,
2422 LINK_DLIST(mru_list, add, mlink);
2423 LINK_SLIST(hash_table[hash], add, hlink);
2424 TRACE(2, ("add_mru %08x.%08x c %d m %d v %d rest %x first %08x.%08x %s\n",
2425 add->last.l_ui, add->last.l_uf, add->count,
2426 (int)add->mode, (int)add->ver, (u_int)add->rs,
2427 add->first.l_ui, add->first.l_uf, sptoa(&add->addr)));
2428 /* if we didn't update an existing entry, alloc replacement */
2430 mon = emalloc(sizeof(*mon));
2439 /* MGOT macro is specific to collect_mru_list() */
2443 if (MRU_GOT_ALL == got) { \
2445 mon = add_mru(mon); \
2452 mrulist_ctrl_c_hook(void)
2454 mrulist_interrupted = TRUE;
2465 const u_int sleep_msecs = 5;
2466 static int ntpd_row_limit = MRU_ROW_LIMIT;
2467 int c_mru_l_rc; /* this function's return code */
2468 u_char got; /* MRU_GOT_* bits */
2477 char req_buf[CTL_MAX_DATA_LEN];
2490 int si; /* server index in response */
2491 int ci; /* client (our) index for validation */
2492 int ri; /* request index (.# suffix) */
2496 sockaddr_u addr_older;
2498 int have_addr_older;
2499 int have_last_older;
2500 u_int restarted_count;
2505 if (!fetch_nonce(nonce, sizeof(nonce)))
2509 restarted_count = 0;
2511 INIT_DLIST(mru_list, mlink);
2512 cb = NTP_HASH_SIZE * sizeof(*hash_table);
2513 INSIST(NULL == hash_table);
2514 hash_table = emalloc_zero(cb);
2517 list_complete = FALSE;
2523 mon = emalloc_zero(cb);
2526 next_report = time(NULL) + MRU_REPORT_SECS;
2528 limit = min(3 * MAXFRAGS, ntpd_row_limit);
2530 snprintf(req_buf, sizeof(req_buf), "nonce=%s, frags=%d%s",
2531 nonce, frags, parms);
2536 fprintf(stderr, "READ_MRU parms: %s\n", req_buf);
2538 qres = doqueryex(CTL_OP_READ_MRU, 0, 0,
2539 strlen(req_buf), req_buf,
2540 &rstatus, &rsize, &rdata, TRUE);
2542 if (CERR_UNKNOWNVAR == qres && ri > 0) {
2544 * None of the supplied prior entries match, so
2545 * toss them from our list and try again.
2549 "no overlap between %d prior entries and server MRU list\n",
2552 recent = HEAD_DLIST(mru_list, mlink);
2553 INSIST(recent != NULL);
2556 "tossing prior entry %s to resync\n",
2557 sptoa(&recent->addr));
2558 UNLINK_DLIST(recent, mlink);
2559 hash = NTP_HASH_ADDR(&recent->addr);
2560 UNLINK_SLIST(unlinked, hash_table[hash],
2561 recent, hlink, mru);
2562 INSIST(unlinked == recent);
2566 if (NULL == HEAD_DLIST(mru_list, mlink)) {
2568 if (restarted_count > 8) {
2570 "Giving up after 8 restarts from the beginning.\n"
2571 "With high-traffic NTP servers, this can occur if the\n"
2572 "MRU list is limited to less than about 16 seconds' of\n"
2573 "entries. See the 'mru' ntp.conf directive to adjust.\n");
2574 goto cleanup_return;
2578 "---> Restarting from the beginning, retry #%u\n",
2581 } else if (CERR_UNKNOWNVAR == qres) {
2583 "CERR_UNKNOWNVAR from ntpd but no priors given.\n");
2584 goto cleanup_return;
2585 } else if (CERR_BADVALUE == qres) {
2590 "Reverted to row limit from fragments limit.\n");
2592 /* ntpd has lower cap on row limit */
2594 limit = min(limit, ntpd_row_limit);
2597 "Row limit reduced to %d following CERR_BADVALUE.\n",
2600 } else if (ERR_INCOMPLETE == qres ||
2601 ERR_TIMEOUT == qres) {
2603 * Reduce the number of rows/frags requested by
2604 * half to recover from lost response fragments.
2607 frags = max(2, frags / 2);
2610 "Frag limit reduced to %d following incomplete response.\n",
2613 limit = max(2, limit / 2);
2616 "Row limit reduced to %d following incomplete response.\n",
2620 show_error_msg(qres, 0);
2621 goto cleanup_return;
2624 * This is a cheap cop-out implementation of rawmode
2625 * output for mrulist. A better approach would be to
2626 * dump similar output after the list is collected by
2627 * ntpq with a continuous sequence of indexes. This
2628 * cheap approach has indexes resetting to zero for
2629 * each query/response, and duplicates are not
2632 if (!qres && rawmode)
2633 printvars(rsize, rdata, rstatus, TYPE_SYS, 1, stdout);
2635 have_addr_older = FALSE;
2636 have_last_older = FALSE;
2637 while (!qres && nextvar(&rsize, &rdata, &tag, &val)) {
2639 fprintf(stderr, "nextvar gave: %s = %s\n",
2644 if (!strcmp(tag, "addr.older")) {
2645 if (!have_last_older) {
2647 "addr.older %s before last.older\n",
2649 goto cleanup_return;
2651 if (!decodenetnum(val, &addr_older)) {
2653 "addr.older %s garbled\n",
2655 goto cleanup_return;
2657 hash = NTP_HASH_ADDR(&addr_older);
2658 for (recent = hash_table[hash];
2660 recent = recent->hlink)
2665 if (NULL == recent) {
2667 "addr.older %s not in hash table\n",
2669 goto cleanup_return;
2671 if (!L_ISEQU(&last_older,
2674 "last.older %08x.%08x mismatches %08x.%08x expected.\n",
2679 goto cleanup_return;
2681 have_addr_older = TRUE;
2682 } else if (1 != sscanf(tag, "addr.%d", &si)
2685 else if (decodenetnum(val, &mon->addr))
2690 if (!strcmp(tag, "last.older")) {
2691 if ('0' != val[0] ||
2693 !hextolfp(val + 2, &last_older)) {
2695 "last.older %s garbled\n",
2697 goto cleanup_return;
2699 have_last_older = TRUE;
2700 } else if (!strcmp(tag, "last.newest")) {
2703 "last.newest %s before complete row, got = 0x%x\n",
2705 goto cleanup_return;
2709 "last.newest %s before now=\n",
2711 goto cleanup_return;
2713 head = HEAD_DLIST(mru_list, mlink);
2715 if ('0' != val[0] ||
2717 !hextolfp(val + 2, &newest) ||
2721 "last.newest %s mismatches %08x.%08x",
2725 goto cleanup_return;
2728 list_complete = TRUE;
2729 } else if (1 != sscanf(tag, "last.%d", &si) ||
2730 si != ci || '0' != val[0] ||
2732 !hextolfp(val + 2, &mon->last)) {
2737 * allow interrupted retrieval,
2738 * using most recent retrieved
2739 * entry's last seen timestamp
2740 * as the end of operation.
2747 if (1 != sscanf(tag, "first.%d", &si) ||
2748 si != ci || '0' != val[0] ||
2750 !hextolfp(val + 2, &mon->first))
2752 MGOT(MRU_GOT_FIRST);
2756 if (!strcmp(tag, "nonce")) {
2757 strlcpy(nonce, val, sizeof(nonce));
2760 } else if (strcmp(tag, "now") ||
2763 !hextolfp(val + 2, pnow))
2769 if (1 != sscanf(tag, "ct.%d", &si) ||
2771 1 != sscanf(val, "%d", &mon->count)
2774 MGOT(MRU_GOT_COUNT);
2778 if (1 != sscanf(tag, "mv.%d", &si) ||
2780 1 != sscanf(val, "%d", &mv))
2782 mon->mode = PKT_MODE(mv);
2783 mon->ver = PKT_VERSION(mv);
2788 if (1 != sscanf(tag, "rs.%d", &si) ||
2790 1 != sscanf(val, "0x%hx", &mon->rs))
2798 /* ignore unknown tags */
2802 list_complete = TRUE;
2803 if (list_complete) {
2804 INSIST(0 == ri || have_addr_older);
2806 if (mrulist_interrupted) {
2807 printf("mrulist retrieval interrupted by operator.\n"
2808 "Displaying partial client list.\n");
2811 if (list_complete || mrulist_interrupted) {
2813 "\rRetrieved %u unique MRU entries and %u updates.\n",
2814 mru_count, mru_dupes);
2818 if (time(NULL) >= next_report) {
2819 next_report += MRU_REPORT_SECS;
2820 fprintf(stderr, "\r%u (%u updates) ", mru_count,
2826 * Snooze for a bit between queries to let ntpd catch
2827 * up with other duties.
2831 #elif !defined(HAVE_NANOSLEEP)
2832 sleep((sleep_msecs / 1000) + 1);
2835 struct timespec interv = { 0,
2836 1000 * sleep_msecs };
2837 nanosleep(&interv, NULL);
2841 * If there were no errors, increase the number of rows
2842 * to a maximum of 3 * MAXFRAGS (the most packets ntpq
2843 * can handle in one response), on the assumption that
2844 * no less than 3 rows fit in each packet, capped at
2845 * our best guess at the server's row limit.
2849 frags = min(MAXFRAGS, frags + 1);
2851 limit = min3(3 * MAXFRAGS,
2858 * prepare next query with as many address and last-seen
2859 * timestamps as will fit in a single packet.
2862 req_end = req_buf + sizeof(req_buf);
2863 #define REQ_ROOM (req_end - req)
2864 snprintf(req, REQ_ROOM, "nonce=%s, %s=%d%s", nonce,
2874 if (nonce_uses >= 4) {
2875 if (!fetch_nonce(nonce, sizeof(nonce)))
2876 goto cleanup_return;
2881 for (ri = 0, recent = HEAD_DLIST(mru_list, mlink);
2883 ri++, recent = NEXT_DLIST(mru_list, recent, mlink)) {
2885 snprintf(buf, sizeof(buf),
2886 ", addr.%d=%s, last.%d=0x%08x.%08x",
2887 ri, sptoa(&recent->addr), ri,
2888 recent->last.l_ui, recent->last.l_uf);
2889 chars = strlen(buf);
2890 if ((size_t)REQ_ROOM <= chars)
2892 memcpy(req, buf, chars + 1);
2898 goto retain_hash_table;
2913 * qcmp_mru_addr - sort MRU entries by remote address.
2915 * All IPv4 addresses sort before any IPv6, addresses are sorted by
2916 * value within address family.
2924 const mru * const * ppm1 = v1;
2925 const mru * const * ppm2 = v2;
2936 af1 = AF(&pm1->addr);
2937 af2 = AF(&pm2->addr);
2940 return (AF_INET == af1)
2944 cmplen = SIZEOF_INADDR(af1);
2945 addr_off = (AF_INET == af1)
2946 ? offsetof(struct sockaddr_in, sin_addr)
2947 : offsetof(struct sockaddr_in6, sin6_addr);
2949 return memcmp((const char *)&pm1->addr + addr_off,
2950 (const char *)&pm2->addr + addr_off,
2961 return -qcmp_mru_addr(v1, v2);
2966 * qcmp_mru_count - sort MRU entries by times seen (hit count).
2974 const mru * const * ppm1 = v1;
2975 const mru * const * ppm2 = v2;
2982 return (pm1->count < pm2->count)
2984 : ((pm1->count == pm2->count)
2996 return -qcmp_mru_count(v1, v2);
3001 * qcmp_mru_avgint - sort MRU entries by average interval.
3009 const mru * const * ppm1 = v1;
3010 const mru * const * ppm2 = v2;
3020 interval = pm1->last;
3021 L_SUB(&interval, &pm1->first);
3022 LFPTOD(&interval, avg1);
3025 interval = pm2->last;
3026 L_SUB(&interval, &pm2->first);
3027 LFPTOD(&interval, avg2);
3032 else if (avg1 > avg2)
3035 /* secondary sort on lstint - rarely tested */
3036 if (L_ISEQU(&pm1->last, &pm2->last))
3038 else if (L_ISGEQ(&pm1->last, &pm2->last))
3051 return -qcmp_mru_avgint(v1, v2);
3056 * mrulist - ntpq's mrulist command to fetch an arbitrarily large Most
3057 * Recently Used (seen) remote address list from ntpd.
3059 * Similar to ntpdc's monlist command, but not limited to a single
3060 * request/response, and thereby not limited to a few hundred remote
3063 * See ntpd/ntp_control.c read_mru_list() for comments on the way
3064 * CTL_OP_READ_MRU is designed to be used.
3066 * mrulist intentionally differs from monlist in the way the avgint
3067 * column is calculated. monlist includes the time after the last
3068 * packet from the client until the monlist query time in the average,
3069 * while mrulist excludes it. That is, monlist's average interval grows
3070 * over time for remote addresses not heard from in some time, while it
3071 * remains unchanged in mrulist. This also affects the avgint value for
3072 * entries representing a single packet, with identical first and last
3073 * timestamps. mrulist shows 0 avgint, monlist shows a value identical
3078 struct parse * pcmd,
3082 const char mincount_eq[] = "mincount=";
3083 const char resall_eq[] = "resall=";
3084 const char resany_eq[] = "resany=";
3085 const char maxlstint_eq[] = "maxlstint=";
3086 const char laddr_eq[] = "laddr=";
3087 const char sort_eq[] = "sort=";
3088 mru_sort_order order;
3090 char parms_buf[128];
3106 mrulist_interrupted = FALSE;
3107 push_ctrl_c_handler(&mrulist_ctrl_c_hook);
3109 "Ctrl-C will stop MRU retrieval and display partial results.\n");
3112 order = MRUSORT_DEF;
3113 parms_buf[0] = '\0';
3115 for (i = 0; i < pcmd->nargs; i++) {
3116 arg = pcmd->argval[i].string;
3118 cb = strlen(arg) + 1;
3119 if ((!strncmp(resall_eq, arg, sizeof(resall_eq)
3120 - 1) || !strncmp(resany_eq, arg,
3121 sizeof(resany_eq) - 1) || !strncmp(
3122 mincount_eq, arg, sizeof(mincount_eq) - 1)
3123 || !strncmp(laddr_eq, arg, sizeof(laddr_eq)
3124 - 1) || !strncmp(maxlstint_eq, arg,
3125 sizeof(laddr_eq) - 1)) && parms + cb + 2 <=
3126 parms_buf + sizeof(parms_buf)) {
3127 /* these are passed intact to ntpd */
3128 memcpy(parms, ", ", 2);
3130 memcpy(parms, arg, cb);
3132 } else if (!strncmp(sort_eq, arg,
3133 sizeof(sort_eq) - 1)) {
3134 arg += sizeof(sort_eq) - 1;
3136 n < COUNTOF(mru_sort_keywords);
3138 if (!strcmp(mru_sort_keywords[n],
3141 if (n < COUNTOF(mru_sort_keywords))
3143 } else if (!strcmp("limited", arg) ||
3144 !strcmp("kod", arg)) {
3145 /* transform to resany=... */
3146 snprintf(buf, sizeof(buf),
3151 cb = 1 + strlen(buf);
3153 parms_buf + sizeof(parms_buf)) {
3154 memcpy(parms, buf, cb);
3159 "ignoring unrecognized mrulist parameter: %s\n",
3165 if (!collect_mru_list(parms, &now))
3168 /* display the results */
3170 goto cleanup_return;
3172 /* construct an array of entry pointers in default order */
3173 sorted = eallocarray(mru_count, sizeof(*sorted));
3175 if (MRUSORT_R_DEF != order) {
3176 ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3177 INSIST(ppentry < sorted + mru_count);
3182 REV_ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3183 INSIST(ppentry < sorted + mru_count);
3186 REV_ITER_DLIST_END()
3189 if (ppentry - sorted != (int)mru_count) {
3191 "mru_count %u should match MRU list depth %ld.\n",
3192 mru_count, (long)(ppentry - sorted));
3194 goto cleanup_return;
3197 /* re-sort sorted[] if not default or reverse default */
3198 if (MRUSORT_R_DEF < order)
3199 qsort(sorted, mru_count, sizeof(sorted[0]),
3200 mru_qcmp_table[order]);
3202 mrulist_interrupted = FALSE;
3203 printf( "lstint avgint rstr r m v count rport remote address\n"
3204 "==============================================================================\n");
3206 for (ppentry = sorted; ppentry < sorted + mru_count; ppentry++) {
3209 L_SUB(&interval, &recent->last);
3210 LFPTOD(&interval, flstint);
3211 lstint = (int)(flstint + 0.5);
3212 interval = recent->last;
3213 L_SUB(&interval, &recent->first);
3214 LFPTOD(&interval, favgint);
3215 favgint /= recent->count;
3216 avgint = (int)(favgint + 0.5);
3217 fprintf(fp, "%6d %6d %4hx %c %d %d %6d %5u %s\n",
3218 lstint, avgint, recent->rs,
3219 (RES_KOD & recent->rs)
3221 : (RES_LIMITED & recent->rs)
3224 (int)recent->mode, (int)recent->ver,
3225 recent->count, SRCPORT(&recent->addr),
3226 nntohost(&recent->addr));
3229 if (mrulist_interrupted) {
3230 fputs("\n --interrupted--\n", fp);
3238 "--- completed, freeing sorted[] pointers\n");
3245 fprintf(stderr, "... freeing MRU entries\n");
3248 ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3252 fprintf(stderr, "... freeing hash_table[]\n");
3257 INIT_DLIST(mru_list, mlink);
3259 pop_ctrl_c_handler(&mrulist_ctrl_c_hook);
3264 * validate_ifnum - helper for ifstats()
3266 * Ensures rows are received in order and complete.
3276 if (prow->ifnum == ifnum)
3278 if (prow->ifnum + 1 <= ifnum) {
3279 if (*pfields < IFSTATS_FIELDS)
3280 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3281 *pfields, IFSTATS_FIELDS);
3283 prow->ifnum = ifnum;
3287 "received if index %u, have %d of %d fields for index %u, aborting.\n",
3288 ifnum, *pfields, IFSTATS_FIELDS, prow->ifnum);
3294 * another_ifstats_field - helper for ifstats()
3296 * If all fields for the row have been received, print it.
3299 another_ifstats_field(
3308 /* we understand 12 tags */
3309 if (IFSTATS_FIELDS > *pfields)
3312 " interface name send\n"
3313 " # address/broadcast drop flag ttl mc received sent failed peers uptime\n"
3314 "==============================================================================\n");
3317 "%3u %-24.24s %c %4x %3d %2d %6d %6d %6d %5d %8d\n"
3319 prow->ifnum, prow->name,
3323 prow->flags, prow->ttl, prow->mcast_count,
3324 prow->received, prow->sent, prow->send_errors,
3325 prow->peer_count, prow->uptime, sptoa(&prow->addr));
3326 if (!SOCK_UNSPEC(&prow->bcast))
3327 fprintf(fp, " %s\n", sptoa(&prow->bcast));
3328 ifnum = prow->ifnum;
3330 prow->ifnum = ifnum;
3335 * ifstats - ntpq -c ifstats modeled on ntpdc -c ifstats.
3339 struct parse * pcmd,
3343 const char addr_fmt[] = "addr.%u";
3344 const char bcast_fmt[] = "bcast.%u";
3345 const char en_fmt[] = "en.%u"; /* enabled */
3346 const char flags_fmt[] = "flags.%u";
3347 const char mc_fmt[] = "mc.%u"; /* mcast count */
3348 const char name_fmt[] = "name.%u";
3349 const char pc_fmt[] = "pc.%u"; /* peer count */
3350 const char rx_fmt[] = "rx.%u";
3351 const char tl_fmt[] = "tl.%u"; /* ttl */
3352 const char tx_fmt[] = "tx.%u";
3353 const char txerr_fmt[] = "txerr.%u";
3354 const char up_fmt[] = "up.%u"; /* uptime */
3367 qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, 0, NULL, &rstatus,
3369 if (qres) /* message already displayed */
3373 " interface name send\n"
3374 " # address/broadcast drop flag ttl mc received sent failed peers uptime\n"
3375 "==============================================================================\n");
3381 while (nextvar(&dsize, &datap, &tag, &val)) {
3383 fprintf(stderr, "nextvar gave: %s = %s\n", tag,
3391 if (1 == sscanf(tag, addr_fmt, &ui) &&
3392 decodenetnum(val, &row.addr))
3397 if (1 == sscanf(tag, bcast_fmt, &ui) &&
3399 decodenetnum(val, &row.bcast)))
3404 if (1 == sscanf(tag, en_fmt, &ui) &&
3405 1 == sscanf(val, "%d", &row.enabled))
3410 if (1 == sscanf(tag, flags_fmt, &ui) &&
3411 1 == sscanf(val, "0x%x", &row.flags))
3416 if (1 == sscanf(tag, mc_fmt, &ui) &&
3417 1 == sscanf(val, "%d", &row.mcast_count))
3422 if (1 == sscanf(tag, name_fmt, &ui)) {
3427 len - 2 < sizeof(row.name)) {
3429 memcpy(row.name, val + 1, len);
3430 row.name[len] = '\0';
3437 if (1 == sscanf(tag, pc_fmt, &ui) &&
3438 1 == sscanf(val, "%d", &row.peer_count))
3443 if (1 == sscanf(tag, rx_fmt, &ui) &&
3444 1 == sscanf(val, "%d", &row.received))
3449 if (1 == sscanf(tag, tl_fmt, &ui) &&
3450 1 == sscanf(val, "%d", &row.ttl))
3452 else if (1 == sscanf(tag, tx_fmt, &ui) &&
3453 1 == sscanf(val, "%d", &row.sent))
3455 else if (1 == sscanf(tag, txerr_fmt, &ui) &&
3456 1 == sscanf(val, "%d", &row.send_errors))
3461 if (1 == sscanf(tag, up_fmt, &ui) &&
3462 1 == sscanf(val, "%d", &row.uptime))
3468 /* error out if rows out of order */
3469 validate_ifnum(fp, ui, &fields, &row);
3470 /* if the row is complete, print it */
3471 another_ifstats_field(&fields, &row, fp);
3474 if (fields != IFSTATS_FIELDS)
3475 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3476 fields, IFSTATS_FIELDS);
3483 * validate_reslist_idx - helper for reslist()
3485 * Ensures rows are received in order and complete.
3488 validate_reslist_idx(
3495 if (prow->idx == idx)
3497 if (prow->idx + 1 == idx) {
3498 if (*pfields < RESLIST_FIELDS)
3499 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3500 *pfields, RESLIST_FIELDS);
3506 "received reslist index %u, have %d of %d fields for index %u, aborting.\n",
3507 idx, *pfields, RESLIST_FIELDS, prow->idx);
3513 * another_reslist_field - helper for reslist()
3515 * If all fields for the row have been received, print it.
3518 another_reslist_field(
3524 char addrmaskstr[128];
3525 int prefix; /* subnet mask as prefix bits count */
3529 /* we understand 4 tags */
3530 if (RESLIST_FIELDS > *pfields)
3533 prefix = sockaddr_masktoprefixlen(&prow->mask);
3535 snprintf(addrmaskstr, sizeof(addrmaskstr), "%s/%d",
3536 stoa(&prow->addr), prefix);
3538 snprintf(addrmaskstr, sizeof(addrmaskstr), "%s %s",
3539 stoa(&prow->addr), stoa(&prow->mask));
3542 " hits addr/prefix or addr mask\n"
3544 "==============================================================================\n");
3549 prow->hits, addrmaskstr, prow->flagstr);
3557 * reslist - ntpq -c reslist modeled on ntpdc -c reslist.
3561 struct parse * pcmd,
3565 const char addr_fmtu[] = "addr.%u";
3566 const char mask_fmtu[] = "mask.%u";
3567 const char hits_fmt[] = "hits.%u";
3568 const char flags_fmt[] = "flags.%u";
3569 const char qdata[] = "addr_restrictions";
3570 const int qdata_chars = COUNTOF(qdata) - 1;
3583 qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, qdata_chars,
3584 qdata, &rstatus, &dsize, &datap);
3585 if (qres) /* message already displayed */
3589 " hits addr/prefix or addr mask\n"
3591 "==============================================================================\n");
3597 while (nextvar(&dsize, &datap, &tag, &val)) {
3599 fprintf(stderr, "nextvar gave: %s = %s\n", tag,
3607 if (1 == sscanf(tag, addr_fmtu, &ui) &&
3608 decodenetnum(val, &row.addr))
3613 if (1 == sscanf(tag, flags_fmt, &ui)) {
3615 row.flagstr[0] = '\0';
3619 memcpy(row.flagstr, val, len);
3620 row.flagstr[len] = '\0';
3627 if (1 == sscanf(tag, hits_fmt, &ui) &&
3628 1 == sscanf(val, "%lu", &row.hits))
3633 if (1 == sscanf(tag, mask_fmtu, &ui) &&
3634 decodenetnum(val, &row.mask))
3640 /* error out if rows out of order */
3641 validate_reslist_idx(fp, ui, &fields, &row);
3642 /* if the row is complete, print it */
3643 another_reslist_field(&fields, &row, fp);
3646 if (fields != RESLIST_FIELDS)
3647 fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3648 fields, RESLIST_FIELDS);
3655 * collect_display_vdc
3658 collect_display_vdc(
3665 static const char * const suf[2] = { "adr", "port" };
3666 static const char * const leapbits[4] = { "00", "01",
3668 struct varlist vl[MAXLIST];
3684 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3686 if (NTP_ADD != pvdc->type) {
3687 doaddvlist(vl, pvdc->tag);
3689 for (n = 0; n < COUNTOF(suf); n++) {
3690 snprintf(tagbuf, sizeof(tagbuf), "%s%s",
3692 doaddvlist(vl, tagbuf);
3696 qres = doquerylist(vl, CTL_OP_READVAR, as, 0, &rstatus, &rsize,
3700 return; /* error msg already displayed */
3703 * iterate over the response variables filling vdc_table with
3704 * the retrieved values.
3706 while (nextvar(&rsize, &rdata, &tag, &val)) {
3710 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3711 len = strlen(pvdc->tag);
3712 if (strncmp(tag, pvdc->tag, len))
3714 if (NTP_ADD != pvdc->type) {
3715 if ('\0' != tag[len])
3720 for (n = 0; n < COUNTOF(suf); n++) {
3721 if (strcmp(tag + len, suf[n]))
3729 if (NULL == pvdc->tag)
3731 switch (pvdc->type) {
3734 /* strip surrounding double quotes */
3735 if ('"' == val[0]) {
3737 if (len > 0 && '"' == val[len - 1]) {
3738 val[len - 1] = '\0';
3743 case NTP_MODE: /* fallthru */
3745 pvdc->v.str = estrdup(val);
3749 decodets(val, &pvdc->v.lfp);
3753 if (!decodenetnum(val, &pvdc->v.sau))
3754 fprintf(stderr, "malformed %s=%s\n",
3759 if (0 == n) { /* adr */
3760 if (!decodenetnum(val, &pvdc->v.sau))
3762 "malformed %s=%s\n",
3765 if (atouint(val, &ul))
3766 SET_PORT(&pvdc->v.sau,
3778 fprintf(fp, "associd=%u status=%04x %s,\n", as, rstatus,
3779 statustoa(vtype, rstatus));
3782 for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3783 switch (pvdc->type) {
3786 if (pvdc->v.str != NULL) {
3787 fprintf(fp, "%s %s\n", pvdc->display,
3794 case NTP_ADD: /* fallthru */
3796 fprintf(fp, "%s %s\n", pvdc->display,
3797 nntohostp(&pvdc->v.sau));
3801 fprintf(fp, "%s %s\n", pvdc->display,
3802 prettydate(&pvdc->v.lfp));
3806 atouint(pvdc->v.str, &ul);
3807 fprintf(fp, "%s %s\n", pvdc->display,
3812 atouint(pvdc->v.str, &ul);
3813 fprintf(fp, "%s %s\n", pvdc->display,
3814 leapbits[ul & 0x3]);
3818 fprintf(stderr, "unexpected vdc type %d for %s\n",
3819 pvdc->type, pvdc->tag);
3827 * sysstats - implements ntpq -c sysstats modeled on ntpdc -c sysstats
3835 static vdc sysstats_vdc[] = {
3836 VDC_INIT("ss_uptime", "uptime: ", NTP_STR),
3837 VDC_INIT("ss_reset", "sysstats reset: ", NTP_STR),
3838 VDC_INIT("ss_received", "packets received: ", NTP_STR),
3839 VDC_INIT("ss_thisver", "current version: ", NTP_STR),
3840 VDC_INIT("ss_oldver", "older version: ", NTP_STR),
3841 VDC_INIT("ss_badformat", "bad length or format: ", NTP_STR),
3842 VDC_INIT("ss_badauth", "authentication failed:", NTP_STR),
3843 VDC_INIT("ss_declined", "declined: ", NTP_STR),
3844 VDC_INIT("ss_restricted", "restricted: ", NTP_STR),
3845 VDC_INIT("ss_limited", "rate limited: ", NTP_STR),
3846 VDC_INIT("ss_kodsent", "KoD responses: ", NTP_STR),
3847 VDC_INIT("ss_processed", "processed for time: ", NTP_STR),
3848 VDC_INIT(NULL, NULL, 0)
3851 collect_display_vdc(0, sysstats_vdc, FALSE, fp);
3856 * sysinfo - modeled on ntpdc's sysinfo
3864 static vdc sysinfo_vdc[] = {
3865 VDC_INIT("peeradr", "system peer: ", NTP_ADP),
3866 VDC_INIT("peermode", "system peer mode: ", NTP_MODE),
3867 VDC_INIT("leap", "leap indicator: ", NTP_2BIT),
3868 VDC_INIT("stratum", "stratum: ", NTP_STR),
3869 VDC_INIT("precision", "log2 precision: ", NTP_STR),
3870 VDC_INIT("rootdelay", "root delay: ", NTP_STR),
3871 VDC_INIT("rootdisp", "root dispersion: ", NTP_STR),
3872 VDC_INIT("refid", "reference ID: ", NTP_STR),
3873 VDC_INIT("reftime", "reference time: ", NTP_LFP),
3874 VDC_INIT("sys_jitter", "system jitter: ", NTP_STR),
3875 VDC_INIT("clk_jitter", "clock jitter: ", NTP_STR),
3876 VDC_INIT("clk_wander", "clock wander: ", NTP_STR),
3877 VDC_INIT("bcastdelay", "broadcast delay: ", NTP_STR),
3878 VDC_INIT("authdelay", "symm. auth. delay:", NTP_STR),
3879 VDC_INIT(NULL, NULL, 0)
3882 collect_display_vdc(0, sysinfo_vdc, TRUE, fp);
3887 * kerninfo - modeled on ntpdc's kerninfo
3895 static vdc kerninfo_vdc[] = {
3896 VDC_INIT("koffset", "pll offset: ", NTP_STR),
3897 VDC_INIT("kfreq", "pll frequency: ", NTP_STR),
3898 VDC_INIT("kmaxerr", "maximum error: ", NTP_STR),
3899 VDC_INIT("kesterr", "estimated error: ", NTP_STR),
3900 VDC_INIT("kstflags", "kernel status: ", NTP_STR),
3901 VDC_INIT("ktimeconst", "pll time constant: ", NTP_STR),
3902 VDC_INIT("kprecis", "precision: ", NTP_STR),
3903 VDC_INIT("kfreqtol", "frequency tolerance: ", NTP_STR),
3904 VDC_INIT("kppsfreq", "pps frequency: ", NTP_STR),
3905 VDC_INIT("kppsstab", "pps stability: ", NTP_STR),
3906 VDC_INIT("kppsjitter", "pps jitter: ", NTP_STR),
3907 VDC_INIT("kppscalibdur", "calibration interval ", NTP_STR),
3908 VDC_INIT("kppscalibs", "calibration cycles: ", NTP_STR),
3909 VDC_INIT("kppsjitexc", "jitter exceeded: ", NTP_STR),
3910 VDC_INIT("kppsstbexc", "stability exceeded: ", NTP_STR),
3911 VDC_INIT("kppscaliberrs", "calibration errors: ", NTP_STR),
3912 VDC_INIT(NULL, NULL, 0)
3915 collect_display_vdc(0, kerninfo_vdc, TRUE, fp);
3920 * monstats - implements ntpq -c monstats
3928 static vdc monstats_vdc[] = {
3929 VDC_INIT("mru_enabled", "enabled: ", NTP_STR),
3930 VDC_INIT("mru_depth", "addresses: ", NTP_STR),
3931 VDC_INIT("mru_deepest", "peak addresses: ", NTP_STR),
3932 VDC_INIT("mru_maxdepth", "maximum addresses: ", NTP_STR),
3933 VDC_INIT("mru_mindepth", "reclaim above count:", NTP_STR),
3934 VDC_INIT("mru_maxage", "reclaim older than: ", NTP_STR),
3935 VDC_INIT("mru_mem", "kilobytes: ", NTP_STR),
3936 VDC_INIT("mru_maxmem", "maximum kilobytes: ", NTP_STR),
3937 VDC_INIT(NULL, NULL, 0)
3940 collect_display_vdc(0, monstats_vdc, FALSE, fp);
3945 * iostats - ntpq -c iostats - network input and output counters
3953 static vdc iostats_vdc[] = {
3954 VDC_INIT("iostats_reset", "time since reset: ", NTP_STR),
3955 VDC_INIT("total_rbuf", "receive buffers: ", NTP_STR),
3956 VDC_INIT("free_rbuf", "free receive buffers: ", NTP_STR),
3957 VDC_INIT("used_rbuf", "used receive buffers: ", NTP_STR),
3958 VDC_INIT("rbuf_lowater", "low water refills: ", NTP_STR),
3959 VDC_INIT("io_dropped", "dropped packets: ", NTP_STR),
3960 VDC_INIT("io_ignored", "ignored packets: ", NTP_STR),
3961 VDC_INIT("io_received", "received packets: ", NTP_STR),
3962 VDC_INIT("io_sent", "packets sent: ", NTP_STR),
3963 VDC_INIT("io_sendfailed", "packet send failures: ", NTP_STR),
3964 VDC_INIT("io_wakeups", "input wakeups: ", NTP_STR),
3965 VDC_INIT("io_goodwakeups", "useful input wakeups: ", NTP_STR),
3966 VDC_INIT(NULL, NULL, 0)
3969 collect_display_vdc(0, iostats_vdc, FALSE, fp);
3974 * timerstats - ntpq -c timerstats - interval timer counters
3982 static vdc timerstats_vdc[] = {
3983 VDC_INIT("timerstats_reset", "time since reset: ", NTP_STR),
3984 VDC_INIT("timer_overruns", "timer overruns: ", NTP_STR),
3985 VDC_INIT("timer_xmts", "calls to transmit: ", NTP_STR),
3986 VDC_INIT(NULL, NULL, 0)
3989 collect_display_vdc(0, timerstats_vdc, FALSE, fp);
3994 * authinfo - implements ntpq -c authinfo
4002 static vdc authinfo_vdc[] = {
4003 VDC_INIT("authreset", "time since reset:", NTP_STR),
4004 VDC_INIT("authkeys", "stored keys: ", NTP_STR),
4005 VDC_INIT("authfreek", "free keys: ", NTP_STR),
4006 VDC_INIT("authklookups", "key lookups: ", NTP_STR),
4007 VDC_INIT("authknotfound", "keys not found: ", NTP_STR),
4008 VDC_INIT("authkuncached", "uncached keys: ", NTP_STR),
4009 VDC_INIT("authkexpired", "expired keys: ", NTP_STR),
4010 VDC_INIT("authencrypts", "encryptions: ", NTP_STR),
4011 VDC_INIT("authdecrypts", "decryptions: ", NTP_STR),
4012 VDC_INIT(NULL, NULL, 0)
4015 collect_display_vdc(0, authinfo_vdc, FALSE, fp);
4020 * pstats - show statistics for a peer
4028 static vdc pstats_vdc[] = {
4029 VDC_INIT("src", "remote host: ", NTP_ADD),
4030 VDC_INIT("dst", "local address: ", NTP_ADD),
4031 VDC_INIT("timerec", "time last received: ", NTP_STR),
4032 VDC_INIT("timer", "time until next send:", NTP_STR),
4033 VDC_INIT("timereach", "reachability change: ", NTP_STR),
4034 VDC_INIT("sent", "packets sent: ", NTP_STR),
4035 VDC_INIT("received", "packets received: ", NTP_STR),
4036 VDC_INIT("badauth", "bad authentication: ", NTP_STR),
4037 VDC_INIT("bogusorg", "bogus origin: ", NTP_STR),
4038 VDC_INIT("oldpkt", "duplicate: ", NTP_STR),
4039 VDC_INIT("seldisp", "bad dispersion: ", NTP_STR),
4040 VDC_INIT("selbroken", "bad reference time: ", NTP_STR),
4041 VDC_INIT("candidate", "candidate order: ", NTP_STR),
4042 VDC_INIT(NULL, NULL, 0)
4046 associd = checkassocid(pcmd->argval[0].uval);
4050 collect_display_vdc(associd, pstats_vdc, TRUE, fp);