140982f5e45969d582e1f6fcc4f2b96fd40bfa65
[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 #define len_quote_string(str) len_quote_string_maybe((str), 0);
84
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);
88
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 ].
95  *
96  * Returns a NULL-terminated array of strings, which should be freed with
97  * g_strfreev.
98  */
99 gchar ** split_quoted_strings(const gchar *string);
100
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.
103  *
104  * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
105  */
106 char *          strquotedstr(char **saveptr);
107
108 char *  sanitize_string(const char *str);
109
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.
113  *
114  * @param str The string to encode
115  *
116  * @return The encoded string. An empty string will be returned for NULL.
117  */
118 char * hexencode_string(const char *str);
119
120 /* Decode a string using URI-style hexadecimal encoding.
121  *
122  * @param str The string to decode
123  * @param err return location for a GError
124  *
125  * @return The decoded string. An empty string will be returned for NULL
126  * or if an error occurs.
127  */
128 char * hexdecode_string(const char *str, GError **err);
129
130 int     copy_file(char *dst, char *src, char **errmsg);
131
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.
135  */
136 GPtrArray * expand_braced_alternates(char * source);
137 char * collapse_braced_alternates(GPtrArray *source);
138
139 /*
140  *   validate_email return 0 if the following characters are present
141  *   * ( ) < > [ ] , ; : ! $ \ / "
142  *   else returns 1
143  */
144 int validate_mailto(const char *mailto);
145
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
151  *   readdir64().
152  * - This function cannot be run simultaneously on the same directory
153  *   handle. */
154 char * portable_readdir(DIR*);
155
156 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
157                                            gpointer user_data);
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);
165
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);
172
173 void free_new_argv(int new_argc, char **new_argv);
174
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);
178
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.
183  *
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
186  * not NULL.
187  *
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)
193  */
194 int resolve_hostname(const char *hostname, int socktype,
195                      struct addrinfo **res, char **canonname);
196
197 /* Interpret a status (as returned from wait() and friends)
198  * into a human-readable sentence.
199  *
200  * Caller is responsible for freeing the resulting string.
201  * The resulting string has already been translated.
202  *
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.
206  *
207  * @param subject: subject of the sentence (program name, etc.)
208  * @param status: the exit status
209  * @returns: newly allocated string describing status
210  */
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);
214
215 /*
216  * Userid manipulation
217  */
218
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 
221  * defined.  
222  *
223  * @param who: one of the RUNNING_AS_* constants, below.
224  */
225 typedef enum {
226         /* doesn't matter */
227     RUNNING_AS_ANY,
228
229         /* userid is 0 */
230     RUNNING_AS_ROOT,
231
232         /* userid belongs to dumpuser (from config) */
233     RUNNING_AS_DUMPUSER,
234
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,
239
240         /* userid belongs to CLIENT_LOGIN (from --with-user) */
241     RUNNING_AS_CLIENT_LOGIN,
242
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
247 } running_as_flags;
248
249 void check_running_as(running_as_flags who);
250
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 
253  * defined.
254  *
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
258  */
259 int set_root_privs(int need_root);
260
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.
264  *
265  * @returns: true if the priviledge change succeeded
266  */
267 int become_root(void);
268
269 /*
270  * Process parameters
271  */
272
273 /* The 'context' of a process gives a general description of how it is
274  * used.  This affects log output, among other things.
275  */
276 typedef enum {
277     /* default context (logging to stderr, etc. -- not pretty) */
278     CONTEXT_DEFAULT = 0,
279
280     /* user-interfacing command-line utility like amadmin */
281     CONTEXT_CMDLINE,
282
283     /* daemon like amandad or sendbackup */
284     CONTEXT_DAEMON,
285
286     /* a utility used from shell scripts, and thus probably invoked
287      * quite often */
288     CONTEXT_SCRIPTUTIL,
289 } pcontext_t;
290
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.
294  *
295  * @param pname: the new process name
296  */
297 void set_pname(char *pname);
298
299 /* Get the current process name; the result is in a static buffer, and
300  * should *not* be free()d by the caller.
301  *
302  * @returns: process name
303  */
304 char *get_pname(void);
305
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.
309  *
310  * @param pname: the new process type
311  */
312 void set_ptype(char *ptype);
313
314 /* Get the current process name; the result is in a static buffer, and
315  * should *not* be free()d by the caller.
316  *
317  * @returns: process name
318  */
319 char *get_ptype(void);
320
321 /* Set the process's context
322  *
323  * @param context: the new context
324  */
325 void set_pcontext(pcontext_t context);
326
327 /* Get the process's context
328  *
329  * @returns: the context
330  */
331 pcontext_t get_pcontext(void);
332
333 /*
334  * Readline support
335  *
336  * This either includes the system readline header we found in configure,
337  * or prototypes some simple stub functions that are used instead.
338  */
339
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 */
353
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 */
368
369 char *base64_decode_alloc_string(char *);
370
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. */
375 #ifdef __OpenBSD__
376 void openbsd_fd_inform(void);
377 #else
378 #define openbsd_fd_inform()
379 #endif
380
381 /* Add all properties to an ARGV
382  *
383  * @param argvchild: Pointer to the ARGV.
384  * @param proplist: The property list
385  */
386 void property_add_to_argv(GPtrArray *argv_ptr, GHashTable *proplist);
387
388 /* Print the argv_ptr with g_debug()
389  *
390  * @param argv_ptr: GPtrArray of an array to print.
391  */
392 void debug_executing(GPtrArray *argv_ptr);
393
394 /* execute the program and get the first line from stdout ot stderr */
395 char *get_first_line(GPtrArray *argv_ptr);
396 #endif  /* UTIL_H */