2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 1999 University of Maryland at College Park
4 * Copyright (c) 2007-2012 Zmanda, Inc. All Rights Reserved.
7 * Permission to use, copy, modify, distribute, and sell this software and its
8 * documentation for any purpose is hereby granted without fee, provided that
9 * the above copyright notice appear in all copies and that both that
10 * copyright notice and this permission notice appear in supporting
11 * documentation, and that the name of U.M. not be used in advertising or
12 * publicity pertaining to distribution of the software without specific,
13 * written prior permission. U.M. makes no representations about the
14 * suitability of this software for any purpose. It is provided "as is"
15 * without express or implied warranty.
17 * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
19 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
21 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 * Authors: the Amanda Development Team. Its members are listed in a
25 * file named AUTHORS, in the root directory of this distribution.
28 * $Id: util.h,v 1.17 2006/07/26 15:17:36 martinea Exp $
37 #include <glib-object.h>
40 #include "glib-util.h"
42 #define BIGINT INT_MAX
44 #define BSTRNCMP(a,b) strncmp(a, b, strlen(b))
46 /* internal types and variables */
48 /* Function to get the GQuark for errors,
49 * with error codes specified by AmUtilError
51 * @return The GQuark that's used for errors
53 GQuark am_util_error_quark(void);
55 /* Error codes that may be returned by these functions */
57 AM_UTIL_ERROR_HEXDECODEINVAL,
61 int connect_portrange(sockaddr_union *, in_port_t, in_port_t, char *,
62 sockaddr_union *, int);
63 int bind_portrange(int, sockaddr_union *, in_port_t, in_port_t,
66 /* just like an accept() call, but periodically calling PROLONG(PROLONG_DATA) and
67 * returning -1 with errno set to 0 if PROLONG returns false. Note that the socket
68 * need not be configured as non-blocking.
70 * Other arguments are just like for accept(2).
72 int interruptible_accept(int sock, struct sockaddr *addr, socklen_t *addrlen,
73 gboolean (*prolong)(gpointer data), gpointer prolong_data);
75 ssize_t full_writev(int, struct iovec *, int);
77 char * construct_datestamp(time_t *t);
78 char * construct_timestamp(time_t *t);
80 /* quote_string only adds "" if they're required; quote_string_always
81 * always adds "" around the string */
82 #define quote_string(str) quote_string_maybe((str), 0)
83 #define quote_string_always(str) quote_string_maybe((str), 1)
84 #define len_quote_string(str) len_quote_string_maybe((str), 0);
86 /*@only@*//*@null@*/char *quote_string_maybe(const char *str, gboolean always);
87 /*@only@*//*@null@*/char *unquote_string(const char *str);
88 /*@only@*//*@null@*/int len_quote_string_maybe(const char *str, gboolean always);
90 /* Split a string into space-delimited words, obeying quoting as created by
91 * quote_string. To keep compatibility with the old split(), this has the
92 * characteristic that multiple consecutive spaces are not collapsed into
93 * a single space: "x y" parses as [ "x", "", "y", NULL ]. The strings are
94 * unquoted before they are returned, unlike split(). An empty string is
95 * split into [ "", NULL ].
97 * Returns a NULL-terminated array of strings, which should be freed with
100 gchar ** split_quoted_strings(const gchar *string);
102 /* Like strtok_r, but consider a quoted string to be a single token. Caller
103 * must begin parsing with strtok_r first, then pass the saveptr to this function.
105 * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
107 char * strquotedstr(char **saveptr);
109 char * sanitize_string(const char *str);
111 /* Encode a string using URI-style hexadecimal encoding.
112 * Non-alphanumeric characters will be replaced with "%xx"
113 * where "xx" is the two-digit hexadecimal representation of the character.
115 * @param str The string to encode
117 * @return The encoded string. An empty string will be returned for NULL.
119 char * hexencode_string(const char *str);
121 /* Decode a string using URI-style hexadecimal encoding.
123 * @param str The string to decode
124 * @param err return location for a GError
126 * @return The decoded string. An empty string will be returned for NULL
127 * or if an error occurs.
129 char * hexdecode_string(const char *str, GError **err);
131 int copy_file(char *dst, char *src, char **errmsg);
133 /* These two functions handle "braced alternates", which is a syntax borrowed,
134 * partially, from shells. See perl/Amanda/Util.pod for a full description of
135 * the syntax they support.
137 GPtrArray * expand_braced_alternates(char * source);
138 char * collapse_braced_alternates(GPtrArray *source);
141 * validate_email return 0 if the following characters are present
142 * * ( ) < > [ ] , ; : ! $ \ / "
145 int validate_mailto(const char *mailto);
147 /* This function is a portable reimplementation of readdir(). It
148 * returns a newly-allocated string, that should be freed with
149 * free(). Returns NULL on error or end of directory.
150 * It is reentrant, with the following exceptions:
151 * - This function cannot be run at the same time as readdir() or
153 * - This function cannot be run simultaneously on the same directory
155 char * portable_readdir(DIR*);
157 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
159 /* This function will search the given directory handle for files
160 matching the given POSIX extended regular expression.
161 For each matching file, the functor will be called with the given
162 user data. Stops when the functor returns FALSE, or all files have
163 been searched. Returns the number of matching files. */
164 int search_directory(DIR * handle, const char * regex,
165 SearchDirectoryFunctor functor, gpointer user_data);
167 /* This function extracts a substring match from a regular expression
168 match result, and copies it into a newly allocated string. Example
169 usage to get the first matched substring:
170 substring = find_regmatch(whole_string, pmatch[1])
171 Note that pmatch[0] yields the entire matching portion of the string. */
172 char* find_regex_substring(const char* base_string, const regmatch_t match);
174 void free_new_argv(int new_argc, char **new_argv);
176 /* Like strcmp(a, b), except that NULL strings are sorted before non-NULL
177 * strings, instead of segfaulting. */
178 int compare_possibly_null_strings(const char * a, const char * b);
180 /* Given a hostname, call getaddrinfo to resolve it. Optionally get the
181 * entire set of results (if res is not NULL) and the canonical name of
182 * the host (if canonname is not NULL). The canonical name might
183 * expand e.g., www.domain.com to server3.webfarm.hosting.com.
185 * If not NULL, the caller is responsible for freeing res with freeaddrinfo().
186 * Similarly, the caller is responsible for freeing canonname if it is
189 * @param hostname: the hostname to start with
190 * @param socktype: the socket type (SOCK_DGRAM or SOCK_STREAM)
191 * @param res: (result) if not NULL, the results from getaddrinfo()
192 * @param canonname: (result) if not NULL, the newly-allocated canonical name of the host
193 * @returns: 0 on success, otherwise a getaddrinfo result (for use with gai_strerror)
195 int resolve_hostname(const char *hostname, int socktype,
196 struct addrinfo **res, char **canonname);
198 /* Interpret a status (as returned from wait() and friends)
199 * into a human-readable sentence.
201 * Caller is responsible for freeing the resulting string.
202 * The resulting string has already been translated.
204 * The macro definition allows this to work even when amwait_t
205 * is 'union wait' (4.3BSD). The cast is safe because the two
206 * argument types are interchangeable.
208 * @param subject: subject of the sentence (program name, etc.)
209 * @param status: the exit status
210 * @returns: newly allocated string describing status
212 #define str_exit_status(subject, status) \
213 _str_exit_status((subject), *(amwait_t *)&(status))
214 char *_str_exit_status(char *subject, amwait_t status);
217 * Userid manipulation
220 /* Check that the current uid and euid are set to a specific user,
221 * calling error() if not. Does nothing if CHECK_USERID is not
224 * @param who: one of the RUNNING_AS_* constants, below.
233 /* userid belongs to dumpuser (from config) */
236 /* prefer that userid belongs to dumpuser, but accept when userid belongs to
237 * CLIENT_LOGIN with a debug-log message (needed because amandad always runs
238 * as CLIENT_LOGIN, even on server) */
239 RUNNING_AS_DUMPUSER_PREFERRED,
241 /* userid belongs to CLIENT_LOGIN (from --with-user) */
242 RUNNING_AS_CLIENT_LOGIN,
244 RUNNING_AS_USER_MASK = (1 << 8) - 1,
245 /* '|' this on to only check the uid, not the euid; use this for programs
246 * that will call become_root() */
247 RUNNING_AS_UID_ONLY = 1 << 8
250 void check_running_as(running_as_flags who);
252 /* Drop and regain root priviledges; used from setuid-root binaries which only
253 * need to be root for certain operations. Does nothing if SINGLE_USERID is
256 * @param need_root: if 1, try to assume root priviledges; otherwise, drop
257 * priviledges. If -1, drop them irreversibly.
258 * @returns: true if the priviledge change succeeded
260 int set_root_privs(int need_root);
262 /* Become root completely, by setting the uid to 0. This is used by setuid-root
263 * apps which will exec subprocesses which will also need root priviledges. Does
264 * nothing if SINGLE_USERID is defined.
266 * @returns: true if the priviledge change succeeded
268 int become_root(void);
274 /* The 'context' of a process gives a general description of how it is
275 * used. This affects log output, among other things.
278 /* default context (logging to stderr, etc. -- not pretty) */
281 /* user-interfacing command-line utility like amadmin */
284 /* daemon like amandad or sendbackup */
287 /* a utility used from shell scripts, and thus probably invoked
292 /* Set the name of the process. The parameter is copied, and remains
293 * the responsibility of the caller on return. This value is used in log
294 * messages and other output throughout Amanda.
296 * @param pname: the new process name
298 void set_pname(char *pname);
300 /* Get the current process name; the result is in a static buffer, and
301 * should *not* be free()d by the caller.
303 * @returns: process name
305 char *get_pname(void);
307 /* Set the type of the process. The parameter is copied, and remains
308 * the responsibility of the caller on return. This value dictates the
309 * directory in which debug logs are stored.
311 * @param pname: the new process type
313 void set_ptype(char *ptype);
315 /* Get the current process name; the result is in a static buffer, and
316 * should *not* be free()d by the caller.
318 * @returns: process name
320 char *get_ptype(void);
322 /* Set the process's context
324 * @param context: the new context
326 void set_pcontext(pcontext_t context);
328 /* Get the process's context
330 * @returns: the context
332 pcontext_t get_pcontext(void);
337 * This either includes the system readline header we found in configure,
338 * or prototypes some simple stub functions that are used instead.
341 #ifdef HAVE_LIBREADLINE
342 # if defined(HAVE_READLINE_READLINE_H)
343 # include <readline/readline.h>
344 # elif defined(HAVE_READLINE_H)
345 # include <readline.h>
346 # else /* !defined(HAVE_READLINE_H) */
347 extern char *readline ();
348 # endif /* !defined(HAVE_READLINE_H) */
349 /* char *cmdline = NULL; */
350 #else /* !defined(HAVE_LIBREADLINE) */
351 /* use our own readline */
352 char * readline(const char *prompt);
353 #endif /* HAVE_LIBREADLINE */
355 #ifdef HAVE_READLINE_HISTORY
356 # if defined(HAVE_READLINE_HISTORY_H)
357 # include <readline/history.h>
358 # elif defined(HAVE_HISTORY_H)
359 # include <history.h>
360 # else /* !defined(HAVE_HISTORY_H) */
361 extern void add_history ();
362 extern int write_history ();
363 extern int read_history ();
364 # endif /* defined(HAVE_READLINE_HISTORY_H) */
365 #else /* !defined(HAVE_READLINE_HISTORY) */
366 /* use our own add_history */
367 void add_history(const char *line);
368 #endif /* HAVE_READLINE_HISTORY */
370 char *base64_decode_alloc_string(char *);
372 /* Inform the OpenBSD pthread library about the high-numbered file descriptors
373 * that an amandad service inherits. This won't be necessary once the new
374 * threading library is availble (OpenBSD 5.0?), but won't hurt anyway. See the
375 * thread "Backup issues with OpenBSD 4.5 machines" from September 2009. */
377 void openbsd_fd_inform(void);
379 #define openbsd_fd_inform()
382 /* Add all properties to an ARGV
384 * @param argvchild: Pointer to the ARGV.
385 * @param proplist: The property list
387 void property_add_to_argv(GPtrArray *argv_ptr, GHashTable *proplist);
389 /* Print the argv_ptr with g_debug()
391 * @param argv_ptr: GPtrArray of an array to print.
393 void debug_executing(GPtrArray *argv_ptr);
395 /* execute the program and get the first line from stdout ot stderr */
396 char *get_first_line(GPtrArray *argv_ptr);
398 gboolean make_amanda_tmpdir(void);