X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?p=elogind.git;a=blobdiff_plain;f=src%2Futil.c;h=0988675f09be39f291cd565b446ffeb0dba4dd1f;hp=ed0991a68b45d1a4b699f6de08ca54dcf81797e5;hb=55293c152a0c8a8720461a26e2d6e24b5612d1f0;hpb=5b6319dceedd81f3f1ce7eb70ea5defaef43bcec diff --git a/src/util.c b/src/util.c index ed0991a68..0988675f0 100644 --- a/src/util.c +++ b/src/util.c @@ -44,6 +44,8 @@ #include #include #include +#include +#include #include "macro.h" #include "util.h" @@ -241,6 +243,29 @@ int parse_boolean(const char *v) { return -EINVAL; } +int parse_pid(const char *s, pid_t* ret_pid) { + unsigned long ul; + pid_t pid; + int r; + + assert(s); + assert(ret_pid); + + if ((r = safe_atolu(s, &ul)) < 0) + return r; + + pid = (pid_t) ul; + + if ((unsigned long) pid != ul) + return -ERANGE; + + if (pid <= 0) + return -ERANGE; + + *ret_pid = pid; + return 0; +} + int safe_atou(const char *s, unsigned *ret_u) { char *x = NULL; unsigned long l; @@ -2182,6 +2207,80 @@ void rename_process(const char name[8]) { strncpy(program_invocation_name, name, strlen(program_invocation_name)); } +void sigset_add_many(sigset_t *ss, ...) { + va_list ap; + int sig; + + assert(ss); + + va_start(ap, ss); + while ((sig = va_arg(ap, int)) > 0) + assert_se(sigaddset(ss, sig) == 0); + va_end(ap); +} + +char* gethostname_malloc(void) { + struct utsname u; + + assert_se(uname(&u) >= 0); + + if (u.nodename[0]) + return strdup(u.nodename); + + return strdup(u.sysname); +} + +char* getlogname_malloc(void) { + uid_t uid; + long bufsize; + char *buf, *name; + struct passwd pwbuf, *pw = NULL; + struct stat st; + + if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0) + uid = st.st_uid; + else + uid = getuid(); + + /* Shortcut things to avoid NSS lookups */ + if (uid == 0) + return strdup("root"); + + if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0) + bufsize = 4096; + + if (!(buf = malloc(bufsize))) + return NULL; + + if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) { + name = strdup(pw->pw_name); + free(buf); + return name; + } + + free(buf); + + if (asprintf(&name, "%lu", (unsigned long) uid) < 0) + return NULL; + + return name; +} + +char *getttyname_malloc(void) { + char path[PATH_MAX], *p; + + if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0) + return strdup("unknown"); + + char_array_0(path); + + p = path; + if (startswith(path, "/dev/")) + p += 5; + + return strdup(p); +} + static const char *const ioprio_class_table[] = { [IOPRIO_CLASS_NONE] = "none", [IOPRIO_CLASS_RT] = "realtime",