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("\"\"");
441 } else if (!always && (match("[:\'\\\"[:space:][:cntrl:]]", str)) == 0) {
443 * String does not need to be quoted since it contains
444 * neither whitespace, control or quote characters.
449 * Allocate maximum possible string length.
450 * (a string of all quotes plus room for leading ", trailing " and NULL)
452 ret = s = alloc((strlen(str) * 2) + 2 + 1);
454 while (*str != '\0') {
460 } else if (*str == '\n') {
465 } else if (*str == '\r') {
470 } else if (*str == '\f') {
475 } else if (*str == '\\') {
498 if ((str == NULL) || (*str == '\0')) {
504 ret = in = out = stralloc(str);
505 while (*in != '\0') {
517 } else if (*in == 't') {
521 } else if (*in == 'r') {
525 } else if (*in == 'f') {
529 } else if (*in >= '0' && *in <= '7') {
533 while (i < 3 && *in >= '0' && *in <= '7') {
534 c = (c << 3) + *(in++) - '0';
539 } else if (*in == '\0') {
540 /* trailing backslash -- ignore */
552 split_quoted_strings(
565 p = start = local = g_strdup(string);
566 strs = g_ptr_array_new();
569 if (!iq && *p == ' ') {
571 g_ptr_array_add(strs, unquote_string(start));
573 } else if (*p == '\\') {
574 /* next character is taken literally; if it's a multicharacter
575 * escape (e.g., \171), that doesn't bother us here */
578 } else if (*p == '\"') {
585 g_ptr_array_add(strs, unquote_string(start));
587 /* now convert strs into a strv, by stealing its references to the underlying
589 result = g_new0(char *, strs->len + 1);
590 memmove(result, strs->pdata, sizeof(char *) * strs->len);
592 g_ptr_array_free(strs, TRUE); /* TRUE => free pdata, strings are not freed */
599 strquotedstr(char **saveptr)
601 char * tok = strtok_r(NULL, " ", saveptr);
613 while (in_quote || in_backslash || *p != '\0') {
615 /* append a new token */
616 t = strtok_r(NULL, " ", saveptr);
624 in_quote = !in_quote;
625 else if (*p == '\\') {
643 if ((str == NULL) || (*str == '\0')) {
647 for (s = ret; *s != '\0'; s++) {
648 if (iscntrl((int)*s))
655 char *hexencode_string(const char *str)
657 size_t orig_len, new_len, i;
661 s = g_string_sized_new(0);
664 new_len = orig_len = strlen(str);
665 for (i = 0; i < orig_len; i++) {
666 if (!g_ascii_isalnum(str[i])) {
670 s = g_string_sized_new(new_len);
672 for (i = 0; i < orig_len; i++) {
673 if (g_ascii_isalnum(str[i])) {
674 g_string_append_c(s, str[i]);
676 g_string_append_printf(s, "%%%02hhx", str[i]);
682 g_string_free(s, FALSE);
686 char *hexdecode_string(const char *str, GError **err)
688 size_t orig_len, new_len, i;
692 s = g_string_sized_new(0);
695 new_len = orig_len = strlen(str);
696 for (i = 0; i < orig_len; i++) {
701 s = g_string_sized_new(new_len);
703 for (i = 0; (orig_len > 2) && (i < orig_len-2); i++) {
707 for (j = 1; j < 3; j++) {
709 if (str[i+j] >= '0' && str[i+j] <= '9') {
710 tmp += str[i+j] - '0';
711 } else if (str[i+j] >= 'a' && str[i+j] <= 'f') {
712 tmp += str[i+j] - 'a' + 10;
713 } else if (str[i+j] >= 'A' && str[i+j] <= 'F') {
714 tmp += str[i+j] - 'A' + 10;
717 g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL,
718 "Illegal character (non-hex) 0x%02hhx at offset %zd", str[i+j], i+j);
719 g_string_truncate(s, 0);
724 g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL,
725 "Encoded NULL at starting offset %zd", i);
726 g_string_truncate(s, 0);
729 g_string_append_c(s, tmp);
732 g_string_append_c(s, str[i]);
735 for ( /*nothing*/; i < orig_len; i++) {
737 g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL,
738 "'%%' found at offset %zd, but fewer than two characters follow it (%zd)", i, orig_len-i-1);
739 g_string_truncate(s, 0);
742 g_string_append_c(s, str[i]);
748 g_string_free(s, FALSE);
752 /* Helper for parse_braced_component; this will turn a single element array
753 * matching /^\d+\.\.\d+$/ into a sequence of numbered array elements. */
755 expand_braced_sequence(GPtrArray *arr)
759 int ldigits, rdigits, ndigits;
761 gboolean leading_zero;
763 /* check whether the element matches the pattern */
764 /* expand last element of the array only */
765 elt = g_ptr_array_index(arr, arr->len-1);
767 for (l = p = elt; *p && g_ascii_isdigit(*p); p++)
776 for (r = p; *p && g_ascii_isdigit(*p); p++)
783 /* we have a match, so extract start and end */
784 start = g_ascii_strtoull(l, NULL, 10);
785 end = g_ascii_strtoull(r, NULL, 10);
786 leading_zero = *l == '0';
787 ndigits = MAX(ldigits, rdigits);
792 if (end - start > 100000)
795 /* remove last from the array */
796 g_ptr_array_remove_index(arr, arr->len - 1);
798 /* Add new elements */
799 while (start <= end) {
801 g_ptr_array_add(arr, g_strdup_printf("%0*ju",
802 ndigits, (uintmax_t)start));
804 g_ptr_array_add(arr, g_strdup_printf("%ju", (uintmax_t)start));
812 /* Helper for expand_braced_alternates; returns a list of un-escaped strings
813 * for the first "component" of str, where a component is a plain string or a
814 * brace-enclosed set of alternatives. str is pointing to the first character
815 * of the next component on return. */
817 parse_braced_component(char **str)
819 GPtrArray *result = g_ptr_array_new();
823 char *local = g_malloc(strlen(*str)+1);
824 char *current = local;
828 if (*p == '\0' || *p == '{') {
829 /* unterminated { .. } or extra '{' */
831 g_ptr_array_free(result, TRUE);
835 if (*p == '}' || *p == ',') {
837 g_ptr_array_add(result, g_strdup(current));
838 result = expand_braced_sequence(result);
848 if (*(p+1) == '{' || *(p+1) == '}' || *(p+1) == '\\' || *(p+1) == ',')
861 /* no braces -- just un-escape a plain string */
862 char *local = g_malloc(strlen(*str)+1);
866 while (*p && *p != '{') {
868 if (*(p+1) == '{' || *(p+1) == '}' || *(p+1) == '\\' || *(p+1) == ',')
874 g_ptr_array_add(result, local);
882 expand_braced_alternates(
885 GPtrArray *rval = g_ptr_array_new();
887 g_ptr_array_add(rval, g_strdup(""));
890 GPtrArray *new_components;
894 new_components = parse_braced_component(&source);
895 if (!new_components) {
897 g_ptr_array_free(rval, TRUE);
901 new_rval = g_ptr_array_new();
903 /* do a cartesian join of rval and new_components */
904 for (i = 0; i < rval->len; i++) {
905 for (j = 0; j < new_components->len; j++) {
906 g_ptr_array_add(new_rval, g_strconcat(
907 g_ptr_array_index(rval, i),
908 g_ptr_array_index(new_components, j),
913 g_ptr_array_free(rval, TRUE);
914 g_ptr_array_free(new_components, TRUE);
922 collapse_braced_alternates(
925 GString *result = NULL;
928 result = g_string_new("{");
930 for (i = 0; i < source->len; i ++) {
931 const char *str = g_ptr_array_index(source, i);
934 if (strchr(str, ',') || strchr(str, '\\') ||
935 strchr(str, '{') || strchr(str, '}')) {
940 qstr = d = g_malloc(strlen(str)*2+1);
942 if (*s == ',' || *s == '\\' || *s == '{' || *s == '}')
948 g_string_append_printf(result, "%s%s", qstr? qstr : str,
949 (i < source->len-1)? "," : "");
954 g_string_append(result, "}");
955 return g_string_free(result, FALSE);
959 Return 0 if the following characters are present
960 * ( ) < > [ ] , ; : ! $ \ / "
968 return !match("\\*|<|>|\\(|\\)|\\[|\\]|,|;|:|\\\\|/|\"|\\!|\\$|\\|", mailto);
982 if ((infd = open(src, O_RDONLY)) == -1) {
984 quoted = quote_string(src);
985 *errmsg = vstrallocf(_("Can't open file '%s' for reading: %s"),
986 quoted, strerror(save_errno));
991 if ((outfd = open(dst, O_WRONLY|O_CREAT, 0600)) == -1) {
993 quoted = quote_string(dst);
994 *errmsg = vstrallocf(_("Can't open file '%s' for writting: %s"),
995 quoted, strerror(save_errno));
1001 while((nb=read(infd, &buf, SIZEOF(buf))) > 0) {
1002 if(full_write(outfd,&buf,nb) < nb) {
1004 quoted = quote_string(dst);
1005 *errmsg = vstrallocf(_("Error writing to '%s': %s"),
1006 quoted, strerror(save_errno));
1016 quoted = quote_string(src);
1017 *errmsg = vstrallocf(_("Error reading from '%s': %s"),
1018 quoted, strerror(save_errno));
1030 #ifndef HAVE_READLINE
1032 * simple readline() replacements, used when we don't have readline
1033 * support from the system.
1040 g_printf("%s", prompt);
1043 return agets(stdin);
1050 (void)line; /* Quiet unused parameter warning */
1055 /* Order of preference: readdir64(), readdir(). */
1056 #if HAVE_DECL_READDIR64
1057 # define USE_DIRENT64
1058 # define USE_READDIR64
1059 #elif HAVE_DECL_READDIR
1060 # define USE_READDIR
1062 # error No readdir() or readdir64() available!
1065 char * portable_readdir(DIR* handle) {
1068 struct dirent64 *entry_p;
1070 struct dirent *entry_p;
1073 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1075 g_static_mutex_lock(&mutex);
1078 entry_p = readdir(handle);
1080 #ifdef USE_READDIR64
1081 entry_p = readdir64(handle);
1084 g_static_mutex_unlock(&mutex);
1086 if (entry_p == NULL)
1089 /* FIXME: According to glibc documentation, d_name may not be
1090 null-terminated in some cases on some very old platforms. Not
1091 sure what to do about that case. */
1092 return strdup(entry_p->d_name);
1095 int search_directory(DIR * handle, const char * regex,
1096 SearchDirectoryFunctor functor, gpointer user_data) {
1098 regex_t compiled_regex;
1099 gboolean done = FALSE;
1101 if (regcomp(&compiled_regex, regex, REG_EXTENDED | REG_NOSUB) != 0) {
1102 regfree(&compiled_regex);
1111 read_name = portable_readdir(handle);
1112 if (read_name == NULL) {
1113 regfree(&compiled_regex);
1116 result = regexec(&compiled_regex, read_name, 0, NULL, 0);
1119 done = !functor(read_name, user_data);
1123 regfree(&compiled_regex);
1127 char* find_regex_substring(const char* base_string, const regmatch_t match) {
1131 size = match.rm_eo - match.rm_so;
1132 rval = malloc(size+1);
1133 memcpy(rval, base_string + match.rm_so, size);
1139 int compare_possibly_null_strings(const char * a, const char * b) {
1141 /* NULL or otherwise, they're the same. */
1143 } else if (a == NULL) {
1146 } else if (b == NULL) {
1150 /* a != NULL != b */
1151 return strcmp(a, b);
1156 resolve_hostname(const char *hostname,
1158 struct addrinfo **res,
1161 struct addrinfo hints;
1162 struct addrinfo *myres;
1166 if (res) *res = NULL;
1169 flags = AI_CANONNAME;
1172 #ifdef AI_ADDRCONFIG
1173 flags |= AI_ADDRCONFIG;
1176 memset(&hints, 0, sizeof(hints));
1178 /* get any kind of addresss */
1179 hints.ai_family = AF_UNSPEC;
1181 /* even if getaddrinfo supports IPv6, don't let it return
1182 * such an address */
1183 hints.ai_family = AF_INET;
1185 hints.ai_flags = flags;
1186 hints.ai_socktype = socktype;
1187 result = getaddrinfo(hostname, NULL, &hints, &myres);
1192 if (canonname && myres && myres->ai_canonname) {
1193 *canonname = stralloc(myres->ai_canonname);
1199 freeaddrinfo(myres);
1210 if (WIFEXITED(status)) {
1211 int exitstatus = WEXITSTATUS(status);
1212 if (exitstatus == 0)
1213 return vstrallocf(_("%s exited normally"), subject);
1215 return vstrallocf(_("%s exited with status %d"), subject, exitstatus);
1218 if (WIFSIGNALED(status)) {
1219 int signal = WTERMSIG(status);
1221 if (WCOREDUMP(status))
1222 return vstrallocf(_("%s exited after receiving signal %d (core dumped)"),
1226 return vstrallocf(_("%s exited after receiving signal %d"),
1230 if (WIFSTOPPED(status)) {
1231 int signal = WSTOPSIG(status);
1232 return vstrallocf(_("%s stopped temporarily after receiving signal %d"),
1237 if (WIFCONTINUED(status)) {
1238 return vstrallocf(_("%s was resumed"), subject);
1242 return vstrallocf(_("%s exited in unknown circumstances"), subject);
1246 check_running_as(running_as_flags who)
1252 char *uname_me = NULL;
1253 char *uname_target = NULL;
1257 if ((pw = getpwuid(uid_me)) == NULL) {
1258 error(_("current userid %ld not found in password database"), (long)uid_me);
1261 uname_me = stralloc(pw->pw_name);
1263 #ifndef SINGLE_USERID
1264 if (!(who & RUNNING_AS_UID_ONLY) && uid_me != geteuid()) {
1265 error(_("euid (%lld) does not match uid (%lld); is this program setuid-root when it shouldn't be?"),
1266 (long long int)geteuid(), (long long int)uid_me);
1271 switch (who & RUNNING_AS_USER_MASK) {
1272 case RUNNING_AS_ANY:
1273 uid_target = uid_me;
1274 uname_target = uname_me;
1278 case RUNNING_AS_ROOT:
1280 uname_target = "root";
1283 case RUNNING_AS_DUMPUSER_PREFERRED:
1284 dumpuser = getconf_str(CNF_DUMPUSER);
1285 if ((pw = getpwnam(dumpuser)) != NULL &&
1286 uid_me != pw->pw_uid) {
1287 if ((pw = getpwnam(CLIENT_LOGIN)) != NULL &&
1288 uid_me == pw->pw_uid) {
1289 /* uid == CLIENT_LOGIN: not ideal, but OK */
1290 dbprintf(_("NOTE: running as '%s', which is the client"
1291 " user, not the dumpuser ('%s'); forging"
1293 CLIENT_LOGIN, dumpuser);
1294 uid_target = uid_me; /* force success below */
1300 case RUNNING_AS_DUMPUSER:
1301 uname_target = getconf_str(CNF_DUMPUSER);
1302 if ((pw = getpwnam(uname_target)) == NULL) {
1303 error(_("cannot look up dumpuser \"%s\""), uname_target);
1306 uid_target = pw->pw_uid;
1309 case RUNNING_AS_CLIENT_LOGIN:
1310 uname_target = CLIENT_LOGIN;
1311 if ((pw = getpwnam(uname_target)) == NULL) {
1312 error(_("cannot look up client user \"%s\""), uname_target);
1315 uid_target = pw->pw_uid;
1319 error(_("Unknown check_running_as() call"));
1323 if (uid_me != uid_target) {
1324 error(_("running as user \"%s\" instead of \"%s\""), uname_me, uname_target);
1330 /* Quiet unused variable warning */
1336 set_root_privs(int need_root)
1338 #ifndef SINGLE_USERID
1339 static gboolean first_call = TRUE;
1340 static uid_t unpriv = 1;
1343 /* save the original real userid (that of our invoker) */
1346 /* and set all of our userids (including, importantly, the saved
1350 /* don't need to do this next time */
1354 if (need_root == 1) {
1355 if (geteuid() == 0) return 1; /* already done */
1357 if (seteuid(0) == -1) return 0;
1358 /* (we don't switch the group back) */
1359 } else if (need_root == -1) {
1360 /* make sure the euid is 0 so that we can set the uid */
1361 if (geteuid() != 0) {
1362 if (seteuid(0) == -1) return 0;
1365 /* now set the uid to the unprivileged userid */
1366 if (setuid(unpriv) == -1) return 0;
1368 if (geteuid() != 0) return 1; /* already done */
1370 /* set the *effective* userid only */
1371 if (seteuid(unpriv) == -1) return 0;
1372 if (setegid(getgid()) == -1) return 0;
1375 (void)need_root; /* Quiet unused variable warning */
1383 #ifndef SINGLE_USERID
1384 /* first, set the effective userid to 0 */
1385 if (seteuid(0) == -1) return 0;
1387 /* then, set all of the userids to 0 */
1388 if (setuid(0) == -1) return 0;
1394 base64_decode_alloc_string(
1398 size_t in_len = strlen(in);
1399 size_t out_len = 3 * (in_len / 4) + 3;
1401 out = malloc(out_len);
1402 if (!base64_decode(in, in_len, out, &out_len)) {
1406 out[out_len] = '\0';
1412 /* A GHFunc (callback for g_hash_table_foreach),
1413 * Store a property and it's value in an ARGV.
1415 * @param key_p: (char *) property name.
1416 * @param value_p: (GSList *) property values list.
1417 * @param user_data_p: (char ***) pointer to ARGV.
1420 proplist_add_to_argv(
1423 gpointer user_data_p)
1425 char *property_s = key_p;
1426 property_t *value_s = value_p;
1427 GPtrArray *argv_ptr = user_data_p;
1429 char *q, *w, *qprop;
1431 q = stralloc(property_s);
1432 /* convert to lower case */
1433 for (w=q; *w != '\0'; w++) {
1438 qprop = stralloc2("--", q);
1440 for(value=value_s->values; value != NULL; value = value->next) {
1441 g_ptr_array_add(argv_ptr, stralloc(qprop));
1442 g_ptr_array_add(argv_ptr, stralloc((char *)value->data));
1448 property_add_to_argv(
1449 GPtrArray *argv_ptr,
1450 GHashTable *proplist)
1452 g_hash_table_foreach(proplist, &proplist_add_to_argv, argv_ptr);
1457 * Process parameters
1460 static char *pname = NULL;
1461 static char *ptype = NULL;
1462 static pcontext_t pcontext = CONTEXT_DEFAULT;
1467 pname = newstralloc(pname, p);
1473 if (!pname) pname = stralloc("unknown");
1480 ptype = newstralloc(ptype, p);
1486 if (!ptype) ptype = stralloc("unknown");
1491 set_pcontext(pcontext_t pc)
1504 openbsd_fd_inform(void)
1507 for (i = DATA_FD_OFFSET; i < DATA_FD_OFFSET + DATA_FD_COUNT*2; i++) {
1508 /* a simple fcntl() will cause the library to "look" at this file
1509 * descriptor, which is good enough */
1510 (void)fcntl(i, F_GETFL);
1517 GPtrArray *argv_ptr)
1520 char *cmdline = stralloc((char *)g_ptr_array_index(argv_ptr, 0));
1522 for (i = 1; i < argv_ptr->len-1; i++) {
1523 char *arg = g_shell_quote((char *)g_ptr_array_index(argv_ptr, i));
1524 cmdline = vstrextend(&cmdline, " ", arg, NULL);
1527 g_debug("Executing: %s\n", cmdline);