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/>.
25 #include "system/network.h"
26 #include "system/filesys.h"
27 #include "system/locale.h"
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"
40 #define uwrap_enabled() 0
45 * @brief Misc utility functions
49 Find a suitable temporary directory. The result should be copied immediately
50 as it may be overwritten by a subsequent call.
52 _PUBLIC_
const char *tmpdir(void)
55 if ((p
= getenv("TMPDIR")))
62 Check if a file exists - call vfs_file_exist for samba files.
64 _PUBLIC_
bool file_exist(const char *fname
)
68 if (stat(fname
, &st
) != 0) {
72 return ((S_ISREG(st
.st_mode
)) || (S_ISFIFO(st
.st_mode
)));
76 Check a files mod time.
79 _PUBLIC_
time_t file_modtime(const char *fname
)
83 if (stat(fname
,&st
) != 0)
90 Check if a directory exists.
93 _PUBLIC_
bool directory_exist(const char *dname
)
98 if (stat(dname
,&st
) != 0) {
102 ret
= S_ISDIR(st
.st_mode
);
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
,
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 "
132 DEBUG(0, ("lstat failed on directory %s: %s\n",
133 dname
, strerror(errno
)));
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",
145 if (st
.st_uid
!= uid
&& !uwrap_enabled()) {
146 DEBUG(0, ("invalid ownership on directory "
151 if ((st
.st_mode
& 0777) != dir_perms
) {
152 DEBUG(0, ("invalid permissions on directory "
163 Sleep for a specified number of milliseconds.
166 _PUBLIC_
void msleep(unsigned int t
)
170 tval
.tv_sec
= t
/1000;
171 tval
.tv_usec
= 1000*(t
%1000);
172 /* this should be the real select - do NOT replace
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
)
184 char hostname
[HOST_NAME_MAX
];
186 /* get my host name */
187 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
188 DEBUG(0,("gethostname failed\n"));
192 /* Ensure null termination. */
193 hostname
[sizeof(hostname
)-1] = '\0';
195 /* split off any parts after an initial . */
196 p
= strchr_m(hostname
, '.');
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. */
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
)
226 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd
,op
,(double)offset
,(double)count
,type
));
229 lock
.l_whence
= SEEK_SET
;
230 lock
.l_start
= offset
;
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
)));
242 (lock
.l_type
!= F_UNLCK
) &&
244 (lock
.l_pid
!= getpid())) {
245 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd
,(int)lock
.l_pid
));
249 /* it must be not locked or locked by me */
253 /* a lock set or unset */
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
)));
260 /* everything went OK */
261 DEBUG(8,("fcntl_lock: Lock call successful\n"));
266 void print_asc(int level
, const uint8_t *buf
,int len
)
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
)
282 static const uint8_t empty
[16] = { 0, };
283 bool skipped
= false;
287 if (!DEBUGLVL(level
)) return;
292 if ((omit_zero_bytes
== true) &&
295 (memcmp(&buf
[i
], &empty
, 16) == 0))
302 DEBUGADD(level
,("[%04X] ",i
));
306 DEBUGADD(level
,("%02X ",(int)buf
[i
]));
308 if (i
%8 == 0) DEBUGADD(level
,(" "));
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) &&
316 (memcmp(&buf
[i
], &empty
, 16) == 0)) {
318 DEBUGADD(level
,("skipping zero buffer bytes\n"));
328 DEBUGADD(level
,(" "));
329 if (n
>8) DEBUGADD(level
,(" "));
330 while (n
--) DEBUGADD(level
,(" "));
332 print_asc(level
,&buf
[i
-(i
%16)],n
); DEBUGADD(level
,( " " ));
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
)
370 smb_panic("smb_xmalloc: called with zero size.\n");
371 if ((p
= malloc(size
)) == NULL
)
372 smb_panic("smb_xmalloc: malloc fail.\n");
377 Memdup with smb_panic on fail.
380 _PUBLIC_
void *smb_xmemdup(const void *p
, size_t size
)
383 p2
= smb_xmalloc(size
);
389 strdup that aborts on malloc fail.
392 char *smb_xstrdup(const char *s
)
394 #if defined(PARANOID_MALLOC_CHECKER)
401 #define strdup rep_strdup
404 char *s1
= strdup(s
);
405 #if defined(PARANOID_MALLOC_CHECKER)
409 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
412 smb_panic("smb_xstrdup: malloc failed");
419 strndup that aborts on malloc fail.
422 char *smb_xstrndup(const char *s
, size_t n
)
424 #if defined(PARANOID_MALLOC_CHECKER)
430 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
432 #define strndup rep_strndup
435 char *s1
= strndup(s
, n
);
436 #if defined(PARANOID_MALLOC_CHECKER)
440 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
443 smb_panic("smb_xstrndup: malloc failed");
451 Like strdup but for memory.
454 _PUBLIC_
void *memdup(const void *p
, size_t size
)
467 * Write a password to the log file.
469 * @note Only actually does something if DEBUG_PASSWORD was defined during
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
);
485 * see if a range of memory is all zero. A NULL pointer is considered
488 _PUBLIC_
bool all_zero(const uint8_t *ptr
, size_t size
)
491 if (!ptr
) return true;
492 for (i
=0;i
<size
;i
++) {
493 if (ptr
[i
]) return false;
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
505 count
>= MAX_MALLOC_SIZE
/el_size
) {
511 return malloc(el_size
* count
);
513 return realloc(ptr
, el_size
* count
);
516 /****************************************************************************
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
)
535 /* Ignore null or empty strings. */
536 if (!s
|| (s
[0] == '\0'))
539 front_len
= front
? strlen(front
) : 0;
540 back_len
= back
? strlen(back
) : 0;
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);
555 while ((len
>= back_len
) && strncmp(s
+len
-back_len
,back
,back_len
)==0) {
556 s
[len
-back_len
]='\0';
565 Find the number of 'c' chars in a string
567 _PUBLIC_ _PURE_
size_t count_chars(const char *s
, char c
)
572 if (*s
== c
) 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
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
)
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
]))))
606 i
++; /* next hex digit */
608 if (!(p2
= strchr(hexchars
, toupper((unsigned char)strhex
[i
]))))
611 /* get the two nybbles */
612 hinybble
= PTR_DIFF(p1
, hexchars
);
613 lonybble
= PTR_DIFF(p2
, hexchars
);
615 if (num_chars
>= p_len
) {
619 p
[num_chars
] = (hinybble
<< 4) | lonybble
;
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
,
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
)
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
)
666 hex_buffer
= talloc_array(mem_ctx
, char, (len
*2)+1);
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
);
679 varient of strcmp() that handles NULL ptrs
681 _PUBLIC_
int strcmp_safe(const char *s1
, const char *s2
)
686 if (s1
== NULL
|| s2
== NULL
) {
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
698 _PUBLIC_
size_t ascii_len_n(const char *src
, size_t n
)
702 len
= strnlen(src
, n
);
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
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) {
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) {
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
)
742 for (len
= 0; SVAL(buf
,len
); len
+= 2) ;
748 return the number of bytes occupied by a buffer in CH_UTF16 format
749 the result includes the null termination
752 _PUBLIC_
size_t utf16_len_n(const void *src
, size_t n
)
756 for (len
= 0; (len
+2 < n
) && SVAL(src
, len
); len
+= 2) ;
767 * @brief String utilities.
770 static bool next_token_internal_talloc(TALLOC_CTX
*ctx
,
789 /* default to simple separators */
794 /* find the first non sep char, if left-trimming is requested */
796 while (*s
&& strchr_m(sep
,*s
)) {
806 /* When restarting we need to go from here. */
809 /* Work out the length needed. */
810 for (quoted
= false; *s
&&
811 (quoted
|| !strchr_m(sep
,*s
)); s
++) {
819 /* We started with len = 1 so we have space for the nul. */
820 *pp_buff
= talloc_array(ctx
, char, len
);
825 /* copy over the token */
828 for (quoted
= false; *s
&&
829 (quoted
|| !strchr_m(sep
,*s
)); s
++) {
837 *ptr
= (*s
) ? s
+1 : s
;
843 bool next_token_talloc(TALLOC_CTX
*ctx
,
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
,
862 return next_token_internal_talloc(ctx
, ptr
, pp_buff
, sep
, false);