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.h,v 1.17 2006/07/26 15:17:36 martinea Exp $
36 #include <glib-object.h>
39 #include "glib-util.h"
41 #define BIGINT INT_MAX
43 #define BSTRNCMP(a,b) strncmp(a, b, strlen(b))
45 /* internal types and variables */
47 /* Function to get the GQuark for errors,
48 * with error codes specified by AmUtilError
50 * @return The GQuark that's used for errors
52 GQuark am_util_error_quark(void);
54 /* Error codes that may be returned by these functions */
56 AM_UTIL_ERROR_HEXDECODEINVAL,
60 int connect_portrange(sockaddr_union *, in_port_t, in_port_t, char *,
61 sockaddr_union *, int);
62 int bind_portrange(int, sockaddr_union *, in_port_t, in_port_t,
65 /* just like an accept() call, but periodically calling PROLONG(PROLONG_DATA) and
66 * returning -1 with errno set to 0 if PROLONG returns false. Note that the socket
67 * need not be configured as non-blocking.
69 * Other arguments are just like for accept(2).
71 int interruptible_accept(int sock, struct sockaddr *addr, socklen_t *addrlen,
72 gboolean (*prolong)(gpointer data), gpointer prolong_data);
74 ssize_t full_writev(int, struct iovec *, int);
76 char * construct_datestamp(time_t *t);
77 char * construct_timestamp(time_t *t);
79 /* quote_string only adds "" if they're required; quote_string_always
80 * always adds "" around the string */
81 #define quote_string(str) quote_string_maybe((str), 0)
82 #define quote_string_always(str) quote_string_maybe((str), 1)
84 /*@only@*//*@null@*/char *quote_string_maybe(const char *str, gboolean always);
85 /*@only@*//*@null@*/char *unquote_string(const char *str);
87 /* Split a string into space-delimited words, obeying quoting as created by
88 * quote_string. To keep compatibility with the old split(), this has the
89 * characteristic that multiple consecutive spaces are not collapsed into
90 * a single space: "x y" parses as [ "x", "", "y", NULL ]. The strings are
91 * unquoted before they are returned, unlike split(). An empty string is
92 * split into [ "", NULL ].
94 * Returns a NULL-terminated array of strings, which should be freed with
97 gchar ** split_quoted_strings(const gchar *string);
99 /* Like strtok_r, but consider a quoted string to be a single token. Caller
100 * must begin parsing with strtok_r first, then pass the saveptr to this function.
102 * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
104 char * strquotedstr(char **saveptr);
106 char * sanitize_string(const char *str);
108 /* Encode a string using URI-style hexadecimal encoding.
109 * Non-alphanumeric characters will be replaced with "%xx"
110 * where "xx" is the two-digit hexadecimal representation of the character.
112 * @param str The string to encode
114 * @return The encoded string. An empty string will be returned for NULL.
116 char * hexencode_string(const char *str);
118 /* Decode a string using URI-style hexadecimal encoding.
120 * @param str The string to decode
121 * @param err return location for a GError
123 * @return The decoded string. An empty string will be returned for NULL
124 * or if an error occurs.
126 char * hexdecode_string(const char *str, GError **err);
128 int copy_file(char *dst, char *src, char **errmsg);
130 /* These two functions handle "braced alternates", which is a syntax borrowed,
131 * partially, from shells. See perl/Amanda/Util.pod for a full description of
132 * the syntax they support.
134 GPtrArray * expand_braced_alternates(char * source);
135 char * collapse_braced_alternates(GPtrArray *source);
138 * validate_email return 0 if the following characters are present
139 * * ( ) < > [ ] , ; : ! $ \ / "
142 int validate_mailto(const char *mailto);
144 /* This function is a portable reimplementation of readdir(). It
145 * returns a newly-allocated string, that should be freed with
146 * free(). Returns NULL on error or end of directory.
147 * It is reentrant, with the following exceptions:
148 * - This function cannot be run at the same time as readdir() or
150 * - This function cannot be run simultaneously on the same directory
152 char * portable_readdir(DIR*);
154 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
156 /* This function will search the given directory handle for files
157 matching the given POSIX extended regular expression.
158 For each matching file, the functor will be called with the given
159 user data. Stops when the functor returns FALSE, or all files have
160 been searched. Returns the number of matching files. */
161 int search_directory(DIR * handle, const char * regex,
162 SearchDirectoryFunctor functor, gpointer user_data);
164 /* This function extracts a substring match from a regular expression
165 match result, and copies it into a newly allocated string. Example
166 usage to get the first matched substring:
167 substring = find_regmatch(whole_string, pmatch[1])
168 Note that pmatch[0] yields the entire matching portion of the string. */
169 char* find_regex_substring(const char* base_string, const regmatch_t match);
171 void free_new_argv(int new_argc, char **new_argv);
173 /* Like strcmp(a, b), except that NULL strings are sorted before non-NULL
174 * strings, instead of segfaulting. */
175 int compare_possibly_null_strings(const char * a, const char * b);
177 /* Given a hostname, call getaddrinfo to resolve it. Optionally get the
178 * entire set of results (if res is not NULL) and the canonical name of
179 * the host (if canonname is not NULL). The canonical name might
180 * expand e.g., www.domain.com to server3.webfarm.hosting.com.
182 * If not NULL, the caller is responsible for freeing res with freeaddrinfo().
183 * Similarly, the caller is responsible for freeing canonname if it is
186 * @param hostname: the hostname to start with
187 * @param socktype: the socket type (SOCK_DGRAM or SOCK_STREAM)
188 * @param res: (result) if not NULL, the results from getaddrinfo()
189 * @param canonname: (result) if not NULL, the newly-allocated canonical name of the host
190 * @returns: 0 on success, otherwise a getaddrinfo result (for use with gai_strerror)
192 int resolve_hostname(const char *hostname, int socktype,
193 struct addrinfo **res, char **canonname);
195 /* Interpret a status (as returned from wait() and friends)
196 * into a human-readable sentence.
198 * Caller is responsible for freeing the resulting string.
199 * The resulting string has already been translated.
201 * The macro definition allows this to work even when amwait_t
202 * is 'union wait' (4.3BSD). The cast is safe because the two
203 * argument types are interchangeable.
205 * @param subject: subject of the sentence (program name, etc.)
206 * @param status: the exit status
207 * @returns: newly allocated string describing status
209 #define str_exit_status(subject, status) \
210 _str_exit_status((subject), *(amwait_t *)&(status))
211 char *_str_exit_status(char *subject, amwait_t status);
214 * Userid manipulation
217 /* Check that the current uid and euid are set to a specific user,
218 * calling error() if not. Does nothing if CHECK_USERID is not
221 * @param who: one of the RUNNING_AS_* constants, below.
230 /* userid belongs to dumpuser (from config) */
233 /* prefer that userid belongs to dumpuser, but accept when userid belongs to
234 * CLIENT_LOGIN with a debug-log message (needed because amandad always runs
235 * as CLIENT_LOGIN, even on server) */
236 RUNNING_AS_DUMPUSER_PREFERRED,
238 /* userid belongs to CLIENT_LOGIN (from --with-user) */
239 RUNNING_AS_CLIENT_LOGIN,
241 RUNNING_AS_USER_MASK = (1 << 8) - 1,
242 /* '|' this on to only check the uid, not the euid; use this for programs
243 * that will call become_root() */
244 RUNNING_AS_UID_ONLY = 1 << 8
247 void check_running_as(running_as_flags who);
249 /* Drop and regain root priviledges; used from setuid-root binaries which only
250 * need to be root for certain operations. Does nothing if SINGLE_USERID is
253 * @param need_root: if 1, try to assume root priviledges; otherwise, drop
254 * priviledges. If -1, drop them irreversibly.
255 * @returns: true if the priviledge change succeeded
257 int set_root_privs(int need_root);
259 /* Become root completely, by setting the uid to 0. This is used by setuid-root
260 * apps which will exec subprocesses which will also need root priviledges. Does
261 * nothing if SINGLE_USERID is defined.
263 * @returns: true if the priviledge change succeeded
265 int become_root(void);
271 /* The 'context' of a process gives a general description of how it is
272 * used. This affects log output, among other things.
275 /* default context (logging to stderr, etc. -- not pretty) */
278 /* user-interfacing command-line utility like amadmin */
281 /* daemon like amandad or sendbackup */
284 /* a utility used from shell scripts, and thus probably invoked
289 /* Set the name of the process. The parameter is copied, and remains
290 * the responsibility of the caller on return. This value is used in log
291 * messages and other output throughout Amanda.
293 * @param pname: the new process name
295 void set_pname(char *pname);
297 /* Get the current process name; the result is in a static buffer, and
298 * should *not* be free()d by the caller.
300 * @returns: process name
302 char *get_pname(void);
304 /* Set the type of the process. The parameter is copied, and remains
305 * the responsibility of the caller on return. This value dictates the
306 * directory in which debug logs are stored.
308 * @param pname: the new process type
310 void set_ptype(char *ptype);
312 /* Get the current process name; the result is in a static buffer, and
313 * should *not* be free()d by the caller.
315 * @returns: process name
317 char *get_ptype(void);
319 /* Set the process's context
321 * @param context: the new context
323 void set_pcontext(pcontext_t context);
325 /* Get the process's context
327 * @returns: the context
329 pcontext_t get_pcontext(void);
334 * This either includes the system readline header we found in configure,
335 * or prototypes some simple stub functions that are used instead.
339 # ifdef HAVE_READLINE_READLINE_H
340 # include <readline/readline.h>
341 # ifdef HAVE_READLINE_HISTORY_H
342 # include <readline/history.h>
345 # ifdef HAVE_READLINE_H
346 # include <readline.h>
347 # ifdef HAVE_HISTORY_H
348 # include <history.h>
354 char * readline(const char *prompt);
355 void add_history(const char *line);
359 char *base64_decode_alloc_string(char *);
361 /* Inform the OpenBSD pthread library about the high-numbered file descriptors
362 * that an amandad service inherits. This won't be necessary once the new
363 * threading library is availble (OpenBSD 5.0?), but won't hurt anyway. See the
364 * thread "Backup issues with OpenBSD 4.5 machines" from September 2009. */
366 void openbsd_fd_inform(void);
368 #define openbsd_fd_inform()
371 /* Add all properties to an ARGV
373 * @param argvchild: Pointer to the ARGV.
374 * @param proplist: The property list
376 void property_add_to_argv(GPtrArray *argv_ptr, GHashTable *proplist);
378 /* Print the argv_ptr with g_debug()
380 * @param argv_ptr: GPtrArray of an array to print.
382 void debug_executing(GPtrArray *argv_ptr);