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)
83 #define len_quote_string(str) len_quote_string_maybe((str), 0);
85 /*@only@*//*@null@*/char *quote_string_maybe(const char *str, gboolean always);
86 /*@only@*//*@null@*/char *unquote_string(const char *str);
87 /*@only@*//*@null@*/int len_quote_string_maybe(const char *str, gboolean always);
89 /* Split a string into space-delimited words, obeying quoting as created by
90 * quote_string. To keep compatibility with the old split(), this has the
91 * characteristic that multiple consecutive spaces are not collapsed into
92 * a single space: "x y" parses as [ "x", "", "y", NULL ]. The strings are
93 * unquoted before they are returned, unlike split(). An empty string is
94 * split into [ "", NULL ].
96 * Returns a NULL-terminated array of strings, which should be freed with
99 gchar ** split_quoted_strings(const gchar *string);
101 /* Like strtok_r, but consider a quoted string to be a single token. Caller
102 * must begin parsing with strtok_r first, then pass the saveptr to this function.
104 * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
106 char * strquotedstr(char **saveptr);
108 char * sanitize_string(const char *str);
110 /* Encode a string using URI-style hexadecimal encoding.
111 * Non-alphanumeric characters will be replaced with "%xx"
112 * where "xx" is the two-digit hexadecimal representation of the character.
114 * @param str The string to encode
116 * @return The encoded string. An empty string will be returned for NULL.
118 char * hexencode_string(const char *str);
120 /* Decode a string using URI-style hexadecimal encoding.
122 * @param str The string to decode
123 * @param err return location for a GError
125 * @return The decoded string. An empty string will be returned for NULL
126 * or if an error occurs.
128 char * hexdecode_string(const char *str, GError **err);
130 int copy_file(char *dst, char *src, char **errmsg);
132 /* These two functions handle "braced alternates", which is a syntax borrowed,
133 * partially, from shells. See perl/Amanda/Util.pod for a full description of
134 * the syntax they support.
136 GPtrArray * expand_braced_alternates(char * source);
137 char * collapse_braced_alternates(GPtrArray *source);
140 * validate_email return 0 if the following characters are present
141 * * ( ) < > [ ] , ; : ! $ \ / "
144 int validate_mailto(const char *mailto);
146 /* This function is a portable reimplementation of readdir(). It
147 * returns a newly-allocated string, that should be freed with
148 * free(). Returns NULL on error or end of directory.
149 * It is reentrant, with the following exceptions:
150 * - This function cannot be run at the same time as readdir() or
152 * - This function cannot be run simultaneously on the same directory
154 char * portable_readdir(DIR*);
156 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
158 /* This function will search the given directory handle for files
159 matching the given POSIX extended regular expression.
160 For each matching file, the functor will be called with the given
161 user data. Stops when the functor returns FALSE, or all files have
162 been searched. Returns the number of matching files. */
163 int search_directory(DIR * handle, const char * regex,
164 SearchDirectoryFunctor functor, gpointer user_data);
166 /* This function extracts a substring match from a regular expression
167 match result, and copies it into a newly allocated string. Example
168 usage to get the first matched substring:
169 substring = find_regmatch(whole_string, pmatch[1])
170 Note that pmatch[0] yields the entire matching portion of the string. */
171 char* find_regex_substring(const char* base_string, const regmatch_t match);
173 void free_new_argv(int new_argc, char **new_argv);
175 /* Like strcmp(a, b), except that NULL strings are sorted before non-NULL
176 * strings, instead of segfaulting. */
177 int compare_possibly_null_strings(const char * a, const char * b);
179 /* Given a hostname, call getaddrinfo to resolve it. Optionally get the
180 * entire set of results (if res is not NULL) and the canonical name of
181 * the host (if canonname is not NULL). The canonical name might
182 * expand e.g., www.domain.com to server3.webfarm.hosting.com.
184 * If not NULL, the caller is responsible for freeing res with freeaddrinfo().
185 * Similarly, the caller is responsible for freeing canonname if it is
188 * @param hostname: the hostname to start with
189 * @param socktype: the socket type (SOCK_DGRAM or SOCK_STREAM)
190 * @param res: (result) if not NULL, the results from getaddrinfo()
191 * @param canonname: (result) if not NULL, the newly-allocated canonical name of the host
192 * @returns: 0 on success, otherwise a getaddrinfo result (for use with gai_strerror)
194 int resolve_hostname(const char *hostname, int socktype,
195 struct addrinfo **res, char **canonname);
197 /* Interpret a status (as returned from wait() and friends)
198 * into a human-readable sentence.
200 * Caller is responsible for freeing the resulting string.
201 * The resulting string has already been translated.
203 * The macro definition allows this to work even when amwait_t
204 * is 'union wait' (4.3BSD). The cast is safe because the two
205 * argument types are interchangeable.
207 * @param subject: subject of the sentence (program name, etc.)
208 * @param status: the exit status
209 * @returns: newly allocated string describing status
211 #define str_exit_status(subject, status) \
212 _str_exit_status((subject), *(amwait_t *)&(status))
213 char *_str_exit_status(char *subject, amwait_t status);
216 * Userid manipulation
219 /* Check that the current uid and euid are set to a specific user,
220 * calling error() if not. Does nothing if CHECK_USERID is not
223 * @param who: one of the RUNNING_AS_* constants, below.
232 /* userid belongs to dumpuser (from config) */
235 /* prefer that userid belongs to dumpuser, but accept when userid belongs to
236 * CLIENT_LOGIN with a debug-log message (needed because amandad always runs
237 * as CLIENT_LOGIN, even on server) */
238 RUNNING_AS_DUMPUSER_PREFERRED,
240 /* userid belongs to CLIENT_LOGIN (from --with-user) */
241 RUNNING_AS_CLIENT_LOGIN,
243 RUNNING_AS_USER_MASK = (1 << 8) - 1,
244 /* '|' this on to only check the uid, not the euid; use this for programs
245 * that will call become_root() */
246 RUNNING_AS_UID_ONLY = 1 << 8
249 void check_running_as(running_as_flags who);
251 /* Drop and regain root priviledges; used from setuid-root binaries which only
252 * need to be root for certain operations. Does nothing if SINGLE_USERID is
255 * @param need_root: if 1, try to assume root priviledges; otherwise, drop
256 * priviledges. If -1, drop them irreversibly.
257 * @returns: true if the priviledge change succeeded
259 int set_root_privs(int need_root);
261 /* Become root completely, by setting the uid to 0. This is used by setuid-root
262 * apps which will exec subprocesses which will also need root priviledges. Does
263 * nothing if SINGLE_USERID is defined.
265 * @returns: true if the priviledge change succeeded
267 int become_root(void);
273 /* The 'context' of a process gives a general description of how it is
274 * used. This affects log output, among other things.
277 /* default context (logging to stderr, etc. -- not pretty) */
280 /* user-interfacing command-line utility like amadmin */
283 /* daemon like amandad or sendbackup */
286 /* a utility used from shell scripts, and thus probably invoked
291 /* Set the name of the process. The parameter is copied, and remains
292 * the responsibility of the caller on return. This value is used in log
293 * messages and other output throughout Amanda.
295 * @param pname: the new process name
297 void set_pname(char *pname);
299 /* Get the current process name; the result is in a static buffer, and
300 * should *not* be free()d by the caller.
302 * @returns: process name
304 char *get_pname(void);
306 /* Set the type of the process. The parameter is copied, and remains
307 * the responsibility of the caller on return. This value dictates the
308 * directory in which debug logs are stored.
310 * @param pname: the new process type
312 void set_ptype(char *ptype);
314 /* Get the current process name; the result is in a static buffer, and
315 * should *not* be free()d by the caller.
317 * @returns: process name
319 char *get_ptype(void);
321 /* Set the process's context
323 * @param context: the new context
325 void set_pcontext(pcontext_t context);
327 /* Get the process's context
329 * @returns: the context
331 pcontext_t get_pcontext(void);
336 * This either includes the system readline header we found in configure,
337 * or prototypes some simple stub functions that are used instead.
340 #ifdef HAVE_LIBREADLINE
341 # if defined(HAVE_READLINE_READLINE_H)
342 # include <readline/readline.h>
343 # elif defined(HAVE_READLINE_H)
344 # include <readline.h>
345 # else /* !defined(HAVE_READLINE_H) */
346 extern char *readline ();
347 # endif /* !defined(HAVE_READLINE_H) */
348 /* char *cmdline = NULL; */
349 #else /* !defined(HAVE_LIBREADLINE) */
350 /* use our own readline */
351 char * readline(const char *prompt);
352 #endif /* HAVE_LIBREADLINE */
354 #ifdef HAVE_READLINE_HISTORY
355 # if defined(HAVE_READLINE_HISTORY_H)
356 # include <readline/history.h>
357 # elif defined(HAVE_HISTORY_H)
358 # include <history.h>
359 # else /* !defined(HAVE_HISTORY_H) */
360 extern void add_history ();
361 extern int write_history ();
362 extern int read_history ();
363 # endif /* defined(HAVE_READLINE_HISTORY_H) */
364 #else /* !defined(HAVE_READLINE_HISTORY) */
365 /* use our own add_history */
366 void add_history(const char *line);
367 #endif /* HAVE_READLINE_HISTORY */
369 char *base64_decode_alloc_string(char *);
371 /* Inform the OpenBSD pthread library about the high-numbered file descriptors
372 * that an amandad service inherits. This won't be necessary once the new
373 * threading library is availble (OpenBSD 5.0?), but won't hurt anyway. See the
374 * thread "Backup issues with OpenBSD 4.5 machines" from September 2009. */
376 void openbsd_fd_inform(void);
378 #define openbsd_fd_inform()
381 /* Add all properties to an ARGV
383 * @param argvchild: Pointer to the ARGV.
384 * @param proplist: The property list
386 void property_add_to_argv(GPtrArray *argv_ptr, GHashTable *proplist);
388 /* Print the argv_ptr with g_debug()
390 * @param argv_ptr: GPtrArray of an array to print.
392 void debug_executing(GPtrArray *argv_ptr);