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();
965 g_ptr_array_add(rval, g_strdup(""));
968 GPtrArray *new_components;
972 new_components = parse_braced_component(&source);
973 if (!new_components) {
975 for (i = 0, pdata = rval->pdata; i < rval->len; i++)
977 g_ptr_array_free(rval, TRUE);
981 new_rval = g_ptr_array_new();
983 /* do a cartesian join of rval and new_components */
984 for (i = 0; i < rval->len; i++) {
985 for (j = 0; j < new_components->len; j++) {
986 g_ptr_array_add(new_rval, g_strconcat(
987 g_ptr_array_index(rval, i),
988 g_ptr_array_index(new_components, j),
993 for (i = 0, pdata = rval->pdata; i < rval->len; i++)
995 g_ptr_array_free(rval, TRUE);
996 for (i = 0, pdata = new_components->pdata; i < new_components->len; i++)
998 g_ptr_array_free(new_components, TRUE);
1006 collapse_braced_alternates(
1009 GString *result = NULL;
1012 result = g_string_new("{");
1014 for (i = 0; i < source->len; i ++) {
1015 const char *str = g_ptr_array_index(source, i);
1018 if (strchr(str, ',') || strchr(str, '\\') ||
1019 strchr(str, '{') || strchr(str, '}')) {
1024 qstr = d = g_malloc(strlen(str)*2+1);
1026 if (*s == ',' || *s == '\\' || *s == '{' || *s == '}')
1032 g_string_append_printf(result, "%s%s", qstr? qstr : str,
1033 (i < source->len-1)? "," : "");
1038 g_string_append(result, "}");
1039 return g_string_free(result, FALSE);
1043 Return 0 if the following characters are present
1044 * ( ) < > [ ] , ; : ! $ \ / "
1052 return !match("\\*|<|>|\\(|\\)|\\[|\\]|,|;|:|\\\\|/|\"|\\!|\\$|\\|", mailto);
1066 if ((infd = open(src, O_RDONLY)) == -1) {
1068 quoted = quote_string(src);
1069 *errmsg = vstrallocf(_("Can't open file '%s' for reading: %s"),
1070 quoted, strerror(save_errno));
1075 if ((outfd = open(dst, O_WRONLY|O_CREAT, 0600)) == -1) {
1077 quoted = quote_string(dst);
1078 *errmsg = vstrallocf(_("Can't open file '%s' for writting: %s"),
1079 quoted, strerror(save_errno));
1085 while((nb=read(infd, &buf, SIZEOF(buf))) > 0) {
1086 if(full_write(outfd,&buf,nb) < nb) {
1088 quoted = quote_string(dst);
1089 *errmsg = vstrallocf(_("Error writing to '%s': %s"),
1090 quoted, strerror(save_errno));
1100 quoted = quote_string(src);
1101 *errmsg = vstrallocf(_("Error reading from '%s': %s"),
1102 quoted, strerror(save_errno));
1114 #ifndef HAVE_LIBREADLINE
1116 * simple readline() replacements, used when we don't have readline
1117 * support from the system.
1124 g_printf("%s", prompt);
1127 return agets(stdin);
1134 (void)line; /* Quiet unused parameter warning */
1139 /* Order of preference: readdir64(), readdir(). */
1140 #if HAVE_DECL_READDIR64
1141 # define USE_DIRENT64
1142 # define USE_READDIR64
1143 #elif HAVE_DECL_READDIR
1144 # define USE_READDIR
1146 # error No readdir() or readdir64() available!
1149 #if (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 31))
1150 # pragma GCC diagnostic push
1151 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
1154 char * portable_readdir(DIR* handle) {
1157 struct dirent64 *entry_p;
1159 struct dirent *entry_p;
1162 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1164 g_static_mutex_lock(&mutex);
1167 entry_p = readdir(handle);
1169 #ifdef USE_READDIR64
1170 entry_p = readdir64(handle);
1173 g_static_mutex_unlock(&mutex);
1175 if (entry_p == NULL)
1178 /* FIXME: According to glibc documentation, d_name may not be
1179 null-terminated in some cases on some very old platforms. Not
1180 sure what to do about that case. */
1181 return strdup(entry_p->d_name);
1183 #if (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 31))
1184 # pragma GCC diagnostic pop
1187 int search_directory(DIR * handle, const char * regex,
1188 SearchDirectoryFunctor functor, gpointer user_data) {
1190 regex_t compiled_regex;
1191 gboolean done = FALSE;
1193 if (regcomp(&compiled_regex, regex, REG_EXTENDED | REG_NOSUB) != 0) {
1194 regfree(&compiled_regex);
1203 read_name = portable_readdir(handle);
1204 if (read_name == NULL) {
1205 regfree(&compiled_regex);
1208 result = regexec(&compiled_regex, read_name, 0, NULL, 0);
1211 done = !functor(read_name, user_data);
1215 regfree(&compiled_regex);
1219 char* find_regex_substring(const char* base_string, const regmatch_t match) {
1223 size = match.rm_eo - match.rm_so;
1224 rval = malloc(size+1);
1225 memcpy(rval, base_string + match.rm_so, size);
1231 int compare_possibly_null_strings(const char * a, const char * b) {
1233 /* NULL or otherwise, they're the same. */
1235 } else if (a == NULL) {
1238 } else if (b == NULL) {
1242 /* a != NULL != b */
1243 return strcmp(a, b);
1248 resolve_hostname(const char *hostname,
1250 struct addrinfo **res,
1253 struct addrinfo hints;
1254 struct addrinfo *myres;
1258 if (res) *res = NULL;
1261 flags = AI_CANONNAME;
1264 #ifdef AI_ADDRCONFIG
1265 flags |= AI_ADDRCONFIG;
1268 memset(&hints, 0, sizeof(hints));
1270 /* get any kind of addresss */
1271 hints.ai_family = AF_UNSPEC;
1273 /* even if getaddrinfo supports IPv6, don't let it return
1274 * such an address */
1275 hints.ai_family = AF_INET;
1277 hints.ai_flags = flags;
1278 hints.ai_socktype = socktype;
1279 result = getaddrinfo(hostname, NULL, &hints, &myres);
1284 if (canonname && myres && myres->ai_canonname) {
1285 *canonname = stralloc(myres->ai_canonname);
1291 freeaddrinfo(myres);
1302 if (WIFEXITED(status)) {
1303 int exitstatus = WEXITSTATUS(status);
1304 if (exitstatus == 0)
1305 return vstrallocf(_("%s exited normally"), subject);
1307 return vstrallocf(_("%s exited with status %d"), subject, exitstatus);
1310 if (WIFSIGNALED(status)) {
1311 int signal = WTERMSIG(status);
1313 if (WCOREDUMP(status))
1314 return vstrallocf(_("%s exited after receiving signal %d (core dumped)"),
1318 return vstrallocf(_("%s exited after receiving signal %d"),
1322 if (WIFSTOPPED(status)) {
1323 int signal = WSTOPSIG(status);
1324 return vstrallocf(_("%s stopped temporarily after receiving signal %d"),
1329 if (WIFCONTINUED(status)) {
1330 return vstrallocf(_("%s was resumed"), subject);
1334 return vstrallocf(_("%s exited in unknown circumstances"), subject);
1338 check_running_as(running_as_flags who)
1344 char *uname_me = NULL;
1345 char *uname_target = NULL;
1349 if ((pw = getpwuid(uid_me)) == NULL) {
1350 error(_("current userid %ld not found in password database"), (long)uid_me);
1353 uname_me = stralloc(pw->pw_name);
1355 #ifndef SINGLE_USERID
1356 if (!(who & RUNNING_AS_UID_ONLY) && uid_me != geteuid()) {
1357 error(_("euid (%lld) does not match uid (%lld); is this program setuid-root when it shouldn't be?"),
1358 (long long int)geteuid(), (long long int)uid_me);
1363 switch (who & RUNNING_AS_USER_MASK) {
1364 case RUNNING_AS_ANY:
1365 uid_target = uid_me;
1366 uname_target = uname_me;
1370 case RUNNING_AS_ROOT:
1372 uname_target = "root";
1375 case RUNNING_AS_DUMPUSER_PREFERRED:
1376 dumpuser = getconf_str(CNF_DUMPUSER);
1377 if ((pw = getpwnam(dumpuser)) != NULL &&
1378 uid_me != pw->pw_uid) {
1379 if ((pw = getpwnam(CLIENT_LOGIN)) != NULL &&
1380 uid_me == pw->pw_uid) {
1381 /* uid == CLIENT_LOGIN: not ideal, but OK */
1382 dbprintf(_("NOTE: running as '%s', which is the client"
1383 " user, not the dumpuser ('%s'); forging"
1385 CLIENT_LOGIN, dumpuser);
1386 uid_target = uid_me; /* force success below */
1392 case RUNNING_AS_DUMPUSER:
1393 uname_target = getconf_str(CNF_DUMPUSER);
1394 if ((pw = getpwnam(uname_target)) == NULL) {
1395 error(_("cannot look up dumpuser \"%s\""), uname_target);
1398 uid_target = pw->pw_uid;
1401 case RUNNING_AS_CLIENT_LOGIN:
1402 uname_target = CLIENT_LOGIN;
1403 if ((pw = getpwnam(uname_target)) == NULL) {
1404 error(_("cannot look up client user \"%s\""), uname_target);
1407 uid_target = pw->pw_uid;
1411 error(_("Unknown check_running_as() call"));
1415 if (uid_me != uid_target) {
1416 error(_("running as user \"%s\" instead of \"%s\""), uname_me, uname_target);
1422 /* Quiet unused variable warning */
1428 set_root_privs(int need_root)
1430 #ifndef SINGLE_USERID
1431 static gboolean first_call = TRUE;
1432 static uid_t unpriv = 1;
1435 /* save the original real userid (that of our invoker) */
1438 /* and set all of our userids (including, importantly, the saved
1442 /* don't need to do this next time */
1446 if (need_root == 1) {
1447 if (geteuid() == 0) return 1; /* already done */
1449 if (seteuid(0) == -1) return 0;
1450 /* (we don't switch the group back) */
1451 } else if (need_root == -1) {
1452 /* make sure the euid is 0 so that we can set the uid */
1453 if (geteuid() != 0) {
1454 if (seteuid(0) == -1) return 0;
1457 /* now set the uid to the unprivileged userid */
1458 if (setuid(unpriv) == -1) return 0;
1460 if (geteuid() != 0) return 1; /* already done */
1462 /* set the *effective* userid only */
1463 if (seteuid(unpriv) == -1) return 0;
1464 if (setegid(getgid()) == -1) return 0;
1467 (void)need_root; /* Quiet unused variable warning */
1475 #ifndef SINGLE_USERID
1476 /* first, set the effective userid to 0 */
1477 if (seteuid(0) == -1) return 0;
1479 /* then, set all of the userids to 0 */
1480 if (setuid(0) == -1) return 0;
1486 base64_decode_alloc_string(
1490 size_t in_len = strlen(in);
1491 size_t out_len = 3 * (in_len / 4) + 3;
1493 out = malloc(out_len);
1494 if (!base64_decode(in, in_len, out, &out_len)) {
1498 out[out_len] = '\0';
1504 /* A GHFunc (callback for g_hash_table_foreach),
1505 * Store a property and it's value in an ARGV.
1507 * @param key_p: (char *) property name.
1508 * @param value_p: (GSList *) property values list.
1509 * @param user_data_p: (char ***) pointer to ARGV.
1512 proplist_add_to_argv(
1515 gpointer user_data_p)
1517 char *property_s = key_p;
1518 property_t *value_s = value_p;
1519 GPtrArray *argv_ptr = user_data_p;
1521 char *q, *w, *qprop;
1523 q = stralloc(property_s);
1524 /* convert to lower case */
1525 for (w=q; *w != '\0'; w++) {
1530 qprop = stralloc2("--", q);
1532 for(value=value_s->values; value != NULL; value = value->next) {
1533 g_ptr_array_add(argv_ptr, stralloc(qprop));
1534 g_ptr_array_add(argv_ptr, stralloc((char *)value->data));
1540 property_add_to_argv(
1541 GPtrArray *argv_ptr,
1542 GHashTable *proplist)
1544 g_hash_table_foreach(proplist, &proplist_add_to_argv, argv_ptr);
1549 * Process parameters
1552 static char *pname = NULL;
1553 static char *ptype = NULL;
1554 static pcontext_t pcontext = CONTEXT_DEFAULT;
1559 pname = newstralloc(pname, p);
1565 if (!pname) pname = stralloc("unknown");
1572 ptype = newstralloc(ptype, p);
1578 if (!ptype) ptype = stralloc("unknown");
1583 set_pcontext(pcontext_t pc)
1596 openbsd_fd_inform(void)
1599 for (i = DATA_FD_OFFSET; i < DATA_FD_OFFSET + DATA_FD_COUNT*2; i++) {
1600 /* a simple fcntl() will cause the library to "look" at this file
1601 * descriptor, which is good enough */
1602 (void)fcntl(i, F_GETFL);
1609 GPtrArray *argv_ptr)
1612 char *cmdline = stralloc((char *)g_ptr_array_index(argv_ptr, 0));
1614 for (i = 1; i < argv_ptr->len-1; i++) {
1615 char *arg = g_shell_quote((char *)g_ptr_array_index(argv_ptr, i));
1616 cmdline = vstrextend(&cmdline, " ", arg, NULL);
1619 g_debug("Executing: %s\n", cmdline);
1625 GPtrArray *argv_ptr)
1627 char *output_string = NULL;
1628 int inpipe[2], outpipe[2], errpipe[2];
1632 assert(argv_ptr != NULL);
1633 assert(argv_ptr->pdata != NULL);
1634 assert(argv_ptr->len >= 1);
1636 if (pipe(inpipe) == -1) {
1637 error(_("error [open pipe: %s]"), strerror(errno));
1640 if (pipe(outpipe) == -1) {
1641 error(_("error [open pipe: %s]"), strerror(errno));
1644 if (pipe(errpipe) == -1) {
1645 error(_("error [open pipe: %s]"), strerror(errno));
1650 switch(pid = fork()) {
1652 error(_("error [fork: %s]"), strerror(errno));
1655 default: /* parent process */
1661 case 0: /* child process */
1667 dup2(outpipe[1], 1);
1668 dup2(errpipe[1], 2);
1670 debug_executing(argv_ptr);
1671 g_fprintf(stdout, "unknown\n");
1672 execv((char *)*argv_ptr->pdata, (char **)argv_ptr->pdata);
1673 error(_("error [exec %s: %s]"), (char *)*argv_ptr->pdata, strerror(errno));
1678 out = fdopen(outpipe[0],"r");
1679 err = fdopen(errpipe[0],"r");
1681 output_string = agets(out);
1683 output_string = agets(err);
1688 waitpid(pid, NULL, 0);
1690 return output_string;