59d29a0cef6986810b9c73a196af103893a5d947
[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
48 int     connect_portrange(sockaddr_union *, in_port_t, in_port_t, char *,
49                           sockaddr_union *, int);
50 int     bind_portrange(int, sockaddr_union *, in_port_t, in_port_t,
51                        char *);
52
53 ssize_t full_writev(int, struct iovec *, int);
54
55 char *  construct_datestamp(time_t *t);
56 char *  construct_timestamp(time_t *t);
57
58 /*@only@*//*@null@*/char *quote_string(const char *str);
59 /*@only@*//*@null@*/char *unquote_string(const char *str);
60 int     needs_quotes(const char * str);
61
62 /* Split a string into space-delimited words, obeying quoting as created by
63  * quote_string.  To keep compatibility with the old split(), this has the
64  * characteristic that multiple consecutive spaces are not collapsed into
65  * a single space: "x  y" parses as [ "x", "", "y", NULL ].  The strings are
66  * unquoted before they are returned, unlike split().  An empty string is
67  * split into [ "", NULL ].
68  *
69  * Returns a NULL-terminated array of strings, which should be freed with
70  * g_strfreev.
71  */
72 gchar ** split_quoted_strings(const gchar *string);
73
74 /* Like strtok_r, but consider a quoted string to be a single token.  Caller
75  * must begin parsing with strtok_r first, then pass the saveptr to this function.
76  *
77  * Returns NULL on unparseable strings (e.g., unterminated quotes, bad escapes)
78  */
79 char *          strquotedstr(char **saveptr);
80
81 char *  sanitize_string(const char *str);
82 int     copy_file(char *dst, char *src, char **errmsg);
83
84 /*
85  *   validate_email return 0 if the following characters are present
86  *   * ( ) < > [ ] , ; : ! $ \ / "
87  *   else returns 1
88  */
89 int validate_mailto(const char *mailto);
90
91 /* This function is a portable reimplementation of readdir(). It
92  * returns a newly-allocated string, that should be freed with
93  * free(). Returns NULL on error or end of directory.
94  * It is reentrant, with the following exceptions:
95  * - This function cannot be run at the same time as readdir() or
96  *   readdir64().
97  * - This function cannot be run simultaneously on the same directory
98  *   handle. */
99 char * portable_readdir(DIR*);
100
101 typedef gboolean (*SearchDirectoryFunctor)(const char * filename,
102                                            gpointer user_data);
103 /* This function will search the given directory handle for files
104    matching the given POSIX extended regular expression.
105    For each matching file, the functor will be called with the given
106    user data. Stops when the functor returns FALSE, or all files have
107    been searched. Returns the number of matching files. */
108 int search_directory(DIR * handle, const char * regex,
109                      SearchDirectoryFunctor functor, gpointer user_data);
110
111 /* This function extracts a substring match from a regular expression
112    match result, and copies it into a newly allocated string. Example
113    usage to get the first matched substring:
114    substring = find_regmatch(whole_string, pmatch[1])
115    Note that pmatch[0] yields the entire matching portion of the string. */
116 char* find_regex_substring(const char* base_string, const regmatch_t match);
117
118 void free_new_argv(int new_argc, char **new_argv);
119
120 /* Like strcmp(a, b), except that NULL strings are sorted before non-NULL
121  * strings, instead of segfaulting. */
122 int compare_possibly_null_strings(const char * a, const char * b);
123
124 /* Given a hostname, call getaddrinfo to resolve it.  Optionally get the
125  * entire set of results (if res is not NULL) and the canonical name of
126  * the host (if canonname is not NULL).  The canonical name might
127  * expand e.g., www.domain.com to server3.webfarm.hosting.com.
128  *
129  * If not NULL, the caller is responsible for freeing res with freeaddrinfo().
130  * Similarly, the caller is responsible for freeing canonname if it is
131  * not NULL.
132  *
133  * @param hostname: the hostname to start with
134  * @param res: (result) if not NULL, the results from getaddrinfo()
135  * @param canonname: (result) if not NULL, the canonical name of the host
136  * @returns: newly allocated canonical hostname, or NULL if no
137  * canonical hostname was available.
138  */
139 int resolve_hostname(const char *hostname, int socktype,
140                      struct addrinfo **res, char **canonname);
141
142 /* Interpret a status (as returned from wait() and friends)
143  * into a human-readable sentence.
144  *
145  * Caller is responsible for freeing the resulting string.
146  * The resulting string has already been translated.
147  *
148  * The macro definition allows this to work even when amwait_t
149  * is 'union wait' (4.3BSD).  The cast is safe because the two
150  * argument types are interchangeable.
151  *
152  * @param subject: subject of the sentence (program name, etc.)
153  * @param status: the exit status
154  * @returns: newly allocated string describing status
155  */
156 #define str_exit_status(subject, status) \
157     _str_exit_status((subject), *(amwait_t *)&(status))
158 char *_str_exit_status(char *subject, amwait_t status);
159
160 /*
161  * Userid manipulation
162  */
163
164 /* Check that the current uid and euid are set to a specific user, 
165  * calling error() if not. Does nothing if CHECK_USERID is not 
166  * defined.  
167  *
168  * @param who: one of the RUNNING_AS_* constants, below.
169  */
170 typedef enum {
171         /* doesn't matter */
172     RUNNING_AS_ANY,
173
174         /* userid is 0 */
175     RUNNING_AS_ROOT,
176
177         /* userid belongs to dumpuser (from config) */
178     RUNNING_AS_DUMPUSER,
179
180         /* prefer that userid belongs to dumpuser, but accept when userid belongs to
181          * CLIENT_LOGIN with a debug-log message (needed because amandad always runs
182          * as CLIENT_LOGIN, even on server) */
183     RUNNING_AS_DUMPUSER_PREFERRED,
184
185         /* userid belongs to CLIENT_LOGIN (from --with-user) */
186     RUNNING_AS_CLIENT_LOGIN,
187
188     RUNNING_AS_USER_MASK = (1 << 8) - 1,
189         /* '&' this on to only check the uid, not the euid; use this for programs
190          * that will call become_root() */
191     RUNNING_AS_UID_ONLY = 1 << 8
192 } running_as_flags;
193
194 void check_running_as(running_as_flags who);
195
196 /* Drop and regain root priviledges; used from setuid-root binaries which only
197  * need to be root for certain operations. Does nothing if SINGLE_USERID is 
198  * defined.
199  *
200  * @param need_root: if true, try to assume root priviledges; otherwise, drop
201  * priviledges.
202  * @returns: true if the priviledge change succeeded
203  */
204 int set_root_privs(int need_root);
205
206 /* Become root completely, by setting the uid to 0.  This is used by setuid-root
207  * apps which will exec subprocesses which will also need root priviledges.  Does
208  * nothing if SINGLE_USERID is defined.
209  *
210  * @returns: true if the priviledge change succeeded
211  */
212 int become_root(void);
213
214 /*
215  * Process parameters
216  */
217
218 /* The 'context' of a process gives a general description of how it is
219  * used.  This affects log output, among other things.
220  */
221 typedef enum {
222     /* default context (logging to stderr, etc. -- not pretty) */
223     CONTEXT_DEFAULT = 0,
224
225     /* user-interfacing command-line utility like amadmin */
226     CONTEXT_CMDLINE,
227
228     /* daemon like amandad or sendbackup */
229     CONTEXT_DAEMON,
230
231     /* a utility used from shell scripts, and thus probably invoked
232      * quite often */
233     CONTEXT_SCRIPTUTIL,
234 } pcontext_t;
235
236 /* Set the name of the process.  The parameter is copied, and remains
237  * the responsibility of the caller on return. This value is used in log
238  * messages and other output throughout Amanda.
239  *
240  * @param pname: the new process name
241  */
242 void set_pname(char *pname);
243
244 /* Get the current process name; the result is in a static buffer, and
245  * should *not* be free()d by the caller.
246  *
247  * @returns: process name
248  */
249 char *get_pname(void);
250
251 /* Set the type of the process.  The parameter is copied, and remains
252  * the responsibility of the caller on return.  This value dictates the
253  * directory in which debug logs are stored.
254  *
255  * @param pname: the new process type
256  */
257 void set_ptype(char *ptype);
258
259 /* Get the current process name; the result is in a static buffer, and
260  * should *not* be free()d by the caller.
261  *
262  * @returns: process name
263  */
264 char *get_ptype(void);
265
266 /* Set the process's context
267  *
268  * @param context: the new context
269  */
270 void set_pcontext(pcontext_t context);
271
272 /* Get the process's context
273  *
274  * @returns: the context
275  */
276 pcontext_t get_pcontext(void);
277
278 /*
279  * Readline support
280  *
281  * This either includes the system readline header we found in configure,
282  * or prototypes some simple stub functions that are used instead.
283  */
284
285 #ifdef HAVE_READLINE
286 #  ifdef HAVE_READLINE_READLINE_H
287 #    include <readline/readline.h>
288 #    ifdef HAVE_READLINE_HISTORY_H
289 #      include <readline/history.h>
290 #    endif
291 #  else
292 #    ifdef HAVE_READLINE_H
293 #      include <readline.h>
294 #      ifdef HAVE_HISTORY_H
295 #        include <history.h>
296 #      endif
297 #    endif
298 #  endif
299 #else
300
301 char *  readline(const char *prompt);
302 void    add_history(const char *line);
303
304 #endif
305
306 char *base64_decode_alloc_string(char *);
307
308 /* A GHFunc (callback for g_hash_table_foreach),
309  * Count the number of properties.
310  *
311  * @param key_p: (char *) property name.
312  * @param value_p: (GSList *) property values list.
313  * @param user_data_p: (int *) count are added to that value.
314  */
315 void count_proplist(gpointer key_p,
316                     gpointer value_p,
317                     gpointer user_data_p);
318
319 /* A GHFunc (callback for g_hash_table_foreach),
320  * Store a property and it's value in an ARGV.
321  *
322  * @param key_p: (char *) property name.
323  * @param value_p: (GSList *) property values list.
324  * @param user_data_p: (char ***) pointer to ARGV.
325  */
326 void proplist_add_to_argv(gpointer key_p,
327                           gpointer value_p,
328                           gpointer user_data_p);
329
330 #endif  /* UTIL_H */