spoolss-iremotewinspool-tests: Use more recent client OS version
[Samba.git] / lib / util / util.c
blobf52f69c6ef01599e5099c799a1f8e59f164a9294
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-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/>.
25 #include "replace.h"
26 #include <talloc.h>
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"
34 #include "debug.h"
35 #include "samba_util.h"
36 #include "lib/util/select.h"
38 #undef malloc
39 #undef strcasecmp
40 #undef strncasecmp
41 #undef strdup
42 #undef realloc
43 #undef calloc
45 /**
46 * @file
47 * @brief Misc utility functions
50 /**
51 Find a suitable temporary directory. The result should be copied immediately
52 as it may be overwritten by a subsequent call.
53 **/
54 _PUBLIC_ const char *tmpdir(void)
56 char *p;
57 if ((p = getenv("TMPDIR")))
58 return p;
59 return "/tmp";
63 /**
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.
67 **/
68 int create_unlink_tmp(const char *dir)
70 size_t len = strlen(dir ? dir : (dir = tmpdir()));
71 char fname[len+25];
72 int fd;
73 mode_t mask;
75 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
76 if (len >= sizeof(fname)) {
77 errno = ENOMEM;
78 return -1;
80 mask = umask(S_IRWXO | S_IRWXG);
81 fd = mkstemp(fname);
82 umask(mask);
83 if (fd == -1) {
84 return -1;
86 if (unlink(fname) == -1) {
87 int sys_errno = errno;
88 close(fd);
89 errno = sys_errno;
90 return -1;
92 return fd;
96 /**
97 Check if a file exists - call vfs_file_exist for samba files.
98 **/
99 _PUBLIC_ bool file_exist(const char *fname)
101 struct stat st;
103 if (stat(fname, &st) != 0) {
104 return false;
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)
116 struct stat st;
118 if (stat(fname,&st) != 0)
119 return(0);
121 return(st.st_mtime);
125 Check file permissions.
128 _PUBLIC_ bool file_check_permissions(const char *fname,
129 uid_t uid,
130 mode_t file_perms,
131 struct stat *pst)
133 int ret;
134 struct stat st;
136 if (pst == NULL) {
137 pst = &st;
140 ZERO_STRUCTP(pst);
142 ret = stat(fname, pst);
143 if (ret != 0) {
144 DEBUG(0, ("stat failed on file '%s': %s\n",
145 fname, strerror(errno)));
146 return false;
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,
153 (unsigned int)uid));
154 return false;
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));
162 return false;
165 return true;
169 Check if a directory exists.
172 _PUBLIC_ bool directory_exist(const char *dname)
174 struct stat st;
175 bool ret;
177 if (stat(dname,&st) != 0) {
178 return false;
181 ret = S_ISDIR(st.st_mode);
182 if(!ret)
183 errno = ENOTDIR;
184 return ret;
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,
194 mode_t dir_perms)
196 int ret;
197 mode_t old_umask;
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 "
204 "%s: %s\n", dname,
205 strerror(errno)));
206 umask(old_umask);
207 return false;
209 umask(old_umask);
211 if (ret != 0 && errno == EEXIST) {
212 struct stat sbuf;
214 ret = lstat(dname, &sbuf);
215 if (ret != 0) {
216 return false;
219 if (!S_ISDIR(sbuf.st_mode)) {
220 return false;
224 return true;
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,
243 uid_t uid,
244 mode_t dir_perms)
246 struct stat st;
247 bool ok;
248 int rc;
250 ok = directory_create_or_exist(dname, dir_perms);
251 if (!ok) {
252 return false;
255 rc = lstat(dname, &st);
256 if (rc == -1) {
257 DEBUG(0, ("lstat failed on created directory %s: %s\n",
258 dname, strerror(errno)));
259 return false;
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",
265 dname));
266 return false;
268 if (st.st_uid != uid && !uid_wrapper_enabled()) {
269 DBG_NOTICE("invalid ownership on directory "
270 "%s\n", dname);
271 return false;
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));
277 return false;
280 return true;
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)
299 char *p;
300 char hostname[HOST_NAME_MAX];
302 /* get my host name */
303 if (gethostname(hostname, sizeof(hostname)) == -1) {
304 DEBUG(0,("gethostname failed\n"));
305 return NULL;
308 /* Ensure null termination. */
309 hostname[sizeof(hostname)-1] = '\0';
311 /* split off any parts after an initial . */
312 p = strchr_m(hostname, '.');
313 if (p) {
314 *p = 0;
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. */
328 if (pid <= 0) {
329 return false;
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)
341 struct flock lock;
342 int ret;
344 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
346 lock.l_type = type;
347 lock.l_whence = SEEK_SET;
348 lock.l_start = offset;
349 lock.l_len = count;
350 lock.l_pid = 0;
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)));
357 /* a lock query */
358 if (op == F_GETLK) {
359 if ((ret != -1) &&
360 (lock.l_type != F_UNLCK) &&
361 (lock.l_pid != 0) &&
362 (lock.l_pid != getpid())) {
363 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
364 return true;
367 /* it must be not locked or locked by me */
368 return false;
371 /* a lock set or unset */
372 if (ret == -1) {
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)));
375 return false;
378 /* everything went OK */
379 DEBUG(8,("fcntl_lock: Lock call successful\n"));
381 return true;
384 struct debug_channel_level {
385 int channel;
386 int 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),
405 void *private_data)
407 int i;
408 char s[2];
409 s[1] = 0;
411 for (i=0; i<len; i++) {
412 s[0] = isprint(buf[i]) ? buf[i] : '.';
413 cb(s, private_data);
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),
428 void *private_data)
430 int i=0;
431 bool skipped = false;
432 char tmp[16];
434 if (len<=0) return;
436 for (i=0;i<len;) {
438 if (i%16 == 0) {
439 if ((omit_zero_bytes == true) &&
440 (i > 0) &&
441 (len > i+16) &&
442 all_zero(&buf[i], 16))
444 i +=16;
445 continue;
448 if (i<len) {
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);
456 i++;
457 if (i%8 == 0) {
458 cb(" ", private_data);
460 if (i%16 == 0) {
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) &&
468 (len > i+16) &&
469 all_zero(&buf[i], 16)) {
470 if (!skipped) {
471 cb("skipping zero buffer bytes\n",
472 private_data);
473 skipped = true;
479 if (i%16) {
480 int n;
481 n = 16 - (i%16);
482 cb(" ", private_data);
483 if (n>8) {
484 cb(" ", private_data);
486 while (n--) {
487 cb(" ", private_data);
489 n = MIN(8,i%16);
490 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
491 cb(" ", private_data);
492 n = (i%16) - n;
493 if (n>0) {
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)) {
509 return;
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)) {
525 return;
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)) {
539 return;
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,
551 FILE *f)
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)
562 void *p;
563 if (size == 0)
564 smb_panic("smb_xmalloc: called with zero size.\n");
565 if ((p = malloc(size)) == NULL)
566 smb_panic("smb_xmalloc: malloc fail.\n");
567 return p;
571 Memdup with smb_panic on fail.
574 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
576 void *p2;
577 p2 = smb_xmalloc(size);
578 memcpy(p2, p, size);
579 return p2;
583 strdup that aborts on malloc fail.
586 char *smb_xstrdup(const char *s)
588 #if defined(PARANOID_MALLOC_CHECKER)
589 #ifdef strdup
590 #undef strdup
591 #endif
592 #endif
594 #ifndef HAVE_STRDUP
595 #define strdup rep_strdup
596 #endif
598 char *s1 = strdup(s);
599 #if defined(PARANOID_MALLOC_CHECKER)
600 #ifdef strdup
601 #undef strdup
602 #endif
603 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
604 #endif
605 if (!s1) {
606 smb_panic("smb_xstrdup: malloc failed");
608 return s1;
613 strndup that aborts on malloc fail.
616 char *smb_xstrndup(const char *s, size_t n)
618 #if defined(PARANOID_MALLOC_CHECKER)
619 #ifdef strndup
620 #undef strndup
621 #endif
622 #endif
624 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
625 #undef HAVE_STRNDUP
626 #define strndup rep_strndup
627 #endif
629 char *s1 = strndup(s, n);
630 #if defined(PARANOID_MALLOC_CHECKER)
631 #ifdef strndup
632 #undef strndup
633 #endif
634 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
635 #endif
636 if (!s1) {
637 smb_panic("smb_xstrndup: malloc failed");
639 return s1;
645 Like strdup but for memory.
648 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
650 void *p2;
651 if (size == 0)
652 return NULL;
653 p2 = malloc(size);
654 if (!p2)
655 return NULL;
656 memcpy(p2, p, size);
657 return p2;
661 * Write a password to the log file.
663 * @note Only actually does something if DEBUG_PASSWORD was defined during
664 * compile-time.
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);
674 #endif
679 * see if a range of memory is all zero. A NULL pointer is considered
680 * to be all zero
682 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
684 size_t i;
685 if (!ptr) return true;
686 for (i=0;i<size;i++) {
687 if (ptr[i]) return false;
689 return true;
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
698 if (count == 0 ||
699 count >= MAX_MALLOC_SIZE/el_size) {
700 if (free_on_fail)
701 SAFE_FREE(ptr);
702 return NULL;
704 if (!ptr) {
705 return malloc(el_size * count);
707 return realloc(ptr, el_size * count);
710 /****************************************************************************
711 Type-safe malloc.
712 ****************************************************************************/
714 void *malloc_array(size_t el_size, unsigned int count)
716 return realloc_array(NULL, el_size, count, false);
719 /****************************************************************************
720 Type-safe memalign
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) {
726 return NULL;
729 return memalign(align, el_size*count);
732 /****************************************************************************
733 Type-safe calloc.
734 ****************************************************************************/
736 void *calloc_array(size_t size, size_t nmemb)
738 if (nmemb >= MAX_MALLOC_SIZE/size) {
739 return NULL;
741 if (size == 0 || nmemb == 0) {
742 return NULL;
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)
752 bool ret = false;
753 size_t front_len;
754 size_t back_len;
755 size_t len;
757 /* Ignore null or empty strings. */
758 if (!s || (s[0] == '\0')) {
759 return false;
761 len = strlen(s);
763 front_len = front? strlen(front) : 0;
764 back_len = back? strlen(back) : 0;
766 if (front_len) {
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);
776 len -= front_trim;
777 ret=true;
781 if (back_len) {
782 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
783 s[len-back_len]='\0';
784 len -= back_len;
785 ret=true;
788 return ret;
792 Find the number of 'c' chars in a string
794 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
796 size_t count = 0;
798 while (*s) {
799 if (*s == c) count++;
800 s ++;
803 return 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)
818 size_t i = 0;
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]));
831 if (p1 == NULL) {
832 break;
835 i++; /* next hex digit */
837 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
838 if (p2 == NULL) {
839 break;
842 /* get the two nybbles */
843 hinybble = PTR_DIFF(p1, hexchars);
844 lonybble = PTR_DIFF(p2, hexchars);
846 if (num_chars >= p_len) {
847 break;
850 p[num_chars] = (hinybble << 4) | lonybble;
851 num_chars++;
853 p1 = NULL;
854 p2 = NULL;
856 return num_chars;
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,
867 strhex,
868 strlen(strhex));
870 return ret_blob;
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 };
881 size_t i = 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
885 * and newline. */
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++) {
893 if ((i%77) == 0)
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,
899 &hexdump[i], 2);
900 i += 2;
901 } else {
902 i++;
904 } else {
905 i++;
908 ret_blob.length = char_count;
910 return ret_blob;
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)
918 size_t i;
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)
933 char *hex_buffer;
935 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
936 if (!hex_buffer) {
937 return NULL;
939 hex_encode_buf(hex_buffer, buff_in, len);
940 talloc_set_name_const(hex_buffer, hex_buffer);
941 return hex_buffer;
945 varient of strcmp() that handles NULL ptrs
947 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
949 if (s1 == s2) {
950 return 0;
952 if (s1 == NULL || s2 == NULL) {
953 return s1?-1:1;
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
962 limited by 'n' bytes
964 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
966 size_t len;
968 len = strnlen(src, n);
969 if (len+1 <= n) {
970 len += 1;
973 return len;
976 struct anonymous_shared_header {
977 union {
978 size_t length;
979 uint8_t pad[16];
980 } u;
983 /* Map a shared memory buffer of at least nelem counters. */
984 void *anonymous_shared_allocate(size_t orig_bufsz)
986 void *ptr;
987 void *buf;
988 size_t pagesz = getpagesize();
989 size_t pagecnt;
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) {
998 pagecnt += 1;
1000 bufsz = pagesz * pagecnt;
1002 if (orig_bufsz >= bufsz) {
1003 /* integer wrap */
1004 errno = ENOMEM;
1005 return NULL;
1008 #ifdef MAP_ANON
1009 /* BSD */
1010 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1011 -1 /* fd */, 0 /* offset */);
1012 #else
1014 int saved_errno;
1015 int fd;
1017 fd = open("/dev/zero", O_RDWR);
1018 if (fd == -1) {
1019 return NULL;
1022 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1023 fd, 0 /* offset */);
1024 saved_errno = errno;
1025 close(fd);
1026 errno = saved_errno;
1028 #endif
1030 if (buf == MAP_FAILED) {
1031 return NULL;
1034 hdr = (struct anonymous_shared_header *)buf;
1035 hdr->u.length = bufsz;
1037 ptr = (void *)(&hdr[1]);
1039 return ptr;
1042 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1044 #ifdef HAVE_MREMAP
1045 void *buf;
1046 size_t pagesz = getpagesize();
1047 size_t pagecnt;
1048 size_t bufsz;
1049 struct anonymous_shared_header *hdr;
1050 int flags = 0;
1052 if (ptr == NULL) {
1053 errno = EINVAL;
1054 return NULL;
1057 hdr = (struct anonymous_shared_header *)ptr;
1058 hdr--;
1059 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1060 errno = EINVAL;
1061 return NULL;
1064 bufsz = new_size + sizeof(*hdr);
1066 /* round up to full pages */
1067 pagecnt = bufsz / pagesz;
1068 if (bufsz % pagesz) {
1069 pagecnt += 1;
1071 bufsz = pagesz * pagecnt;
1073 if (new_size >= bufsz) {
1074 /* integer wrap */
1075 errno = ENOSPC;
1076 return NULL;
1079 if (bufsz <= hdr->u.length) {
1080 return ptr;
1083 if (maymove) {
1084 flags = MREMAP_MAYMOVE;
1087 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1089 if (buf == MAP_FAILED) {
1090 errno = ENOSPC;
1091 return NULL;
1094 hdr = (struct anonymous_shared_header *)buf;
1095 hdr->u.length = bufsz;
1097 ptr = (void *)(&hdr[1]);
1099 return ptr;
1100 #else
1101 errno = ENOSPC;
1102 return NULL;
1103 #endif
1106 void anonymous_shared_free(void *ptr)
1108 struct anonymous_shared_header *hdr;
1110 if (ptr == NULL) {
1111 return;
1114 hdr = (struct anonymous_shared_header *)ptr;
1116 hdr--;
1118 munmap(hdr, hdr->u.length);
1121 #ifdef DEVELOPER
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)
1128 char *cmd = NULL;
1129 if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1130 return;
1132 if (system(cmd) == -1) {
1133 free(cmd);
1134 return;
1136 free(cmd);
1137 sleep(2);
1139 #endif