| 1 |
/**\file srUtils.c |
| 2 |
* \brief General utilties that fit nowhere else. |
| 3 |
* |
| 4 |
* The namespace for this file is "srUtil". |
| 5 |
* |
| 6 |
* \author Rainer Gerhards <[email protected]> |
| 7 |
* \date 2003-09-09 |
| 8 |
* Coding begun. |
| 9 |
* |
| 10 |
* Copyright 2003-2026 Rainer Gerhards and Adiscon GmbH. |
| 11 |
* |
| 12 |
* This file is part of the rsyslog runtime library. |
| 13 |
* |
| 14 |
* The rsyslog runtime library is free software: you can redistribute it and/or modify |
| 15 |
* it under the terms of the GNU Lesser General Public License as published by |
| 16 |
* the Free Software Foundation, either version 3 of the License, or |
| 17 |
* (at your option) any later version. |
| 18 |
* |
| 19 |
* The rsyslog runtime library is distributed in the hope that it will be useful, |
| 20 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 |
* GNU Lesser General Public License for more details. |
| 23 |
* |
| 24 |
* You should have received a copy of the GNU Lesser General Public License |
| 25 |
* along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>. |
| 26 |
* |
| 27 |
* A copy of the GPL can be found in the file "COPYING" in this distribution. |
| 28 |
* A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution. |
| 29 |
*/ |
| 30 |
#include "config.h" |
| 31 |
|
| 32 |
#include <stdio.h> |
| 33 |
#include <stdlib.h> |
| 34 |
#include <string.h> |
| 35 |
#include <unistd.h> |
| 36 |
#include <errno.h> |
| 37 |
#include <sys/stat.h> |
| 38 |
#include <sys/types.h> |
| 39 |
#include <signal.h> |
| 40 |
#include <assert.h> |
| 41 |
#include <limits.h> |
| 42 |
#include <sys/wait.h> |
| 43 |
#include <ctype.h> |
| 44 |
#include <inttypes.h> |
| 45 |
#include <fcntl.h> |
| 46 |
|
| 47 |
#include "rsyslog.h" |
| 48 |
#include "srUtils.h" |
| 49 |
#include "obj.h" |
| 50 |
#include "errmsg.h" |
| 51 |
#include "glbl.h" |
| 52 |
#include "rsconf.h" |
| 53 |
|
| 54 |
#if _POSIX_TIMERS <= 0 |
| 55 |
#include <sys/time.h> |
| 56 |
#endif |
| 57 |
|
| 58 |
/* here we host some syslog specific names. There currently is no better place |
| 59 |
* to do it, but over here is also not ideal... -- rgerhards, 2008-02-14 |
| 60 |
* rgerhards, 2008-04-16: note in LGPL move: the code tables below exist in |
| 61 |
* the same way in BSD, so it is not a problem to move them from GPLv3 to LGPL. |
| 62 |
* And nobody modified them since it was under LGPL, so we can also move it |
| 63 |
* to ASL 2.0. |
| 64 |
*/ |
| 65 |
syslogName_t syslogPriNames[] = { |
| 66 |
{"alert", LOG_ALERT}, {"crit", LOG_CRIT}, {"debug", LOG_DEBUG}, |
| 67 |
{"emerg", LOG_EMERG}, {"err", LOG_ERR}, {"error", LOG_ERR}, /* DEPRECATED */ |
| 68 |
{"info", LOG_INFO}, {"none", INTERNAL_NOPRI}, /* INTERNAL */ |
| 69 |
{"notice", LOG_NOTICE}, {"panic", LOG_EMERG}, /* DEPRECATED */ |
| 70 |
{"warn", LOG_WARNING}, /* DEPRECATED */ |
| 71 |
{"warning", LOG_WARNING}, {"*", TABLE_ALLPRI}, {NULL, -1}}; |
| 72 |
|
| 73 |
#ifndef LOG_AUTHPRIV |
| 74 |
#define LOG_AUTHPRIV LOG_AUTH |
| 75 |
#endif |
| 76 |
syslogName_t syslogFacNames[] = { |
| 77 |
{"auth", LOG_AUTH}, |
| 78 |
{"authpriv", LOG_AUTHPRIV}, |
| 79 |
{"cron", LOG_CRON}, |
| 80 |
{"daemon", LOG_DAEMON}, |
| 81 |
{"kern", LOG_KERN}, |
| 82 |
{"lpr", LOG_LPR}, |
| 83 |
{"mail", LOG_MAIL}, |
| 84 |
{"mark", LOG_MARK}, /* INTERNAL */ |
| 85 |
{"news", LOG_NEWS}, |
| 86 |
{"ntp", (12 << 3)}, /* NTP, perhaps BSD-specific? */ |
| 87 |
{"security", LOG_AUTH}, /* DEPRECATED */ |
| 88 |
{"bsd_security", (13 << 3)}, /* BSD-specific, unfortunatly with duplicate name... */ |
| 89 |
{"syslog", LOG_SYSLOG}, |
| 90 |
{"user", LOG_USER}, |
| 91 |
{"uucp", LOG_UUCP}, |
| 92 |
#if defined(_AIX) /* AIXPORT : These are necessary for AIX */ |
| 93 |
{"caa", LOG_CAA}, |
| 94 |
{"aso", LOG_ASO}, |
| 95 |
#endif |
| 96 |
#if defined(LOG_FTP) |
| 97 |
{"ftp", LOG_FTP}, |
| 98 |
#endif |
| 99 |
#if defined(LOG_AUDIT) |
| 100 |
{"audit", LOG_AUDIT}, |
| 101 |
#endif |
| 102 |
{"console", (14 << 3)}, /* BSD-specific priority */ |
| 103 |
{"local0", LOG_LOCAL0}, |
| 104 |
{"local1", LOG_LOCAL1}, |
| 105 |
{"local2", LOG_LOCAL2}, |
| 106 |
{"local3", LOG_LOCAL3}, |
| 107 |
{"local4", LOG_LOCAL4}, |
| 108 |
{"local5", LOG_LOCAL5}, |
| 109 |
{"local6", LOG_LOCAL6}, |
| 110 |
{"local7", LOG_LOCAL7}, |
| 111 |
{"invld", LOG_INVLD}, |
| 112 |
{NULL, -1}, |
| 113 |
}; |
| 114 |
|
| 115 |
/* ################################################################# * |
| 116 |
* private members * |
| 117 |
* ################################################################# */ |
| 118 |
|
| 119 |
/* As this is not a "real" object, there won't be any private |
| 120 |
* members in this file. |
| 121 |
*/ |
| 122 |
|
| 123 |
/* ################################################################# * |
| 124 |
* public members * |
| 125 |
* ################################################################# */ |
| 126 |
|
| 127 |
rsRetVal srUtilItoA(char *pBuf, int iLenBuf, number_t iToConv) { |
| 128 |
int i; |
| 129 |
int bIsNegative; |
| 130 |
char szBuf[64]; /* sufficiently large for my lifespan and those of my children... ;) */ |
| 131 |
|
| 132 |
assert(pBuf != NULL); |
| 133 |
assert(iLenBuf > 1); /* This is actually an app error and as thus checked for... */ |
| 134 |
|
| 135 |
if (iToConv < 0) { |
| 136 |
bIsNegative = RSTRUE; |
| 137 |
iToConv *= -1; |
| 138 |
} else |
| 139 |
bIsNegative = RSFALSE; |
| 140 |
|
| 141 |
/* first generate a string with the digits in the reverse direction */ |
| 142 |
i = 0; |
| 143 |
do { |
| 144 |
szBuf[i++] = iToConv % 10 + '0'; |
| 145 |
iToConv /= 10; |
| 146 |
} while (iToConv > 0); /* warning: do...while()! */ |
| 147 |
--i; /* undo last increment - we were pointing at NEXT location */ |
| 148 |
|
| 149 |
/* make sure we are within bounds... */ |
| 150 |
if (i + 2 > iLenBuf) /* +2 because: a) i starts at zero! b) the \0 byte */ |
| 151 |
return RS_RET_PROVIDED_BUFFER_TOO_SMALL; |
| 152 |
|
| 153 |
/* then move it to the right direction... */ |
| 154 |
if (bIsNegative == RSTRUE) *pBuf++ = '-'; |
| 155 |
while (i >= 0) *pBuf++ = szBuf[i--]; |
| 156 |
*pBuf = '\0'; /* terminate it!!! */ |
| 157 |
|
| 158 |
return RS_RET_OK; |
| 159 |
} |
| 160 |
|
| 161 |
uchar *srUtilStrDup(uchar *pOld, size_t len) { |
| 162 |
uchar *pNew; |
| 163 |
|
| 164 |
assert(pOld != NULL); |
| 165 |
|
| 166 |
if ((pNew = malloc(len + 1)) != NULL) memcpy(pNew, pOld, len + 1); |
| 167 |
|
| 168 |
return pNew; |
| 169 |
} |
| 170 |
|
| 171 |
|
| 172 |
/* creates a path recursively |
| 173 |
* Return 0 on success, -1 otherwise. On failure, errno * hold the last OS error. |
| 174 |
* Param "mode" holds the mode that all non-existing directories are to be |
| 175 |
* created with. |
| 176 |
* Note that we have a potential race inside that code, a race that even exists |
| 177 |
* outside of the rsyslog process (if multiple instances run, or other programs |
| 178 |
* generate directories): If the directory does not exist, a context switch happens, |
| 179 |
* at that moment another process creates it, then our creation on the context |
| 180 |
* switch back fails. This actually happened in practice, and depending on the |
| 181 |
* configuration it is even likely to happen. We can not solve this situation |
| 182 |
* with a mutex, as that works only within out process space. So the solution |
| 183 |
* is that we take the optimistic approach, try the creation, and if it fails |
| 184 |
* with "already exists" we go back and do one retry of the check/create |
| 185 |
* sequence. That should then succeed. If the directory is still not found but |
| 186 |
* the creation fails in the similar way, we return an error on that second |
| 187 |
* try because otherwise we would potentially run into an endless loop. |
| 188 |
* loop. -- rgerhards, 2010-03-25 |
| 189 |
* The likeliest scenario for a prolonged contest of creating the parent directiories |
| 190 |
* is within our process space. This can happen with a high probability when two |
| 191 |
* threads, that want to start logging to files within same directory tree, are |
| 192 |
* started close to each other. We should fix what we can. -- nipakoo, 2017-11-25 |
| 193 |
*/ |
| 194 |
static int real_makeFileParentDirs(const uchar *const szFile, |
| 195 |
const size_t lenFile, |
| 196 |
const mode_t mode, |
| 197 |
const uid_t uid, |
| 198 |
const gid_t gid, |
| 199 |
const int bFailOnChownFail) { |
| 200 |
uchar *p; |
| 201 |
uchar *pszWork; |
| 202 |
size_t len; |
| 203 |
|
| 204 |
assert(szFile != NULL); |
| 205 |
assert(lenFile > 0); |
| 206 |
|
| 207 |
len = lenFile + 1; /* add one for '\0'-byte */ |
| 208 |
if ((pszWork = malloc(len)) == NULL) return -1; |
| 209 |
memcpy(pszWork, szFile, len); |
| 210 |
for (p = pszWork + 1; *p; p++) |
| 211 |
if (*p == '/') { |
| 212 |
/* temporarily terminate string, create dir and go on */ |
| 213 |
*p = '\0'; |
| 214 |
int bErr = 0; |
| 215 |
if (mkdir((char *)pszWork, mode) == 0) { |
| 216 |
if (uid != (uid_t)-1 || gid != (gid_t)-1) { |
| 217 |
/* we need to set owner/group */ |
| 218 |
if (chown((char *)pszWork, uid, gid) != 0) { |
| 219 |
LogError(errno, RS_RET_DIR_CHOWN_ERROR, "chown for directory '%s' failed", pszWork); |
| 220 |
if (bFailOnChownFail) { |
| 221 |
/* ignore if configured to do so */ |
| 222 |
bErr = 1; |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
} else if (errno != EEXIST) { |
| 227 |
/* EEXIST is ok, means this component exists */ |
| 228 |
bErr = 1; |
| 229 |
} |
| 230 |
|
| 231 |
if (bErr) { |
| 232 |
int eSave = errno; |
| 233 |
free(pszWork); |
| 234 |
errno = eSave; |
| 235 |
return -1; |
| 236 |
} |
| 237 |
*p = '/'; |
| 238 |
} |
| 239 |
free(pszWork); |
| 240 |
return 0; |
| 241 |
} |
| 242 |
/* note: this small function is the stub for the brain-dead POSIX cancel handling */ |
| 243 |
int makeFileParentDirs(const uchar *const szFile, |
| 244 |
const size_t lenFile, |
| 245 |
const mode_t mode, |
| 246 |
const uid_t uid, |
| 247 |
const gid_t gid, |
| 248 |
const int bFailOnChownFail) { |
| 249 |
static pthread_mutex_t mutParentDir = PTHREAD_MUTEX_INITIALIZER; |
| 250 |
int r; /* needs to be declared OUTSIDE of pthread_cleanup... macros! */ |
| 251 |
pthread_mutex_lock(&mutParentDir); |
| 252 |
pthread_cleanup_push(mutexCancelCleanup, &mutParentDir); |
| 253 |
|
| 254 |
r = real_makeFileParentDirs(szFile, lenFile, mode, uid, gid, bFailOnChownFail); |
| 255 |
|
| 256 |
pthread_mutex_unlock(&mutParentDir); |
| 257 |
pthread_cleanup_pop(0); |
| 258 |
return r; |
| 259 |
} |
| 260 |
|
| 261 |
|
| 262 |
/** |
| 263 |
* @brief Execute a program with up to two optional arguments. |
| 264 |
* |
| 265 |
* This helper forks and then execs `program`. In the child process it resets |
| 266 |
* all signal handlers to defaults and clears any pending alarm before exec. |
| 267 |
* That behavior is intentional to avoid inheriting rsyslogd signal handling |
| 268 |
* into the external command. |
| 269 |
* |
| 270 |
* Arguments are optional and passed as-is (no shell parsing). If @p arg1 is |
| 271 |
* NULL and @p arg2 is non-NULL, @p arg2 is shifted into the first argument |
| 272 |
* position so callers can pass either only arg2 or both without extra logic. |
| 273 |
* |
| 274 |
* If bWait is set, the parent will wait for the child to exit and record |
| 275 |
* its status via glblReportChildProcessExit(). If not set, the child is |
| 276 |
* allowed to continue independently. |
| 277 |
* |
| 278 |
* @param program Executable name/path to run. |
| 279 |
* @param bWait If non-zero, wait for the child to exit before returning. |
| 280 |
* @param arg1 Optional first argument (may be NULL). |
| 281 |
* @param arg2 Optional second argument (may be NULL). |
| 282 |
* @return Child PID on success, 0 on fork failure (errno set). |
| 283 |
*/ |
| 284 |
int execProg(uchar *program, int bWait, uchar *arg1, uchar *arg2) { |
| 285 |
int pid; |
| 286 |
int sig; |
| 287 |
struct sigaction sigAct; |
| 288 |
int i; |
| 289 |
char **exec_argv; |
| 290 |
uchar *args[2]; |
| 291 |
int argc = 0; |
| 292 |
|
| 293 |
if (arg1 == NULL && arg2 != NULL) { |
| 294 |
arg1 = arg2; |
| 295 |
arg2 = NULL; |
| 296 |
} |
| 297 |
if (arg1 != NULL) args[argc++] = arg1; |
| 298 |
if (arg2 != NULL) args[argc++] = arg2; |
| 299 |
|
| 300 |
dbgprintf("exec program '%s' with %d args\n", program, argc); |
| 301 |
pid = fork(); |
| 302 |
if (pid < 0) { |
| 303 |
return 0; |
| 304 |
} |
| 305 |
|
| 306 |
if (pid) { /* Parent */ |
| 307 |
if (bWait) { |
| 308 |
/* waitpid will fail with errno == ECHILD if the child process has already |
| 309 |
been reaped by the rsyslogd main loop (see rsyslogd.c) */ |
| 310 |
int status; |
| 311 |
if (waitpid(pid, &status, 0) == pid) { |
| 312 |
glblReportChildProcessExit(runConf, program, pid, status); |
| 313 |
} else if (errno != ECHILD) { |
| 314 |
/* we do not use logerror(), because |
| 315 |
* that might bring us into an endless |
| 316 |
* loop. At some time, we may |
| 317 |
* reconsider this behaviour. |
| 318 |
*/ |
| 319 |
dbgprintf("could not wait on child after executing '%s'", (char *)program); |
| 320 |
} |
| 321 |
} |
| 322 |
return pid; |
| 323 |
} |
| 324 |
/* Child */ |
| 325 |
alarm(0); /* create a clean environment before we exec the real child */ |
| 326 |
|
| 327 |
memset(&sigAct, 0, sizeof(sigAct)); |
| 328 |
sigemptyset(&sigAct.sa_mask); |
| 329 |
sigAct.sa_handler = SIG_DFL; |
| 330 |
|
| 331 |
for (sig = 1; sig < NSIG; ++sig) sigaction(sig, &sigAct, NULL); |
| 332 |
|
| 333 |
exec_argv = (char **)malloc(sizeof(char *) * (argc + 2)); |
| 334 |
if (exec_argv == NULL) { |
| 335 |
perror("exec"); |
| 336 |
fprintf(stderr, "malloc failed for exec argv\n"); |
| 337 |
exit(1); |
| 338 |
} |
| 339 |
exec_argv[0] = (char *)program; |
| 340 |
for (i = 0; i < argc; ++i) { |
| 341 |
exec_argv[i + 1] = (char *)args[i]; |
| 342 |
} |
| 343 |
exec_argv[argc + 1] = NULL; |
| 344 |
|
| 345 |
execvp((char *)program, exec_argv); |
| 346 |
/* In the long term, it's a good idea to implement some enhanced error |
| 347 |
* checking here. However, it can not easily be done. For starters, we |
| 348 |
* may run into endless loops if we log to syslog. The next problem is |
| 349 |
* that output is typically not seen by the user. For the time being, |
| 350 |
* we use no error reporting, which is quite consitent with the old |
| 351 |
* system() way of doing things. rgerhards, 2007-07-20 |
| 352 |
*/ |
| 353 |
perror("exec"); |
| 354 |
fprintf(stderr, "exec program was '%s'\n", program); |
| 355 |
exit(1); /* not much we can do in this case */ |
| 356 |
} |
| 357 |
|
| 358 |
|
| 359 |
/* skip over whitespace in a standard C string. The |
| 360 |
* provided pointer is advanced to the first non-whitespace |
| 361 |
* charater or the \0 byte, if there is none. It is never |
| 362 |
* moved past the \0. |
| 363 |
*/ |
| 364 |
void skipWhiteSpace(uchar **pp) { |
| 365 |
register uchar *p; |
| 366 |
|
| 367 |
assert(pp != NULL); |
| 368 |
assert(*pp != NULL); |
| 369 |
|
| 370 |
p = *pp; |
| 371 |
while (*p && isspace((int)*p)) ++p; |
| 372 |
*pp = p; |
| 373 |
} |
| 374 |
|
| 375 |
|
| 376 |
/* generate a file name from four parts: |
| 377 |
* <directory name>/<name>.<number> |
| 378 |
* If number is negative, it is not used. If any of the strings is |
| 379 |
* NULL, an empty string is used instead. Length must be provided. |
| 380 |
* lNumDigits is the minimum number of digits that lNum should have. This |
| 381 |
* is to pretty-print the file name, e.g. lNum = 3, lNumDigits= 4 will |
| 382 |
* result in "0003" being used inside the file name. Set lNumDigits to 0 |
| 383 |
* to use as few space as possible. |
| 384 |
* rgerhards, 2008-01-03 |
| 385 |
*/ |
| 386 |
PRAGMA_DIAGNOSTIC_PUSH |
| 387 |
PRAGMA_IGNORE_Wformat_nonliteral rsRetVal genFileName( |
| 388 |
uchar **ppName, uchar *pDirName, size_t lenDirName, uchar *pFName, size_t lenFName, int64_t lNum, int lNumDigits) { |
| 389 |
DEFiRet; |
| 390 |
uchar *pName; |
| 391 |
uchar *pNameWork; |
| 392 |
size_t lenName; |
| 393 |
uchar szBuf[128]; /* buffer for number */ |
| 394 |
char szFmtBuf[32]; /* buffer for snprintf format */ |
| 395 |
size_t lenBuf; |
| 396 |
|
| 397 |
if (lNum < 0) { |
| 398 |
szBuf[0] = '\0'; |
| 399 |
lenBuf = 0; |
| 400 |
} else { |
| 401 |
if (lNumDigits > 0) { |
| 402 |
snprintf(szFmtBuf, sizeof(szFmtBuf), ".%%0%d" PRId64, lNumDigits); |
| 403 |
lenBuf = snprintf((char *)szBuf, sizeof(szBuf), szFmtBuf, lNum); |
| 404 |
} else |
| 405 |
lenBuf = snprintf((char *)szBuf, sizeof(szBuf), ".%" PRId64, lNum); |
| 406 |
} |
| 407 |
|
| 408 |
lenName = lenDirName + 1 + lenFName + lenBuf + 1; /* last +1 for \0 char! */ |
| 409 |
if ((pName = malloc(lenName)) == NULL) ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY); |
| 410 |
|
| 411 |
/* got memory, now construct string */ |
| 412 |
memcpy(pName, pDirName, lenDirName); |
| 413 |
pNameWork = pName + lenDirName; |
| 414 |
*pNameWork++ = '/'; |
| 415 |
memcpy(pNameWork, pFName, lenFName); |
| 416 |
pNameWork += lenFName; |
| 417 |
if (lenBuf > 0) { |
| 418 |
memcpy(pNameWork, szBuf, lenBuf); |
| 419 |
pNameWork += lenBuf; |
| 420 |
} |
| 421 |
*pNameWork = '\0'; |
| 422 |
|
| 423 |
*ppName = pName; |
| 424 |
|
| 425 |
finalize_it: |
| 426 |
RETiRet; |
| 427 |
} |
| 428 |
PRAGMA_DIAGNOSTIC_POP |
| 429 |
|
| 430 |
/* get the number of digits required to represent a given number. We use an |
| 431 |
* iterative approach as we do not like to draw in the floating point |
| 432 |
* library just for log(). -- rgerhards, 2008-01-10 |
| 433 |
*/ |
| 434 |
int getNumberDigits(long lNum) { |
| 435 |
int iDig; |
| 436 |
|
| 437 |
if (lNum == 0) |
| 438 |
iDig = 1; |
| 439 |
else |
| 440 |
for (iDig = 0; lNum != 0; ++iDig) lNum /= 10; |
| 441 |
|
| 442 |
return iDig; |
| 443 |
} |
| 444 |
|
| 445 |
|
| 446 |
/* compute an absolute time timeout suitable for calls to pthread_cond_timedwait() |
| 447 |
* iTimeout is in milliseconds |
| 448 |
* rgerhards, 2008-01-14 |
| 449 |
*/ |
| 450 |
rsRetVal timeoutComp(struct timespec *pt, long iTimeout) { |
| 451 |
#if _POSIX_TIMERS <= 0 |
| 452 |
struct timeval tv; |
| 453 |
#endif |
| 454 |
|
| 455 |
assert(pt != NULL); |
| 456 |
/* compute timeout */ |
| 457 |
|
| 458 |
#if _POSIX_TIMERS > 0 |
| 459 |
/* this is the "regular" code */ |
| 460 |
clock_gettime(CLOCK_REALTIME, pt); |
| 461 |
#else |
| 462 |
gettimeofday(&tv, NULL); |
| 463 |
pt->tv_sec = tv.tv_sec; |
| 464 |
pt->tv_nsec = tv.tv_usec * 1000; |
| 465 |
#endif |
| 466 |
pt->tv_sec += iTimeout / 1000; |
| 467 |
pt->tv_nsec += (iTimeout % 1000) * 1000000; /* think INTEGER arithmetic! */ |
| 468 |
if (pt->tv_nsec > 999999999) { /* overrun? */ |
| 469 |
pt->tv_nsec -= 1000000000; |
| 470 |
++pt->tv_sec; |
| 471 |
} |
| 472 |
return RS_RET_OK; /* so far, this is static... */ |
| 473 |
} |
| 474 |
|
| 475 |
long long currentTimeMills(void) { |
| 476 |
struct timespec tm; |
| 477 |
#if _POSIX_TIMERS <= 0 |
| 478 |
struct timeval tv; |
| 479 |
#endif |
| 480 |
|
| 481 |
#if _POSIX_TIMERS > 0 |
| 482 |
clock_gettime(CLOCK_REALTIME, &tm); |
| 483 |
#else |
| 484 |
gettimeofday(&tv, NULL); |
| 485 |
tm.tv_sec = tv.tv_sec; |
| 486 |
tm.tv_nsec = tv.tv_usec * 1000; |
| 487 |
#endif |
| 488 |
|
| 489 |
return ((long long)tm.tv_sec) * 1000 + (tm.tv_nsec / 1000000); |
| 490 |
} |
| 491 |
|
| 492 |
|
| 493 |
/* This function is kind of the reverse of timeoutComp() - it takes an absolute |
| 494 |
* timeout value and computes how far this is in the future. If the value is already |
| 495 |
* in the past, 0 is returned. The return value is in ms. |
| 496 |
* rgerhards, 2008-01-25 |
| 497 |
*/ |
| 498 |
long timeoutVal(struct timespec *pt) { |
| 499 |
struct timespec t; |
| 500 |
long iTimeout; |
| 501 |
#if _POSIX_TIMERS <= 0 |
| 502 |
struct timeval tv; |
| 503 |
#endif |
| 504 |
|
| 505 |
assert(pt != NULL); |
| 506 |
/* compute timeout */ |
| 507 |
#if _POSIX_TIMERS > 0 |
| 508 |
/* this is the "regular" code */ |
| 509 |
clock_gettime(CLOCK_REALTIME, &t); |
| 510 |
#else |
| 511 |
gettimeofday(&tv, NULL); |
| 512 |
t.tv_sec = tv.tv_sec; |
| 513 |
t.tv_nsec = tv.tv_usec * 1000; |
| 514 |
#endif |
| 515 |
iTimeout = (pt->tv_nsec - t.tv_nsec) / 1000000; |
| 516 |
iTimeout += (pt->tv_sec - t.tv_sec) * 1000; |
| 517 |
|
| 518 |
if (iTimeout < 0) iTimeout = 0; |
| 519 |
|
| 520 |
return iTimeout; |
| 521 |
} |
| 522 |
|
| 523 |
|
| 524 |
/* cancellation cleanup handler - frees provided mutex |
| 525 |
* rgerhards, 2008-01-14 |
| 526 |
*/ |
| 527 |
void mutexCancelCleanup(void *arg) { |
| 528 |
assert(arg != NULL); |
| 529 |
d_pthread_mutex_unlock((pthread_mutex_t *)arg); |
| 530 |
} |
| 531 |
|
| 532 |
|
| 533 |
/* rsSleep() - a fairly portable way to to sleep. It |
| 534 |
* will wake up when |
| 535 |
* a) the wake-time is over |
| 536 |
* rgerhards, 2008-01-28 |
| 537 |
*/ |
| 538 |
void srSleep(int iSeconds, int iuSeconds) { |
| 539 |
struct timeval tvSelectTimeout; |
| 540 |
|
| 541 |
tvSelectTimeout.tv_sec = iSeconds; |
| 542 |
tvSelectTimeout.tv_usec = iuSeconds; /* micro seconds */ |
| 543 |
select(0, NULL, NULL, NULL, &tvSelectTimeout); |
| 544 |
} |
| 545 |
|
| 546 |
|
| 547 |
/* From varmojfekoj's mail on why he provided rs_strerror_r(): |
| 548 |
* There are two problems with strerror_r(): |
| 549 |
* I see you've rewritten some of the code which calls it to use only |
| 550 |
* the supplied buffer; unfortunately the GNU implementation sometimes |
| 551 |
* doesn't use the buffer at all and returns a pointer to some |
| 552 |
* immutable string instead, as noted in the man page. |
| 553 |
* |
| 554 |
* The other problem is that on some systems strerror_r() has a return |
| 555 |
* type of int. |
| 556 |
* |
| 557 |
* So I've written a wrapper function rs_strerror_r(), which should |
| 558 |
* take care of all this and be used instead. |
| 559 |
* |
| 560 |
* Added 2008-01-30 |
| 561 |
*/ |
| 562 |
char *rs_strerror_r(int errnum, char *buf, size_t buflen) { |
| 563 |
#ifndef HAVE_STRERROR_R |
| 564 |
char *pszErr; |
| 565 |
pszErr = strerror(errnum); |
| 566 |
snprintf(buf, buflen, "%s", pszErr); |
| 567 |
#else |
| 568 |
#ifdef STRERROR_R_CHAR_P |
| 569 |
char *p = strerror_r(errnum, buf, buflen); |
| 570 |
if (p != buf) { |
| 571 |
strncpy(buf, p, buflen); |
| 572 |
buf[buflen - 1] = '\0'; |
| 573 |
} |
| 574 |
#else |
| 575 |
strerror_r(errnum, buf, buflen); |
| 576 |
#endif |
| 577 |
#endif /* #ifdef __hpux */ |
| 578 |
return buf; |
| 579 |
} |
| 580 |
|
| 581 |
|
| 582 |
/* Decode a symbolic name to a numeric value */ |
| 583 |
int decodeSyslogName(uchar *name, syslogName_t *codetab) { |
| 584 |
register syslogName_t *c; |
| 585 |
register uchar *p; |
| 586 |
char *end = NULL; |
| 587 |
long val; |
| 588 |
uchar buf[80]; |
| 589 |
|
| 590 |
assert(name != NULL); |
| 591 |
assert(codetab != NULL); |
| 592 |
|
| 593 |
DBGPRINTF("symbolic name: %s", name); |
| 594 |
if (isdigit((int)*name)) { |
| 595 |
DBGPRINTF("\n"); |
| 596 |
errno = 0; |
| 597 |
val = strtol((char *)name, &end, 10); |
| 598 |
if (errno != 0 || end == (char *)name || *end != '\0' || val < INT_MIN || val > INT_MAX) { |
| 599 |
return -1; |
| 600 |
} |
| 601 |
return (int)val; |
| 602 |
} |
| 603 |
strncpy((char *)buf, (char *)name, 79); |
| 604 |
buf[sizeof(buf) - 1] = '\0'; |
| 605 |
for (p = buf; *p; p++) { |
| 606 |
if (isupper((int)*p)) *p = tolower((int)*p); |
| 607 |
} |
| 608 |
for (c = codetab; c->c_name; c++) { |
| 609 |
if (!strcmp((char *)buf, (char *)c->c_name)) { |
| 610 |
DBGPRINTF(" ==> %d\n", c->c_val); |
| 611 |
return (c->c_val); |
| 612 |
} |
| 613 |
} |
| 614 |
DBGPRINTF("\n"); |
| 615 |
return (-1); |
| 616 |
} |
| 617 |
|
| 618 |
|
| 619 |
/** |
| 620 |
* getSubString |
| 621 |
* |
| 622 |
* Copy a string byte by byte until the occurrence |
| 623 |
* of a given separator. |
| 624 |
* |
| 625 |
* \param ppSrc Pointer to a pointer of the source array of characters. If a |
| 626 |
separator detected the Pointer points to the next char after the |
| 627 |
separator. Except if the end of the string is dedected ('\n'). |
| 628 |
Then it points to the terminator char. |
| 629 |
* \param pDst Pointer to the destination array of characters. Here the substing |
| 630 |
will be stored. |
| 631 |
* \param DstSize Maximum numbers of characters to store. |
| 632 |
* \param cSep Separator char. |
| 633 |
* \ret int Returns 0 if no error occurred. |
| 634 |
* |
| 635 |
* rgerhards, 2008-02-12: some notes are due... I will once again fix this function, this time |
| 636 |
* so that it treats ' ' as a request for whitespace. But in general, the function and its callers |
| 637 |
* should be changed over time, this is not really very good code... |
| 638 |
*/ |
| 639 |
int getSubString(uchar **ppSrc, char *pDst, size_t DstSize, char cSep) { |
| 640 |
uchar *pSrc = *ppSrc; |
| 641 |
int iErr = 0; /* 0 = no error, >0 = error */ |
| 642 |
while ((cSep == ' ' ? !isspace(*pSrc) : *pSrc != cSep) && *pSrc != '\n' && *pSrc != '\0' && DstSize > 1) { |
| 643 |
*pDst++ = *(pSrc)++; |
| 644 |
DstSize--; |
| 645 |
} |
| 646 |
/* check if the Dst buffer was to small */ |
| 647 |
if ((cSep == ' ' ? !isspace(*pSrc) : *pSrc != cSep) && *pSrc != '\n' && *pSrc != '\0') { |
| 648 |
dbgprintf("in getSubString, error Src buffer > Dst buffer\n"); |
| 649 |
iErr = 1; |
| 650 |
} |
| 651 |
if (*pSrc == '\0' || *pSrc == '\n') |
| 652 |
/* this line was missing, causing ppSrc to be invalid when it |
| 653 |
* was returned in case of end-of-string. rgerhards 2005-07-29 |
| 654 |
*/ |
| 655 |
*ppSrc = pSrc; |
| 656 |
else |
| 657 |
*ppSrc = pSrc + 1; |
| 658 |
*pDst = '\0'; |
| 659 |
return iErr; |
| 660 |
} |
| 661 |
|
| 662 |
|
| 663 |
/* get the size of a file or return appropriate error code. If an error is returned, |
| 664 |
* *pSize content is undefined. |
| 665 |
* rgerhards, 2009-06-12 |
| 666 |
*/ |
| 667 |
rsRetVal getFileSize(uchar *pszName, off_t *pSize) { |
| 668 |
int ret; |
| 669 |
struct stat statBuf; |
| 670 |
DEFiRet; |
| 671 |
|
| 672 |
ret = stat((char *)pszName, &statBuf); |
| 673 |
if (ret == -1) { |
| 674 |
switch (errno) { |
| 675 |
case EACCES: |
| 676 |
ABORT_FINALIZE(RS_RET_NO_FILE_ACCESS); |
| 677 |
case ENOTDIR: |
| 678 |
case ENOENT: |
| 679 |
ABORT_FINALIZE(RS_RET_FILE_NOT_FOUND); |
| 680 |
default: |
| 681 |
ABORT_FINALIZE(RS_RET_FILE_NO_STAT); |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
*pSize = statBuf.st_size; |
| 686 |
|
| 687 |
finalize_it: |
| 688 |
RETiRet; |
| 689 |
} |
| 690 |
|
| 691 |
/* Returns 1 if the given string contains a non-escaped glob(3) |
| 692 |
* wildcard character and 0 otherwise (or if the string is empty). |
| 693 |
*/ |
| 694 |
int containsGlobWildcard(char *str) { |
| 695 |
char *p; |
| 696 |
if (!str) { |
| 697 |
return 0; |
| 698 |
} |
| 699 |
/* From Linux Programmer's Guide: |
| 700 |
* "A string is a wildcard pattern if it contains one of the characters '?', '*', '{' or '['" |
| 701 |
* "One can remove the special meaning of '?', '*', '{' and '[' by preceding them by a backslash" |
| 702 |
*/ |
| 703 |
for (p = str; *p != '\0'; p++) { |
| 704 |
if ((*p == '?' || *p == '*' || *p == '[' || *p == '{') && (p == str || *(p - 1) != '\\')) { |
| 705 |
return 1; |
| 706 |
} |
| 707 |
} |
| 708 |
return 0; |
| 709 |
} |
| 710 |
|
| 711 |
static void seedRandomInsecureNumber(void) { |
| 712 |
struct timespec t; |
| 713 |
timeoutComp(&t, 0); |
| 714 |
long long x = t.tv_sec * 3 + t.tv_nsec * 2; |
| 715 |
srandom((unsigned int)x); |
| 716 |
} |
| 717 |
|
| 718 |
static long int randomInsecureNumber(void) { |
| 719 |
return random(); |
| 720 |
} |
| 721 |
|
| 722 |
#ifdef OS_LINUX |
| 723 |
static int fdURandom = -1; |
| 724 |
void seedRandomNumber(void) { |
| 725 |
if (fdURandom >= 0) { |
| 726 |
/* Already opened. */ |
| 727 |
return; |
| 728 |
} |
| 729 |
fdURandom = open("/dev/urandom", O_RDONLY); |
| 730 |
if (fdURandom == -1) { |
| 731 |
LogError(errno, RS_RET_IO_ERROR, |
| 732 |
"failed to seed random number generation," |
| 733 |
" will use fallback (open urandom failed)"); |
| 734 |
seedRandomInsecureNumber(); |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
void seedRandomNumberForChild(void) { |
| 739 |
/* The file descriptor inherited from our parent will have been closed after |
| 740 |
* the fork. Discard this and call seedRandomNumber() to open /dev/urandom |
| 741 |
* again. |
| 742 |
*/ |
| 743 |
fdURandom = -1; |
| 744 |
seedRandomNumber(); |
| 745 |
} |
| 746 |
|
| 747 |
long int randomNumber(void) { |
| 748 |
long int ret; |
| 749 |
if (fdURandom >= 0) { |
| 750 |
if (read(fdURandom, &ret, sizeof(long int)) == -1) { |
| 751 |
LogError(errno, RS_RET_IO_ERROR, |
| 752 |
"failed to generate random number, will" |
| 753 |
" use fallback (read urandom failed)"); |
| 754 |
ret = randomInsecureNumber(); |
| 755 |
} |
| 756 |
} else { |
| 757 |
ret = randomInsecureNumber(); |
| 758 |
} |
| 759 |
return ret; |
| 760 |
} |
| 761 |
#else |
| 762 |
void seedRandomNumber(void) { |
| 763 |
seedRandomInsecureNumber(); |
| 764 |
} |
| 765 |
|
| 766 |
void seedRandomNumberForChild(void) { |
| 767 |
seedRandomNumber(); |
| 768 |
} |
| 769 |
|
| 770 |
long int randomNumber(void) { |
| 771 |
return randomInsecureNumber(); |
| 772 |
} |
| 773 |
#endif |
| 774 |
|
| 775 |
|
| 776 |
/* process "binary" parameters where this is needed to execute |
| 777 |
* programs (namely mmexternal and omprog). |
| 778 |
* Most importantly, split them into argv[] and get the binary name |
| 779 |
*/ |
| 780 |
rsRetVal ATTR_NONNULL() split_binary_parameters(uchar **const szBinary, |
| 781 |
char ***const __restrict__ aParams, |
| 782 |
int *const iParams, |
| 783 |
es_str_t *const param_binary) { |
| 784 |
es_size_t iCnt; |
| 785 |
es_size_t iStr; |
| 786 |
int iPrm; |
| 787 |
es_str_t *estrParams = NULL; |
| 788 |
es_str_t *estrBinary = param_binary; |
| 789 |
es_str_t *estrTmp = NULL; |
| 790 |
uchar *c; |
| 791 |
int bInQuotes; |
| 792 |
DEFiRet; |
| 793 |
assert(iParams != NULL); |
| 794 |
assert(param_binary != NULL); |
| 795 |
|
| 796 |
/* Search for end of binary name */ |
| 797 |
c = es_getBufAddr(param_binary); |
| 798 |
iCnt = 0; |
| 799 |
while (iCnt < es_strlen(param_binary)) { |
| 800 |
if (c[iCnt] == ' ') { |
| 801 |
/* Split binary name from parameters */ |
| 802 |
estrBinary = es_newStrFromSubStr(param_binary, 0, iCnt); |
| 803 |
estrParams = es_newStrFromSubStr(param_binary, iCnt + 1, es_strlen(param_binary)); |
| 804 |
break; |
| 805 |
} |
| 806 |
iCnt++; |
| 807 |
} |
| 808 |
*szBinary = (uchar *)es_str2cstr(estrBinary, NULL); |
| 809 |
DBGPRINTF("szBinary = '%s'\n", *szBinary); |
| 810 |
|
| 811 |
*iParams = 1; /* we always have argv[0] */ |
| 812 |
/* count size of argv[] */ |
| 813 |
if (estrParams != NULL) { |
| 814 |
(*iParams)++; /* last parameter is not counted in loop below! */ |
| 815 |
if (Debug) { |
| 816 |
char *params = es_str2cstr(estrParams, NULL); |
| 817 |
dbgprintf("szParams = '%s'\n", params); |
| 818 |
free(params); |
| 819 |
} |
| 820 |
c = es_getBufAddr(estrParams); |
| 821 |
for (iCnt = 0; iCnt < es_strlen(estrParams); ++iCnt) { |
| 822 |
if (c[iCnt] == ' ' && c[iCnt - 1] != '\\') (*iParams)++; |
| 823 |
} |
| 824 |
} |
| 825 |
DBGPRINTF("iParams %d (+1 for NULL terminator)\n", *iParams); |
| 826 |
|
| 827 |
/* create argv[] */ |
| 828 |
CHKmalloc(*aParams = malloc((*iParams + 1) * sizeof(char *))); |
| 829 |
iPrm = 0; |
| 830 |
bInQuotes = FALSE; |
| 831 |
/* Set first parameter to binary */ |
| 832 |
(*aParams)[iPrm] = strdup((char *)*szBinary); |
| 833 |
iPrm++; |
| 834 |
if (estrParams != NULL) { |
| 835 |
iCnt = iStr = 0; |
| 836 |
c = es_getBufAddr(estrParams); /* Reset to beginning */ |
| 837 |
while (iCnt < es_strlen(estrParams)) { |
| 838 |
if (c[iCnt] == '"' && iCnt == iStr && !bInQuotes) { |
| 839 |
bInQuotes = TRUE; |
| 840 |
iStr++; |
| 841 |
} else { |
| 842 |
int bEOL = iCnt + 1 == es_strlen(estrParams); |
| 843 |
int bSpace = c[iCnt] == ' '; |
| 844 |
int bQuoteEnd = bInQuotes && ((bSpace && c[iCnt - 1] == '"') || (c[iCnt] == '"' && bEOL)); |
| 845 |
if (bEOL || bQuoteEnd || (bSpace && !bInQuotes)) { |
| 846 |
int iSubCnt = iCnt - iStr; |
| 847 |
if (bEOL) iSubCnt++; |
| 848 |
if (bQuoteEnd) iSubCnt--; |
| 849 |
estrTmp = es_newStrFromSubStr(estrParams, iStr, iSubCnt); |
| 850 |
} |
| 851 |
|
| 852 |
if (bQuoteEnd) bInQuotes = FALSE; |
| 853 |
} |
| 854 |
|
| 855 |
if (estrTmp != NULL) { |
| 856 |
(*aParams)[iPrm] = es_str2cstr(estrTmp, NULL); |
| 857 |
iStr = iCnt + 1; /* Set new start */ |
| 858 |
DBGPRINTF("Param (%d): '%s'\n", iPrm, (*aParams)[iPrm]); |
| 859 |
es_deleteStr(estrTmp); |
| 860 |
estrTmp = NULL; |
| 861 |
iPrm++; |
| 862 |
} |
| 863 |
iCnt++; |
| 864 |
} |
| 865 |
} |
| 866 |
(*aParams)[iPrm] = NULL; /* NULL per argv[] convention */ |
| 867 |
|
| 868 |
finalize_it: |
| 869 |
if (estrBinary != param_binary) { |
| 870 |
es_deleteStr(estrBinary); |
| 871 |
} |
| 872 |
if (estrParams != NULL) { |
| 873 |
es_deleteStr(estrParams); |
| 874 |
} |
| 875 |
RETiRet; |
| 876 |
} |