summaryrefslogtreecommitdiffstats
path: root/bsd/rtemsbsd/rtems/rtems-ntpq.c
blob: a32556c54b4dec51ddddcfadfc33b1a732c60b47 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/**
 * @file
 *
 * @ingroup rtems_bsd_rtems
 *
 * @brief NTPQ command
 */

/*
 * Copyright (c) 2023 Chris Johns <chrisj@rtems.org>.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Copyright (C) 1992-2020 The University of Delaware and Network Time Foundation,
 * All rights reserved.
 * http://ntp.org/license
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose with or without fee is hereby granted,
 * provided that the above copyright notice appears in all copies and that
 * both the copyright notice and this permission notice appear in supporting
 * documentation, and that the name The University of Delaware not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  The University of Delaware and Network
 * Time Foundation makes no representations about the suitability this
 * software for any purpose.  It is provided "as is" without express or
 * implied warranty.
 *
 * Large pieces of this code have been taken from tnpq and reworked to
 * be something usable on RTEMS.
 */

#include <config.h>

#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/types.h>

#include <rtems.h>
#include <rtems/thread.h>

#include <rtems/ntpq.h>
#include <ntpq.h>
#define LIBNTPQ_C 1
#include <libntpq.h>

#include <rtems/shellconfig-net-services.h>
#include <rtems/libio_.h>

/*
 * NTPQ is sequential
 */
static rtems_recursive_mutex ntpq_lock = RTEMS_RECURSIVE_MUTEX_INITIALIZER("ntpq");

/*
 * NTPQ is full of globals and so we protect usage with single mutex
 * from the user interface. There is no easy way to make ntpq thread
 * safe without a lot of changes and the BSD command support is not
 * fully ported to net seervices.
 */
int rtems_ntpq_error_value;
char rtems_ntpq_error_str[128];
fd_set* rtems_ntpq_fd_set;
size_t rtems_ntpq_fd_set_size;
FILE* rtems_ntpq_outputfp;
char* rtems_ntpq_output_buf;
size_t rtems_ntpq_output_buf_size;

/**
 * SSL support stubs
 */
const char *keytype_name(int nid) {
  (void) nid;
  return "MD5";
}

int keytype_from_text(const char *text, size_t *pdigest_len) {
  (void) text;
  (void) pdigest_len;
  return NID_md5;
}

char *getpass_keytype(int keytype) {
  (void) keytype;
  return "\0";
}

void rtems_ntpq_verror(int error_code, const char* format, va_list ap) {
  rtems_ntpq_error_value = error_code;
  strcpy(rtems_ntpq_error_str, "ntpq: ");
  vsnprintf(
    rtems_ntpq_error_str + 6, sizeof(rtems_ntpq_error_str) - 7, format, ap);
}

void rtems_ntpq_error(int error_code, const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  rtems_ntpq_verror(error_code, format, ap);
  va_end(ap);
}

void rtems_ntpq_error_msg(const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  rtems_ntpq_error(-1, format, ap);
  va_end(ap);
}

/*
 * Default values we use.
 */
#define	DEFHOST		"localhost"	/* default host name */
#define	DEFTIMEOUT	5		/* wait 5 seconds for 1st pkt */
#define	DEFSTIMEOUT	3		/* and 3 more for each additional */
/*
 * Requests are automatically retried once, so total timeout with no
 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds.  At the other
 * extreme, a request eliciting 32 packets of responses each for some
 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
 * 93 seconds to fail each of two times, or 186 seconds.
 * Some commands involve a series of requests, such as "peers" and
 * "mrulist", so the cumulative timeouts are even longer for those.
 */
#define	DEFDELAY	0x51EB852	/* 20 milliseconds, l_fp fraction */
#define	LENHOSTNAME	256		/* host name is 256 characters long */

extern int always_auth;
extern int ai_fam_templ;
extern int ai_fam_default;
extern int wideremote;
extern int rawmode;
extern struct servent *server_entry;
extern struct association *assoc_cache;
extern u_char pktversion;
extern SOCKET sockfd;
extern int havehost;
extern int s_port;
extern struct servent *server_entry;
extern int sequence;
extern struct sock_timeval tvout;
extern struct sock_timeval tvsout;
extern l_fp delay_time;
extern char currenthost[LENHOSTNAME];
extern int currenthostisnum;
extern struct sockaddr_in hostaddr;
extern int showhostnames;
extern int wideremote;

static void rtems_ntpq_init(void) {
  const struct sock_timeval tvout_ = { DEFTIMEOUT, 0 };
  const struct sock_timeval tvsout_ = { DEFSTIMEOUT, 0 };
  if (sockfd > 0) {
    close(sockfd);
    havehost = 0;
  }
  sockfd = -1;
  havehost = 0;
  s_port = 0;
  server_entry = NULL;
  sequence = 0;

  old_rv = 1;
  drefid = -1;
  always_auth = 0;
  rawmode = 0;
  pktversion = NTP_OLDVERSION + 1;
  tvout = tvout_;
  tvsout = tvsout_;
  memset(&delay_time, 0, sizeof(delay_time));
  memset(currenthost, 0, LENHOSTNAME);
  currenthostisnum = 0;
  memset(&hostaddr, 0, sizeof(hostaddr));
  showhostnames = 1;
  wideremote = 0;
  ai_fam_templ = 0;
  ai_fam_default = 0;

  if (assoc_cache != NULL) {
    free(assoc_cache);
  }
  assoc_cache = NULL;
  assoc_cache_slots = 0;
  numassoc = 0;

  numhosts = 0;
}

int rtems_ntpq_create(size_t output_buf_size) {
  size_t alloc_size;
  size_t fd_set_break;
  rtems_recursive_mutex_lock(&ntpq_lock);
  if (rtems_ntpq_output_buf != NULL) {
    rtems_ntpq_error(EEXIST, "already open");
    rtems_recursive_mutex_unlock(&ntpq_lock);
    return -1;
  }
  rtems_ntpq_output_buf_size = output_buf_size;
  alloc_size = output_buf_size;
  if ((alloc_size & 16) != 0) {
    alloc_size = ((alloc_size / 16) + 1) * 16;
  }
  fd_set_break = alloc_size;
  rtems_ntpq_fd_set_size =
    sizeof(fd_set) * (howmany(rtems_libio_number_iops, sizeof(fd_set) * 8));
  alloc_size += rtems_ntpq_fd_set_size;
  rtems_ntpq_output_buf = calloc(1, alloc_size);
  if (rtems_ntpq_output_buf == NULL) {
    rtems_ntpq_fd_set_size = 0;
    rtems_ntpq_error(ENOMEM, "no memory");
    rtems_recursive_mutex_unlock(&ntpq_lock);
    return -1;
  }
  rtems_ntpq_fd_set = (fd_set*) (rtems_ntpq_output_buf + fd_set_break);
  rtems_ntpq_outputfp = fopen("/dev/null", "wb");
  if (rtems_ntpq_outputfp == NULL) {
    rtems_ntpq_error(errno, "buffered file pointer");
    free(rtems_ntpq_output_buf);
    rtems_ntpq_fd_set_size = 0;
    rtems_ntpq_output_buf_size = 0;
    rtems_ntpq_output_buf = NULL;
    rtems_ntpq_fd_set = NULL;
    rtems_recursive_mutex_unlock(&ntpq_lock);
    return -1;
  }
  setbuffer(
    rtems_ntpq_outputfp, &rtems_ntpq_output_buf[0],
    rtems_ntpq_output_buf_size);
  rtems_ntpq_init();
  rtems_recursive_mutex_unlock(&ntpq_lock);
  return 0;
}

void rtems_ntpq_destroy(void) {
  rtems_recursive_mutex_lock(&ntpq_lock);
  if (rtems_ntpq_output_buf != NULL) {
    if (rtems_ntpq_outputfp != NULL) {
      fclose(rtems_ntpq_outputfp);
    }
    free(rtems_ntpq_output_buf);
    rtems_ntpq_fd_set_size = 0;
    rtems_ntpq_output_buf_size = 0;
    rtems_ntpq_output_buf = NULL;
    rtems_ntpq_fd_set = NULL;
  }
  rtems_ntpq_init();
  rtems_recursive_mutex_unlock(&ntpq_lock);
}

int rtems_ntpq_error_code(void) {
  int v;
  rtems_recursive_mutex_lock(&ntpq_lock);
  v = rtems_ntpq_error_value;
  rtems_recursive_mutex_unlock(&ntpq_lock);
  return v;
}

const char* rtems_ntpq_error_text(void) {
  return rtems_ntpq_error_str;
}

int rtems_ntpq_create_check(void) {
  int r = 1;
  rtems_recursive_mutex_lock(&ntpq_lock);
  if (rtems_ntpq_outputfp == NULL) {
    rtems_ntpq_error_msg("not open");
    r = 0;
  }
  rtems_recursive_mutex_unlock(&ntpq_lock);
  return r;
}

const char* rtems_ntpq_output(void) {
  const char* o;
  rtems_recursive_mutex_lock(&ntpq_lock);
  o = rtems_ntpq_output_buf;
  rtems_recursive_mutex_unlock(&ntpq_lock);
  return o;
}

FILE* rtems_ntpq_stdout(void) {
  FILE* fp;
  rtems_recursive_mutex_lock(&ntpq_lock);
  fp = rtems_ntpq_outputfp;
  rtems_recursive_mutex_unlock(&ntpq_lock);
  return fp;
}

static int rtems_getarg(const char *str, int code, arg_v *argp) {
  extern struct association *assoc_cache;
  unsigned long ul;

  switch (code & ~OPT) {
  case NTP_STR:
    argp->string = str;
    break;

  case NTP_ADD:
    if (!getnetnum(str, &argp->netnum, NULL, 0))
      return 0;
    break;

  case NTP_UINT:
    if ('&' == str[0]) {
      if (!atouint(&str[1], &ul)) {
        rtems_ntpq_error_msg(
          "association index `%s' invalid/undecodable", str);
        return 0;
      }
      if (0 == numassoc) {
        dogetassoc(rtems_ntpq_outputfp);
        if (0 == numassoc) {
        rtems_ntpq_error_msg("no associations found, `%s' unknown", str);
          return 0;
        }
      }
      ul = min(ul, numassoc);
      argp->uval = assoc_cache[ul - 1].assid;
      break;
    }
    if (!atouint(str, &argp->uval)) {
        rtems_ntpq_error_msg("illegal unsigned value %s", str);
      return 0;
    }
    break;

  case NTP_INT:
    if (!atoint(str, &argp->ival)) {
      rtems_ntpq_error_msg("illegal integer value %s", str);
      return 0;
    }
    break;

  case IP_VERSION:
    if (!strcmp("-6", str)) {
      argp->ival = 6;
    } else if (!strcmp("-4", str)) {
      argp->ival = 4;
    } else {
      rtems_ntpq_error_msg("version must be either 4 or 6\n");
      return 0;
    }
    break;
  }

  return 1;
}

int rtems_ntpq_query(const int argc, const char** argv) {
  extern struct xcmd builtins[];
  extern struct xcmd opcmds[];
  struct parse pcmd;
  struct xcmd* cmd;
  const char* keyword;
  size_t keyword_len;
  int args = argc;
  int arg;
  rtems_recursive_mutex_lock(&ntpq_lock);
  if (!rtems_ntpq_create_check()) {
    rtems_recursive_mutex_unlock(&ntpq_lock);
    return -1;
  }
  if (argc < 1) {
    rtems_ntpq_error_msg("no arguments provided");
    rtems_recursive_mutex_unlock(&ntpq_lock);
    return -1;
  }
  fflush(rtems_ntpq_outputfp);
  memset(rtems_ntpq_output_buf, 0, rtems_ntpq_output_buf_size);
  keyword = argv[0];
  args--;
  argv++;
  keyword_len = strlen(keyword);
  for (cmd = builtins; cmd->keyword != NULL; ++cmd) {
    if (strncmp(keyword, cmd->keyword, keyword_len) == 0) {
      break;
    }
  }
  if (cmd->keyword == NULL) {
    for (cmd = opcmds; cmd->keyword != NULL; ++cmd) {
      if (strncmp(keyword, cmd->keyword, keyword_len) == 0) {
        break;
      }
    }
    if (cmd->keyword == NULL) {
      rtems_ntpq_error_msg("command not found: %s", keyword);
      rtems_recursive_mutex_unlock(&ntpq_lock);
      return -1;
    }
  }
  pcmd.keyword = keyword;
  pcmd.nargs = 0;
  for (arg = 0; arg < MAXARGS && cmd->arg[arg] != NO; ++arg) {
    if (arg == args) {
      break;
    }
    if (arg > args) {
      rtems_ntpq_error_msg("not enough options: %s", keyword);
      rtems_recursive_mutex_unlock(&ntpq_lock);
      return -1;
    }
    if (!rtems_getarg(argv[arg], cmd->arg[arg], &pcmd.argval[arg])) {
      rtems_recursive_mutex_unlock(&ntpq_lock);
      return -1;
    }
    ++pcmd.nargs;
  }
  cmd->handler(&pcmd, rtems_ntpq_outputfp);
  rtems_recursive_mutex_unlock(&ntpq_lock);
  return 0;
}

int rtems_shell_ntpq_command(int argc, char **argv) {
  int r;
  argc--;
  argv++;
  if (argc < 1) {
    printf("error: no host and commands\n");
    return 1;
  }
  if (strcmp(argv[0], "open") == 0) {
    r = rtems_ntpq_create(4096);
    if (r == 0) {
      printf("ntpq: open");
    }
  } else if (strcmp(argv[0], "close") == 0) {
    rtems_ntpq_destroy();
    printf("ntpq: closed");
    r = 0;
  } else {
    r = rtems_ntpq_query(argc, (const char**) argv);
  }
  if (r == 0) {
    const char* output = rtems_ntpq_output();
    const size_t len = strlen(output);
    printf(rtems_ntpq_output());
    if (len > 0 && output[len - 1] != '\n') {
      printf("\n");
    }
  } else {
    printf("%s\n", rtems_ntpq_error_text());
  }
  return r;
}

rtems_shell_cmd_t rtems_shell_NTPQ_Command =
{
    "ntpq",
    "[help]",
    "misc",
    rtems_shell_ntpq_command,
    NULL,
    NULL
};