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
10 Copyright (C) Swen Schillig 2019
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 3 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include "system/network.h"
29 #include "system/filesys.h"
30 #include "system/locale.h"
31 #include "system/shmem.h"
32 #include "system/passwd.h"
33 #include "system/time.h"
34 #include "system/wait.h"
36 #include "samba_util.h"
37 #include "lib/util/select.h"
40 #ifdef HAVE_SYS_PRCTL_H
41 #include <sys/prctl.h>
53 * @brief Misc utility functions
57 Find a suitable temporary directory. The result should be copied immediately
58 as it may be overwritten by a subsequent call.
60 _PUBLIC_
const char *tmpdir(void)
63 if ((p
= getenv("TMPDIR")))
70 Create a tmp file, open it and immediately unlink it.
71 If dir is NULL uses tmpdir()
72 Returns the file descriptor or -1 on error.
74 int create_unlink_tmp(const char *dir
)
76 size_t len
= strlen(dir
? dir
: (dir
= tmpdir()));
81 len
= snprintf(fname
, sizeof(fname
), "%s/listenerlock_XXXXXX", dir
);
82 if (len
>= sizeof(fname
)) {
86 mask
= umask(S_IRWXO
| S_IRWXG
);
92 if (unlink(fname
) == -1) {
93 int sys_errno
= errno
;
103 Check if a file exists - call vfs_file_exist for samba files.
105 _PUBLIC_
bool file_exist(const char *fname
)
109 if (stat(fname
, &st
) != 0) {
113 return ((S_ISREG(st
.st_mode
)) || (S_ISFIFO(st
.st_mode
)));
117 Check a files mod time.
120 _PUBLIC_
time_t file_modtime(const char *fname
)
124 if (stat(fname
,&st
) != 0)
131 Check file permissions.
134 _PUBLIC_
bool file_check_permissions(const char *fname
,
148 ret
= stat(fname
, pst
);
150 DEBUG(0, ("stat failed on file '%s': %s\n",
151 fname
, strerror(errno
)));
155 if (pst
->st_uid
!= uid
&& !uid_wrapper_enabled()) {
156 DEBUG(0, ("invalid ownership of file '%s': "
157 "owned by uid %u, should be %u\n",
158 fname
, (unsigned int)pst
->st_uid
,
163 if ((pst
->st_mode
& 0777) != file_perms
) {
164 DEBUG(0, ("invalid permissions on file "
165 "'%s': has 0%o should be 0%o\n", fname
,
166 (unsigned int)(pst
->st_mode
& 0777),
167 (unsigned int)file_perms
));
175 Check if a directory exists.
178 _PUBLIC_
bool directory_exist(const char *dname
)
183 if (stat(dname
,&st
) != 0) {
187 ret
= S_ISDIR(st
.st_mode
);
194 * Try to create the specified directory if it didn't exist.
195 * A symlink to a directory is also accepted as a valid existing directory.
197 * @retval true if the directory already existed
198 * or was successfully created.
200 _PUBLIC_
bool directory_create_or_exist(const char *dname
,
206 /* Create directory */
207 old_umask
= umask(0);
208 ret
= mkdir(dname
, dir_perms
);
209 if (ret
== -1 && errno
!= EEXIST
) {
210 int dbg_level
= geteuid() == 0 ? DBGLVL_ERR
: DBGLVL_NOTICE
;
212 DBG_PREFIX(dbg_level
,
213 ("mkdir failed on directory %s: %s\n",
221 if (ret
!= 0 && errno
== EEXIST
) {
224 ret
= lstat(dname
, &sbuf
);
229 if (S_ISDIR(sbuf
.st_mode
)) {
233 if (S_ISLNK(sbuf
.st_mode
)) {
234 ret
= stat(dname
, &sbuf
);
239 if (S_ISDIR(sbuf
.st_mode
)) {
250 _PUBLIC_
bool directory_create_or_exists_recursive(
256 ok
= directory_create_or_exist(dname
, dir_perms
);
258 if (!directory_exist(dname
)) {
259 char tmp
[PATH_MAX
] = {0};
263 /* Use the null context */
264 n
= strlcpy(tmp
, dname
, sizeof(tmp
));
265 if (n
< strlen(dname
)) {
266 DBG_ERR("Path too long!\n");
270 parent
= dirname(tmp
);
271 if (parent
== NULL
) {
272 DBG_ERR("Failed to create dirname!\n");
276 ok
= directory_create_or_exists_recursive(parent
,
282 ok
= directory_create_or_exist(dname
, dir_perms
);
290 * @brief Try to create a specified directory if it doesn't exist.
292 * The function creates a directory with the given uid and permissions if it
293 * doesn't exist. If it exists it makes sure the uid and permissions are
294 * correct and it will fail if they are different.
296 * @param[in] dname The directory to create.
298 * @param[in] uid The uid the directory needs to belong too.
300 * @param[in] dir_perms The expected permissions of the directory.
302 * @return True on success, false on error.
304 _PUBLIC_
bool directory_create_or_exist_strict(const char *dname
,
312 ok
= directory_create_or_exist(dname
, dir_perms
);
317 rc
= lstat(dname
, &st
);
319 DEBUG(0, ("lstat failed on created directory %s: %s\n",
320 dname
, strerror(errno
)));
324 /* Check ownership and permission on existing directory */
325 if (!S_ISDIR(st
.st_mode
)) {
326 DEBUG(0, ("directory %s isn't a directory\n",
330 if (st
.st_uid
!= uid
&& !uid_wrapper_enabled()) {
331 DBG_NOTICE("invalid ownership on directory "
335 if ((st
.st_mode
& 0777) != dir_perms
) {
336 DEBUG(0, ("invalid permissions on directory "
337 "'%s': has 0%o should be 0%o\n", dname
,
338 (unsigned int)(st
.st_mode
& 0777), (unsigned int)dir_perms
));
347 Sleep for a specified number of milliseconds.
350 _PUBLIC_
void smb_msleep(unsigned int t
)
352 sys_poll_intr(NULL
, 0, t
);
356 Get my own name, return in talloc'ed storage.
359 _PUBLIC_
char *get_myname(TALLOC_CTX
*ctx
)
362 char hostname
[HOST_NAME_MAX
];
364 /* get my host name */
365 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
366 DEBUG(0,("gethostname failed\n"));
370 /* Ensure null termination. */
371 hostname
[sizeof(hostname
)-1] = '\0';
373 /* split off any parts after an initial . */
374 p
= strchr_m(hostname
, '.');
379 return talloc_strdup(ctx
, hostname
);
383 Check if a process exists. Does this work on all unixes?
386 _PUBLIC_
bool process_exists_by_pid(pid_t pid
)
388 /* Doing kill with a non-positive pid causes messages to be
389 * sent to places we don't want. */
393 return(kill(pid
,0) == 0 || errno
!= ESRCH
);
397 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
398 is dealt with in posix.c
401 _PUBLIC_
bool fcntl_lock(int fd
, int op
, off_t offset
, off_t count
, int type
)
406 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd
,op
,(double)offset
,(double)count
,type
));
409 lock
.l_whence
= SEEK_SET
;
410 lock
.l_start
= offset
;
414 ret
= fcntl(fd
,op
,&lock
);
416 if (ret
== -1 && errno
!= 0)
417 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno
,strerror(errno
)));
422 (lock
.l_type
!= F_UNLCK
) &&
424 (lock
.l_pid
!= getpid())) {
425 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd
,(int)lock
.l_pid
));
429 /* it must be not locked or locked by me */
433 /* a lock set or unset */
435 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
436 (double)offset
,(double)count
,op
,type
,strerror(errno
)));
440 /* everything went OK */
441 DEBUG(8,("fcntl_lock: Lock call successful\n"));
446 struct debug_channel_level
{
451 static void debugadd_channel_cb(const char *buf
, void *private_data
)
453 struct debug_channel_level
*dcl
=
454 (struct debug_channel_level
*)private_data
;
456 DEBUGADDC(dcl
->channel
, dcl
->level
,("%s", buf
));
459 static void debugadd_cb(const char *buf
, void *private_data
)
461 int *plevel
= (int *)private_data
;
462 DEBUGADD(*plevel
, ("%s", buf
));
465 void print_asc_cb(const uint8_t *buf
, int len
,
466 void (*cb
)(const char *buf
, void *private_data
),
473 for (i
=0; i
<len
; i
++) {
474 s
[0] = isprint(buf
[i
]) ? buf
[i
] : '.';
479 void print_asc(int level
, const uint8_t *buf
,int len
)
481 print_asc_cb(buf
, len
, debugadd_cb
, &level
);
485 * Write dump of binary data to a callback
487 void dump_data_cb(const uint8_t *buf
, int len
,
488 bool omit_zero_bytes
,
489 void (*cb
)(const char *buf
, void *private_data
),
493 bool skipped
= false;
501 if ((omit_zero_bytes
== true) &&
504 all_zero(&buf
[i
], 16))
511 snprintf(tmp
, sizeof(tmp
), "[%04X] ", i
);
512 cb(tmp
, private_data
);
516 snprintf(tmp
, sizeof(tmp
), "%02X ", (int)buf
[i
]);
517 cb(tmp
, private_data
);
520 cb(" ", private_data
);
524 print_asc_cb(&buf
[i
-16], 8, cb
, private_data
);
525 cb(" ", private_data
);
526 print_asc_cb(&buf
[i
-8], 8, cb
, private_data
);
527 cb("\n", private_data
);
529 if ((omit_zero_bytes
== true) &&
531 all_zero(&buf
[i
], 16)) {
533 cb("skipping zero buffer bytes\n",
544 cb(" ", private_data
);
546 cb(" ", private_data
);
549 cb(" ", private_data
);
552 print_asc_cb(&buf
[i
-(i
%16)], n
, cb
, private_data
);
553 cb(" ", private_data
);
556 print_asc_cb(&buf
[i
-n
], n
, cb
, private_data
);
558 cb("\n", private_data
);
564 * Write dump of binary data to the log file.
566 * The data is only written if the log level is at least level.
568 _PUBLIC_
void dump_data(int level
, const uint8_t *buf
, int len
)
570 if (!DEBUGLVL(level
)) {
573 dump_data_cb(buf
, len
, false, debugadd_cb
, &level
);
577 * Write dump of binary data to the log file.
579 * The data is only written if the log level is at least level for
580 * debug class dbgc_class.
582 _PUBLIC_
void dump_data_dbgc(int dbgc_class
, int level
, const uint8_t *buf
, int len
)
584 struct debug_channel_level dcl
= { dbgc_class
, level
};
586 if (!DEBUGLVLC(dbgc_class
, level
)) {
589 dump_data_cb(buf
, len
, false, debugadd_channel_cb
, &dcl
);
593 * Write dump of binary data to the log file.
595 * The data is only written if the log level is at least level.
596 * 16 zero bytes in a row are omitted
598 _PUBLIC_
void dump_data_skip_zeros(int level
, const uint8_t *buf
, int len
)
600 if (!DEBUGLVL(level
)) {
603 dump_data_cb(buf
, len
, true, debugadd_cb
, &level
);
606 static void fprintf_cb(const char *buf
, void *private_data
)
608 FILE *f
= (FILE *)private_data
;
609 fprintf(f
, "%s", buf
);
612 void dump_data_file(const uint8_t *buf
, int len
, bool omit_zero_bytes
,
615 dump_data_cb(buf
, len
, omit_zero_bytes
, fprintf_cb
, f
);
619 malloc that aborts with smb_panic on fail or zero size.
622 _PUBLIC_
void *smb_xmalloc(size_t size
)
626 smb_panic("smb_xmalloc: called with zero size.\n");
627 if ((p
= malloc(size
)) == NULL
)
628 smb_panic("smb_xmalloc: malloc fail.\n");
633 Memdup with smb_panic on fail.
636 _PUBLIC_
void *smb_xmemdup(const void *p
, size_t size
)
639 p2
= smb_xmalloc(size
);
645 strdup that aborts on malloc fail.
648 char *smb_xstrdup(const char *s
)
650 #if defined(PARANOID_MALLOC_CHECKER)
657 #define strdup rep_strdup
660 char *s1
= strdup(s
);
661 #if defined(PARANOID_MALLOC_CHECKER)
665 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
668 smb_panic("smb_xstrdup: malloc failed");
675 strndup that aborts on malloc fail.
678 char *smb_xstrndup(const char *s
, size_t n
)
680 #if defined(PARANOID_MALLOC_CHECKER)
686 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
688 #define strndup rep_strndup
691 char *s1
= strndup(s
, n
);
692 #if defined(PARANOID_MALLOC_CHECKER)
696 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
699 smb_panic("smb_xstrndup: malloc failed");
707 Like strdup but for memory.
710 _PUBLIC_
void *smb_memdup(const void *p
, size_t size
)
723 * Write a password to the log file.
725 * @note Only actually does something if DEBUG_PASSWORD was defined during
728 _PUBLIC_
void dump_data_pw(const char *msg
, const uint8_t * data
, size_t len
)
730 #ifdef DEBUG_PASSWORD
731 DEBUG(11, ("%s", msg
));
732 if (data
!= NULL
&& len
> 0)
734 dump_data(11, data
, len
);
741 * see if a range of memory is all zero. A NULL pointer is considered
744 _PUBLIC_
bool all_zero(const uint8_t *ptr
, size_t size
)
747 if (!ptr
) return true;
748 for (i
=0;i
<size
;i
++) {
749 if (ptr
[i
]) return false;
755 realloc an array, checking for integer overflow in the array size
757 _PUBLIC_
void *realloc_array(void *ptr
, size_t el_size
, unsigned count
, bool free_on_fail
)
759 #define MAX_MALLOC_SIZE 0x7fffffff
761 count
>= MAX_MALLOC_SIZE
/el_size
) {
767 return malloc(el_size
* count
);
769 return realloc(ptr
, el_size
* count
);
772 /****************************************************************************
774 ****************************************************************************/
776 void *malloc_array(size_t el_size
, unsigned int count
)
778 return realloc_array(NULL
, el_size
, count
, false);
781 /****************************************************************************
783 ****************************************************************************/
785 void *memalign_array(size_t el_size
, size_t align
, unsigned int count
)
787 if (el_size
== 0 || count
>= MAX_MALLOC_SIZE
/el_size
) {
791 return memalign(align
, el_size
*count
);
794 /****************************************************************************
796 ****************************************************************************/
798 void *calloc_array(size_t size
, size_t nmemb
)
800 if (nmemb
>= MAX_MALLOC_SIZE
/size
) {
803 if (size
== 0 || nmemb
== 0) {
806 return calloc(nmemb
, size
);
810 Trim the specified elements off the front and back of a string.
812 _PUBLIC_
bool trim_string(char *s
, const char *front
, const char *back
)
819 /* Ignore null or empty strings. */
820 if (!s
|| (s
[0] == '\0')) {
825 front_len
= front
? strlen(front
) : 0;
826 back_len
= back
? strlen(back
) : 0;
829 size_t front_trim
= 0;
831 while (strncmp(s
+front_trim
, front
, front_len
)==0) {
832 front_trim
+= front_len
;
834 if (front_trim
> 0) {
835 /* Must use memmove here as src & dest can
836 * easily overlap. Found by valgrind. JRA. */
837 memmove(s
, s
+front_trim
, (len
-front_trim
)+1);
844 while ((len
>= back_len
) && strncmp(s
+len
-back_len
,back
,back_len
)==0) {
845 s
[len
-back_len
]='\0';
854 Find the number of 'c' chars in a string
856 _PUBLIC_ _PURE_
size_t count_chars(const char *s
, char c
)
861 if (*s
== c
) count
++;
869 * Routine to get hex characters and turn them into a byte array.
870 * the array can be variable length.
871 * - "0xnn" or "0Xnn" is specially catered for.
872 * - The first non-hex-digit character (apart from possibly leading "0x"
873 * finishes the conversion and skips the rest of the input.
874 * - A single hex-digit character at the end of the string is skipped.
876 * valid examples: "0A5D15"; "0x123456"
878 _PUBLIC_
size_t strhex_to_str(char *p
, size_t p_len
, const char *strhex
, size_t strhex_len
)
881 size_t num_chars
= 0;
883 /* skip leading 0x prefix */
884 if (strncasecmp(strhex
, "0x", 2) == 0) {
885 i
+= 2; /* skip two chars */
888 while ((i
< strhex_len
) && (num_chars
< p_len
)) {
889 bool ok
= hex_byte(&strhex
[i
], (uint8_t *)&p
[num_chars
]);
901 * Parse a hex string and return a data blob.
903 _PUBLIC_ DATA_BLOB
strhex_to_data_blob(TALLOC_CTX
*mem_ctx
, const char *strhex
)
905 DATA_BLOB ret_blob
= data_blob_talloc(mem_ctx
, NULL
, strlen(strhex
)/2+1);
907 ret_blob
.length
= strhex_to_str((char *)ret_blob
.data
, ret_blob
.length
,
915 * Parse a hex dump and return a data blob. Hex dump is structured as
916 * is generated from dump_data_cb() elsewhere in this file
919 _PUBLIC_ DATA_BLOB
hexdump_to_data_blob(TALLOC_CTX
*mem_ctx
, const char *hexdump
, size_t hexdump_len
)
921 DATA_BLOB ret_blob
= { 0 };
923 size_t char_count
= 0;
924 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
925 * at the end of the final line to calculate how many are in that line, minus the extra space
927 size_t hexdump_byte_count
= (16 * (hexdump_len
/ 77));
928 if (hexdump_len
% 77) {
929 hexdump_byte_count
+= ((hexdump_len
% 77) - 59 - 2);
932 ret_blob
= data_blob_talloc(mem_ctx
, NULL
, hexdump_byte_count
+1);
933 for (; i
+1 < hexdump_len
&& hexdump
[i
] != 0 && hexdump
[i
+1] != 0; i
++) {
935 i
+= 7; /* Skip the offset at the start of the line */
936 if ((i
%77) < 56) { /* position 56 is after both hex chunks */
937 if (hexdump
[i
] != ' ') {
938 char_count
+= strhex_to_str((char *)&ret_blob
.data
[char_count
],
939 hexdump_byte_count
- char_count
,
949 ret_blob
.length
= char_count
;
955 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
957 _PUBLIC_
void hex_encode_buf(char *dst
, const uint8_t *src
, size_t srclen
)
960 for (i
=0; i
<srclen
; i
++) {
961 snprintf(dst
+ i
*2, 3, "%02X", src
[i
]);
964 * Ensure 0-termination for 0-length buffers
966 dst
[srclen
*2] = '\0';
970 * talloc version of hex_encode_buf()
972 _PUBLIC_
char *hex_encode_talloc(TALLOC_CTX
*mem_ctx
, const unsigned char *buff_in
, size_t len
)
976 hex_buffer
= talloc_array(mem_ctx
, char, (len
*2)+1);
980 hex_encode_buf(hex_buffer
, buff_in
, len
);
981 talloc_set_name_const(hex_buffer
, hex_buffer
);
986 varient of strcmp() that handles NULL ptrs
988 _PUBLIC_
int strcmp_safe(const char *s1
, const char *s2
)
993 if (s1
== NULL
|| s2
== NULL
) {
996 return strcmp(s1
, s2
);
1001 return the number of bytes occupied by a buffer in ASCII format
1002 the result includes the null termination
1003 limited by 'n' bytes
1005 _PUBLIC_
size_t ascii_len_n(const char *src
, size_t n
)
1009 len
= strnlen(src
, n
);
1017 struct anonymous_shared_header
{
1024 /* Map a shared memory buffer of at least nelem counters. */
1025 void *anonymous_shared_allocate(size_t orig_bufsz
)
1029 size_t pagesz
= getpagesize();
1031 size_t bufsz
= orig_bufsz
;
1032 struct anonymous_shared_header
*hdr
;
1034 bufsz
+= sizeof(*hdr
);
1036 /* round up to full pages */
1037 pagecnt
= bufsz
/ pagesz
;
1038 if (bufsz
% pagesz
) {
1041 bufsz
= pagesz
* pagecnt
;
1043 if (orig_bufsz
>= bufsz
) {
1051 buf
= mmap(NULL
, bufsz
, PROT_READ
|PROT_WRITE
, MAP_ANON
|MAP_SHARED
,
1052 -1 /* fd */, 0 /* offset */);
1058 fd
= open("/dev/zero", O_RDWR
);
1063 buf
= mmap(NULL
, bufsz
, PROT_READ
|PROT_WRITE
, MAP_FILE
|MAP_SHARED
,
1064 fd
, 0 /* offset */);
1065 saved_errno
= errno
;
1067 errno
= saved_errno
;
1071 if (buf
== MAP_FAILED
) {
1075 hdr
= (struct anonymous_shared_header
*)buf
;
1076 hdr
->u
.length
= bufsz
;
1078 ptr
= (void *)(&hdr
[1]);
1083 void *anonymous_shared_resize(void *ptr
, size_t new_size
, bool maymove
)
1087 size_t pagesz
= getpagesize();
1090 struct anonymous_shared_header
*hdr
;
1098 hdr
= (struct anonymous_shared_header
*)ptr
;
1100 if (hdr
->u
.length
> (new_size
+ sizeof(*hdr
))) {
1105 bufsz
= new_size
+ sizeof(*hdr
);
1107 /* round up to full pages */
1108 pagecnt
= bufsz
/ pagesz
;
1109 if (bufsz
% pagesz
) {
1112 bufsz
= pagesz
* pagecnt
;
1114 if (new_size
>= bufsz
) {
1120 if (bufsz
<= hdr
->u
.length
) {
1125 flags
= MREMAP_MAYMOVE
;
1128 buf
= mremap(hdr
, hdr
->u
.length
, bufsz
, flags
);
1130 if (buf
== MAP_FAILED
) {
1135 hdr
= (struct anonymous_shared_header
*)buf
;
1136 hdr
->u
.length
= bufsz
;
1138 ptr
= (void *)(&hdr
[1]);
1147 void anonymous_shared_free(void *ptr
)
1149 struct anonymous_shared_header
*hdr
;
1155 hdr
= (struct anonymous_shared_header
*)ptr
;
1159 munmap(hdr
, hdr
->u
.length
);
1163 /* used when you want a debugger started at a particular point in the
1164 code. Mostly useful in code that runs as a child process, where
1165 normal gdb attach is harder to organise.
1167 void samba_start_debugger(void)
1173 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
1175 * Make sure the child process can attach a debugger.
1177 prctl(PR_SET_PTRACER
, pid
, 0, 0, 0);
1183 if (asprintf(&cmd
, "gdb --pid %u", getppid()) == -1) {
1184 _exit(EXIT_FAILURE
);
1187 execlp("xterm", "xterm", "-e", cmd
, (char *) NULL
);