2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 1999 University of Maryland at College Park
6 * Permission to use, copy, modify, distribute, and sell this software and its
7 * documentation for any purpose is hereby granted without fee, provided that
8 * the above copyright notice appear in all copies and that both that
9 * copyright notice and this permission notice appear in supporting
10 * documentation, and that the name of U.M. not be used in advertising or
11 * publicity pertaining to distribution of the software without specific,
12 * written prior permission. U.M. makes no representations about the
13 * suitability of this software for any purpose. It is provided "as is"
14 * without express or implied warranty.
16 * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 * Authors: the Amanda Development Team. Its members are listed in a
24 * file named AUTHORS, in the root directory of this distribution.
27 * $Id: util.c,v 1.42 2006/08/24 01:57:15 paddy_s Exp $
36 #include "sockaddr-util.h"
40 #include "pipespawn.h"
44 static int make_socket(sa_family_t family);
45 static int connect_port(sockaddr_union *addrp, in_port_t port, char *proto,
46 sockaddr_union *svaddr, int nonblock);
54 #if defined(SO_KEEPALIVE) || defined(USE_REUSEADDR)
59 g_debug("make_socket opening socket with family %d", family);
60 s = socket(family, SOCK_STREAM, 0);
63 dbprintf(_("make_socket: socket() failed: %s\n"), strerror(save_errno));
67 if (s < 0 || s >= (int)FD_SETSIZE) {
69 errno = EMFILE; /* out of range */
74 r = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
77 dbprintf(_("make_socket: setsockopt(SO_REUSEADDR) failed: %s\n"),
84 r = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
85 (void *)&on, SIZEOF(on));
88 dbprintf(_("make_socket: setsockopt() failed: %s\n"),
89 strerror(save_errno));
99 GQuark am_util_error_quark(void)
101 return g_quark_from_static_string("am-util-error-quark");
104 /* addrp is my address */
105 /* svaddr is the address of the remote machine */
106 /* return socket on success */
107 /* return -1 on failure */
110 sockaddr_union *addrp,
111 in_port_t first_port,
114 sockaddr_union *svaddr,
119 static in_port_t port_in_use[1024];
120 static int nb_port_in_use = 0;
122 int save_errno = EAGAIN;
124 assert(first_port <= last_port);
125 /* Try a port already used */
126 for(i=0; i < nb_port_in_use; i++) {
127 port = port_in_use[i];
128 if(port >= first_port && port <= last_port) {
129 s = connect_port(addrp, port, proto, svaddr, nonblock);
130 if(s == -2) return -1;
134 if (errno != EAGAIN && errno != EBUSY)
139 /* Try a port in the range */
140 for (port = first_port; port <= last_port; port++) {
141 s = connect_port(addrp, port, proto, svaddr, nonblock);
142 if(s == -2) return -1;
144 port_in_use[nb_port_in_use++] = port;
147 if (errno != EAGAIN && errno != EBUSY)
151 dbprintf(_("connect_portrange: All ports between %d and %d are busy.\n"),
158 /* addrp is my address */
159 /* svaddr is the address of the remote machine */
160 /* return -2: Don't try again */
161 /* return -1: Try with another port */
162 /* return >0: this is the connected socket */
165 sockaddr_union *addrp,
168 sockaddr_union *svaddr,
172 struct servent * servPort;
174 socklen_t_equiv socklen;
177 servPort = getservbyport((int)htons(port), proto);
178 if (servPort != NULL && !strstr(servPort->s_name, "amanda")) {
179 dbprintf(_("connect_port: Skip port %d: owned by %s.\n"),
180 port, servPort->s_name);
185 if ((s = make_socket(SU_GET_FAMILY(addrp))) == -1) return -2;
187 SU_SET_PORT(addrp, port);
188 socklen = SS_LEN(addrp);
189 if (bind(s, (struct sockaddr *)addrp, socklen) != 0) {
192 if(servPort == NULL) {
193 dbprintf(_("connect_port: Try port %d: available - %s\n"),
194 port, strerror(errno));
196 dbprintf(_("connect_port: Try port %d: owned by %s - %s\n"),
197 port, servPort->s_name, strerror(errno));
199 if (save_errno != EADDRINUSE) {
207 if(servPort == NULL) {
208 dbprintf(_("connect_port: Try port %d: available - Success\n"), port);
210 dbprintf(_("connect_port: Try port %d: owned by %s - Success\n"),
211 port, servPort->s_name);
214 /* find out what port was actually used */
216 len = sizeof(*addrp);
217 if (getsockname(s, (struct sockaddr *)addrp, &len) == -1) {
219 dbprintf(_("connect_port: getsockname() failed: %s\n"),
220 strerror(save_errno));
227 fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0)|O_NONBLOCK);
228 if (connect(s, (struct sockaddr *)svaddr, SS_LEN(svaddr)) == -1 && !nonblock) {
230 dbprintf(_("connect_portrange: Connect from %s failed: %s\n"),
232 strerror(save_errno));
233 dbprintf(_("connect_portrange: connect to %s failed: %s\n"),
234 str_sockaddr(svaddr),
235 strerror(save_errno));
238 if (save_errno == ECONNREFUSED ||
239 save_errno == EHOSTUNREACH ||
240 save_errno == ENETUNREACH ||
241 save_errno == ETIMEDOUT) {
247 dbprintf(_("connected to %s\n"),
248 str_sockaddr(svaddr));
249 dbprintf(_("our side is %s\n"),
250 str_sockaddr(addrp));
256 * Bind to a port in the given range. Takes a begin,end pair of port numbers.
258 * Returns negative on error (EGAIN if all ports are in use). Returns 0
264 sockaddr_union *addrp,
265 in_port_t first_port,
271 socklen_t_equiv socklen;
272 struct servent *servPort;
273 const in_port_t num_ports = (in_port_t)(last_port - first_port + 1);
274 int save_errno = EAGAIN;
276 assert(first_port <= last_port);
279 * We pick a different starting port based on our pid and the current
280 * time to avoid always picking the same reserved port twice.
282 port = (in_port_t)(((getpid() + time(0)) % num_ports) + first_port);
285 * Scan through the range, trying all available ports that are either
286 * not taken in /etc/services or registered for *amanda*. Wrap around
287 * if we don't happen to start at the beginning.
289 for (cnt = 0; cnt < num_ports; cnt++) {
290 servPort = getservbyport((int)htons(port), proto);
291 if ((servPort == NULL) || strstr(servPort->s_name, "amanda")) {
292 SU_SET_PORT(addrp, port);
293 socklen = SS_LEN(addrp);
294 if (bind(s, (struct sockaddr *)addrp, socklen) >= 0) {
295 if (servPort == NULL) {
296 g_debug(_("bind_portrange2: Try port %d: Available - Success"), port);
298 g_debug(_("bind_portrange2: Try port %d: Owned by %s - Success."), port, servPort->s_name);
302 if (errno != EAGAIN && errno != EBUSY)
304 if (servPort == NULL) {
305 g_debug(_("bind_portrange2: Try port %d: Available - %s"),
306 port, strerror(errno));
308 g_debug(_("bind_portrange2: Try port %d: Owned by %s - %s"),
309 port, servPort->s_name, strerror(errno));
312 g_debug(_("bind_portrange2: Skip port %d: Owned by %s."),
313 port, servPort->s_name);
315 if (++port > last_port)
318 g_debug(_("bind_portrange: all ports between %d and %d busy"),
326 interruptible_accept(
328 struct sockaddr *addr,
330 gboolean (*prolong)(gpointer data),
331 gpointer prolong_data)
333 SELECT_ARG_TYPE readset;
337 if (sock < 0 || sock >= FD_SETSIZE) {
338 g_debug("interruptible_accept: bad socket %d", sock);
342 memset(&readset, 0, SIZEOF(readset));
345 if (!prolong(prolong_data)) {
351 FD_SET(sock, &readset);
353 /* try accepting for 1s */
354 memset(&tv, 0, SIZEOF(tv));
357 nfound = select(sock+1, &readset, NULL, NULL, &tv);
360 } else if (nfound == 0) {
362 } else if (!FD_ISSET(sock, &readset)) {
363 g_debug("interruptible_accept: select malfunction");
367 int rv = accept(sock, addr, addrlen);
368 if (rv < 0 && errno == EAGAIN)
376 * Writes out the entire iovec
384 ssize_t delta, n, total;
393 n = writev(fd, iov, iovcnt);
404 * Iterate through each iov. Figure out what we still need
407 for (; n > 0; iovcnt--, iov++) {
408 /* 'delta' is the bytes written from this iovec */
409 delta = ((size_t)n < (size_t)iov->iov_len) ? n : (ssize_t)iov->iov_len;
410 /* subtract from the total num bytes written */
413 /* subtract from this iovec */
414 iov->iov_len -= delta;
415 iov->iov_base = (char *)iov->iov_base + delta;
416 /* if this iovec isn't empty, run the writev again */
417 if (iov->iov_len > 0)
427 * For backward compatibility we are trying for minimal quoting. Unless ALWAYS
428 * is true, we only quote a string if it contains whitespace or is misquoted...
439 if ((str == NULL) || (*str == '\0')) {
440 ret = stralloc("\"\"");
443 for (r = str; *r; r++) {
444 if (*r == ':' || *r == '\'' || *r == '\\' || *r == '\"' ||
445 *r <= ' ' || *r == 0x7F )
450 * String does not need to be quoted since it contains
451 * neither whitespace, control or quote characters.
456 * Allocate maximum possible string length.
457 * (a string of all quotes plus room for leading ", trailing " and
460 ret = s = alloc((strlen(str) * 2) + 2 + 1);
462 while (*str != '\0') {
468 } else if (*str == '\n') {
473 } else if (*str == '\r') {
478 } else if (*str == '\f') {
483 } else if (*str == '\\') {
502 len_quote_string_maybe(
508 if ((str == NULL) || (*str == '\0')) {
512 for (r = str; *r; r++) {
513 if (*r == ':' || *r == '\'' || *r == '\\' || *r == '\"' ||
514 *r <= ' ' || *r == 0x7F )
519 * String does not need to be quoted since it contains
520 * neither whitespace, control or quote characters.
525 * Allocate maximum possible string length.
526 * (a string of all quotes plus room for leading ", trailing " and
530 while (*str != '\0') {
536 } else if (*str == '\n') {
541 } else if (*str == '\r') {
546 } else if (*str == '\f') {
551 } else if (*str == '\\') {
575 if ((str == NULL) || (*str == '\0')) {
581 ret = in = out = stralloc(str);
582 while (*in != '\0') {
594 } else if (*in == 't') {
598 } else if (*in == 'r') {
602 } else if (*in == 'f') {
606 } else if (*in >= '0' && *in <= '7') {
610 while (i < 3 && *in >= '0' && *in <= '7') {
611 c = (c << 3) + *(in++) - '0';
616 } else if (*in == '\0') {
617 /* trailing backslash -- ignore */
629 split_quoted_strings(
642 p = start = local = g_strdup(string);
643 strs = g_ptr_array_new();
646 if (!iq && *p == ' ') {
648 g_ptr_array_add(strs, unquote_string(start));
650 } else if (*p == '\\') {
651 /* next character is taken literally; if it's a multicharacter
652 * escape (e.g., \171), that doesn't bother us here */
655 } else if (*p == '\"') {
662 g_ptr_array_add(strs, unquote_string(start));
664 /* now convert strs into a strv, by stealing its references to the underlying
666 result = g_new0(char *, strs->len + 1);
667 memmove(result, strs->pdata, sizeof(char *) * strs->len);
669 g_ptr_array_free(strs, TRUE); /* TRUE => free pdata, strings are not freed */
676 strquotedstr(char **saveptr)
678 char * tok = strtok_r(NULL, " ", saveptr);
690 while (in_quote || in_backslash || *p != '\0') {
692 /* append a new token */
693 t = strtok_r(NULL, " ", saveptr);
701 in_quote = !in_quote;
702 else if (*p == '\\') {
720 if ((str == NULL) || (*str == '\0')) {
724 for (s = ret; *s != '\0'; s++) {
725 if (iscntrl((int)*s))
732 char *hexencode_string(const char *str)
734 size_t orig_len, new_len, i;
738 s = g_string_sized_new(0);
741 new_len = orig_len = strlen(str);
742 for (i = 0; i < orig_len; i++) {
743 if (!g_ascii_isalnum(str[i])) {
747 s = g_string_sized_new(new_len);
749 for (i = 0; i < orig_len; i++) {
750 if (g_ascii_isalnum(str[i])) {
751 g_string_append_c(s, str[i]);
753 g_string_append_printf(s, "%%%02hhx", str[i]);
759 g_string_free(s, FALSE);
763 char *hexdecode_string(const char *str, GError **err)
765 size_t orig_len, new_len, i;
769 s = g_string_sized_new(0);
772 new_len = orig_len = strlen(str);
773 for (i = 0; i < orig_len; i++) {
778 s = g_string_sized_new(new_len);
780 for (i = 0; (orig_len > 2) && (i < orig_len-2); i++) {
784 for (j = 1; j < 3; j++) {
786 if (str[i+j] >= '0' && str[i+j] <= '9') {
787 tmp += str[i+j] - '0';
788 } else if (str[i+j] >= 'a' && str[i+j] <= 'f') {
789 tmp += str[i+j] - 'a' + 10;
790 } else if (str[i+j] >= 'A' && str[i+j] <= 'F') {
791 tmp += str[i+j] - 'A' + 10;
794 g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL,
795 "Illegal character (non-hex) 0x%02hhx at offset %zd", str[i+j], i+j);
796 g_string_truncate(s, 0);
801 g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL,
802 "Encoded NULL at starting offset %zd", i);
803 g_string_truncate(s, 0);
806 g_string_append_c(s, tmp);
809 g_string_append_c(s, str[i]);
812 for ( /*nothing*/; i < orig_len; i++) {
814 g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL,
815 "'%%' found at offset %zd, but fewer than two characters follow it (%zd)", i, orig_len-i-1);
816 g_string_truncate(s, 0);
819 g_string_append_c(s, str[i]);
825 g_string_free(s, FALSE);
829 /* Helper for parse_braced_component; this will turn a single element array
830 * matching /^\d+\.\.\d+$/ into a sequence of numbered array elements. */
832 expand_braced_sequence(GPtrArray *arr)
836 int ldigits, rdigits, ndigits;
838 gboolean leading_zero;
840 /* check whether the element matches the pattern */
841 /* expand last element of the array only */
842 elt = g_ptr_array_index(arr, arr->len-1);
844 for (l = p = elt; *p && g_ascii_isdigit(*p); p++)
853 for (r = p; *p && g_ascii_isdigit(*p); p++)
860 /* we have a match, so extract start and end */
861 start = g_ascii_strtoull(l, NULL, 10);
862 end = g_ascii_strtoull(r, NULL, 10);
863 leading_zero = *l == '0';
864 ndigits = MAX(ldigits, rdigits);
869 if (end - start > 100000)
872 /* remove last from the array */
873 g_ptr_array_remove_index(arr, arr->len - 1);
875 /* Add new elements */
876 while (start <= end) {
878 g_ptr_array_add(arr, g_strdup_printf("%0*ju",
879 ndigits, (uintmax_t)start));
881 g_ptr_array_add(arr, g_strdup_printf("%ju", (uintmax_t)start));
889 /* Helper for expand_braced_alternates; returns a list of un-escaped strings
890 * for the first "component" of str, where a component is a plain string or a
891 * brace-enclosed set of alternatives. str is pointing to the first character
892 * of the next component on return. */
894 parse_braced_component(char **str)
896 GPtrArray *result = g_ptr_array_new();
900 char *local = g_malloc(strlen(*str)+1);
901 char *current = local;
905 if (*p == '\0' || *p == '{') {
906 /* unterminated { .. } or extra '{' */
908 g_ptr_array_free(result, TRUE);
912 if (*p == '}' || *p == ',') {
914 g_ptr_array_add(result, g_strdup(current));
915 result = expand_braced_sequence(result);
925 if (*(p+1) == '{' || *(p+1) == '}' || *(p+1) == '\\' || *(p+1) == ',')
938 /* no braces -- just un-escape a plain string */
939 char *local = g_malloc(strlen(*str)+1);
943 while (*p && *p != '{') {
945 if (*(p+1) == '{' || *(p+1) == '}' || *(p+1) == '\\' || *(p+1) == ',')
951 g_ptr_array_add(result, local);
959 expand_braced_alternates(
962 GPtrArray *rval = g_ptr_array_new();
964 g_ptr_array_add(rval, g_strdup(""));
967 GPtrArray *new_components;
971 new_components = parse_braced_component(&source);
972 if (!new_components) {
974 g_ptr_array_free(rval, TRUE);
978 new_rval = g_ptr_array_new();
980 /* do a cartesian join of rval and new_components */
981 for (i = 0; i < rval->len; i++) {
982 for (j = 0; j < new_components->len; j++) {
983 g_ptr_array_add(new_rval, g_strconcat(
984 g_ptr_array_index(rval, i),
985 g_ptr_array_index(new_components, j),
990 g_ptr_array_free(rval, TRUE);
991 g_ptr_array_free(new_components, TRUE);
999 collapse_braced_alternates(
1002 GString *result = NULL;
1005 result = g_string_new("{");
1007 for (i = 0; i < source->len; i ++) {
1008 const char *str = g_ptr_array_index(source, i);
1011 if (strchr(str, ',') || strchr(str, '\\') ||
1012 strchr(str, '{') || strchr(str, '}')) {
1017 qstr = d = g_malloc(strlen(str)*2+1);
1019 if (*s == ',' || *s == '\\' || *s == '{' || *s == '}')
1025 g_string_append_printf(result, "%s%s", qstr? qstr : str,
1026 (i < source->len-1)? "," : "");
1031 g_string_append(result, "}");
1032 return g_string_free(result, FALSE);
1036 Return 0 if the following characters are present
1037 * ( ) < > [ ] , ; : ! $ \ / "
1045 return !match("\\*|<|>|\\(|\\)|\\[|\\]|,|;|:|\\\\|/|\"|\\!|\\$|\\|", mailto);
1059 if ((infd = open(src, O_RDONLY)) == -1) {
1061 quoted = quote_string(src);
1062 *errmsg = vstrallocf(_("Can't open file '%s' for reading: %s"),
1063 quoted, strerror(save_errno));
1068 if ((outfd = open(dst, O_WRONLY|O_CREAT, 0600)) == -1) {
1070 quoted = quote_string(dst);
1071 *errmsg = vstrallocf(_("Can't open file '%s' for writting: %s"),
1072 quoted, strerror(save_errno));
1078 while((nb=read(infd, &buf, SIZEOF(buf))) > 0) {
1079 if(full_write(outfd,&buf,nb) < nb) {
1081 quoted = quote_string(dst);
1082 *errmsg = vstrallocf(_("Error writing to '%s': %s"),
1083 quoted, strerror(save_errno));
1093 quoted = quote_string(src);
1094 *errmsg = vstrallocf(_("Error reading from '%s': %s"),
1095 quoted, strerror(save_errno));
1107 #ifndef HAVE_LIBREADLINE
1109 * simple readline() replacements, used when we don't have readline
1110 * support from the system.
1117 g_printf("%s", prompt);
1120 return agets(stdin);
1127 (void)line; /* Quiet unused parameter warning */
1132 /* Order of preference: readdir64(), readdir(). */
1133 #if HAVE_DECL_READDIR64
1134 # define USE_DIRENT64
1135 # define USE_READDIR64
1136 #elif HAVE_DECL_READDIR
1137 # define USE_READDIR
1139 # error No readdir() or readdir64() available!
1142 char * portable_readdir(DIR* handle) {
1145 struct dirent64 *entry_p;
1147 struct dirent *entry_p;
1150 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1152 g_static_mutex_lock(&mutex);
1155 entry_p = readdir(handle);
1157 #ifdef USE_READDIR64
1158 entry_p = readdir64(handle);
1161 g_static_mutex_unlock(&mutex);
1163 if (entry_p == NULL)
1166 /* FIXME: According to glibc documentation, d_name may not be
1167 null-terminated in some cases on some very old platforms. Not
1168 sure what to do about that case. */
1169 return strdup(entry_p->d_name);
1172 int search_directory(DIR * handle, const char * regex,
1173 SearchDirectoryFunctor functor, gpointer user_data) {
1175 regex_t compiled_regex;
1176 gboolean done = FALSE;
1178 if (regcomp(&compiled_regex, regex, REG_EXTENDED | REG_NOSUB) != 0) {
1179 regfree(&compiled_regex);
1188 read_name = portable_readdir(handle);
1189 if (read_name == NULL) {
1190 regfree(&compiled_regex);
1193 result = regexec(&compiled_regex, read_name, 0, NULL, 0);
1196 done = !functor(read_name, user_data);
1200 regfree(&compiled_regex);
1204 char* find_regex_substring(const char* base_string, const regmatch_t match) {
1208 size = match.rm_eo - match.rm_so;
1209 rval = malloc(size+1);
1210 memcpy(rval, base_string + match.rm_so, size);
1216 int compare_possibly_null_strings(const char * a, const char * b) {
1218 /* NULL or otherwise, they're the same. */
1220 } else if (a == NULL) {
1223 } else if (b == NULL) {
1227 /* a != NULL != b */
1228 return strcmp(a, b);
1233 resolve_hostname(const char *hostname,
1235 struct addrinfo **res,
1238 struct addrinfo hints;
1239 struct addrinfo *myres;
1243 if (res) *res = NULL;
1246 flags = AI_CANONNAME;
1249 #ifdef AI_ADDRCONFIG
1250 flags |= AI_ADDRCONFIG;
1253 memset(&hints, 0, sizeof(hints));
1255 /* get any kind of addresss */
1256 hints.ai_family = AF_UNSPEC;
1258 /* even if getaddrinfo supports IPv6, don't let it return
1259 * such an address */
1260 hints.ai_family = AF_INET;
1262 hints.ai_flags = flags;
1263 hints.ai_socktype = socktype;
1264 result = getaddrinfo(hostname, NULL, &hints, &myres);
1269 if (canonname && myres && myres->ai_canonname) {
1270 *canonname = stralloc(myres->ai_canonname);
1276 freeaddrinfo(myres);
1287 if (WIFEXITED(status)) {
1288 int exitstatus = WEXITSTATUS(status);
1289 if (exitstatus == 0)
1290 return vstrallocf(_("%s exited normally"), subject);
1292 return vstrallocf(_("%s exited with status %d"), subject, exitstatus);
1295 if (WIFSIGNALED(status)) {
1296 int signal = WTERMSIG(status);
1298 if (WCOREDUMP(status))
1299 return vstrallocf(_("%s exited after receiving signal %d (core dumped)"),
1303 return vstrallocf(_("%s exited after receiving signal %d"),
1307 if (WIFSTOPPED(status)) {
1308 int signal = WSTOPSIG(status);
1309 return vstrallocf(_("%s stopped temporarily after receiving signal %d"),
1314 if (WIFCONTINUED(status)) {
1315 return vstrallocf(_("%s was resumed"), subject);
1319 return vstrallocf(_("%s exited in unknown circumstances"), subject);
1323 check_running_as(running_as_flags who)
1329 char *uname_me = NULL;
1330 char *uname_target = NULL;
1334 if ((pw = getpwuid(uid_me)) == NULL) {
1335 error(_("current userid %ld not found in password database"), (long)uid_me);
1338 uname_me = stralloc(pw->pw_name);
1340 #ifndef SINGLE_USERID
1341 if (!(who & RUNNING_AS_UID_ONLY) && uid_me != geteuid()) {
1342 error(_("euid (%lld) does not match uid (%lld); is this program setuid-root when it shouldn't be?"),
1343 (long long int)geteuid(), (long long int)uid_me);
1348 switch (who & RUNNING_AS_USER_MASK) {
1349 case RUNNING_AS_ANY:
1350 uid_target = uid_me;
1351 uname_target = uname_me;
1355 case RUNNING_AS_ROOT:
1357 uname_target = "root";
1360 case RUNNING_AS_DUMPUSER_PREFERRED:
1361 dumpuser = getconf_str(CNF_DUMPUSER);
1362 if ((pw = getpwnam(dumpuser)) != NULL &&
1363 uid_me != pw->pw_uid) {
1364 if ((pw = getpwnam(CLIENT_LOGIN)) != NULL &&
1365 uid_me == pw->pw_uid) {
1366 /* uid == CLIENT_LOGIN: not ideal, but OK */
1367 dbprintf(_("NOTE: running as '%s', which is the client"
1368 " user, not the dumpuser ('%s'); forging"
1370 CLIENT_LOGIN, dumpuser);
1371 uid_target = uid_me; /* force success below */
1377 case RUNNING_AS_DUMPUSER:
1378 uname_target = getconf_str(CNF_DUMPUSER);
1379 if ((pw = getpwnam(uname_target)) == NULL) {
1380 error(_("cannot look up dumpuser \"%s\""), uname_target);
1383 uid_target = pw->pw_uid;
1386 case RUNNING_AS_CLIENT_LOGIN:
1387 uname_target = CLIENT_LOGIN;
1388 if ((pw = getpwnam(uname_target)) == NULL) {
1389 error(_("cannot look up client user \"%s\""), uname_target);
1392 uid_target = pw->pw_uid;
1396 error(_("Unknown check_running_as() call"));
1400 if (uid_me != uid_target) {
1401 error(_("running as user \"%s\" instead of \"%s\""), uname_me, uname_target);
1407 /* Quiet unused variable warning */
1413 set_root_privs(int need_root)
1415 #ifndef SINGLE_USERID
1416 static gboolean first_call = TRUE;
1417 static uid_t unpriv = 1;
1420 /* save the original real userid (that of our invoker) */
1423 /* and set all of our userids (including, importantly, the saved
1427 /* don't need to do this next time */
1431 if (need_root == 1) {
1432 if (geteuid() == 0) return 1; /* already done */
1434 if (seteuid(0) == -1) return 0;
1435 /* (we don't switch the group back) */
1436 } else if (need_root == -1) {
1437 /* make sure the euid is 0 so that we can set the uid */
1438 if (geteuid() != 0) {
1439 if (seteuid(0) == -1) return 0;
1442 /* now set the uid to the unprivileged userid */
1443 if (setuid(unpriv) == -1) return 0;
1445 if (geteuid() != 0) return 1; /* already done */
1447 /* set the *effective* userid only */
1448 if (seteuid(unpriv) == -1) return 0;
1449 if (setegid(getgid()) == -1) return 0;
1452 (void)need_root; /* Quiet unused variable warning */
1460 #ifndef SINGLE_USERID
1461 /* first, set the effective userid to 0 */
1462 if (seteuid(0) == -1) return 0;
1464 /* then, set all of the userids to 0 */
1465 if (setuid(0) == -1) return 0;
1471 base64_decode_alloc_string(
1475 size_t in_len = strlen(in);
1476 size_t out_len = 3 * (in_len / 4) + 3;
1478 out = malloc(out_len);
1479 if (!base64_decode(in, in_len, out, &out_len)) {
1483 out[out_len] = '\0';
1489 /* A GHFunc (callback for g_hash_table_foreach),
1490 * Store a property and it's value in an ARGV.
1492 * @param key_p: (char *) property name.
1493 * @param value_p: (GSList *) property values list.
1494 * @param user_data_p: (char ***) pointer to ARGV.
1497 proplist_add_to_argv(
1500 gpointer user_data_p)
1502 char *property_s = key_p;
1503 property_t *value_s = value_p;
1504 GPtrArray *argv_ptr = user_data_p;
1506 char *q, *w, *qprop;
1508 q = stralloc(property_s);
1509 /* convert to lower case */
1510 for (w=q; *w != '\0'; w++) {
1515 qprop = stralloc2("--", q);
1517 for(value=value_s->values; value != NULL; value = value->next) {
1518 g_ptr_array_add(argv_ptr, stralloc(qprop));
1519 g_ptr_array_add(argv_ptr, stralloc((char *)value->data));
1525 property_add_to_argv(
1526 GPtrArray *argv_ptr,
1527 GHashTable *proplist)
1529 g_hash_table_foreach(proplist, &proplist_add_to_argv, argv_ptr);
1534 * Process parameters
1537 static char *pname = NULL;
1538 static char *ptype = NULL;
1539 static pcontext_t pcontext = CONTEXT_DEFAULT;
1544 pname = newstralloc(pname, p);
1550 if (!pname) pname = stralloc("unknown");
1557 ptype = newstralloc(ptype, p);
1563 if (!ptype) ptype = stralloc("unknown");
1568 set_pcontext(pcontext_t pc)
1581 openbsd_fd_inform(void)
1584 for (i = DATA_FD_OFFSET; i < DATA_FD_OFFSET + DATA_FD_COUNT*2; i++) {
1585 /* a simple fcntl() will cause the library to "look" at this file
1586 * descriptor, which is good enough */
1587 (void)fcntl(i, F_GETFL);
1594 GPtrArray *argv_ptr)
1597 char *cmdline = stralloc((char *)g_ptr_array_index(argv_ptr, 0));
1599 for (i = 1; i < argv_ptr->len-1; i++) {
1600 char *arg = g_shell_quote((char *)g_ptr_array_index(argv_ptr, i));
1601 cmdline = vstrextend(&cmdline, " ", arg, NULL);
1604 g_debug("Executing: %s\n", cmdline);