s3-registry: make sure root has full registry access (in particular for make test).
[Samba/nascimento.git] / lib / util / util.c
blob0064cef8f2c74eecb8e202505aa660cba763edc5
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2002
6 Copyright (C) Simo Sorce 2001
7 Copyright (C) Jim McDonough (jmcd@us.ibm.com) 2003.
8 Copyright (C) James J Myers 2003
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
25 #include "system/network.h"
26 #include "system/filesys.h"
27 #include "system/locale.h"
28 #undef malloc
29 #undef strcasecmp
30 #undef strncasecmp
31 #undef strdup
32 #undef realloc
34 #if defined(UID_WRAPPER)
35 #if !defined(UID_WRAPPER_REPLACE) && !defined(UID_WRAPPER_NOT_REPLACE)
36 #define UID_WRAPPER_REPLACE
37 #include "../uid_wrapper/uid_wrapper.h"
38 #endif
39 #else
40 #define uwrap_enabled() 0
41 #endif
43 /**
44 * @file
45 * @brief Misc utility functions
48 /**
49 Find a suitable temporary directory. The result should be copied immediately
50 as it may be overwritten by a subsequent call.
51 **/
52 _PUBLIC_ const char *tmpdir(void)
54 char *p;
55 if ((p = getenv("TMPDIR")))
56 return p;
57 return "/tmp";
61 /**
62 Check if a file exists - call vfs_file_exist for samba files.
63 **/
64 _PUBLIC_ bool file_exist(const char *fname)
66 struct stat st;
68 if (stat(fname, &st) != 0) {
69 return false;
72 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
75 /**
76 Check a files mod time.
77 **/
79 _PUBLIC_ time_t file_modtime(const char *fname)
81 struct stat st;
83 if (stat(fname,&st) != 0)
84 return(0);
86 return(st.st_mtime);
89 /**
90 Check if a directory exists.
91 **/
93 _PUBLIC_ bool directory_exist(const char *dname)
95 struct stat st;
96 bool ret;
98 if (stat(dname,&st) != 0) {
99 return false;
102 ret = S_ISDIR(st.st_mode);
103 if(!ret)
104 errno = ENOTDIR;
105 return ret;
109 * Try to create the specified directory if it didn't exist.
111 * @retval true if the directory already existed and has the right permissions
112 * or was successfully created.
114 _PUBLIC_ bool directory_create_or_exist(const char *dname, uid_t uid,
115 mode_t dir_perms)
117 mode_t old_umask;
118 struct stat st;
120 old_umask = umask(0);
121 if (lstat(dname, &st) == -1) {
122 if (errno == ENOENT) {
123 /* Create directory */
124 if (mkdir(dname, dir_perms) == -1) {
125 DEBUG(0, ("error creating directory "
126 "%s: %s\n", dname,
127 strerror(errno)));
128 umask(old_umask);
129 return false;
131 } else {
132 DEBUG(0, ("lstat failed on directory %s: %s\n",
133 dname, strerror(errno)));
134 umask(old_umask);
135 return false;
137 } else {
138 /* Check ownership and permission on existing directory */
139 if (!S_ISDIR(st.st_mode)) {
140 DEBUG(0, ("directory %s isn't a directory\n",
141 dname));
142 umask(old_umask);
143 return false;
145 if (st.st_uid != uid && !uwrap_enabled()) {
146 DEBUG(0, ("invalid ownership on directory "
147 "%s\n", dname));
148 umask(old_umask);
149 return false;
151 if ((st.st_mode & 0777) != dir_perms) {
152 DEBUG(0, ("invalid permissions on directory "
153 "%s\n", dname));
154 umask(old_umask);
155 return false;
158 return true;
163 Sleep for a specified number of milliseconds.
166 _PUBLIC_ void msleep(unsigned int t)
168 struct timeval tval;
170 tval.tv_sec = t/1000;
171 tval.tv_usec = 1000*(t%1000);
172 /* this should be the real select - do NOT replace
173 with sys_select() */
174 select(0,NULL,NULL,NULL,&tval);
178 Get my own name, return in talloc'ed storage.
181 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
183 char *p;
184 char hostname[HOST_NAME_MAX];
186 /* get my host name */
187 if (gethostname(hostname, sizeof(hostname)) == -1) {
188 DEBUG(0,("gethostname failed\n"));
189 return NULL;
192 /* Ensure null termination. */
193 hostname[sizeof(hostname)-1] = '\0';
195 /* split off any parts after an initial . */
196 p = strchr_m(hostname, '.');
197 if (p) {
198 *p = 0;
201 return talloc_strdup(ctx, hostname);
205 Check if a process exists. Does this work on all unixes?
208 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
210 /* Doing kill with a non-positive pid causes messages to be
211 * sent to places we don't want. */
212 SMB_ASSERT(pid > 0);
213 return(kill(pid,0) == 0 || errno != ESRCH);
217 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
218 is dealt with in posix.c
221 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
223 struct flock lock;
224 int ret;
226 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
228 lock.l_type = type;
229 lock.l_whence = SEEK_SET;
230 lock.l_start = offset;
231 lock.l_len = count;
232 lock.l_pid = 0;
234 ret = fcntl(fd,op,&lock);
236 if (ret == -1 && errno != 0)
237 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
239 /* a lock query */
240 if (op == F_GETLK) {
241 if ((ret != -1) &&
242 (lock.l_type != F_UNLCK) &&
243 (lock.l_pid != 0) &&
244 (lock.l_pid != getpid())) {
245 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
246 return true;
249 /* it must be not locked or locked by me */
250 return false;
253 /* a lock set or unset */
254 if (ret == -1) {
255 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
256 (double)offset,(double)count,op,type,strerror(errno)));
257 return false;
260 /* everything went OK */
261 DEBUG(8,("fcntl_lock: Lock call successful\n"));
263 return true;
266 void print_asc(int level, const uint8_t *buf,int len)
268 int i;
269 for (i=0;i<len;i++)
270 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
274 * Write dump of binary data to the log file.
276 * The data is only written if the log level is at least level.
278 static void _dump_data(int level, const uint8_t *buf, int len,
279 bool omit_zero_bytes)
281 int i=0;
282 static const uint8_t empty[16] = { 0, };
283 bool skipped = false;
285 if (len<=0) return;
287 if (!DEBUGLVL(level)) return;
289 for (i=0;i<len;) {
291 if (i%16 == 0) {
292 if ((omit_zero_bytes == true) &&
293 (i > 0) &&
294 (len > i+16) &&
295 (memcmp(&buf[i], &empty, 16) == 0))
297 i +=16;
298 continue;
301 if (i<len) {
302 DEBUGADD(level,("[%04X] ",i));
306 DEBUGADD(level,("%02X ",(int)buf[i]));
307 i++;
308 if (i%8 == 0) DEBUGADD(level,(" "));
309 if (i%16 == 0) {
311 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
312 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
314 if ((omit_zero_bytes == true) &&
315 (len > i+16) &&
316 (memcmp(&buf[i], &empty, 16) == 0)) {
317 if (!skipped) {
318 DEBUGADD(level,("skipping zero buffer bytes\n"));
319 skipped = true;
325 if (i%16) {
326 int n;
327 n = 16 - (i%16);
328 DEBUGADD(level,(" "));
329 if (n>8) DEBUGADD(level,(" "));
330 while (n--) DEBUGADD(level,(" "));
331 n = MIN(8,i%16);
332 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
333 n = (i%16) - n;
334 if (n>0) print_asc(level,&buf[i-n],n);
335 DEBUGADD(level,("\n"));
341 * Write dump of binary data to the log file.
343 * The data is only written if the log level is at least level.
345 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
347 _dump_data(level, buf, len, false);
351 * Write dump of binary data to the log file.
353 * The data is only written if the log level is at least level.
354 * 16 zero bytes in a row are omitted
356 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
358 _dump_data(level, buf, len, true);
363 malloc that aborts with smb_panic on fail or zero size.
366 _PUBLIC_ void *smb_xmalloc(size_t size)
368 void *p;
369 if (size == 0)
370 smb_panic("smb_xmalloc: called with zero size.\n");
371 if ((p = malloc(size)) == NULL)
372 smb_panic("smb_xmalloc: malloc fail.\n");
373 return p;
377 Memdup with smb_panic on fail.
380 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
382 void *p2;
383 p2 = smb_xmalloc(size);
384 memcpy(p2, p, size);
385 return p2;
389 strdup that aborts on malloc fail.
392 char *smb_xstrdup(const char *s)
394 #if defined(PARANOID_MALLOC_CHECKER)
395 #ifdef strdup
396 #undef strdup
397 #endif
398 #endif
400 #ifndef HAVE_STRDUP
401 #define strdup rep_strdup
402 #endif
404 char *s1 = strdup(s);
405 #if defined(PARANOID_MALLOC_CHECKER)
406 #ifdef strdup
407 #undef strdup
408 #endif
409 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
410 #endif
411 if (!s1) {
412 smb_panic("smb_xstrdup: malloc failed");
414 return s1;
419 strndup that aborts on malloc fail.
422 char *smb_xstrndup(const char *s, size_t n)
424 #if defined(PARANOID_MALLOC_CHECKER)
425 #ifdef strndup
426 #undef strndup
427 #endif
428 #endif
430 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
431 #undef HAVE_STRNDUP
432 #define strndup rep_strndup
433 #endif
435 char *s1 = strndup(s, n);
436 #if defined(PARANOID_MALLOC_CHECKER)
437 #ifdef strndup
438 #undef strndup
439 #endif
440 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
441 #endif
442 if (!s1) {
443 smb_panic("smb_xstrndup: malloc failed");
445 return s1;
451 Like strdup but for memory.
454 _PUBLIC_ void *memdup(const void *p, size_t size)
456 void *p2;
457 if (size == 0)
458 return NULL;
459 p2 = malloc(size);
460 if (!p2)
461 return NULL;
462 memcpy(p2, p, size);
463 return p2;
467 * Write a password to the log file.
469 * @note Only actually does something if DEBUG_PASSWORD was defined during
470 * compile-time.
472 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
474 #ifdef DEBUG_PASSWORD
475 DEBUG(11, ("%s", msg));
476 if (data != NULL && len > 0)
478 dump_data(11, data, len);
480 #endif
485 * see if a range of memory is all zero. A NULL pointer is considered
486 * to be all zero
488 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
490 int i;
491 if (!ptr) return true;
492 for (i=0;i<size;i++) {
493 if (ptr[i]) return false;
495 return true;
499 realloc an array, checking for integer overflow in the array size
501 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
503 #define MAX_MALLOC_SIZE 0x7fffffff
504 if (count == 0 ||
505 count >= MAX_MALLOC_SIZE/el_size) {
506 if (free_on_fail)
507 SAFE_FREE(ptr);
508 return NULL;
510 if (!ptr) {
511 return malloc(el_size * count);
513 return realloc(ptr, el_size * count);
516 /****************************************************************************
517 Type-safe malloc.
518 ****************************************************************************/
520 void *malloc_array(size_t el_size, unsigned int count)
522 return realloc_array(NULL, el_size, count, false);
526 Trim the specified elements off the front and back of a string.
528 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
530 bool ret = false;
531 size_t front_len;
532 size_t back_len;
533 size_t len;
535 /* Ignore null or empty strings. */
536 if (!s || (s[0] == '\0'))
537 return false;
539 front_len = front? strlen(front) : 0;
540 back_len = back? strlen(back) : 0;
542 len = strlen(s);
544 if (front_len) {
545 while (len && strncmp(s, front, front_len)==0) {
546 /* Must use memmove here as src & dest can
547 * easily overlap. Found by valgrind. JRA. */
548 memmove(s, s+front_len, (len-front_len)+1);
549 len -= front_len;
550 ret=true;
554 if (back_len) {
555 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
556 s[len-back_len]='\0';
557 len -= back_len;
558 ret=true;
561 return ret;
565 Find the number of 'c' chars in a string
567 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
569 size_t count = 0;
571 while (*s) {
572 if (*s == c) count++;
573 s ++;
576 return count;
580 Routine to get hex characters and turn them into a 16 byte array.
581 the array can be variable length, and any non-hex-numeric
582 characters are skipped. "0xnn" or "0Xnn" is specially catered
583 for.
585 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
589 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
591 size_t i = 0;
592 size_t num_chars = 0;
593 uint8_t lonybble, hinybble;
594 const char *hexchars = "0123456789ABCDEF";
595 char *p1 = NULL, *p2 = NULL;
597 /* skip leading 0x prefix */
598 if (strncasecmp(strhex, "0x", 2) == 0) {
599 i += 2; /* skip two chars */
602 for (; i < strhex_len && strhex[i] != 0; i++) {
603 if (!(p1 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
604 break;
606 i++; /* next hex digit */
608 if (!(p2 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
609 break;
611 /* get the two nybbles */
612 hinybble = PTR_DIFF(p1, hexchars);
613 lonybble = PTR_DIFF(p2, hexchars);
615 if (num_chars >= p_len) {
616 break;
619 p[num_chars] = (hinybble << 4) | lonybble;
620 num_chars++;
622 p1 = NULL;
623 p2 = NULL;
625 return num_chars;
628 /**
629 * Parse a hex string and return a data blob.
631 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
633 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
635 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
636 strhex,
637 strlen(strhex));
639 return ret_blob;
644 * Routine to print a buffer as HEX digits, into an allocated string.
646 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
648 int i;
649 char *hex_buffer;
651 *out_hex_buffer = malloc_array_p(char, (len*2)+1);
652 hex_buffer = *out_hex_buffer;
654 for (i = 0; i < len; i++)
655 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
659 * talloc version of hex_encode()
661 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
663 int i;
664 char *hex_buffer;
666 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
667 if (!hex_buffer) {
668 return NULL;
671 for (i = 0; i < len; i++)
672 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
674 talloc_set_name_const(hex_buffer, hex_buffer);
675 return hex_buffer;
679 varient of strcmp() that handles NULL ptrs
681 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
683 if (s1 == s2) {
684 return 0;
686 if (s1 == NULL || s2 == NULL) {
687 return s1?-1:1;
689 return strcmp(s1, s2);
694 return the number of bytes occupied by a buffer in ASCII format
695 the result includes the null termination
696 limited by 'n' bytes
698 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
700 size_t len;
702 len = strnlen(src, n);
703 if (len+1 <= n) {
704 len += 1;
707 return len;
711 Set a boolean variable from the text value stored in the passed string.
712 Returns true in success, false if the passed string does not correctly
713 represent a boolean.
716 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
718 if (strwicmp(boolean_string, "yes") == 0 ||
719 strwicmp(boolean_string, "true") == 0 ||
720 strwicmp(boolean_string, "on") == 0 ||
721 strwicmp(boolean_string, "1") == 0) {
722 *boolean = true;
723 return true;
724 } else if (strwicmp(boolean_string, "no") == 0 ||
725 strwicmp(boolean_string, "false") == 0 ||
726 strwicmp(boolean_string, "off") == 0 ||
727 strwicmp(boolean_string, "0") == 0) {
728 *boolean = false;
729 return true;
731 return false;
735 return the number of bytes occupied by a buffer in CH_UTF16 format
736 the result includes the null termination
738 _PUBLIC_ size_t utf16_len(const void *buf)
740 size_t len;
742 for (len = 0; SVAL(buf,len); len += 2) ;
744 return len + 2;
748 return the number of bytes occupied by a buffer in CH_UTF16 format
749 the result includes the null termination
750 limited by 'n' bytes
752 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
754 size_t len;
756 for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
758 if (len+2 <= n) {
759 len += 2;
762 return len;
766 * @file
767 * @brief String utilities.
770 static bool next_token_internal_talloc(TALLOC_CTX *ctx,
771 const char **ptr,
772 char **pp_buff,
773 const char *sep,
774 bool ltrim)
776 const char *s;
777 const char *saved_s;
778 char *pbuf;
779 bool quoted;
780 size_t len=1;
782 *pp_buff = NULL;
783 if (!ptr) {
784 return(false);
787 s = *ptr;
789 /* default to simple separators */
790 if (!sep) {
791 sep = " \t\n\r";
794 /* find the first non sep char, if left-trimming is requested */
795 if (ltrim) {
796 while (*s && strchr_m(sep,*s)) {
797 s++;
801 /* nothing left? */
802 if (!*s) {
803 return false;
806 /* When restarting we need to go from here. */
807 saved_s = s;
809 /* Work out the length needed. */
810 for (quoted = false; *s &&
811 (quoted || !strchr_m(sep,*s)); s++) {
812 if (*s == '\"') {
813 quoted = !quoted;
814 } else {
815 len++;
819 /* We started with len = 1 so we have space for the nul. */
820 *pp_buff = talloc_array(ctx, char, len);
821 if (!*pp_buff) {
822 return false;
825 /* copy over the token */
826 pbuf = *pp_buff;
827 s = saved_s;
828 for (quoted = false; *s &&
829 (quoted || !strchr_m(sep,*s)); s++) {
830 if ( *s == '\"' ) {
831 quoted = !quoted;
832 } else {
833 *pbuf++ = *s;
837 *ptr = (*s) ? s+1 : s;
838 *pbuf = 0;
840 return true;
843 bool next_token_talloc(TALLOC_CTX *ctx,
844 const char **ptr,
845 char **pp_buff,
846 const char *sep)
848 return next_token_internal_talloc(ctx, ptr, pp_buff, sep, true);
852 * Get the next token from a string, return false if none found. Handles
853 * double-quotes. This version does not trim leading separator characters
854 * before looking for a token.
857 bool next_token_no_ltrim_talloc(TALLOC_CTX *ctx,
858 const char **ptr,
859 char **pp_buff,
860 const char *sep)
862 return next_token_internal_talloc(ctx, ptr, pp_buff, sep, false);