s3: VFS: solarisacl: Add solarisacl_sys_acl_delete_def_fd().
[Samba.git] / lib / util / samba_util.h
blob4e279b72df166bf789433d0b508fb55d65744c6a
1 /*
2 Unix SMB/CIFS implementation.
3 Utility functions for Samba
4 Copyright (C) Andrew Tridgell 1992-1999
5 Copyright (C) Jelmer Vernooij 2005
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #ifndef _SAMBA_UTIL_H_
22 #define _SAMBA_UTIL_H_
24 #ifndef SAMBA_UTIL_CORE_ONLY
25 #include "lib/util/charset/charset.h"
26 #else
27 #include "charset_compat.h"
28 #endif
30 #include "lib/util/attr.h"
32 /* for TALLOC_CTX */
33 #include <talloc.h>
35 /* for struct stat */
36 #include <sys/stat.h>
38 /**
39 * @file
40 * @brief Helpful macros
43 struct smbsrv_tcon;
45 extern const char *panic_action;
47 #include "lib/util/time.h"
48 #include "lib/util/data_blob.h"
49 #include "lib/util/byteorder.h"
50 #include "lib/util/talloc_stack.h"
51 #include "lib/util/talloc_keep_secret.h"
53 #ifndef ABS
54 #define ABS(a) ((a)>0?(a):(-(a)))
55 #endif
57 #include "lib/util/memory.h"
58 #include "lib/util/discard.h"
60 #include "fault.h"
62 #include "lib/util/util.h"
64 /**
65 * Write backtrace to debug log
67 _PUBLIC_ void dump_core_setup(const char *progname, const char *logfile);
69 /**
70 register a fault handler.
71 Should only be called once in the execution of smbd.
73 _PUBLIC_ bool register_fault_handler(const char *name, void (*fault_handler)(int sig));
75 #include "lib/util/signal.h" /* Avoid /usr/include/signal.h */
77 struct sockaddr;
79 _PUBLIC_ int sys_getnameinfo(const struct sockaddr *psa,
80 int salen,
81 char *host,
82 size_t hostlen,
83 char *service,
84 size_t servlen,
85 int flags);
87 /* The following definitions come from lib/util/genrand.c */
89 #include "lib/util/genrand.h"
91 /**
92 generate a single random uint32_t
93 **/
94 _PUBLIC_ uint32_t generate_random(void);
96 /**
97 * generate a single random uint64_t
98 * @see generate_unique_u64
99 **/
100 _PUBLIC_ uint64_t generate_random_u64(void);
103 * @brief Generate random nonces usable for re-use detection.
105 * We have a lot of places which require a unique id that can
106 * be used as a unique identitier for caching states.
108 * Always using generate_nonce_buffer() has it's performance costs,
109 * it's typically much better than generate_random_buffer(), but
110 * still it's overhead we want to avoid in performance critical
111 * workloads.
113 * We call generate_nonce_buffer() just once per given state
114 * and process.
116 * This is much lighter than generate_random_u64() and it's
117 * designed for performance critical code paths.
119 * @veto_value It is garanteed that the return value if different from
120 * the veto_value.
122 * @return a unique value per given state and process
124 * @see generate_random_u64
126 uint64_t generate_unique_u64(uint64_t veto_value);
129 very basic password quality checker
131 _PUBLIC_ bool check_password_quality(const char *s);
134 * Generate a random text password (based on printable ascii characters).
135 * This function is designed to provide a password that
136 * meats the complexity requirements of UF_NORMAL_ACCOUNT objects
137 * and they should be human readable and writeable on any keyboard layout.
139 * Characters used are:
140 * ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_-#.,@$%&!?:;<=>()[]~
142 _PUBLIC_ char *generate_random_password(TALLOC_CTX *mem_ctx, size_t min, size_t max);
145 * Generate a random machine password
147 * min and max are the number of utf16 characters used
148 * to generate on utf8 compatible password.
150 * Note: if 'unix charset' is not 'utf8' (the default)
151 * then each utf16 character is only filled with
152 * values from 0x01 to 0x7f (ascii values without 0x00).
153 * This is important as the password neets to be
154 * a valid value as utf8 string and at the same time
155 * a valid value in the 'unix charset'.
157 * If 'unix charset' is 'utf8' (the default) then
158 * each utf16 character is a random value from 0x0000
159 * 0xFFFF (exluding the surrogate ranges from 0xD800-0xDFFF)
160 * while the translation from CH_UTF16MUNGED
161 * to CH_UTF8 replaces invalid values (see utf16_munged_pull()).
163 * Note: these passwords may not pass the complexity requirements
164 * for UF_NORMAL_ACCOUNT objects (except krbtgt accounts).
166 _PUBLIC_ char *generate_random_machine_password(TALLOC_CTX *mem_ctx, size_t min, size_t max);
169 Use the random number generator to generate a random string.
171 _PUBLIC_ char *generate_random_str_list(TALLOC_CTX *mem_ctx, size_t len, const char *list);
174 * Generate a random text string consisting of the specified length.
175 * The returned string will be allocated.
177 * Characters used are: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_-#.,
179 _PUBLIC_ char *generate_random_str(TALLOC_CTX *mem_ctx, size_t len);
182 * Generate an array of unique text strings all of the same length.
183 * The returned strings will be allocated.
184 * Returns NULL if the number of unique combinations cannot be created.
186 * Characters used are: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_-#.,
188 _PUBLIC_ char** generate_unique_strs(TALLOC_CTX *mem_ctx, size_t len,
189 uint32_t num);
191 /* The following definitions come from lib/util/dprintf.c */
193 _PUBLIC_ int d_fprintf(FILE *f, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
194 _PUBLIC_ int d_printf(const char *format, ...) PRINTF_ATTRIBUTE(1,2);
195 _PUBLIC_ void display_set_stderr(void);
197 /* The following definitions come from lib/util/util_str.c */
199 bool next_token_talloc(TALLOC_CTX *ctx,
200 const char **ptr,
201 char **pp_buff,
202 const char *sep);
205 * Get the next token from a string, return false if none found. Handles
206 * double-quotes. This version does not trim leading separator characters
207 * before looking for a token.
209 bool next_token_no_ltrim_talloc(TALLOC_CTX *ctx,
210 const char **ptr,
211 char **pp_buff,
212 const char *sep);
216 Trim the specified elements off the front and back of a string.
218 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back);
221 Find the number of 'c' chars in a string
223 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c);
226 Routine to get hex characters and turn them into a 16 byte array.
227 the array can be variable length, and any non-hex-numeric
228 characters are skipped. "0xnn" or "0Xnn" is specially catered
229 for.
231 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
235 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len);
237 /**
238 * Parse a hex string and return a data blob.
240 _PUBLIC_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex) ;
243 * Parse a hex dump and return a data blob
245 _PUBLIC_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t len);
248 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
250 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen);
253 * talloc version of hex_encode_buf()
255 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len);
257 #include "substitute.h"
260 Unescape a URL encoded string, in place.
262 _PUBLIC_ char *rfc1738_unescape(char *buf);
265 * rfc1738_escape_part
266 * Returns a static buffer that contains the RFC
267 * 1738 compliant, escaped version of the given url segment. (escapes
268 * unsafe, reserved and % chars) It would mangle the :// in http://,
269 * and mangle paths (because of /).
271 _PUBLIC_ char *rfc1738_escape_part(TALLOC_CTX *mem_ctx, const char *url);
274 varient of strcmp() that handles NULL ptrs
276 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2);
279 return the number of bytes occupied by a buffer in ASCII format
280 the result includes the null termination
281 limited by 'n' bytes
283 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n);
286 Set a boolean variable from the text value stored in the passed string.
287 Returns true in success, false if the passed string does not correctly
288 represent a boolean.
290 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean);
293 * Parse a string containing a boolean value.
295 * val will be set to the read value.
297 * @retval true if a boolean value was parsed, false otherwise.
299 _PUBLIC_ bool conv_str_bool(const char * str, bool * val);
302 * Convert a size specification like 16K into an integral number of bytes.
304 _PUBLIC_ bool conv_str_size_error(const char * str, uint64_t * val);
307 * Parse a uint64_t value from a string
309 * val will be set to the value read.
311 * @retval true if parsing was successful, false otherwise
313 _PUBLIC_ bool conv_str_u64(const char * str, uint64_t * val);
316 * @brief Constant time compare to memory regions.
318 * @param[in] s1 The first memory region to compare.
320 * @param[in] s2 The second memory region to compare.
322 * @param[in] n The length of the memory to comapre.
324 * @return 0 when the memory regions are equal, 0 if not.
326 _PUBLIC_ int memcmp_const_time(const void *s1, const void *s2, size_t n);
329 Do a case-insensitive, whitespace-ignoring string compare.
331 _PUBLIC_ int strwicmp(const char *psz1, const char *psz2);
334 String replace.
336 _PUBLIC_ void string_replace(char *s, char oldc, char newc);
339 * Compare 2 strings.
341 * @note The comparison is case-insensitive.
343 _PUBLIC_ bool strequal(const char *s1, const char *s2);
345 #include "util_strlist.h"
347 /* The following definitions come from lib/util/util_strlist_v3.c */
350 * Needed for making an "unconst" list "const"
352 _PUBLIC_ const char **const_str_list(char **list);
355 * str_list_make, v3 version. The v4 version does not
356 * look at quoted strings with embedded blanks, so
357 * do NOT merge this function please!
359 char **str_list_make_v3(TALLOC_CTX *mem_ctx, const char *string,
360 const char *sep);
363 const char **str_list_make_v3_const(TALLOC_CTX *mem_ctx,
364 const char *string,
365 const char *sep);
367 /* The following definitions come from lib/util/util_file.c */
371 * Read one line (data until next newline or eof) and allocate it
373 _PUBLIC_ char *afdgets(int fd, TALLOC_CTX *mem_ctx, size_t hint);
375 char *fgets_slash(TALLOC_CTX *mem_ctx, char *s2, size_t maxlen, FILE *f);
378 load a file into memory from a fd.
380 _PUBLIC_ char *fd_load(int fd, size_t *size, size_t maxsize, TALLOC_CTX *mem_ctx);
383 char **file_lines_parse(const char *p, size_t size, int *numlines, TALLOC_CTX *mem_ctx);
386 load a file into memory
388 _PUBLIC_ char *file_load(const char *fname, size_t *size, size_t maxsize, TALLOC_CTX *mem_ctx);
391 load a file into memory and return an array of pointers to lines in the file
392 must be freed with talloc_free().
394 _PUBLIC_ char **file_lines_load(const char *fname, int *numlines, size_t maxsize, TALLOC_CTX *mem_ctx);
397 load a fd into memory and return an array of pointers to lines in the file
398 must be freed with talloc_free(). If convert is true calls unix_to_dos on
399 the list.
401 _PUBLIC_ char **fd_lines_load(int fd, int *numlines, size_t maxsize, TALLOC_CTX *mem_ctx);
403 _PUBLIC_ bool file_save_mode(const char *fname, const void *packet,
404 size_t length, mode_t mode);
406 save a lump of data into a file. Mostly used for debugging
408 _PUBLIC_ bool file_save(const char *fname, const void *packet, size_t length);
409 _PUBLIC_ int vfdprintf(int fd, const char *format, va_list ap) PRINTF_ATTRIBUTE(2,0);
410 _PUBLIC_ int fdprintf(int fd, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
413 compare two files, return true if the two files have the same content
415 bool file_compare(const char *path1, const char *path2);
418 load from a pipe into memory.
420 char *file_ploadv(char * const argl[], size_t *size);
422 /* The following definitions come from lib/util/util.c */
426 Find a suitable temporary directory. The result should be copied immediately
427 as it may be overwritten by a subsequent call.
429 _PUBLIC_ const char *tmpdir(void);
432 * Creates and immediately unlinks a file. Returns open file descriptor.
434 _PUBLIC_ int create_unlink_tmp(const char *dir);
437 Check if a file exists - call vfs_file_exist for samba files.
439 _PUBLIC_ bool file_exist(const char *fname);
442 Check a files mod time.
444 _PUBLIC_ time_t file_modtime(const char *fname);
447 Check if a directory exists.
449 _PUBLIC_ bool directory_exist(const char *dname);
452 Check file permissions.
454 _PUBLIC_ bool file_check_permissions(const char *fname,
455 uid_t uid,
456 mode_t file_perms,
457 struct stat *pst);
460 * Try to create the specified directory if it didn't exist.
462 * @retval true if the directory already existed and has the right permissions
463 * or was successfully created.
465 _PUBLIC_ bool directory_create_or_exist(const char *dname, mode_t dir_perms);
468 * @brief Try to create a specified directory and the parent directory if they
469 * don't exist.
471 * @param[in] dname The directory path to create.
473 * @param[in] dir_perms The permission of the directories.
475 * @return true on success, false otherwise.
477 _PUBLIC_ bool directory_create_or_exists_recursive(
478 const char *dname,
479 mode_t dir_perms);
481 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
482 uid_t uid,
483 mode_t dir_perms);
485 #include "blocking.h"
488 Sleep for a specified number of milliseconds.
490 _PUBLIC_ void smb_msleep(unsigned int t);
493 Get my own name, return in talloc'ed storage.
495 _PUBLIC_ char* get_myname(TALLOC_CTX *mem_ctx);
498 Check if a process exists. Does this work on all unixes?
500 _PUBLIC_ bool process_exists_by_pid(pid_t pid);
503 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
504 is dealt with in posix.c
506 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type);
509 * Write dump of binary data to the log file.
511 * The data is only written if the log level is at least level.
512 * 16 zero bytes in a row are omitted
514 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len);
517 malloc that aborts with smb_panic on fail or zero size.
519 _PUBLIC_ void *smb_xmalloc(size_t size);
522 Memdup with smb_panic on fail.
524 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size);
527 strdup that aborts on malloc fail.
529 _PUBLIC_ char *smb_xstrdup(const char *s);
531 char *smb_xstrndup(const char *s, size_t n);
534 Like strdup but for memory.
536 _PUBLIC_ void *smb_memdup(const void *p, size_t size);
539 * Write a password to the log file.
541 * @note Only actually does something if DEBUG_PASSWORD was defined during
542 * compile-time.
544 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len);
547 * see if a range of memory is all zero. A NULL pointer is considered
548 * to be all zero
550 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size);
553 realloc an array, checking for integer overflow in the array size
555 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail);
557 void *malloc_array(size_t el_size, unsigned int count);
559 void *memalign_array(size_t el_size, size_t align, unsigned int count);
561 void *calloc_array(size_t size, size_t nmemb);
563 /* The following definitions come from lib/util/fsusage.c */
567 * Retrieve amount of free disk space.
568 * this does all of the system specific guff to get the free disk space.
569 * It is derived from code in the GNU fileutils package, but has been
570 * considerably mangled for use here
572 * results are returned in *dfree and *dsize, in 512 byte units
574 _PUBLIC_ int sys_fsusage(const char *path, uint64_t *dfree, uint64_t *dsize);
576 /* The following definitions come from lib/util/ms_fnmatch.c */
580 * @file
581 * @brief MS-style Filename matching
584 int ms_fnmatch_protocol(const char *pattern, const char *string, int protocol,
585 bool is_case_sensitive);
587 /** a generic fnmatch function - uses for non-CIFS pattern matching */
588 int gen_fnmatch(const char *pattern, const char *string);
590 #include "idtree.h"
591 #include "idtree_random.h"
593 #include "become_daemon.h"
596 * @brief Get a password from the console.
598 * You should make sure that the buffer is an empty string!
600 * You can also use this function to ask for a username. Then you can fill the
601 * buffer with the username and it is shows to the users. If the users just
602 * presses enter the buffer will be untouched.
604 * @code
605 * char username[128];
607 * snprintf(username, sizeof(username), "john");
609 * smb_getpass("Username:", username, sizeof(username), 1, 0);
610 * @endcode
612 * The prompt will look like this:
614 * Username: [john]
616 * If you press enter then john is used as the username, or you can type it in
617 * to change it.
619 * @param[in] prompt The prompt to show to ask for the password.
621 * @param[out] buf The buffer the password should be stored. It NEEDS to be
622 * empty or filled out.
624 * @param[in] len The length of the buffer.
626 * @param[in] echo Should we echo what you type.
628 * @param[in] verify Should we ask for the password twice.
630 * @return 0 on success, -1 on error.
632 _PUBLIC_ int samba_getpass(const char *prompt, char *buf, size_t len,
633 bool echo, bool verify);
636 * Load a ini-style file.
638 bool pm_process( const char *fileName,
639 bool (*sfunc)(const char *, void *),
640 bool (*pfunc)(const char *, const char *, void *),
641 void *userdata);
642 bool pm_process_with_flags(const char *filename,
643 bool allow_empty_values,
644 bool (*sfunc)(const char *section, void *private_data),
645 bool (*pfunc)(const char *name, const char *value,
646 void *private_data),
647 void *private_data);
649 void print_asc(int level, const uint8_t *buf,int len);
650 void print_asc_cb(const uint8_t *buf, int len,
651 void (*cb)(const char *buf, void *private_data),
652 void *private_data);
655 * Add an id to an array of ids.
657 * num should be a pointer to an integer that holds the current
658 * number of elements in ids. It will be updated by this function.
661 bool add_uid_to_array_unique(TALLOC_CTX *mem_ctx, uid_t uid,
662 uid_t **uids, uint32_t *num_uids);
663 bool add_gid_to_array_unique(TALLOC_CTX *mem_ctx, gid_t gid,
664 gid_t **gids, uint32_t *num_gids);
667 * Allocate anonymous shared memory of the given size
669 void *anonymous_shared_allocate(size_t bufsz);
670 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove);
671 void anonymous_shared_free(void *ptr);
674 run a command as a child process, with a timeout.
676 any stdout/stderr from the child will appear in the Samba logs with
677 the specified log levels
679 If callback is set then the callback is called on completion
680 with the return code from the command
682 struct tevent_context;
683 struct tevent_req;
684 struct tevent_req *samba_runcmd_send(TALLOC_CTX *mem_ctx,
685 struct tevent_context *ev,
686 struct timeval endtime,
687 int stdout_log_level,
688 int stderr_log_level,
689 const char * const *argv0, ...);
690 int samba_runcmd_recv(struct tevent_req *req, int *perrno);
691 int samba_runcmd_export_stdin(struct tevent_req *req);
693 #ifdef DEVELOPER
694 void samba_start_debugger(void);
695 #endif
698 * Samba code should use samba_tevent_context_init() instead of
699 * tevent_context_init() in order to get the debug output.
701 struct tevent_context *samba_tevent_context_init(TALLOC_CTX *mem_ctx);
704 * if same samba code needs to use a specific tevent backend
705 * it can use something like this:
707 * samba_tevent_set_debug(ev, "pysmb_tevent");
709 void samba_tevent_set_debug(struct tevent_context *ev, const char *name);
711 #endif /* _SAMBA_UTIL_H_ */