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"
46 * @brief Misc utility functions
50 Find a suitable temporary directory. The result should be copied immediately
51 as it may be overwritten by a subsequent call.
53 _PUBLIC_
const char *tmpdir(void)
56 if ((p
= getenv("TMPDIR")))
63 Create a tmp file, open it and immediately unlink it.
64 If dir is NULL uses tmpdir()
65 Returns the file descriptor or -1 on error.
67 int create_unlink_tmp(const char *dir
)
69 size_t len
= strlen(dir
? dir
: (dir
= tmpdir()));
74 len
= snprintf(fname
, sizeof(fname
), "%s/listenerlock_XXXXXX", dir
);
75 if (len
>= sizeof(fname
)) {
79 mask
= umask(S_IRWXO
| S_IRWXG
);
85 if (unlink(fname
) == -1) {
86 int sys_errno
= errno
;
96 Check if a file exists - call vfs_file_exist for samba files.
98 _PUBLIC_
bool file_exist(const char *fname
)
102 if (stat(fname
, &st
) != 0) {
106 return ((S_ISREG(st
.st_mode
)) || (S_ISFIFO(st
.st_mode
)));
110 Check a files mod time.
113 _PUBLIC_
time_t file_modtime(const char *fname
)
117 if (stat(fname
,&st
) != 0)
124 Check file permissions.
127 _PUBLIC_
bool file_check_permissions(const char *fname
,
141 ret
= stat(fname
, pst
);
143 DEBUG(0, ("stat failed on file '%s': %s\n",
144 fname
, strerror(errno
)));
148 if (pst
->st_uid
!= uid
&& !uid_wrapper_enabled()) {
149 DEBUG(0, ("invalid ownership of file '%s': "
150 "owned by uid %u, should be %u\n",
151 fname
, (unsigned int)pst
->st_uid
,
156 if ((pst
->st_mode
& 0777) != file_perms
) {
157 DEBUG(0, ("invalid permissions on file "
158 "'%s': has 0%o should be 0%o\n", fname
,
159 (unsigned int)(pst
->st_mode
& 0777),
160 (unsigned int)file_perms
));
168 Check if a directory exists.
171 _PUBLIC_
bool directory_exist(const char *dname
)
176 if (stat(dname
,&st
) != 0) {
180 ret
= S_ISDIR(st
.st_mode
);
187 * Try to create the specified directory if it didn't exist.
189 * @retval true if the directory already existed
190 * or was successfully created.
192 _PUBLIC_
bool directory_create_or_exist(const char *dname
,
199 ret
= lstat(dname
, &st
);
204 if (errno
!= ENOENT
) {
205 DBG_WARNING("lstat failed on directory %s: %s\n",
206 dname
, strerror(errno
));
210 /* Create directory */
211 old_umask
= umask(0);
212 ret
= mkdir(dname
, dir_perms
);
213 if (ret
== -1 && errno
!= EEXIST
) {
214 DEBUG(0, ("mkdir failed on directory "
222 ret
= lstat(dname
, &st
);
224 DEBUG(0, ("lstat failed on created directory %s: %s\n",
225 dname
, strerror(errno
)));
233 * @brief Try to create a specified directory if it doesn't exist.
235 * The function creates a directory with the given uid and permissions if it
236 * doesn't exist. If it exists it makes sure the uid and permissions are
237 * correct and it will fail if they are different.
239 * @param[in] dname The directory to create.
241 * @param[in] uid The uid the directory needs to belong too.
243 * @param[in] dir_perms The expected permissions of the directory.
245 * @return True on success, false on error.
247 _PUBLIC_
bool directory_create_or_exist_strict(const char *dname
,
255 ok
= directory_create_or_exist(dname
, dir_perms
);
260 rc
= lstat(dname
, &st
);
262 DEBUG(0, ("lstat failed on created directory %s: %s\n",
263 dname
, strerror(errno
)));
267 /* Check ownership and permission on existing directory */
268 if (!S_ISDIR(st
.st_mode
)) {
269 DEBUG(0, ("directory %s isn't a directory\n",
273 if (st
.st_uid
!= uid
&& !uid_wrapper_enabled()) {
274 DBG_NOTICE("invalid ownership on directory "
278 if ((st
.st_mode
& 0777) != dir_perms
) {
279 DEBUG(0, ("invalid permissions on directory "
280 "'%s': has 0%o should be 0%o\n", dname
,
281 (unsigned int)(st
.st_mode
& 0777), (unsigned int)dir_perms
));
290 Sleep for a specified number of milliseconds.
293 _PUBLIC_
void smb_msleep(unsigned int t
)
295 #if defined(HAVE_NANOSLEEP)
300 ts
.tv_nsec
= 1000000*(t
%1000);
304 ret
= nanosleep(&ts
, &ts
);
305 } while (ret
< 0 && errno
== EINTR
&& (ts
.tv_sec
> 0 || ts
.tv_nsec
> 0));
307 unsigned int tdiff
=0;
308 struct timeval tval
,t1
,t2
;
315 tval
.tv_sec
= (t
-tdiff
)/1000;
316 tval
.tv_usec
= 1000*((t
-tdiff
)%1000);
318 /* Never wait for more than 1 sec. */
319 if (tval
.tv_sec
> 1) {
326 select(0,&fds
,NULL
,NULL
,&tval
);
329 if (t2
.tv_sec
< t1
.tv_sec
) {
330 /* Someone adjusted time... */
334 tdiff
= usec_time_diff(&t2
,&t1
)/1000;
340 Get my own name, return in talloc'ed storage.
343 _PUBLIC_
char *get_myname(TALLOC_CTX
*ctx
)
346 char hostname
[HOST_NAME_MAX
];
348 /* get my host name */
349 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
350 DEBUG(0,("gethostname failed\n"));
354 /* Ensure null termination. */
355 hostname
[sizeof(hostname
)-1] = '\0';
357 /* split off any parts after an initial . */
358 p
= strchr_m(hostname
, '.');
363 return talloc_strdup(ctx
, hostname
);
367 Check if a process exists. Does this work on all unixes?
370 _PUBLIC_
bool process_exists_by_pid(pid_t pid
)
372 /* Doing kill with a non-positive pid causes messages to be
373 * sent to places we don't want. */
377 return(kill(pid
,0) == 0 || errno
!= ESRCH
);
381 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
382 is dealt with in posix.c
385 _PUBLIC_
bool fcntl_lock(int fd
, int op
, off_t offset
, off_t count
, int type
)
390 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd
,op
,(double)offset
,(double)count
,type
));
393 lock
.l_whence
= SEEK_SET
;
394 lock
.l_start
= offset
;
398 ret
= fcntl(fd
,op
,&lock
);
400 if (ret
== -1 && errno
!= 0)
401 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno
,strerror(errno
)));
406 (lock
.l_type
!= F_UNLCK
) &&
408 (lock
.l_pid
!= getpid())) {
409 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd
,(int)lock
.l_pid
));
413 /* it must be not locked or locked by me */
417 /* a lock set or unset */
419 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
420 (double)offset
,(double)count
,op
,type
,strerror(errno
)));
424 /* everything went OK */
425 DEBUG(8,("fcntl_lock: Lock call successful\n"));
430 struct debug_channel_level
{
435 static void debugadd_channel_cb(const char *buf
, void *private_data
)
437 struct debug_channel_level
*dcl
=
438 (struct debug_channel_level
*)private_data
;
440 DEBUGADDC(dcl
->channel
, dcl
->level
,("%s", buf
));
443 static void debugadd_cb(const char *buf
, void *private_data
)
445 int *plevel
= (int *)private_data
;
446 DEBUGADD(*plevel
, ("%s", buf
));
449 void print_asc_cb(const uint8_t *buf
, int len
,
450 void (*cb
)(const char *buf
, void *private_data
),
457 for (i
=0; i
<len
; i
++) {
458 s
[0] = isprint(buf
[i
]) ? buf
[i
] : '.';
463 void print_asc(int level
, const uint8_t *buf
,int len
)
465 print_asc_cb(buf
, len
, debugadd_cb
, &level
);
469 * Write dump of binary data to a callback
471 void dump_data_cb(const uint8_t *buf
, int len
,
472 bool omit_zero_bytes
,
473 void (*cb
)(const char *buf
, void *private_data
),
477 static const uint8_t empty
[16] = { 0, };
478 bool skipped
= false;
486 if ((omit_zero_bytes
== true) &&
489 (memcmp(&buf
[i
], &empty
, 16) == 0))
496 snprintf(tmp
, sizeof(tmp
), "[%04X] ", i
);
497 cb(tmp
, private_data
);
501 snprintf(tmp
, sizeof(tmp
), "%02X ", (int)buf
[i
]);
502 cb(tmp
, private_data
);
505 cb(" ", private_data
);
509 print_asc_cb(&buf
[i
-16], 8, cb
, private_data
);
510 cb(" ", private_data
);
511 print_asc_cb(&buf
[i
-8], 8, cb
, private_data
);
512 cb("\n", private_data
);
514 if ((omit_zero_bytes
== true) &&
516 (memcmp(&buf
[i
], &empty
, 16) == 0)) {
518 cb("skipping zero buffer bytes\n",
529 cb(" ", private_data
);
531 cb(" ", private_data
);
534 cb(" ", private_data
);
537 print_asc_cb(&buf
[i
-(i
%16)], n
, cb
, private_data
);
538 cb(" ", private_data
);
541 print_asc_cb(&buf
[i
-n
], n
, cb
, private_data
);
543 cb("\n", private_data
);
549 * Write dump of binary data to the log file.
551 * The data is only written if the log level is at least level.
553 _PUBLIC_
void dump_data(int level
, const uint8_t *buf
, int len
)
555 if (!DEBUGLVL(level
)) {
558 dump_data_cb(buf
, len
, false, debugadd_cb
, &level
);
562 * Write dump of binary data to the log file.
564 * The data is only written if the log level is at least level for
565 * debug class dbgc_class.
567 _PUBLIC_
void dump_data_dbgc(int dbgc_class
, int level
, const uint8_t *buf
, int len
)
569 struct debug_channel_level dcl
= { dbgc_class
, level
};
571 if (!DEBUGLVLC(dbgc_class
, level
)) {
574 dump_data_cb(buf
, len
, false, debugadd_channel_cb
, &dcl
);
578 * Write dump of binary data to the log file.
580 * The data is only written if the log level is at least level.
581 * 16 zero bytes in a row are omitted
583 _PUBLIC_
void dump_data_skip_zeros(int level
, const uint8_t *buf
, int len
)
585 if (!DEBUGLVL(level
)) {
588 dump_data_cb(buf
, len
, true, debugadd_cb
, &level
);
591 static void fprintf_cb(const char *buf
, void *private_data
)
593 FILE *f
= (FILE *)private_data
;
594 fprintf(f
, "%s", buf
);
597 void dump_data_file(const uint8_t *buf
, int len
, bool omit_zero_bytes
,
600 dump_data_cb(buf
, len
, omit_zero_bytes
, fprintf_cb
, f
);
604 malloc that aborts with smb_panic on fail or zero size.
607 _PUBLIC_
void *smb_xmalloc(size_t size
)
611 smb_panic("smb_xmalloc: called with zero size.\n");
612 if ((p
= malloc(size
)) == NULL
)
613 smb_panic("smb_xmalloc: malloc fail.\n");
618 Memdup with smb_panic on fail.
621 _PUBLIC_
void *smb_xmemdup(const void *p
, size_t size
)
624 p2
= smb_xmalloc(size
);
630 strdup that aborts on malloc fail.
633 char *smb_xstrdup(const char *s
)
635 #if defined(PARANOID_MALLOC_CHECKER)
642 #define strdup rep_strdup
645 char *s1
= strdup(s
);
646 #if defined(PARANOID_MALLOC_CHECKER)
650 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
653 smb_panic("smb_xstrdup: malloc failed");
660 strndup that aborts on malloc fail.
663 char *smb_xstrndup(const char *s
, size_t n
)
665 #if defined(PARANOID_MALLOC_CHECKER)
671 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
673 #define strndup rep_strndup
676 char *s1
= strndup(s
, n
);
677 #if defined(PARANOID_MALLOC_CHECKER)
681 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
684 smb_panic("smb_xstrndup: malloc failed");
692 Like strdup but for memory.
695 _PUBLIC_
void *smb_memdup(const void *p
, size_t size
)
708 * Write a password to the log file.
710 * @note Only actually does something if DEBUG_PASSWORD was defined during
713 _PUBLIC_
void dump_data_pw(const char *msg
, const uint8_t * data
, size_t len
)
715 #ifdef DEBUG_PASSWORD
716 DEBUG(11, ("%s", msg
));
717 if (data
!= NULL
&& len
> 0)
719 dump_data(11, data
, len
);
726 * see if a range of memory is all zero. A NULL pointer is considered
729 _PUBLIC_
bool all_zero(const uint8_t *ptr
, size_t size
)
732 if (!ptr
) return true;
733 for (i
=0;i
<size
;i
++) {
734 if (ptr
[i
]) return false;
740 realloc an array, checking for integer overflow in the array size
742 _PUBLIC_
void *realloc_array(void *ptr
, size_t el_size
, unsigned count
, bool free_on_fail
)
744 #define MAX_MALLOC_SIZE 0x7fffffff
746 count
>= MAX_MALLOC_SIZE
/el_size
) {
752 return malloc(el_size
* count
);
754 return realloc(ptr
, el_size
* count
);
757 /****************************************************************************
759 ****************************************************************************/
761 void *malloc_array(size_t el_size
, unsigned int count
)
763 return realloc_array(NULL
, el_size
, count
, false);
766 /****************************************************************************
768 ****************************************************************************/
770 void *memalign_array(size_t el_size
, size_t align
, unsigned int count
)
772 if (el_size
== 0 || count
>= MAX_MALLOC_SIZE
/el_size
) {
776 return memalign(align
, el_size
*count
);
779 /****************************************************************************
781 ****************************************************************************/
783 void *calloc_array(size_t size
, size_t nmemb
)
785 if (nmemb
>= MAX_MALLOC_SIZE
/size
) {
788 if (size
== 0 || nmemb
== 0) {
791 return calloc(nmemb
, size
);
795 Trim the specified elements off the front and back of a string.
797 _PUBLIC_
bool trim_string(char *s
, const char *front
, const char *back
)
804 /* Ignore null or empty strings. */
805 if (!s
|| (s
[0] == '\0')) {
810 front_len
= front
? strlen(front
) : 0;
811 back_len
= back
? strlen(back
) : 0;
814 size_t front_trim
= 0;
816 while (strncmp(s
+front_trim
, front
, front_len
)==0) {
817 front_trim
+= front_len
;
819 if (front_trim
> 0) {
820 /* Must use memmove here as src & dest can
821 * easily overlap. Found by valgrind. JRA. */
822 memmove(s
, s
+front_trim
, (len
-front_trim
)+1);
829 while ((len
>= back_len
) && strncmp(s
+len
-back_len
,back
,back_len
)==0) {
830 s
[len
-back_len
]='\0';
839 Find the number of 'c' chars in a string
841 _PUBLIC_ _PURE_
size_t count_chars(const char *s
, char c
)
846 if (*s
== c
) count
++;
854 * Routine to get hex characters and turn them into a byte array.
855 * the array can be variable length.
856 * - "0xnn" or "0Xnn" is specially catered for.
857 * - The first non-hex-digit character (apart from possibly leading "0x"
858 * finishes the conversion and skips the rest of the input.
859 * - A single hex-digit character at the end of the string is skipped.
861 * valid examples: "0A5D15"; "0x123456"
863 _PUBLIC_
size_t strhex_to_str(char *p
, size_t p_len
, const char *strhex
, size_t strhex_len
)
866 size_t num_chars
= 0;
867 uint8_t lonybble
, hinybble
;
868 const char *hexchars
= "0123456789ABCDEF";
869 char *p1
= NULL
, *p2
= NULL
;
871 /* skip leading 0x prefix */
872 if (strncasecmp(strhex
, "0x", 2) == 0) {
873 i
+= 2; /* skip two chars */
876 for (; i
+1 < strhex_len
&& strhex
[i
] != 0 && strhex
[i
+1] != 0; i
++) {
877 p1
= strchr(hexchars
, toupper((unsigned char)strhex
[i
]));
882 i
++; /* next hex digit */
884 p2
= strchr(hexchars
, toupper((unsigned char)strhex
[i
]));
889 /* get the two nybbles */
890 hinybble
= PTR_DIFF(p1
, hexchars
);
891 lonybble
= PTR_DIFF(p2
, hexchars
);
893 if (num_chars
>= p_len
) {
897 p
[num_chars
] = (hinybble
<< 4) | lonybble
;
907 * Parse a hex string and return a data blob.
909 _PUBLIC_ _PURE_ DATA_BLOB
strhex_to_data_blob(TALLOC_CTX
*mem_ctx
, const char *strhex
)
911 DATA_BLOB ret_blob
= data_blob_talloc(mem_ctx
, NULL
, strlen(strhex
)/2+1);
913 ret_blob
.length
= strhex_to_str((char *)ret_blob
.data
, ret_blob
.length
,
921 * Parse a hex dump and return a data blob. Hex dump is structured as
922 * is generated from dump_data_cb() elsewhere in this file
925 _PUBLIC_ _PURE_ DATA_BLOB
hexdump_to_data_blob(TALLOC_CTX
*mem_ctx
, const char *hexdump
, size_t hexdump_len
)
927 DATA_BLOB ret_blob
= {'\0'};
929 size_t char_count
= 0;
930 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
931 * at the end of the final line to calculate how many are in that line, minus the extra space
933 size_t hexdump_byte_count
= (16 * (hexdump_len
/ 77));
934 if (hexdump_len
% 77) {
935 hexdump_byte_count
+= ((hexdump_len
% 77) - 59 - 2);
938 ret_blob
= data_blob_talloc(mem_ctx
, NULL
, hexdump_byte_count
+1);
939 for (; i
+1 < hexdump_len
&& hexdump
[i
] != 0 && hexdump
[i
+1] != 0; i
++) {
941 i
+= 7; /* Skip the offset at the start of the line */
942 if ((i
%77) < 56) { /* position 56 is after both hex chunks */
943 if (hexdump
[i
] != ' ') {
944 char_count
+= strhex_to_str((char *)&ret_blob
.data
[char_count
],
945 hexdump_byte_count
- char_count
,
955 ret_blob
.length
= char_count
;
961 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
963 _PUBLIC_
void hex_encode_buf(char *dst
, const uint8_t *src
, size_t srclen
)
966 for (i
=0; i
<srclen
; i
++) {
967 snprintf(dst
+ i
*2, 3, "%02X", src
[i
]);
970 * Ensure 0-termination for 0-length buffers
972 dst
[srclen
*2] = '\0';
976 * talloc version of hex_encode_buf()
978 _PUBLIC_
char *hex_encode_talloc(TALLOC_CTX
*mem_ctx
, const unsigned char *buff_in
, size_t len
)
982 hex_buffer
= talloc_array(mem_ctx
, char, (len
*2)+1);
986 hex_encode_buf(hex_buffer
, buff_in
, len
);
987 talloc_set_name_const(hex_buffer
, hex_buffer
);
992 varient of strcmp() that handles NULL ptrs
994 _PUBLIC_
int strcmp_safe(const char *s1
, const char *s2
)
999 if (s1
== NULL
|| s2
== NULL
) {
1002 return strcmp(s1
, s2
);
1007 return the number of bytes occupied by a buffer in ASCII format
1008 the result includes the null termination
1009 limited by 'n' bytes
1011 _PUBLIC_
size_t ascii_len_n(const char *src
, size_t n
)
1015 len
= strnlen(src
, n
);
1023 struct anonymous_shared_header
{
1030 /* Map a shared memory buffer of at least nelem counters. */
1031 void *anonymous_shared_allocate(size_t orig_bufsz
)
1035 size_t pagesz
= getpagesize();
1037 size_t bufsz
= orig_bufsz
;
1038 struct anonymous_shared_header
*hdr
;
1040 bufsz
+= sizeof(*hdr
);
1042 /* round up to full pages */
1043 pagecnt
= bufsz
/ pagesz
;
1044 if (bufsz
% pagesz
) {
1047 bufsz
= pagesz
* pagecnt
;
1049 if (orig_bufsz
>= bufsz
) {
1057 buf
= mmap(NULL
, bufsz
, PROT_READ
|PROT_WRITE
, MAP_ANON
|MAP_SHARED
,
1058 -1 /* fd */, 0 /* offset */);
1064 fd
= open("/dev/zero", O_RDWR
);
1069 buf
= mmap(NULL
, bufsz
, PROT_READ
|PROT_WRITE
, MAP_FILE
|MAP_SHARED
,
1070 fd
, 0 /* offset */);
1071 saved_errno
= errno
;
1073 errno
= saved_errno
;
1077 if (buf
== MAP_FAILED
) {
1081 hdr
= (struct anonymous_shared_header
*)buf
;
1082 hdr
->u
.length
= bufsz
;
1084 ptr
= (void *)(&hdr
[1]);
1089 void *anonymous_shared_resize(void *ptr
, size_t new_size
, bool maymove
)
1093 size_t pagesz
= getpagesize();
1096 struct anonymous_shared_header
*hdr
;
1104 hdr
= (struct anonymous_shared_header
*)ptr
;
1106 if (hdr
->u
.length
> (new_size
+ sizeof(*hdr
))) {
1111 bufsz
= new_size
+ sizeof(*hdr
);
1113 /* round up to full pages */
1114 pagecnt
= bufsz
/ pagesz
;
1115 if (bufsz
% pagesz
) {
1118 bufsz
= pagesz
* pagecnt
;
1120 if (new_size
>= bufsz
) {
1126 if (bufsz
<= hdr
->u
.length
) {
1131 flags
= MREMAP_MAYMOVE
;
1134 buf
= mremap(hdr
, hdr
->u
.length
, bufsz
, flags
);
1136 if (buf
== MAP_FAILED
) {
1141 hdr
= (struct anonymous_shared_header
*)buf
;
1142 hdr
->u
.length
= bufsz
;
1144 ptr
= (void *)(&hdr
[1]);
1153 void anonymous_shared_free(void *ptr
)
1155 struct anonymous_shared_header
*hdr
;
1161 hdr
= (struct anonymous_shared_header
*)ptr
;
1165 munmap(hdr
, hdr
->u
.length
);
1169 /* used when you want a debugger started at a particular point in the
1170 code. Mostly useful in code that runs as a child process, where
1171 normal gdb attach is harder to organise.
1173 void samba_start_debugger(void)
1176 if (asprintf(&cmd
, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1179 if (system(cmd
) == -1) {