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 ssize_t full_writev(int, struct iovec *, int);
67 char * construct_datestamp(time_t *t);
68 char * construct_timestamp(time_t *t);
70 /* quote_string only adds "" if they're required; quote_string_always
71 * always adds "" around the string */
72 #define quote_string(str) quote_string_maybe((str), 0)
73 #define quote_string_always(str) quote_string_maybe((str), 1)
75 /*@only@*//*@null@*/char *quote_string_maybe(const char *str, gboolean always);
76 /*@only@*//*@null@*/char *unquote_string(const char *str);
78 /* Split a string into space-delimited words, obeying quoting as created by
79 * quote_string. To keep compatibility with the old split(), this has the
80 * characteristic that multiple consecutive spaces are not collapsed into
81 * a single space: "x y" parses as [ "x", "", "y", NULL ]. The strings are
82 * unquoted before they are returned, unlike split(). An empty string is
83 * split into [ "", NULL ].
85 * Returns a NULL-terminated array of strings, which should be freed with
88 gchar ** split_quoted_strings(const gchar *string);
90 /* Like strtok_r, but consider a quoted string to be a single token. Caller
91 * must begin parsing with strtok_r first, then pass the saveptr to this function.
93 * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
95 char * strquotedstr(char **saveptr);
97 char * sanitize_string(const char *str);
99 /* Encode a string using URI-style hexadecimal encoding.
100 * Non-alphanumeric characters will be replaced with "%xx"
101 * where "xx" is the two-digit hexadecimal representation of the character.
103 * @param str The string to encode
105 * @return The encoded string. An empty string will be returned for NULL.
107 char * hexencode_string(const char *str);
109 /* Decode a string using URI-style hexadecimal encoding.
111 * @param str The string to decode
112 * @param err return location for a GError
114 * @return The decoded string. An empty string will be returned for NULL
115 * or if an error occurs.
117 char * hexdecode_string(const char *str, GError **err);
119 int copy_file(char *dst, char *src, char **errmsg);
121 /* These two functions handle "braced alternates", which is a syntax borrowed,
122 * partially, from shells. Comma-separated strings enclosed in curly braces
123 * expand into multiple alternatives for the entire string.
126 * "{foo,bar,bat}" -> [ "foo", "bar", "bat" ]
127 * "foo{1,2}bar" -> [ "foo1bar", "foo2bar" ]
128 * "foo{1\,2,3}bar" -> [ "foo1,2bar", "foo3bar" ]
129 * "{a,b}-{1,2}" -> [ "a-1", "a-2", "b-1", "b-2" ]
131 * Note that nested braces are not processed. Braces, commas, and backslashes
132 * may be escaped with backslashes. Returns NULL on invalid strings.
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 res: (result) if not NULL, the results from getaddrinfo()
188 * @param canonname: (result) if not NULL, the canonical name of the host
189 * @returns: newly allocated canonical hostname, or NULL if no
190 * canonical hostname was available.
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 /* A GHFunc (callback for g_hash_table_foreach),
362 * Count the number of properties.
364 * @param key_p: (char *) property name.
365 * @param value_p: (GSList *) property values list.
366 * @param user_data_p: (int *) count are added to that value.
368 void count_proplist(gpointer key_p,
370 gpointer user_data_p);
372 /* A GHFunc (callback for g_hash_table_foreach),
373 * Store a property and it's value in an ARGV.
375 * @param key_p: (char *) property name.
376 * @param value_p: (GSList *) property values list.
377 * @param user_data_p: (char ***) pointer to ARGV.
379 void proplist_add_to_argv(gpointer key_p,
381 gpointer user_data_p);
384 /* Inform the OpenBSD pthread library about the high-numbered file descriptors
385 * that an amandad service inherits. This won't be necessary once the new
386 * threading library is availble (OpenBSD 5.0?), but won't hurt anyway. See the
387 * thread "Backup issues with OpenBSD 4.5 machines" from September 2009. */
389 void openbsd_fd_inform(void);
391 #define openbsd_fd_inform()
394 /* Print the argv_ptr with g_debug()
396 * @param argv_ptr: GPtrArray of an array to print.
398 void debug_executing(GPtrArray *argv_ptr);