Imported Upstream version 3.2.0
[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  * All Rights Reserved.
5  *
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.
15  *
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.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /*
27  * $Id: util.h,v 1.17 2006/07/26 15:17:36 martinea Exp $
28  */
29 #ifndef UTIL_H
30 #define UTIL_H
31
32 #include "amanda.h"
33 #include "sl.h"
34
35 #include <glib.h>
36 #include <glib-object.h>
37 #include <regex.h>
38
39 #include "glib-util.h"
40
41 #define BIGINT  INT_MAX
42
43 #define BSTRNCMP(a,b)  strncmp(a, b, strlen(b))
44
45 /* internal types and variables */
46
47 /* Function to get the GQuark for errors,
48  * with error codes specified by AmUtilError
49  *
50  * @return The GQuark that's used for errors
51  */
52 GQuark am_util_error_quark(void);
53
54 /* Error codes that may be returned by these functions */
55 typedef enum {
56     AM_UTIL_ERROR_HEXDECODEINVAL,
57 } AmUtilError;
58
59
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,
63                        char *);
64
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.
68  *
69  * Other arguments are just like for accept(2).
70  */
71 int     interruptible_accept(int sock, struct sockaddr *addr, socklen_t *addrlen,
72             gboolean (*prolong)(gpointer data), gpointer prolong_data);
73
74 ssize_t full_writev(int, struct iovec *, int);
75
76 char *  construct_datestamp(time_t *t);
77 char *  construct_timestamp(time_t *t);
78
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
84 /*@only@*//*@null@*/char *quote_string_maybe(const char *str, gboolean always);
85 /*@only@*//*@null@*/char *unquote_string(const char *str);
86
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 ].
93  *
94  * Returns a NULL-terminated array of strings, which should be freed with
95  * g_strfreev.
96  */
97 gchar ** split_quoted_strings(const gchar *string);
98
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.
101  *
102  * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
103  */
104 char *          strquotedstr(char **saveptr);
105
106 char *  sanitize_string(const char *str);
107
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.
111  *
112  * @param str The string to encode
113  *
114  * @return The encoded string. An empty string will be returned for NULL.
115  */
116 char * hexencode_string(const char *str);
117
118 /* Decode a string using URI-style hexadecimal encoding.
119  *
120  * @param str The string to decode
121  * @param err return location for a GError
122  *
123  * @return The decoded string. An empty string will be returned for NULL
124  * or if an error occurs.
125  */
126 char * hexdecode_string(const char *str, GError **err);
127
128 int     copy_file(char *dst, char *src, char **errmsg);
129
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.
133  */
134 GPtrArray * expand_braced_alternates(char * source);
135 char * collapse_braced_alternates(GPtrArray *source);
136
137 /*
138  *   validate_email return 0 if the following characters are present
139  *   * ( ) < > [ ] , ; : ! $ \ / "
140  *   else returns 1
141  */
142 int validate_mailto(const char *mailto);
143
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
149  *   readdir64().
150  * - This function cannot be run simultaneously on the same directory
151  *   handle. */
152 char * portable_readdir(DIR*);
153
154 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
155                                            gpointer user_data);
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);
163
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);
170
171 void free_new_argv(int new_argc, char **new_argv);
172
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);
176
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.
181  *
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
184  * not NULL.
185  *
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)
191  */
192 int resolve_hostname(const char *hostname, int socktype,
193                      struct addrinfo **res, char **canonname);
194
195 /* Interpret a status (as returned from wait() and friends)
196  * into a human-readable sentence.
197  *
198  * Caller is responsible for freeing the resulting string.
199  * The resulting string has already been translated.
200  *
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.
204  *
205  * @param subject: subject of the sentence (program name, etc.)
206  * @param status: the exit status
207  * @returns: newly allocated string describing status
208  */
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);
212
213 /*
214  * Userid manipulation
215  */
216
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 
219  * defined.  
220  *
221  * @param who: one of the RUNNING_AS_* constants, below.
222  */
223 typedef enum {
224         /* doesn't matter */
225     RUNNING_AS_ANY,
226
227         /* userid is 0 */
228     RUNNING_AS_ROOT,
229
230         /* userid belongs to dumpuser (from config) */
231     RUNNING_AS_DUMPUSER,
232
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,
237
238         /* userid belongs to CLIENT_LOGIN (from --with-user) */
239     RUNNING_AS_CLIENT_LOGIN,
240
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
245 } running_as_flags;
246
247 void check_running_as(running_as_flags who);
248
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 
251  * defined.
252  *
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
256  */
257 int set_root_privs(int need_root);
258
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.
262  *
263  * @returns: true if the priviledge change succeeded
264  */
265 int become_root(void);
266
267 /*
268  * Process parameters
269  */
270
271 /* The 'context' of a process gives a general description of how it is
272  * used.  This affects log output, among other things.
273  */
274 typedef enum {
275     /* default context (logging to stderr, etc. -- not pretty) */
276     CONTEXT_DEFAULT = 0,
277
278     /* user-interfacing command-line utility like amadmin */
279     CONTEXT_CMDLINE,
280
281     /* daemon like amandad or sendbackup */
282     CONTEXT_DAEMON,
283
284     /* a utility used from shell scripts, and thus probably invoked
285      * quite often */
286     CONTEXT_SCRIPTUTIL,
287 } pcontext_t;
288
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.
292  *
293  * @param pname: the new process name
294  */
295 void set_pname(char *pname);
296
297 /* Get the current process name; the result is in a static buffer, and
298  * should *not* be free()d by the caller.
299  *
300  * @returns: process name
301  */
302 char *get_pname(void);
303
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.
307  *
308  * @param pname: the new process type
309  */
310 void set_ptype(char *ptype);
311
312 /* Get the current process name; the result is in a static buffer, and
313  * should *not* be free()d by the caller.
314  *
315  * @returns: process name
316  */
317 char *get_ptype(void);
318
319 /* Set the process's context
320  *
321  * @param context: the new context
322  */
323 void set_pcontext(pcontext_t context);
324
325 /* Get the process's context
326  *
327  * @returns: the context
328  */
329 pcontext_t get_pcontext(void);
330
331 /*
332  * Readline support
333  *
334  * This either includes the system readline header we found in configure,
335  * or prototypes some simple stub functions that are used instead.
336  */
337
338 #ifdef HAVE_READLINE
339 #  ifdef HAVE_READLINE_READLINE_H
340 #    include <readline/readline.h>
341 #    ifdef HAVE_READLINE_HISTORY_H
342 #      include <readline/history.h>
343 #    endif
344 #  else
345 #    ifdef HAVE_READLINE_H
346 #      include <readline.h>
347 #      ifdef HAVE_HISTORY_H
348 #        include <history.h>
349 #      endif
350 #    endif
351 #  endif
352 #else
353
354 char *  readline(const char *prompt);
355 void    add_history(const char *line);
356
357 #endif
358
359 char *base64_decode_alloc_string(char *);
360
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. */
365 #ifdef __OpenBSD__
366 void openbsd_fd_inform(void);
367 #else
368 #define openbsd_fd_inform()
369 #endif
370
371 /* Add all properties to an ARGV
372  *
373  * @param argvchild: Pointer to the ARGV.
374  * @param proplist: The property list
375  */
376 void property_add_to_argv(GPtrArray *argv_ptr, GHashTable *proplist);
377
378 /* Print the argv_ptr with g_debug()
379  *
380  * @param argv_ptr: GPtrArray of an array to print.
381  */
382 void debug_executing(GPtrArray *argv_ptr);
383
384 #endif  /* UTIL_H */