PageRenderTime 57ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/amanda/tags/3_1_5/common-src/util.h

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