• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/ucode/lib/log.c

  1 /*
  2  * Copyright (C) 2023 Jo-Philipp Wich <jo@mein.io>
  3  *
  4  * Permission to use, copy, modify, and/or distribute this software for any
  5  * purpose with or without fee is hereby granted, provided that the above
  6  * copyright notice and this permission notice appear in all copies.
  7  *
  8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 15  */
 16 
 17 /**
 18  * # System logging functions
 19  *
 20  * The `log` module provides bindings to the POSIX syslog functions `openlog()`,
 21  * `syslog()` and `closelog()` as well as - when available - the OpenWrt
 22  * specific ulog library functions.
 23  *
 24  * Functions can be individually imported and directly accessed using the
 25  * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}
 26  * syntax:
 27  *
 28  *   ```
 29  *   import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';
 30  *
 31  *   openlog("my-log-ident", LOG_PID, LOG_USER);
 32  *   syslog(LOG_ERR, "An error occurred!");
 33  *
 34  *   // OpenWrt specific ulog functions
 35  *   import { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';
 36  *
 37  *   ulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");
 38  *   ulog(LOG_INFO, "The current epoch is %d", time());
 39  *   ```
 40  *
 41  * Alternatively, the module namespace can be imported
 42  * using a wildcard import statement:
 43  *
 44  *   ```
 45  *   import * as log from 'log';
 46  *
 47  *   log.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);
 48  *   log.syslog(log.LOG_ERR, "An error occurred!");
 49  *
 50  *   // OpenWrt specific ulog functions
 51  *   log.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");
 52  *   log.ulog(log.LOG_INFO, "The current epoch is %d", time());
 53  *   ```
 54  *
 55  * Additionally, the log module namespace may also be imported by invoking the
 56  * `ucode` interpreter with the `-llog` switch.
 57  *
 58  * ## Constants
 59  *
 60  * The `log` module declares a number of numeric constants to specify logging
 61  * facility, priority and option values, as well as ulog specific channels.
 62  *
 63  * ### Syslog Options
 64  *
 65  * | Constant Name | Description                                             |
 66  * |---------------|---------------------------------------------------------|
 67  * | `LOG_PID`     | Include PID with each message.                          |
 68  * | `LOG_CONS`    | Log to console if error occurs while sending to syslog. |
 69  * | `LOG_NDELAY`  | Open the connection to the logger immediately.          |
 70  * | `LOG_ODELAY`  | Delay open until the first message is logged.           |
 71  * | `LOG_NOWAIT`  | Do not wait for child processes created during logging. |
 72  *
 73  * ### Syslog Facilities
 74  *
 75  * | Constant Name  | Description                                      |
 76  * |----------------|--------------------------------------------------|
 77  * | `LOG_AUTH`     | Authentication/authorization messages.           |
 78  * | `LOG_AUTHPRIV` | Private authentication messages.                 |
 79  * | `LOG_CRON`     | Clock daemon (cron and at commands).             |
 80  * | `LOG_DAEMON`   | System daemons without separate facility values. |
 81  * | `LOG_FTP`      | FTP server daemon.                               |
 82  * | `LOG_KERN`     | Kernel messages.                                 |
 83  * | `LOG_LPR`      | Line printer subsystem.                          |
 84  * | `LOG_MAIL`     | Mail system.                                     |
 85  * | `LOG_NEWS`     | Network news subsystem.                          |
 86  * | `LOG_SYSLOG`   | Messages generated internally by syslogd.        |
 87  * | `LOG_USER`     | Generic user-level messages.                     |
 88  * | `LOG_UUCP`     | UUCP subsystem.                                  |
 89  * | `LOG_LOCAL0`   | Local use 0 (custom facility).                   |
 90  * | `LOG_LOCAL1`   | Local use 1 (custom facility).                   |
 91  * | `LOG_LOCAL2`   | Local use 2 (custom facility).                   |
 92  * | `LOG_LOCAL3`   | Local use 3 (custom facility).                   |
 93  * | `LOG_LOCAL4`   | Local use 4 (custom facility).                   |
 94  * | `LOG_LOCAL5`   | Local use 5 (custom facility).                   |
 95  * | `LOG_LOCAL6`   | Local use 6 (custom facility).                   |
 96  * | `LOG_LOCAL7`   | Local use 7 (custom facility).                   |
 97  *
 98  * ### Syslog Priorities
 99  *
100  * | Constant Name | Description                         |
101  * |---------------|-------------------------------------|
102  * | `LOG_EMERG`   | System is unusable.                 |
103  * | `LOG_ALERT`   | Action must be taken immediately.   |
104  * | `LOG_CRIT`    | Critical conditions.                |
105  * | `LOG_ERR`     | Error conditions.                   |
106  * | `LOG_WARNING` | Warning conditions.                 |
107  * | `LOG_NOTICE`  | Normal, but significant, condition. |
108  * | `LOG_INFO`    | Informational message.              |
109  * | `LOG_DEBUG`   | Debug-level message.                |
110  *
111  * ### Ulog channels
112  *
113  * | Constant Name | Description                          |
114  * |---------------|--------------------------------------|
115  * | `ULOG_KMSG`   | Log messages to `/dev/kmsg` (dmesg). |
116  * | `ULOG_STDIO`  | Log messages to stdout.              |
117  * | `ULOG_SYSLOG` | Log messages to syslog.              |
118  *
119  * @module log
120  */
121 
122 #include <syslog.h>
123 #include <errno.h>
124 
125 #ifdef HAVE_ULOG
126 #include <libubox/ulog.h>
127 #endif
128 
129 #include "ucode/module.h"
130 #include "ucode/internal/lib.h"
131 
132 
133 static char log_ident[32];
134 
135 /**
136  * The following log option strings are recognized:
137  *
138  * | Log Option | Description                                                |
139  * |------------|------------------------------------------------------------|
140  * | `"pid"`    | Include PID with each message.                             |
141  * | `"cons"`   | Log to console if an error occurs while sending to syslog. |
142  * | `"ndelay"` | Open the connection to the logger immediately.             |
143  * | `"odelay"` | Delay open until the first message is logged.              |
144  * | `"nowait"` | Do not wait for child processes created during logging.    |
145  *
146  * @typedef {string} module:log.LogOption
147  * @enum {module:log.LogOption}
148  *
149  */
150 static const struct { const char *name; int value; } log_options[] = {
151         { "pid", LOG_PID },
152         { "cons", LOG_CONS },
153         { "ndelay", LOG_NDELAY },
154         { "odelay", LOG_ODELAY },
155         { "nowait", LOG_NOWAIT },
156 };
157 
158 /**
159  * The following log facility strings are recognized:
160  *
161  * | Facility     | Description                                      |
162  * |--------------|--------------------------------------------------|
163  * | `"auth"`     | Authentication/authorization messages.           |
164  * | `"authpriv"` | Private authentication messages.                 |
165  * | `"cron"`     | Clock daemon (cron and at commands).             |
166  * | `"daemon"`   | System daemons without separate facility values. |
167  * | `"ftp"`      | FTP server daemon.                               |
168  * | `"kern"`     | Kernel messages.                                 |
169  * | `"lpr"`      | Line printer subsystem.                          |
170  * | `"mail"`     | Mail system.                                     |
171  * | `"news"`     | Network news subsystem.                          |
172  * | `"syslog"`   | Messages generated internally by syslogd.        |
173  * | `"user"`     | Generic user-level messages.                     |
174  * | `"uucp"`     | UUCP subsystem.                                  |
175  * | `"local0"`   | Local use 0 (custom facility).                   |
176  * | `"local1"`   | Local use 1 (custom facility).                   |
177  * | `"local2"`   | Local use 2 (custom facility).                   |
178  * | `"local3"`   | Local use 3 (custom facility).                   |
179  * | `"local4"`   | Local use 4 (custom facility).                   |
180  * | `"local5"`   | Local use 5 (custom facility).                   |
181  * | `"local6"`   | Local use 6 (custom facility).                   |
182  * | `"local7"`   | Local use 7 (custom facility).                   |
183  *
184  * @typedef {string} module:log.LogFacility
185  * @enum {module:log.LogFacility}
186  */
187 static const struct { const char *name; int value; } log_facilities[] = {
188         { "auth", LOG_AUTH },
189 #ifdef LOG_AUTHPRIV
190         { "authpriv", LOG_AUTHPRIV },
191 #endif
192         { "cron", LOG_CRON },
193         { "daemon", LOG_DAEMON },
194 #ifdef LOG_FTP
195         { "ftp", LOG_FTP },
196 #endif
197         { "kern", LOG_KERN },
198         { "lpr", LOG_LPR },
199         { "mail", LOG_MAIL },
200         { "news", LOG_NEWS },
201         { "syslog", LOG_SYSLOG },
202         { "user", LOG_USER },
203         { "uucp", LOG_UUCP },
204         { "local0", LOG_LOCAL0 },
205         { "local1", LOG_LOCAL1 },
206         { "local2", LOG_LOCAL2 },
207         { "local3", LOG_LOCAL3 },
208         { "local4", LOG_LOCAL4 },
209         { "local5", LOG_LOCAL5 },
210         { "local6", LOG_LOCAL6 },
211         { "local7", LOG_LOCAL7 },
212 };
213 
214 /**
215  * The following log priority strings are recognized:
216  *
217  * | Priority    | Description                         |
218  * |-------------|-------------------------------------|
219  * | `"emerg"`   | System is unusable.                 |
220  * | `"alert"`   | Action must be taken immediately.   |
221  * | `"crit"`    | Critical conditions.                |
222  * | `"err"`     | Error conditions.                   |
223  * | `"warning"` | Warning conditions.                 |
224  * | `"notice"`  | Normal, but significant, condition. |
225  * | `"info"`    | Informational message.              |
226  * | `"debug"`   | Debug-level message.                |
227  *
228  * @typedef {string} module:log.LogPriority
229  * @enum {module:log.LogPriority}
230  */
231 static const struct { const char *name; int value; } log_priorities[] = {
232         { "emerg", LOG_EMERG },
233         { "alert", LOG_ALERT },
234         { "crit", LOG_CRIT },
235         { "err", LOG_ERR },
236         { "warning", LOG_WARNING },
237         { "notice", LOG_NOTICE },
238         { "info", LOG_INFO },
239         { "debug", LOG_DEBUG },
240 };
241 
242 
243 static int
244 parse_facility(uc_value_t *facility)
245 {
246         char *s;
247         int rv;
248 
249         switch (ucv_type(facility)) {
250         case UC_STRING:
251                 s = ucv_string_get(facility);
252 
253                 for (size_t i = 0; i < ARRAY_SIZE(log_facilities); i++)
254                         if (s && !strcasecmp(s, log_facilities[i].name))
255                                 return log_facilities[i].value;
256 
257                 return -1;
258 
259         case UC_INTEGER:
260                 rv = ucv_int64_get(facility);
261 
262                 if (errno == ERANGE || rv < 0)
263                         return -1;
264 
265                 return rv;
266 
267         case UC_NULL:
268                 return 0;
269 
270         default:
271                 return -1;
272         }
273 }
274 
275 static int
276 parse_options(uc_value_t *option)
277 {
278         char *s;
279         int rv;
280 
281         switch (ucv_type(option)) {
282         case UC_ARRAY:
283                 rv = 0;
284 
285                 for (size_t i = 0; i < ucv_array_length(option); i++) {
286                         uc_value_t *opt = ucv_array_get(option, i);
287                         char *s = ucv_string_get(opt);
288                         size_t j;
289 
290                         for (j = 0; j < ARRAY_SIZE(log_options); j++)
291                                 if (s && !strcasecmp(log_options[j].name, s))
292                                         break;
293 
294                         if (j == ARRAY_SIZE(log_options))
295                                 return -1;
296 
297                         rv |= log_options[j].value;
298                 }
299 
300                 return rv;
301 
302         case UC_STRING:
303                 s = ucv_string_get(option);
304 
305                 for (size_t i = 0; i < ARRAY_SIZE(log_options); i++)
306                         if (s && !strcasecmp(s, log_options[i].name))
307                                 return log_options[i].value;
308 
309                 return -1;
310 
311         case UC_INTEGER:
312                 rv = ucv_int64_get(option);
313 
314                 if (errno == ERANGE || rv < 0)
315                         return -1;
316 
317                 return rv;
318 
319         case UC_NULL:
320                 return 0;
321 
322         default:
323                 return -1;
324         }
325 }
326 
327 static int
328 parse_priority(uc_value_t *priority)
329 {
330         char *s;
331         int rv;
332 
333         switch (ucv_type(priority)) {
334         case UC_STRING:
335                 s = ucv_string_get(priority);
336 
337                 for (size_t i = 0; i < ARRAY_SIZE(log_priorities); i++)
338                         if (s && !strcasecmp(s, log_priorities[i].name))
339                                 return log_priorities[i].value;
340 
341                 return -1;
342 
343         case UC_INTEGER:
344                 rv = ucv_int64_get(priority);
345 
346                 if (errno == ERANGE || rv < 0)
347                         return -1;
348 
349                 return rv;
350 
351         case UC_NULL:
352                 return LOG_INFO;
353 
354         default:
355                 return -1;
356         }
357 }
358 
359 static char *
360 parse_ident(uc_vm_t *vm, uc_value_t *ident)
361 {
362         if (!ident)
363                 return NULL;
364 
365         char *s = ucv_to_string(vm, ident);
366 
367         snprintf(log_ident, sizeof(log_ident), "%s", s ? s : "");
368         free(s);
369 
370         return log_ident[0] ? log_ident : NULL;
371 }
372 
373 /**
374  * Open connection to system logger.
375  *
376  * The `openlog()` function instructs the program to establish a connection to
377  * the system log service and configures the default facility and identification
378  * for use in subsequent log operations. It may be omitted, in which case the
379  * first call to `syslog()` will implicitly call `openlog()` with a default
380  * ident value representing the program name and a default `LOG_USER` facility.
381  *
382  * The log option argument may be either a single string value containing an
383  * option name, an array of option name strings or a numeric value representing
384  * a bitmask of `LOG_*` option constants.
385  *
386  * The facility argument may be either a single string value containing a
387  * facility name or one of the numeric `LOG_*` facility constants in the module
388  * namespace.
389  *
390  * Returns `true` if the system `openlog()` function was invoked.
391  *
392  * Returns `false` if an invalid argument, such as an unrecognized option or
393  * facility name, was provided.
394  *
395  * @function module:log#openlog
396  *
397  * @param {string} [ident]
398  * A string identifying the program name. If omitted, the name of the calling
399  * process is used by default.
400  *
401  * @param {number|module:log.LogOption|module:log.LogOption[]} [options]
402  * Logging options to use.
403  *
404  * See {@link module:log.LogOption|LogOption} for recognized option names.
405  *
406  * @param {number|module:log.LogFacility} [facility="user"]
407  * The facility to use for log messages generated by subsequent syslog calls.
408  *
409  * See {@link module:log.LogFacility|LogFacility} for recognized facility names.
410  *
411  * @returns {boolean}
412  *
413  * @example
414  * // Example usage of openlog function
415  * openlog("myapp", LOG_PID | LOG_NDELAY, LOG_LOCAL0);
416  *
417  * // Using option names instead of bitmask and LOG_USER facility
418  * openlog("myapp", [ "pid", "ndelay" ], "user");
419  */
420 static uc_value_t *
421 uc_openlog(uc_vm_t *vm, size_t nargs)
422 {
423         char *ident = parse_ident(vm, uc_fn_arg(0));
424         int options = parse_options(uc_fn_arg(1));
425         int facility = parse_facility(uc_fn_arg(2));
426 
427         if (options == -1 || facility == -1)
428                 return ucv_boolean_new(false);
429 
430         openlog(ident, options, uc_fn_arg(2) ? facility : LOG_USER);
431 
432         return ucv_boolean_new(true);
433 }
434 
435 /**
436  * Log a message to the system logger.
437  *
438  * This function logs a message to the system logger. The function behaves in a
439  * sprintf-like manner, allowing the use of format strings and associated
440  * arguments to construct log messages.
441  *
442  * If the `openlog` function has not been called explicitly before, `syslog()`
443  * implicitly calls `openlog()`, using a default ident and `LOG_USER` facility
444  * value before logging the message.
445  *
446  * If the `format` argument is not a string and not `null`, it will be
447  * implicitly converted to a string and logged as-is, without further format
448  * string processing.
449  *
450  * Returns `true` if a message was passed to the system `syslog()` function.
451  *
452  * Returns `false` if an invalid priority value or an empty message was given.
453  *
454  * @function module:log#syslog
455  *
456  * @param {number|module:log.LogPriority} priority
457  * Log message priority. May be either a number value (potentially bitwise OR-ed
458  * with a log facility constant) which is passed as-is to the system `syslog()`
459  * function or a priority name string.
460  *
461  * See {@link module:log.LogPriority|LogPriority} for recognized priority names.
462  *
463  * @param {*} format
464  * The sprintf-like format string for the log message, or any other, non-null,
465  * non-string value type which will be implicitly stringified and logged as-is.
466  *
467  * @param {...*} [args]
468  * In case a format string value was provided in the previous argument, then
469  * all subsequent arguments are used to replace the placeholders in the format
470  * string.
471  *
472  * @returns {boolean}
473  *
474  * @example
475  * // Example usage of syslog function with format string and arguments
476  * const username = "user123";
477  * const errorCode = 404;
478  * syslog(LOG_ERR, "User %s encountered error: %d", username, errorCode);
479  *
480  * // If openlog has not been called explicitly, it is implicitly called with defaults:
481  * syslog(LOG_INFO, "This message will be logged with default settings.");
482  *
483  * // Selectively override used facility by OR-ing numeric constant
484  * const password =" secret";
485  * syslog(LOG_DEBUG|LOG_AUTHPRIV, "The password %s has been wrong", secret);
486  *
487  * // Using priority names for logging
488  * syslog("emerg", "System shutdown imminent!");
489  *
490  * // Implicit stringification
491  * syslog("debug", { foo: 1, bar: true, baz: [1, 2, 3] });
492  */
493 static uc_value_t *
494 uc_syslog(uc_vm_t *vm, size_t nargs)
495 {
496         int priority = parse_priority(uc_fn_arg(0));
497 
498         if (priority == -1 || nargs < 2)
499                 return ucv_boolean_new(false);
500 
501         uc_value_t *fmt = uc_fn_arg(1), *msg;
502         uc_cfn_ptr_t fmtfn;
503         char *s;
504 
505         switch (ucv_type(fmt)) {
506         case UC_STRING:
507                 fmtfn = uc_stdlib_function("sprintf");
508                 msg = fmtfn(vm, nargs - 1);
509 
510                 if (msg) {
511                         syslog(priority, "%s", ucv_string_get(msg));
512                         ucv_put(msg);
513 
514                         return ucv_boolean_new(true);
515                 }
516 
517                 break;
518 
519         case UC_NULL:
520                 break;
521 
522         default:
523                 s = ucv_to_string(vm, fmt);
524 
525                 if (s) {
526                         syslog(priority, "%s", s);
527                         free(s);
528 
529                         return ucv_boolean_new(true);
530                 }
531 
532                 break;
533         }
534 
535         return ucv_boolean_new(false);
536 }
537 
538 /**
539  * Close connection to system logger.
540  *
541  * The usage of this function is optional, and usually an explicit log
542  * connection tear down is not required.
543  *
544  * @function module:log#closelog
545  */
546 static uc_value_t *
547 uc_closelog(uc_vm_t *vm, size_t nargs)
548 {
549         closelog();
550 
551         return NULL;
552 }
553 
554 
555 #ifdef HAVE_ULOG
556 /**
557  * The following ulog channel strings are recognized:
558  *
559  * | Channel    | Description                                       |
560  * |------------|---------------------------------------------------|
561  * | `"kmsg"`   | Log to `/dev/kmsg`, log messages appear in dmesg. |
562  * | `"syslog"` | Use standard `syslog()` mechanism.                |
563  * | `"stdio"`  | Use stderr for log output.                        |
564  *
565  * @typedef {string} module:log.UlogChannel
566  * @enum {module:log.UlogChannel}
567  */
568 static const struct { const char *name; int value; } ulog_channels[] = {
569         { "kmsg", ULOG_KMSG },
570         { "syslog", ULOG_SYSLOG },
571         { "stdio", ULOG_STDIO },
572 };
573 
574 static int
575 parse_channels(uc_value_t *channels)
576 {
577         char *s;
578         int rv;
579 
580         switch (ucv_type(channels)) {
581         case UC_ARRAY:
582                 rv = 0;
583 
584                 for (size_t i = 0; i < ucv_array_length(channels); i++) {
585                         uc_value_t *channel = ucv_array_get(channels, i);
586                         char *s = ucv_string_get(channel);
587                         size_t j;
588 
589                         for (j = 0; j < ARRAY_SIZE(ulog_channels); j++)
590                                 if (s && !strcasecmp(s, ulog_channels[j].name))
591                                         break;
592 
593                         if (j == ARRAY_SIZE(ulog_channels))
594                                 return -1;
595 
596                         rv |= ulog_channels[j].value;
597                 }
598 
599                 return rv;
600 
601         case UC_STRING:
602                 s = ucv_string_get(channels);
603 
604                 for (size_t i = 0; i < ARRAY_SIZE(ulog_channels); i++)
605                         if (s && !strcasecmp(s, ulog_channels[i].name))
606                                 return ulog_channels[i].value;
607 
608                 return -1;
609 
610         case UC_INTEGER:
611                 rv = ucv_uint64_get(channels);
612 
613                 if (errno == ERANGE)
614                         return -1;
615 
616                 return rv & (ULOG_KMSG|ULOG_STDIO|ULOG_SYSLOG);
617 
618         case UC_NULL:
619                 return 0;
620 
621         default:
622                 return -1;
623         }
624 }
625 
626 /**
627  * Configure ulog logger.
628  *
629  * This functions configures the ulog mechanism and is analogous to using the
630  * `openlog()` function in conjunction with `syslog()`.
631  *
632  * The `ulog_open()` function is OpenWrt specific and may not be present on
633  * other systems. Use `openlog()` and `syslog()` instead for portability to
634  * non-OpenWrt environments.
635  *
636  * A program may use multiple channels to simultaneously output messages using
637  * different means. The channel argument may either be a single string value
638  * containing a channel name, an array of channel names or a numeric value
639  * representing a bitmask of `ULOG_*` channel constants.
640  *
641  * The facility argument may be either a single string value containing a
642  * facility name or one of the numeric `LOG_*` facility constants in the module
643  * namespace.
644  *
645  * The default facility value varies, depending on the execution context of the
646  * program. In OpenWrt's preinit boot phase, or when stdout is not connected to
647  * an interactive terminal, the facility defaults to `"daemon"` (`LOG_DAEMON`),
648  * otherwise to `"user"` (`LOG_USER`).
649  *
650  * Likewise, the default channel is selected depending on the context. During
651  * OpenWrt's preinit boot phase, the `"kmsg"` channel is used, for interactive
652  * terminals the `"stdio"` one and for all other cases the `"syslog"` channel
653  * is selected.
654  *
655  * Returns `true` if ulog was configured.
656  *
657  * Returns `false` if an invalid argument, such as an unrecognized channel or
658  * facility name, was provided.
659  *
660  * @function module:log#ulog_open
661  *
662  * @param {number|module:log.UlogChannel|module:log.UlogChannel[]} [channel]
663  * Specifies the log channels to use.
664  *
665  * See {@link module:log.UlogChannel|UlogChannel} for recognized channel names.
666  *
667  * @param {number|module:log.LogFacility} [facility]
668  * The facility to use for log messages generated by subsequent `ulog()` calls.
669  *
670  * See {@link module:log.LogFacility|LogFacility} for recognized facility names.
671  *
672  * @param {string} [ident]
673  * A string identifying the program name. If omitted, the name of the calling
674  * process is used by default.
675  *
676  * @returns {boolean}
677  *
678  * @example
679  * // Log to dmesg and stderr
680  * ulog_open(["stdio", "kmsg"], "daemon", "my-program");
681  *
682  * // Use numeric constants and use implicit default ident
683  * ulog_open(ULOG_SYSLOG, LOG_LOCAL0);
684  */
685 static uc_value_t *
686 uc_ulog_open(uc_vm_t *vm, size_t nargs)
687 {
688         int channels = parse_channels(uc_fn_arg(0));
689         int facility = parse_facility(uc_fn_arg(1));
690         char *ident = parse_ident(vm, uc_fn_arg(2));
691 
692         if (channels == -1 || facility == -1)
693                 return ucv_boolean_new(false);
694 
695         /* -1 lets libubox pick its context dependent defaults */
696         if (!uc_fn_arg(0))
697                 channels = -1;
698 
699         if (!uc_fn_arg(1))
700                 facility = -1;
701 
702         ulog_open(channels, facility, ident);
703 
704         return ucv_boolean_new(true);
705 }
706 
707 static uc_value_t *
708 uc_ulog_log_common(uc_vm_t *vm, size_t nargs, int priority)
709 {
710         uc_value_t *fmt = uc_fn_arg(0), *msg;
711         uc_cfn_ptr_t fmtfn;
712         char *s;
713 
714         switch (ucv_type(fmt)) {
715         case UC_STRING:
716                 fmtfn = uc_stdlib_function("sprintf");
717                 msg = fmtfn(vm, nargs);
718 
719                 if (msg) {
720                         ulog(priority, "%s", ucv_string_get(msg));
721                         ucv_put(msg);
722 
723                         return ucv_boolean_new(true);
724                 }
725 
726                 break;
727 
728         case UC_NULL:
729                 break;
730 
731         default:
732                 s = ucv_to_string(vm, fmt);
733 
734                 if (s) {
735                         ulog(priority, "%s", s);
736                         free(s);
737 
738                         return ucv_boolean_new(true);
739                 }
740 
741                 break;
742         }
743 
744         return ucv_boolean_new(false);
745 }
746 
747 /**
748  * Log a message via the ulog mechanism.
749  *
750  * The `ulog()` function outputs the given log message to all configured ulog
751  * channels unless the given priority level exceeds the globally configured ulog
752  * priority threshold. See {@link module:log#ulog_threshold|ulog_threshold()}
753  * for details.
754  *
755  * The `ulog()` function is OpenWrt specific and may not be present on other
756  * systems. Use `syslog()` instead for portability to non-OpenWrt environments.
757  *
758  * Like `syslog()`, the function behaves in a sprintf-like manner, allowing the
759  * use of format strings and associated arguments to construct log messages.
760  *
761  * If the `ulog_open()` function has not been called explicitly before, `ulog()`
762  * implicitly configures certain defaults, see
763  * {@link module:log#ulog_open|ulog_open()} for a detailed description.
764  *
765  * If the `format` argument is not a string and not `null`, it will be
766  * implicitly converted to a string and logged as-is, without further format
767  * string processing.
768  *
769  * Returns `true` if a message was passed to the underlying `ulog()` function.
770  *
771  * Returns `false` if an invalid priority value or an empty message was given.
772  *
773  * @function module:log#ulog
774  *
775  * @param {number|module:log.LogPriority} priority
776  * Log message priority. May be either a number value or a priority name string.
777  *
778  * See {@link module:log.LogPriority|LogPriority} for recognized priority names.
779  *
780  * @param {*} format
781  * The sprintf-like format string for the log message, or any other, non-null,
782  * non-string value type which will be implicitly stringified and logged as-is.
783  *
784  * @param {...*} [args]
785  * In case a format string value was provided in the previous argument, then
786  * all subsequent arguments are used to replace the placeholders in the format
787  * string.
788  *
789  * @returns {boolean}
790  *
791  * @example
792  * // Example usage of ulog function with format string and arguments
793  * const username = "user123";
794  * const errorCode = 404;
795  * ulog(LOG_ERR, "User %s encountered error: %d", username, errorCode);
796  *
797  * // Using priority names for logging
798  * ulog("err", "General error encountered");
799  *
800  * // Implicit stringification
801  * ulog("debug", { foo: 1, bar: true, baz: [1, 2, 3] });
802  *
803  * @see module:log#ulog_open
804  * @see module:log#ulog_threshold
805  * @see module:log#syslog
806  */
807 static uc_value_t *
808 uc_ulog_log(uc_vm_t *vm, size_t nargs)
809 {
810         int priority = parse_priority(uc_fn_arg(0));
811 
812         if (priority == -1 || nargs < 2)
813                 return ucv_boolean_new(false);
814 
815         return uc_ulog_log_common(vm, nargs - 1, priority);
816 }
817 
818 /**
819  * Close ulog logger.
820  *
821  * Resets the ulog channels, the default facility and the log ident value to
822  * defaults.
823  *
824  * In case the `"syslog"` channel has been configured, the underlying
825  * `closelog()` function will be invoked.
826  *
827  * The usage of this function is optional, and usually an explicit ulog teardown
828  * is not required.
829  *
830  * The `ulog_close()` function is OpenWrt specific and may not be present on
831  * other systems. Use `closelog()` in conjunction with `syslog()` instead for
832  * portability to non-OpenWrt environments.
833  *
834  * @function module:log#ulog_close
835  *
836  * @see module:log#closelog
837  */
838 static uc_value_t *
839 uc_ulog_close(uc_vm_t *vm, size_t nargs)
840 {
841         ulog_close();
842 
843         return NULL;
844 }
845 
846 /**
847  * Set ulog priority threshold.
848  *
849  * This function configures the application wide log message threshold for log
850  * messages emitted with `ulog()`. Any message with a priority higher (= less
851  * severe) than the threshold priority will be discarded. This is useful to
852  * implement application wide verbosity settings without having to wrap `ulog()`
853  * invocations into a helper function or guarding code.
854  *
855  * When no explicit threshold has been set, `LOG_DEBUG` is used by default,
856  * allowing log messages with all known priorities.
857  *
858  * The `ulog_threshold()` function is OpenWrt specific and may not be present on
859  * other systems. There is no syslog equivalent to this ulog specific threshold
860  * mechanism.
861  *
862  * The priority argument may be either a string value containing a priority name
863  * or one of the numeric `LOG_*` priority constants in the module namespace.
864  *
865  * Returns `true` if a threshold was set.
866  *
867  * Returns `false` if an invalid priority value was given.
868  *
869  * @function module:log#ulog_threshold
870  *
871  * @param {number|module:log.LogPriority} [priority]
872  * The priority threshold to configure.
873  *
874  * See {@link module:log.LogPriority|LogPriority} for recognized priority names.
875  *
876  * @returns {boolean}
877  *
878  * @example
879  * // Set threshold to "warning" or more severe
880  * ulog_threshold(LOG_WARNING);
881  *
882  * // This message will be suppressed
883  * ulog(LOG_DEBUG, "Testing thresholds");
884  *
885  * // Using priority name
886  * ulog_threshold("debug");
887  */
888 static uc_value_t *
889 uc_ulog_threshold(uc_vm_t *vm, size_t nargs)
890 {
891         int priority = parse_priority(uc_fn_arg(0));
892 
893         if (priority == -1)
894                 return ucv_boolean_new(false);
895 
896         ulog_threshold(priority);
897 
898         return ucv_boolean_new(true);
899 }
900 
901 /**
902  * Invoke ulog with LOG_INFO.
903  *
904  * This function is convenience wrapper for `ulog(LOG_INFO, ...)`.
905  *
906  * See {@link module:log#ulog|ulog()} for details.
907  *
908  * @function module:log#INFO
909  *
910  * @param {*} format
911  * The sprintf-like format string for the log message, or any other, non-null,
912  * non-string value type which will be implicitly stringified and logged as-is.
913  *
914  * @param {...*} [args]
915  * In case a format string value was provided in the previous argument, then
916  * all subsequent arguments are used to replace the placeholders in the format
917  * string.
918  *
919  * @returns {boolean}
920  *
921  * @example
922  * INFO("This is an info log message");
923  */
924 static uc_value_t *
925 uc_ulog_INFO(uc_vm_t *vm, size_t nargs)
926 {
927         return uc_ulog_log_common(vm, nargs, LOG_INFO);
928 }
929 
930 /**
931  * Invoke ulog with LOG_NOTICE.
932  *
933  * This function is convenience wrapper for `ulog(LOG_NOTICE, ...)`.
934  *
935  * See {@link module:log#ulog|ulog()} for details.
936  *
937  * @function module:log#NOTE
938  *
939  * @param {*} format
940  * The sprintf-like format string for the log message, or any other, non-null,
941  * non-string value type which will be implicitly stringified and logged as-is.
942  *
943  * @param {...*} [args]
944  * In case a format string value was provided in the previous argument, then
945  * all subsequent arguments are used to replace the placeholders in the format
946  * string.
947  *
948  * @returns {boolean}
949  *
950  * @example
951  * NOTE("This is a notification log message");
952  */
953 static uc_value_t *
954 uc_ulog_NOTE(uc_vm_t *vm, size_t nargs)
955 {
956         return uc_ulog_log_common(vm, nargs, LOG_NOTICE);
957 }
958 
959 /**
960  * Invoke ulog with LOG_WARNING.
961  *
962  * This function is convenience wrapper for `ulog(LOG_WARNING, ...)`.
963  *
964  * See {@link module:log#ulog|ulog()} for details.
965  *
966  * @function module:log#WARN
967  *
968  * @param {*} format
969  * The sprintf-like format string for the log message, or any other, non-null,
970  * non-string value type which will be implicitly stringified and logged as-is.
971  *
972  * @param {...*} [args]
973  * In case a format string value was provided in the previous argument, then
974  * all subsequent arguments are used to replace the placeholders in the format
975  * string.
976  *
977  * @returns {boolean}
978  *
979  * @example
980  * WARN("This is a warning");
981  */
982 static uc_value_t *
983 uc_ulog_WARN(uc_vm_t *vm, size_t nargs)
984 {
985         return uc_ulog_log_common(vm, nargs, LOG_WARNING);
986 }
987 
988 /**
989  * Invoke ulog with LOG_ERR.
990  *
991  * This function is convenience wrapper for `ulog(LOG_ERR, ...)`.
992  *
993  * See {@link module:log#ulog|ulog()} for details.
994  *
995  * @function module:log#ERR
996  *
997  * @param {*} format
998  * The sprintf-like format string for the log message, or any other, non-null,
999  * non-string value type which will be implicitly stringified and logged as-is.
1000  *
1001  * @param {...*} [args]
1002  * In case a format string value was provided in the previous argument, then
1003  * all subsequent arguments are used to replace the placeholders in the format
1004  * string.
1005  *
1006  * @returns {boolean}
1007  *
1008  * @example
1009  * ERR("This is an error!");
1010  */
1011 static uc_value_t *
1012 uc_ulog_ERR(uc_vm_t *vm, size_t nargs)
1013 {
1014         return uc_ulog_log_common(vm, nargs, LOG_ERR);
1015 }
1016 #endif
1017 
1018 
1019 static const uc_function_list_t global_fns[] = {
1020         { "openlog",            uc_openlog },
1021         { "syslog",                     uc_syslog },
1022         { "closelog",           uc_closelog },
1023 
1024 #ifdef HAVE_ULOG
1025         { "ulog_open",          uc_ulog_open },
1026         { "ulog",                       uc_ulog_log },
1027         { "ulog_close",         uc_ulog_close },
1028         { "ulog_threshold",     uc_ulog_threshold },
1029         { "INFO",                       uc_ulog_INFO },
1030         { "NOTE",                       uc_ulog_NOTE },
1031         { "WARN",                       uc_ulog_WARN },
1032         { "ERR",                        uc_ulog_ERR },
1033 #endif
1034 };
1035 
1036 
1037 void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
1038 {
1039         uc_function_list_register(scope, global_fns);
1040 
1041 #define ADD_CONST(x) ucv_object_add(scope, #x, ucv_int64_new(x))
1042 
1043         ADD_CONST(LOG_PID);
1044         ADD_CONST(LOG_CONS);
1045         ADD_CONST(LOG_NDELAY);
1046         ADD_CONST(LOG_ODELAY);
1047         ADD_CONST(LOG_NOWAIT);
1048 
1049         ADD_CONST(LOG_AUTH);
1050 #ifdef LOG_AUTHPRIV
1051         ADD_CONST(LOG_AUTHPRIV);
1052 #endif
1053         ADD_CONST(LOG_CRON);
1054         ADD_CONST(LOG_DAEMON);
1055 #ifdef LOG_FTP
1056         ADD_CONST(LOG_FTP);
1057 #endif
1058         ADD_CONST(LOG_KERN);
1059         ADD_CONST(LOG_LPR);
1060         ADD_CONST(LOG_MAIL);
1061         ADD_CONST(LOG_NEWS);
1062         ADD_CONST(LOG_SYSLOG);
1063         ADD_CONST(LOG_USER);
1064         ADD_CONST(LOG_UUCP);
1065         ADD_CONST(LOG_LOCAL0);
1066         ADD_CONST(LOG_LOCAL1);
1067         ADD_CONST(LOG_LOCAL2);
1068         ADD_CONST(LOG_LOCAL3);
1069         ADD_CONST(LOG_LOCAL4);
1070         ADD_CONST(LOG_LOCAL5);
1071         ADD_CONST(LOG_LOCAL6);
1072         ADD_CONST(LOG_LOCAL7);
1073 
1074         ADD_CONST(LOG_EMERG);
1075         ADD_CONST(LOG_ALERT);
1076         ADD_CONST(LOG_CRIT);
1077         ADD_CONST(LOG_ERR);
1078         ADD_CONST(LOG_WARNING);
1079         ADD_CONST(LOG_NOTICE);
1080         ADD_CONST(LOG_INFO);
1081         ADD_CONST(LOG_DEBUG);
1082 
1083 #ifdef HAVE_ULOG
1084         ADD_CONST(ULOG_KMSG);
1085         ADD_CONST(ULOG_SYSLOG);
1086         ADD_CONST(ULOG_STDIO);
1087 #endif
1088 }
1089 

This page was automatically generated by LXR 0.3.1.  •  OpenWrt