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-2011
7 Copyright (C) Jim McDonough (jmcd@us.ibm.com) 2003.
8 Copyright (C) James J Myers 2003
9 Copyright (C) Volker Lendecke 2010
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "system/network.h"
28 #include "system/filesys.h"
29 #include "system/locale.h"
30 #include "system/shmem.h"
31 #include "system/passwd.h"
32 #include "system/time.h"
33 #include "system/wait.h"
35 #include "samba_util.h"
36 #include "lib/util/select.h"
47 * @brief Misc utility functions
51 Find a suitable temporary directory. The result should be copied immediately
52 as it may be overwritten by a subsequent call.
54 _PUBLIC_
const char *tmpdir(void)
57 if ((p
= getenv("TMPDIR")))
64 Create a tmp file, open it and immediately unlink it.
65 If dir is NULL uses tmpdir()
66 Returns the file descriptor or -1 on error.
68 int create_unlink_tmp(const char *dir
)
70 size_t len
= strlen(dir
? dir
: (dir
= tmpdir()));
75 len
= snprintf(fname
, sizeof(fname
), "%s/listenerlock_XXXXXX", dir
);
76 if (len
>= sizeof(fname
)) {
80 mask
= umask(S_IRWXO
| S_IRWXG
);
86 if (unlink(fname
) == -1) {
87 int sys_errno
= errno
;
97 Check if a file exists - call vfs_file_exist for samba files.
99 _PUBLIC_
bool file_exist(const char *fname
)
103 if (stat(fname
, &st
) != 0) {
107 return ((S_ISREG(st
.st_mode
)) || (S_ISFIFO(st
.st_mode
)));
111 Check a files mod time.
114 _PUBLIC_
time_t file_modtime(const char *fname
)
118 if (stat(fname
,&st
) != 0)
125 Check file permissions.
128 _PUBLIC_
bool file_check_permissions(const char *fname
,
142 ret
= stat(fname
, pst
);
144 DEBUG(0, ("stat failed on file '%s': %s\n",
145 fname
, strerror(errno
)));
149 if (pst
->st_uid
!= uid
&& !uid_wrapper_enabled()) {
150 DEBUG(0, ("invalid ownership of file '%s': "
151 "owned by uid %u, should be %u\n",
152 fname
, (unsigned int)pst
->st_uid
,
157 if ((pst
->st_mode
& 0777) != file_perms
) {
158 DEBUG(0, ("invalid permissions on file "
159 "'%s': has 0%o should be 0%o\n", fname
,
160 (unsigned int)(pst
->st_mode
& 0777),
161 (unsigned int)file_perms
));
169 Check if a directory exists.
172 _PUBLIC_
bool directory_exist(const char *dname
)
177 if (stat(dname
,&st
) != 0) {
181 ret
= S_ISDIR(st
.st_mode
);
188 * Try to create the specified directory if it didn't exist.
190 * @retval true if the directory already existed
191 * or was successfully created.
193 _PUBLIC_
bool directory_create_or_exist(const char *dname
,
199 /* Create directory */
200 old_umask
= umask(0);
201 ret
= mkdir(dname
, dir_perms
);
202 if (ret
== -1 && errno
!= EEXIST
) {
203 DEBUG(0, ("mkdir failed on directory "
211 if (ret
!= 0 && errno
== EEXIST
) {
214 ret
= lstat(dname
, &sbuf
);
219 if (!S_ISDIR(sbuf
.st_mode
)) {
228 * @brief Try to create a specified directory if it doesn't exist.
230 * The function creates a directory with the given uid and permissions if it
231 * doesn't exist. If it exists it makes sure the uid and permissions are
232 * correct and it will fail if they are different.
234 * @param[in] dname The directory to create.
236 * @param[in] uid The uid the directory needs to belong too.
238 * @param[in] dir_perms The expected permissions of the directory.
240 * @return True on success, false on error.
242 _PUBLIC_
bool directory_create_or_exist_strict(const char *dname
,
250 ok
= directory_create_or_exist(dname
, dir_perms
);
255 rc
= lstat(dname
, &st
);
257 DEBUG(0, ("lstat failed on created directory %s: %s\n",
258 dname
, strerror(errno
)));
262 /* Check ownership and permission on existing directory */
263 if (!S_ISDIR(st
.st_mode
)) {
264 DEBUG(0, ("directory %s isn't a directory\n",
268 if (st
.st_uid
!= uid
&& !uid_wrapper_enabled()) {
269 DBG_NOTICE("invalid ownership on directory "
273 if ((st
.st_mode
& 0777) != dir_perms
) {
274 DEBUG(0, ("invalid permissions on directory "
275 "'%s': has 0%o should be 0%o\n", dname
,
276 (unsigned int)(st
.st_mode
& 0777), (unsigned int)dir_perms
));
285 Sleep for a specified number of milliseconds.
288 _PUBLIC_
void smb_msleep(unsigned int t
)
290 sys_poll_intr(NULL
, 0, t
);
294 Get my own name, return in talloc'ed storage.
297 _PUBLIC_
char *get_myname(TALLOC_CTX
*ctx
)
300 char hostname
[HOST_NAME_MAX
];
302 /* get my host name */
303 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
304 DEBUG(0,("gethostname failed\n"));
308 /* Ensure null termination. */
309 hostname
[sizeof(hostname
)-1] = '\0';
311 /* split off any parts after an initial . */
312 p
= strchr_m(hostname
, '.');
317 return talloc_strdup(ctx
, hostname
);
321 Check if a process exists. Does this work on all unixes?
324 _PUBLIC_
bool process_exists_by_pid(pid_t pid
)
326 /* Doing kill with a non-positive pid causes messages to be
327 * sent to places we don't want. */
331 return(kill(pid
,0) == 0 || errno
!= ESRCH
);
335 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
336 is dealt with in posix.c
339 _PUBLIC_
bool fcntl_lock(int fd
, int op
, off_t offset
, off_t count
, int type
)
344 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd
,op
,(double)offset
,(double)count
,type
));
347 lock
.l_whence
= SEEK_SET
;
348 lock
.l_start
= offset
;
352 ret
= fcntl(fd
,op
,&lock
);
354 if (ret
== -1 && errno
!= 0)
355 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno
,strerror(errno
)));
360 (lock
.l_type
!= F_UNLCK
) &&
362 (lock
.l_pid
!= getpid())) {
363 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd
,(int)lock
.l_pid
));
367 /* it must be not locked or locked by me */
371 /* a lock set or unset */
373 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
374 (double)offset
,(double)count
,op
,type
,strerror(errno
)));
378 /* everything went OK */
379 DEBUG(8,("fcntl_lock: Lock call successful\n"));
384 struct debug_channel_level
{
389 static void debugadd_channel_cb(const char *buf
, void *private_data
)
391 struct debug_channel_level
*dcl
=
392 (struct debug_channel_level
*)private_data
;
394 DEBUGADDC(dcl
->channel
, dcl
->level
,("%s", buf
));
397 static void debugadd_cb(const char *buf
, void *private_data
)
399 int *plevel
= (int *)private_data
;
400 DEBUGADD(*plevel
, ("%s", buf
));
403 void print_asc_cb(const uint8_t *buf
, int len
,
404 void (*cb
)(const char *buf
, void *private_data
),
411 for (i
=0; i
<len
; i
++) {
412 s
[0] = isprint(buf
[i
]) ? buf
[i
] : '.';
417 void print_asc(int level
, const uint8_t *buf
,int len
)
419 print_asc_cb(buf
, len
, debugadd_cb
, &level
);
423 * Write dump of binary data to a callback
425 void dump_data_cb(const uint8_t *buf
, int len
,
426 bool omit_zero_bytes
,
427 void (*cb
)(const char *buf
, void *private_data
),
431 bool skipped
= false;
439 if ((omit_zero_bytes
== true) &&
442 all_zero(&buf
[i
], 16))
449 snprintf(tmp
, sizeof(tmp
), "[%04X] ", i
);
450 cb(tmp
, private_data
);
454 snprintf(tmp
, sizeof(tmp
), "%02X ", (int)buf
[i
]);
455 cb(tmp
, private_data
);
458 cb(" ", private_data
);
462 print_asc_cb(&buf
[i
-16], 8, cb
, private_data
);
463 cb(" ", private_data
);
464 print_asc_cb(&buf
[i
-8], 8, cb
, private_data
);
465 cb("\n", private_data
);
467 if ((omit_zero_bytes
== true) &&
469 all_zero(&buf
[i
], 16)) {
471 cb("skipping zero buffer bytes\n",
482 cb(" ", private_data
);
484 cb(" ", private_data
);
487 cb(" ", private_data
);
490 print_asc_cb(&buf
[i
-(i
%16)], n
, cb
, private_data
);
491 cb(" ", private_data
);
494 print_asc_cb(&buf
[i
-n
], n
, cb
, private_data
);
496 cb("\n", private_data
);
502 * Write dump of binary data to the log file.
504 * The data is only written if the log level is at least level.
506 _PUBLIC_
void dump_data(int level
, const uint8_t *buf
, int len
)
508 if (!DEBUGLVL(level
)) {
511 dump_data_cb(buf
, len
, false, debugadd_cb
, &level
);
515 * Write dump of binary data to the log file.
517 * The data is only written if the log level is at least level for
518 * debug class dbgc_class.
520 _PUBLIC_
void dump_data_dbgc(int dbgc_class
, int level
, const uint8_t *buf
, int len
)
522 struct debug_channel_level dcl
= { dbgc_class
, level
};
524 if (!DEBUGLVLC(dbgc_class
, level
)) {
527 dump_data_cb(buf
, len
, false, debugadd_channel_cb
, &dcl
);
531 * Write dump of binary data to the log file.
533 * The data is only written if the log level is at least level.
534 * 16 zero bytes in a row are omitted
536 _PUBLIC_
void dump_data_skip_zeros(int level
, const uint8_t *buf
, int len
)
538 if (!DEBUGLVL(level
)) {
541 dump_data_cb(buf
, len
, true, debugadd_cb
, &level
);
544 static void fprintf_cb(const char *buf
, void *private_data
)
546 FILE *f
= (FILE *)private_data
;
547 fprintf(f
, "%s", buf
);
550 void dump_data_file(const uint8_t *buf
, int len
, bool omit_zero_bytes
,
553 dump_data_cb(buf
, len
, omit_zero_bytes
, fprintf_cb
, f
);
557 malloc that aborts with smb_panic on fail or zero size.
560 _PUBLIC_
void *smb_xmalloc(size_t size
)
564 smb_panic("smb_xmalloc: called with zero size.\n");
565 if ((p
= malloc(size
)) == NULL
)
566 smb_panic("smb_xmalloc: malloc fail.\n");
571 Memdup with smb_panic on fail.
574 _PUBLIC_
void *smb_xmemdup(const void *p
, size_t size
)
577 p2
= smb_xmalloc(size
);
583 strdup that aborts on malloc fail.
586 char *smb_xstrdup(const char *s
)
588 #if defined(PARANOID_MALLOC_CHECKER)
595 #define strdup rep_strdup
598 char *s1
= strdup(s
);
599 #if defined(PARANOID_MALLOC_CHECKER)
603 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
606 smb_panic("smb_xstrdup: malloc failed");
613 strndup that aborts on malloc fail.
616 char *smb_xstrndup(const char *s
, size_t n
)
618 #if defined(PARANOID_MALLOC_CHECKER)
624 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
626 #define strndup rep_strndup
629 char *s1
= strndup(s
, n
);
630 #if defined(PARANOID_MALLOC_CHECKER)
634 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
637 smb_panic("smb_xstrndup: malloc failed");
645 Like strdup but for memory.
648 _PUBLIC_
void *smb_memdup(const void *p
, size_t size
)
661 * Write a password to the log file.
663 * @note Only actually does something if DEBUG_PASSWORD was defined during
666 _PUBLIC_
void dump_data_pw(const char *msg
, const uint8_t * data
, size_t len
)
668 #ifdef DEBUG_PASSWORD
669 DEBUG(11, ("%s", msg
));
670 if (data
!= NULL
&& len
> 0)
672 dump_data(11, data
, len
);
679 * see if a range of memory is all zero. A NULL pointer is considered
682 _PUBLIC_
bool all_zero(const uint8_t *ptr
, size_t size
)
685 if (!ptr
) return true;
686 for (i
=0;i
<size
;i
++) {
687 if (ptr
[i
]) return false;
693 realloc an array, checking for integer overflow in the array size
695 _PUBLIC_
void *realloc_array(void *ptr
, size_t el_size
, unsigned count
, bool free_on_fail
)
697 #define MAX_MALLOC_SIZE 0x7fffffff
699 count
>= MAX_MALLOC_SIZE
/el_size
) {
705 return malloc(el_size
* count
);
707 return realloc(ptr
, el_size
* count
);
710 /****************************************************************************
712 ****************************************************************************/
714 void *malloc_array(size_t el_size
, unsigned int count
)
716 return realloc_array(NULL
, el_size
, count
, false);
719 /****************************************************************************
721 ****************************************************************************/
723 void *memalign_array(size_t el_size
, size_t align
, unsigned int count
)
725 if (el_size
== 0 || count
>= MAX_MALLOC_SIZE
/el_size
) {
729 return memalign(align
, el_size
*count
);
732 /****************************************************************************
734 ****************************************************************************/
736 void *calloc_array(size_t size
, size_t nmemb
)
738 if (nmemb
>= MAX_MALLOC_SIZE
/size
) {
741 if (size
== 0 || nmemb
== 0) {
744 return calloc(nmemb
, size
);
748 Trim the specified elements off the front and back of a string.
750 _PUBLIC_
bool trim_string(char *s
, const char *front
, const char *back
)
757 /* Ignore null or empty strings. */
758 if (!s
|| (s
[0] == '\0')) {
763 front_len
= front
? strlen(front
) : 0;
764 back_len
= back
? strlen(back
) : 0;
767 size_t front_trim
= 0;
769 while (strncmp(s
+front_trim
, front
, front_len
)==0) {
770 front_trim
+= front_len
;
772 if (front_trim
> 0) {
773 /* Must use memmove here as src & dest can
774 * easily overlap. Found by valgrind. JRA. */
775 memmove(s
, s
+front_trim
, (len
-front_trim
)+1);
782 while ((len
>= back_len
) && strncmp(s
+len
-back_len
,back
,back_len
)==0) {
783 s
[len
-back_len
]='\0';
792 Find the number of 'c' chars in a string
794 _PUBLIC_ _PURE_
size_t count_chars(const char *s
, char c
)
799 if (*s
== c
) count
++;
807 * Routine to get hex characters and turn them into a byte array.
808 * the array can be variable length.
809 * - "0xnn" or "0Xnn" is specially catered for.
810 * - The first non-hex-digit character (apart from possibly leading "0x"
811 * finishes the conversion and skips the rest of the input.
812 * - A single hex-digit character at the end of the string is skipped.
814 * valid examples: "0A5D15"; "0x123456"
816 _PUBLIC_
size_t strhex_to_str(char *p
, size_t p_len
, const char *strhex
, size_t strhex_len
)
819 size_t num_chars
= 0;
820 uint8_t lonybble
, hinybble
;
821 const char *hexchars
= "0123456789ABCDEF";
822 char *p1
= NULL
, *p2
= NULL
;
824 /* skip leading 0x prefix */
825 if (strncasecmp(strhex
, "0x", 2) == 0) {
826 i
+= 2; /* skip two chars */
829 for (; i
+1 < strhex_len
&& strhex
[i
] != 0 && strhex
[i
+1] != 0; i
++) {
830 p1
= strchr(hexchars
, toupper((unsigned char)strhex
[i
]));
835 i
++; /* next hex digit */
837 p2
= strchr(hexchars
, toupper((unsigned char)strhex
[i
]));
842 /* get the two nybbles */
843 hinybble
= PTR_DIFF(p1
, hexchars
);
844 lonybble
= PTR_DIFF(p2
, hexchars
);
846 if (num_chars
>= p_len
) {
850 p
[num_chars
] = (hinybble
<< 4) | lonybble
;
860 * Parse a hex string and return a data blob.
862 _PUBLIC_ _PURE_ DATA_BLOB
strhex_to_data_blob(TALLOC_CTX
*mem_ctx
, const char *strhex
)
864 DATA_BLOB ret_blob
= data_blob_talloc(mem_ctx
, NULL
, strlen(strhex
)/2+1);
866 ret_blob
.length
= strhex_to_str((char *)ret_blob
.data
, ret_blob
.length
,
874 * Parse a hex dump and return a data blob. Hex dump is structured as
875 * is generated from dump_data_cb() elsewhere in this file
878 _PUBLIC_ _PURE_ DATA_BLOB
hexdump_to_data_blob(TALLOC_CTX
*mem_ctx
, const char *hexdump
, size_t hexdump_len
)
880 DATA_BLOB ret_blob
= { 0 };
882 size_t char_count
= 0;
883 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
884 * at the end of the final line to calculate how many are in that line, minus the extra space
886 size_t hexdump_byte_count
= (16 * (hexdump_len
/ 77));
887 if (hexdump_len
% 77) {
888 hexdump_byte_count
+= ((hexdump_len
% 77) - 59 - 2);
891 ret_blob
= data_blob_talloc(mem_ctx
, NULL
, hexdump_byte_count
+1);
892 for (; i
+1 < hexdump_len
&& hexdump
[i
] != 0 && hexdump
[i
+1] != 0; i
++) {
894 i
+= 7; /* Skip the offset at the start of the line */
895 if ((i
%77) < 56) { /* position 56 is after both hex chunks */
896 if (hexdump
[i
] != ' ') {
897 char_count
+= strhex_to_str((char *)&ret_blob
.data
[char_count
],
898 hexdump_byte_count
- char_count
,
908 ret_blob
.length
= char_count
;
914 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
916 _PUBLIC_
void hex_encode_buf(char *dst
, const uint8_t *src
, size_t srclen
)
919 for (i
=0; i
<srclen
; i
++) {
920 snprintf(dst
+ i
*2, 3, "%02X", src
[i
]);
923 * Ensure 0-termination for 0-length buffers
925 dst
[srclen
*2] = '\0';
929 * talloc version of hex_encode_buf()
931 _PUBLIC_
char *hex_encode_talloc(TALLOC_CTX
*mem_ctx
, const unsigned char *buff_in
, size_t len
)
935 hex_buffer
= talloc_array(mem_ctx
, char, (len
*2)+1);
939 hex_encode_buf(hex_buffer
, buff_in
, len
);
940 talloc_set_name_const(hex_buffer
, hex_buffer
);
945 varient of strcmp() that handles NULL ptrs
947 _PUBLIC_
int strcmp_safe(const char *s1
, const char *s2
)
952 if (s1
== NULL
|| s2
== NULL
) {
955 return strcmp(s1
, s2
);
960 return the number of bytes occupied by a buffer in ASCII format
961 the result includes the null termination
964 _PUBLIC_
size_t ascii_len_n(const char *src
, size_t n
)
968 len
= strnlen(src
, n
);
976 struct anonymous_shared_header
{
983 /* Map a shared memory buffer of at least nelem counters. */
984 void *anonymous_shared_allocate(size_t orig_bufsz
)
988 size_t pagesz
= getpagesize();
990 size_t bufsz
= orig_bufsz
;
991 struct anonymous_shared_header
*hdr
;
993 bufsz
+= sizeof(*hdr
);
995 /* round up to full pages */
996 pagecnt
= bufsz
/ pagesz
;
997 if (bufsz
% pagesz
) {
1000 bufsz
= pagesz
* pagecnt
;
1002 if (orig_bufsz
>= bufsz
) {
1010 buf
= mmap(NULL
, bufsz
, PROT_READ
|PROT_WRITE
, MAP_ANON
|MAP_SHARED
,
1011 -1 /* fd */, 0 /* offset */);
1017 fd
= open("/dev/zero", O_RDWR
);
1022 buf
= mmap(NULL
, bufsz
, PROT_READ
|PROT_WRITE
, MAP_FILE
|MAP_SHARED
,
1023 fd
, 0 /* offset */);
1024 saved_errno
= errno
;
1026 errno
= saved_errno
;
1030 if (buf
== MAP_FAILED
) {
1034 hdr
= (struct anonymous_shared_header
*)buf
;
1035 hdr
->u
.length
= bufsz
;
1037 ptr
= (void *)(&hdr
[1]);
1042 void *anonymous_shared_resize(void *ptr
, size_t new_size
, bool maymove
)
1046 size_t pagesz
= getpagesize();
1049 struct anonymous_shared_header
*hdr
;
1057 hdr
= (struct anonymous_shared_header
*)ptr
;
1059 if (hdr
->u
.length
> (new_size
+ sizeof(*hdr
))) {
1064 bufsz
= new_size
+ sizeof(*hdr
);
1066 /* round up to full pages */
1067 pagecnt
= bufsz
/ pagesz
;
1068 if (bufsz
% pagesz
) {
1071 bufsz
= pagesz
* pagecnt
;
1073 if (new_size
>= bufsz
) {
1079 if (bufsz
<= hdr
->u
.length
) {
1084 flags
= MREMAP_MAYMOVE
;
1087 buf
= mremap(hdr
, hdr
->u
.length
, bufsz
, flags
);
1089 if (buf
== MAP_FAILED
) {
1094 hdr
= (struct anonymous_shared_header
*)buf
;
1095 hdr
->u
.length
= bufsz
;
1097 ptr
= (void *)(&hdr
[1]);
1106 void anonymous_shared_free(void *ptr
)
1108 struct anonymous_shared_header
*hdr
;
1114 hdr
= (struct anonymous_shared_header
*)ptr
;
1118 munmap(hdr
, hdr
->u
.length
);
1122 /* used when you want a debugger started at a particular point in the
1123 code. Mostly useful in code that runs as a child process, where
1124 normal gdb attach is harder to organise.
1126 void samba_start_debugger(void)
1129 if (asprintf(&cmd
, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1132 if (system(cmd
) == -1) {