Imported Upstream version 3.3.3
[debian/amanda] / common-src / util.h
1 /*
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.
5  * All Rights Reserved.
6  *
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.
16  *
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.
23  *
24  * Authors: the Amanda Development Team.  Its members are listed in a
25  * file named AUTHORS, in the root directory of this distribution.
26  */
27 /*
28  * $Id: util.h,v 1.17 2006/07/26 15:17:36 martinea Exp $
29  */
30 #ifndef UTIL_H
31 #define UTIL_H
32
33 #include "amanda.h"
34 #include "am_sl.h"
35
36 #include <glib.h>
37 #include <glib-object.h>
38 #include <regex.h>
39
40 #include "glib-util.h"
41
42 #define BIGINT  INT_MAX
43
44 #define BSTRNCMP(a,b)  strncmp(a, b, strlen(b))
45
46 /* internal types and variables */
47
48 /* Function to get the GQuark for errors,
49  * with error codes specified by AmUtilError
50  *
51  * @return The GQuark that's used for errors
52  */
53 GQuark am_util_error_quark(void);
54
55 /* Error codes that may be returned by these functions */
56 typedef enum {
57     AM_UTIL_ERROR_HEXDECODEINVAL,
58 } AmUtilError;
59
60
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,
64                        char *);
65
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.
69  *
70  * Other arguments are just like for accept(2).
71  */
72 int     interruptible_accept(int sock, struct sockaddr *addr, socklen_t *addrlen,
73             gboolean (*prolong)(gpointer data), gpointer prolong_data);
74
75 ssize_t full_writev(int, struct iovec *, int);
76
77 char *  construct_datestamp(time_t *t);
78 char *  construct_timestamp(time_t *t);
79
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);
85
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);
89
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 ].
96  *
97  * Returns a NULL-terminated array of strings, which should be freed with
98  * g_strfreev.
99  */
100 gchar ** split_quoted_strings(const gchar *string);
101
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.
104  *
105  * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
106  */
107 char *          strquotedstr(char **saveptr);
108
109 char *  sanitize_string(const char *str);
110
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.
114  *
115  * @param str The string to encode
116  *
117  * @return The encoded string. An empty string will be returned for NULL.
118  */
119 char * hexencode_string(const char *str);
120
121 /* Decode a string using URI-style hexadecimal encoding.
122  *
123  * @param str The string to decode
124  * @param err return location for a GError
125  *
126  * @return The decoded string. An empty string will be returned for NULL
127  * or if an error occurs.
128  */
129 char * hexdecode_string(const char *str, GError **err);
130
131 int     copy_file(char *dst, char *src, char **errmsg);
132
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.
136  */
137 GPtrArray * expand_braced_alternates(char * source);
138 char * collapse_braced_alternates(GPtrArray *source);
139
140 /*
141  *   validate_email return 0 if the following characters are present
142  *   * ( ) < > [ ] , ; : ! $ \ / "
143  *   else returns 1
144  */
145 int validate_mailto(const char *mailto);
146
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
152  *   readdir64().
153  * - This function cannot be run simultaneously on the same directory
154  *   handle. */
155 char * portable_readdir(DIR*);
156
157 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
158                                            gpointer user_data);
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);
166
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);
173
174 void free_new_argv(int new_argc, char **new_argv);
175
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);
179
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.
184  *
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
187  * not NULL.
188  *
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)
194  */
195 int resolve_hostname(const char *hostname, int socktype,
196                      struct addrinfo **res, char **canonname);
197
198 /* Interpret a status (as returned from wait() and friends)
199  * into a human-readable sentence.
200  *
201  * Caller is responsible for freeing the resulting string.
202  * The resulting string has already been translated.
203  *
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.
207  *
208  * @param subject: subject of the sentence (program name, etc.)
209  * @param status: the exit status
210  * @returns: newly allocated string describing status
211  */
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);
215
216 /*
217  * Userid manipulation
218  */
219
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 
222  * defined.  
223  *
224  * @param who: one of the RUNNING_AS_* constants, below.
225  */
226 typedef enum {
227         /* doesn't matter */
228     RUNNING_AS_ANY,
229
230         /* userid is 0 */
231     RUNNING_AS_ROOT,
232
233         /* userid belongs to dumpuser (from config) */
234     RUNNING_AS_DUMPUSER,
235
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,
240
241         /* userid belongs to CLIENT_LOGIN (from --with-user) */
242     RUNNING_AS_CLIENT_LOGIN,
243
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
248 } running_as_flags;
249
250 void check_running_as(running_as_flags who);
251
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 
254  * defined.
255  *
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
259  */
260 int set_root_privs(int need_root);
261
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.
265  *
266  * @returns: true if the priviledge change succeeded
267  */
268 int become_root(void);
269
270 /*
271  * Process parameters
272  */
273
274 /* The 'context' of a process gives a general description of how it is
275  * used.  This affects log output, among other things.
276  */
277 typedef enum {
278     /* default context (logging to stderr, etc. -- not pretty) */
279     CONTEXT_DEFAULT = 0,
280
281     /* user-interfacing command-line utility like amadmin */
282     CONTEXT_CMDLINE,
283
284     /* daemon like amandad or sendbackup */
285     CONTEXT_DAEMON,
286
287     /* a utility used from shell scripts, and thus probably invoked
288      * quite often */
289     CONTEXT_SCRIPTUTIL,
290 } pcontext_t;
291
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.
295  *
296  * @param pname: the new process name
297  */
298 void set_pname(char *pname);
299
300 /* Get the current process name; the result is in a static buffer, and
301  * should *not* be free()d by the caller.
302  *
303  * @returns: process name
304  */
305 char *get_pname(void);
306
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.
310  *
311  * @param pname: the new process type
312  */
313 void set_ptype(char *ptype);
314
315 /* Get the current process name; the result is in a static buffer, and
316  * should *not* be free()d by the caller.
317  *
318  * @returns: process name
319  */
320 char *get_ptype(void);
321
322 /* Set the process's context
323  *
324  * @param context: the new context
325  */
326 void set_pcontext(pcontext_t context);
327
328 /* Get the process's context
329  *
330  * @returns: the context
331  */
332 pcontext_t get_pcontext(void);
333
334 /*
335  * Readline support
336  *
337  * This either includes the system readline header we found in configure,
338  * or prototypes some simple stub functions that are used instead.
339  */
340
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 */
354
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 */
369
370 char *base64_decode_alloc_string(char *);
371
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. */
376 #ifdef __OpenBSD__
377 void openbsd_fd_inform(void);
378 #else
379 #define openbsd_fd_inform()
380 #endif
381
382 /* Add all properties to an ARGV
383  *
384  * @param argvchild: Pointer to the ARGV.
385  * @param proplist: The property list
386  */
387 void property_add_to_argv(GPtrArray *argv_ptr, GHashTable *proplist);
388
389 /* Print the argv_ptr with g_debug()
390  *
391  * @param argv_ptr: GPtrArray of an array to print.
392  */
393 void debug_executing(GPtrArray *argv_ptr);
394
395 /* execute the program and get the first line from stdout ot stderr */
396 char *get_first_line(GPtrArray *argv_ptr);
397
398 gboolean make_amanda_tmpdir(void);
399
400 #endif  /* UTIL_H */