Revert "lib/util: make use of tfork in samba_runcmd_send()"
[samba.git] / lib / util / util.c
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
10    
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.
15    
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.
20    
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/>.
23 */
24
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"
37
38 #undef malloc
39 #undef strcasecmp
40 #undef strncasecmp
41 #undef strdup
42 #undef realloc
43 #undef calloc
44
45 /**
46  * @file
47  * @brief Misc utility functions
48  */
49
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)
55 {
56         char *p;
57         if ((p = getenv("TMPDIR")))
58                 return p;
59         return "/tmp";
60 }
61
62
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)
69 {
70         size_t len = strlen(dir ? dir : (dir = tmpdir()));
71         char fname[len+25];
72         int fd;
73         mode_t mask;
74
75         len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
76         if (len >= sizeof(fname)) {
77                 errno = ENOMEM;
78                 return -1;
79         }
80         mask = umask(S_IRWXO | S_IRWXG);
81         fd = mkstemp(fname);
82         umask(mask);
83         if (fd == -1) {
84                 return -1;
85         }
86         if (unlink(fname) == -1) {
87                 int sys_errno = errno;
88                 close(fd);
89                 errno = sys_errno;
90                 return -1;
91         }
92         return fd;
93 }
94
95
96 /**
97  Check if a file exists - call vfs_file_exist for samba files.
98 **/
99 _PUBLIC_ bool file_exist(const char *fname)
100 {
101         struct stat st;
102
103         if (stat(fname, &st) != 0) {
104                 return false;
105         }
106
107         return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
108 }
109
110 /**
111  Check a files mod time.
112 **/
113
114 _PUBLIC_ time_t file_modtime(const char *fname)
115 {
116         struct stat st;
117   
118         if (stat(fname,&st) != 0) 
119                 return(0);
120
121         return(st.st_mtime);
122 }
123
124 /**
125  Check file permissions.
126 **/
127
128 _PUBLIC_ bool file_check_permissions(const char *fname,
129                                      uid_t uid,
130                                      mode_t file_perms,
131                                      struct stat *pst)
132 {
133         int ret;
134         struct stat st;
135
136         if (pst == NULL) {
137                 pst = &st;
138         }
139
140         ZERO_STRUCTP(pst);
141
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;
147         }
148
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;
155         }
156
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;
163         }
164
165         return true;
166 }
167
168 /**
169  Check if a directory exists.
170 **/
171
172 _PUBLIC_ bool directory_exist(const char *dname)
173 {
174         struct stat st;
175         bool ret;
176
177         if (stat(dname,&st) != 0) {
178                 return false;
179         }
180
181         ret = S_ISDIR(st.st_mode);
182         if(!ret)
183                 errno = ENOTDIR;
184         return ret;
185 }
186
187 /**
188  * Try to create the specified directory if it didn't exist.
189  *
190  * @retval true if the directory already existed
191  * or was successfully created.
192  */
193 _PUBLIC_ bool directory_create_or_exist(const char *dname,
194                                         mode_t dir_perms)
195 {
196         int ret;
197         struct stat st;
198         mode_t old_umask;
199
200         ret = lstat(dname, &st);
201         if (ret == 0) {
202                 return true;
203         }
204
205         if (errno != ENOENT) {
206                 DBG_WARNING("lstat failed on directory %s: %s\n",
207                             dname, strerror(errno));
208                 return false;
209         }
210
211         /* Create directory */
212         old_umask = umask(0);
213         ret = mkdir(dname, dir_perms);
214         if (ret == -1 && errno != EEXIST) {
215                 DEBUG(0, ("mkdir failed on directory "
216                           "%s: %s\n", dname,
217                           strerror(errno)));
218                 umask(old_umask);
219                 return false;
220         }
221         umask(old_umask);
222
223         ret = lstat(dname, &st);
224         if (ret == -1) {
225                 DEBUG(0, ("lstat failed on created directory %s: %s\n",
226                           dname, strerror(errno)));
227                 return false;
228         }
229
230         return true;
231 }
232
233 /**
234  * @brief Try to create a specified directory if it doesn't exist.
235  *
236  * The function creates a directory with the given uid and permissions if it
237  * doesn't exist. If it exists it makes sure the uid and permissions are
238  * correct and it will fail if they are different.
239  *
240  * @param[in]  dname  The directory to create.
241  *
242  * @param[in]  uid    The uid the directory needs to belong too.
243  *
244  * @param[in]  dir_perms  The expected permissions of the directory.
245  *
246  * @return True on success, false on error.
247  */
248 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
249                                                uid_t uid,
250                                                mode_t dir_perms)
251 {
252         struct stat st;
253         bool ok;
254         int rc;
255
256         ok = directory_create_or_exist(dname, dir_perms);
257         if (!ok) {
258                 return false;
259         }
260
261         rc = lstat(dname, &st);
262         if (rc == -1) {
263                 DEBUG(0, ("lstat failed on created directory %s: %s\n",
264                           dname, strerror(errno)));
265                 return false;
266         }
267
268         /* Check ownership and permission on existing directory */
269         if (!S_ISDIR(st.st_mode)) {
270                 DEBUG(0, ("directory %s isn't a directory\n",
271                         dname));
272                 return false;
273         }
274         if (st.st_uid != uid && !uid_wrapper_enabled()) {
275                 DBG_NOTICE("invalid ownership on directory "
276                           "%s\n", dname);
277                 return false;
278         }
279         if ((st.st_mode & 0777) != dir_perms) {
280                 DEBUG(0, ("invalid permissions on directory "
281                           "'%s': has 0%o should be 0%o\n", dname,
282                           (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
283                 return false;
284         }
285
286         return true;
287 }
288
289
290 /**
291  Sleep for a specified number of milliseconds.
292 **/
293
294 _PUBLIC_ void smb_msleep(unsigned int t)
295 {
296         sys_poll_intr(NULL, 0, t);
297 }
298
299 /**
300  Get my own name, return in talloc'ed storage.
301 **/
302
303 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
304 {
305         char *p;
306         char hostname[HOST_NAME_MAX];
307
308         /* get my host name */
309         if (gethostname(hostname, sizeof(hostname)) == -1) {
310                 DEBUG(0,("gethostname failed\n"));
311                 return NULL;
312         }
313
314         /* Ensure null termination. */
315         hostname[sizeof(hostname)-1] = '\0';
316
317         /* split off any parts after an initial . */
318         p = strchr_m(hostname, '.');
319         if (p) {
320                 *p = 0;
321         }
322
323         return talloc_strdup(ctx, hostname);
324 }
325
326 /**
327  Check if a process exists. Does this work on all unixes?
328 **/
329
330 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
331 {
332         /* Doing kill with a non-positive pid causes messages to be
333          * sent to places we don't want. */
334         if (pid <= 0) {
335                 return false;
336         }
337         return(kill(pid,0) == 0 || errno != ESRCH);
338 }
339
340 /**
341  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
342  is dealt with in posix.c
343 **/
344
345 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
346 {
347         struct flock lock;
348         int ret;
349
350         DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
351
352         lock.l_type = type;
353         lock.l_whence = SEEK_SET;
354         lock.l_start = offset;
355         lock.l_len = count;
356         lock.l_pid = 0;
357
358         ret = fcntl(fd,op,&lock);
359
360         if (ret == -1 && errno != 0)
361                 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
362
363         /* a lock query */
364         if (op == F_GETLK) {
365                 if ((ret != -1) &&
366                                 (lock.l_type != F_UNLCK) && 
367                                 (lock.l_pid != 0) && 
368                                 (lock.l_pid != getpid())) {
369                         DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
370                         return true;
371                 }
372
373                 /* it must be not locked or locked by me */
374                 return false;
375         }
376
377         /* a lock set or unset */
378         if (ret == -1) {
379                 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
380                         (double)offset,(double)count,op,type,strerror(errno)));
381                 return false;
382         }
383
384         /* everything went OK */
385         DEBUG(8,("fcntl_lock: Lock call successful\n"));
386
387         return true;
388 }
389
390 struct debug_channel_level {
391         int channel;
392         int level;
393 };
394
395 static void debugadd_channel_cb(const char *buf, void *private_data)
396 {
397         struct debug_channel_level *dcl =
398                 (struct debug_channel_level *)private_data;
399
400         DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
401 }
402
403 static void debugadd_cb(const char *buf, void *private_data)
404 {
405         int *plevel = (int *)private_data;
406         DEBUGADD(*plevel, ("%s", buf));
407 }
408
409 void print_asc_cb(const uint8_t *buf, int len,
410                   void (*cb)(const char *buf, void *private_data),
411                   void *private_data)
412 {
413         int i;
414         char s[2];
415         s[1] = 0;
416
417         for (i=0; i<len; i++) {
418                 s[0] = isprint(buf[i]) ? buf[i] : '.';
419                 cb(s, private_data);
420         }
421 }
422
423 void print_asc(int level, const uint8_t *buf,int len)
424 {
425         print_asc_cb(buf, len, debugadd_cb, &level);
426 }
427
428 /**
429  * Write dump of binary data to a callback
430  */
431 void dump_data_cb(const uint8_t *buf, int len,
432                   bool omit_zero_bytes,
433                   void (*cb)(const char *buf, void *private_data),
434                   void *private_data)
435 {
436         int i=0;
437         static const uint8_t empty[16] = { 0, };
438         bool skipped = false;
439         char tmp[16];
440
441         if (len<=0) return;
442
443         for (i=0;i<len;) {
444
445                 if (i%16 == 0) {
446                         if ((omit_zero_bytes == true) &&
447                             (i > 0) &&
448                             (len > i+16) &&
449                             (memcmp(&buf[i], &empty, 16) == 0))
450                         {
451                                 i +=16;
452                                 continue;
453                         }
454
455                         if (i<len)  {
456                                 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
457                                 cb(tmp, private_data);
458                         }
459                 }
460
461                 snprintf(tmp, sizeof(tmp), "%02X ", (int)buf[i]);
462                 cb(tmp, private_data);
463                 i++;
464                 if (i%8 == 0) {
465                         cb("  ", private_data);
466                 }
467                 if (i%16 == 0) {
468
469                         print_asc_cb(&buf[i-16], 8, cb, private_data);
470                         cb(" ", private_data);
471                         print_asc_cb(&buf[i-8], 8, cb, private_data);
472                         cb("\n", private_data);
473
474                         if ((omit_zero_bytes == true) &&
475                             (len > i+16) &&
476                             (memcmp(&buf[i], &empty, 16) == 0)) {
477                                 if (!skipped) {
478                                         cb("skipping zero buffer bytes\n",
479                                            private_data);
480                                         skipped = true;
481                                 }
482                         }
483                 }
484         }
485
486         if (i%16) {
487                 int n;
488                 n = 16 - (i%16);
489                 cb("  ", private_data);
490                 if (n>8) {
491                         cb(" ", private_data);
492                 }
493                 while (n--) {
494                         cb("   ", private_data);
495                 }
496                 n = MIN(8,i%16);
497                 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
498                 cb(" ", private_data);
499                 n = (i%16) - n;
500                 if (n>0) {
501                         print_asc_cb(&buf[i-n], n, cb, private_data);
502                 }
503                 cb("\n", private_data);
504         }
505
506 }
507
508 /**
509  * Write dump of binary data to the log file.
510  *
511  * The data is only written if the log level is at least level.
512  */
513 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
514 {
515         if (!DEBUGLVL(level)) {
516                 return;
517         }
518         dump_data_cb(buf, len, false, debugadd_cb, &level);
519 }
520
521 /**
522  * Write dump of binary data to the log file.
523  *
524  * The data is only written if the log level is at least level for
525  * debug class dbgc_class.
526  */
527 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
528 {
529         struct debug_channel_level dcl = { dbgc_class, level };
530
531         if (!DEBUGLVLC(dbgc_class, level)) {
532                 return;
533         }
534         dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
535 }
536
537 /**
538  * Write dump of binary data to the log file.
539  *
540  * The data is only written if the log level is at least level.
541  * 16 zero bytes in a row are omitted
542  */
543 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
544 {
545         if (!DEBUGLVL(level)) {
546                 return;
547         }
548         dump_data_cb(buf, len, true, debugadd_cb, &level);
549 }
550
551 static void fprintf_cb(const char *buf, void *private_data)
552 {
553         FILE *f = (FILE *)private_data;
554         fprintf(f, "%s", buf);
555 }
556
557 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
558                     FILE *f)
559 {
560         dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
561 }
562
563 /**
564  malloc that aborts with smb_panic on fail or zero size.
565 **/
566
567 _PUBLIC_ void *smb_xmalloc(size_t size)
568 {
569         void *p;
570         if (size == 0)
571                 smb_panic("smb_xmalloc: called with zero size.\n");
572         if ((p = malloc(size)) == NULL)
573                 smb_panic("smb_xmalloc: malloc fail.\n");
574         return p;
575 }
576
577 /**
578  Memdup with smb_panic on fail.
579 **/
580
581 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
582 {
583         void *p2;
584         p2 = smb_xmalloc(size);
585         memcpy(p2, p, size);
586         return p2;
587 }
588
589 /**
590  strdup that aborts on malloc fail.
591 **/
592
593 char *smb_xstrdup(const char *s)
594 {
595 #if defined(PARANOID_MALLOC_CHECKER)
596 #ifdef strdup
597 #undef strdup
598 #endif
599 #endif
600
601 #ifndef HAVE_STRDUP
602 #define strdup rep_strdup
603 #endif
604
605         char *s1 = strdup(s);
606 #if defined(PARANOID_MALLOC_CHECKER)
607 #ifdef strdup
608 #undef strdup
609 #endif
610 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
611 #endif
612         if (!s1) {
613                 smb_panic("smb_xstrdup: malloc failed");
614         }
615         return s1;
616
617 }
618
619 /**
620  strndup that aborts on malloc fail.
621 **/
622
623 char *smb_xstrndup(const char *s, size_t n)
624 {
625 #if defined(PARANOID_MALLOC_CHECKER)
626 #ifdef strndup
627 #undef strndup
628 #endif
629 #endif
630
631 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
632 #undef HAVE_STRNDUP
633 #define strndup rep_strndup
634 #endif
635
636         char *s1 = strndup(s, n);
637 #if defined(PARANOID_MALLOC_CHECKER)
638 #ifdef strndup
639 #undef strndup
640 #endif
641 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
642 #endif
643         if (!s1) {
644                 smb_panic("smb_xstrndup: malloc failed");
645         }
646         return s1;
647 }
648
649
650
651 /**
652  Like strdup but for memory.
653 **/
654
655 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
656 {
657         void *p2;
658         if (size == 0)
659                 return NULL;
660         p2 = malloc(size);
661         if (!p2)
662                 return NULL;
663         memcpy(p2, p, size);
664         return p2;
665 }
666
667 /**
668  * Write a password to the log file.
669  *
670  * @note Only actually does something if DEBUG_PASSWORD was defined during 
671  * compile-time.
672  */
673 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
674 {
675 #ifdef DEBUG_PASSWORD
676         DEBUG(11, ("%s", msg));
677         if (data != NULL && len > 0)
678         {
679                 dump_data(11, data, len);
680         }
681 #endif
682 }
683
684
685 /**
686  * see if a range of memory is all zero. A NULL pointer is considered
687  * to be all zero 
688  */
689 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
690 {
691         size_t i;
692         if (!ptr) return true;
693         for (i=0;i<size;i++) {
694                 if (ptr[i]) return false;
695         }
696         return true;
697 }
698
699 /**
700   realloc an array, checking for integer overflow in the array size
701 */
702 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
703 {
704 #define MAX_MALLOC_SIZE 0x7fffffff
705         if (count == 0 ||
706             count >= MAX_MALLOC_SIZE/el_size) {
707                 if (free_on_fail)
708                         SAFE_FREE(ptr);
709                 return NULL;
710         }
711         if (!ptr) {
712                 return malloc(el_size * count);
713         }
714         return realloc(ptr, el_size * count);
715 }
716
717 /****************************************************************************
718  Type-safe malloc.
719 ****************************************************************************/
720
721 void *malloc_array(size_t el_size, unsigned int count)
722 {
723         return realloc_array(NULL, el_size, count, false);
724 }
725
726 /****************************************************************************
727  Type-safe memalign
728 ****************************************************************************/
729
730 void *memalign_array(size_t el_size, size_t align, unsigned int count)
731 {
732         if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
733                 return NULL;
734         }
735
736         return memalign(align, el_size*count);
737 }
738
739 /****************************************************************************
740  Type-safe calloc.
741 ****************************************************************************/
742
743 void *calloc_array(size_t size, size_t nmemb)
744 {
745         if (nmemb >= MAX_MALLOC_SIZE/size) {
746                 return NULL;
747         }
748         if (size == 0 || nmemb == 0) {
749                 return NULL;
750         }
751         return calloc(nmemb, size);
752 }
753
754 /**
755  Trim the specified elements off the front and back of a string.
756 **/
757 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
758 {
759         bool ret = false;
760         size_t front_len;
761         size_t back_len;
762         size_t len;
763
764         /* Ignore null or empty strings. */
765         if (!s || (s[0] == '\0')) {
766                 return false;
767         }
768         len = strlen(s);
769
770         front_len       = front? strlen(front) : 0;
771         back_len        = back? strlen(back) : 0;
772
773         if (front_len) {
774                 size_t front_trim = 0;
775
776                 while (strncmp(s+front_trim, front, front_len)==0) {
777                         front_trim += front_len;
778                 }
779                 if (front_trim > 0) {
780                         /* Must use memmove here as src & dest can
781                          * easily overlap. Found by valgrind. JRA. */
782                         memmove(s, s+front_trim, (len-front_trim)+1);
783                         len -= front_trim;
784                         ret=true;
785                 }
786         }
787
788         if (back_len) {
789                 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
790                         s[len-back_len]='\0';
791                         len -= back_len;
792                         ret=true;
793                 }
794         }
795         return ret;
796 }
797
798 /**
799  Find the number of 'c' chars in a string
800 **/
801 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
802 {
803         size_t count = 0;
804
805         while (*s) {
806                 if (*s == c) count++;
807                 s ++;
808         }
809
810         return count;
811 }
812
813 /**
814  * Routine to get hex characters and turn them into a byte array.
815  * the array can be variable length.
816  * -  "0xnn" or "0Xnn" is specially catered for.
817  * - The first non-hex-digit character (apart from possibly leading "0x"
818  *   finishes the conversion and skips the rest of the input.
819  * - A single hex-digit character at the end of the string is skipped.
820  *
821  * valid examples: "0A5D15"; "0x123456"
822  */
823 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
824 {
825         size_t i = 0;
826         size_t num_chars = 0;
827         uint8_t   lonybble, hinybble;
828         const char     *hexchars = "0123456789ABCDEF";
829         char           *p1 = NULL, *p2 = NULL;
830
831         /* skip leading 0x prefix */
832         if (strncasecmp(strhex, "0x", 2) == 0) {
833                 i += 2; /* skip two chars */
834         }
835
836         for (; i+1 < strhex_len && strhex[i] != 0 && strhex[i+1] != 0; i++) {
837                 p1 = strchr(hexchars, toupper((unsigned char)strhex[i]));
838                 if (p1 == NULL) {
839                         break;
840                 }
841
842                 i++; /* next hex digit */
843
844                 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
845                 if (p2 == NULL) {
846                         break;
847                 }
848
849                 /* get the two nybbles */
850                 hinybble = PTR_DIFF(p1, hexchars);
851                 lonybble = PTR_DIFF(p2, hexchars);
852
853                 if (num_chars >= p_len) {
854                         break;
855                 }
856
857                 p[num_chars] = (hinybble << 4) | lonybble;
858                 num_chars++;
859
860                 p1 = NULL;
861                 p2 = NULL;
862         }
863         return num_chars;
864 }
865
866 /**
867  * Parse a hex string and return a data blob.
868  */
869 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex) 
870 {
871         DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
872
873         ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
874                                         strhex,
875                                         strlen(strhex));
876
877         return ret_blob;
878 }
879
880 /**
881  * Parse a hex dump and return a data blob. Hex dump is structured as 
882  * is generated from dump_data_cb() elsewhere in this file
883  * 
884  */
885 _PUBLIC_ _PURE_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
886 {
887         DATA_BLOB ret_blob = { 0 };
888         size_t i = 0;
889         size_t char_count = 0;
890         /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
891          * at the end of the final line to calculate how many are in that line, minus the extra space
892          * and newline. */
893         size_t hexdump_byte_count = (16 * (hexdump_len / 77));
894         if (hexdump_len % 77) {
895                 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
896         }
897         
898         ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
899         for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
900                 if ((i%77) == 0) 
901                         i += 7; /* Skip the offset at the start of the line */
902                 if ((i%77) < 56) { /* position 56 is after both hex chunks */
903                         if (hexdump[i] != ' ') {
904                                 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
905                                                             hexdump_byte_count - char_count,
906                                                             &hexdump[i], 2);
907                                 i += 2;
908                         } else {
909                                 i++;
910                         }
911                 } else {
912                         i++;
913                 }
914         }
915         ret_blob.length = char_count;
916         
917         return ret_blob;
918 }
919
920 /**
921  * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
922  */
923 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
924 {
925         size_t i;
926         for (i=0; i<srclen; i++) {
927                 snprintf(dst + i*2, 3, "%02X", src[i]);
928         }
929         /*
930          * Ensure 0-termination for 0-length buffers
931          */
932         dst[srclen*2] = '\0';
933 }
934
935 /**
936  * talloc version of hex_encode_buf()
937  */
938 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
939 {
940         char *hex_buffer;
941
942         hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
943         if (!hex_buffer) {
944                 return NULL;
945         }
946         hex_encode_buf(hex_buffer, buff_in, len);
947         talloc_set_name_const(hex_buffer, hex_buffer);
948         return hex_buffer;
949 }
950
951 /**
952   varient of strcmp() that handles NULL ptrs
953 **/
954 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
955 {
956         if (s1 == s2) {
957                 return 0;
958         }
959         if (s1 == NULL || s2 == NULL) {
960                 return s1?-1:1;
961         }
962         return strcmp(s1, s2);
963 }
964
965
966 /**
967 return the number of bytes occupied by a buffer in ASCII format
968 the result includes the null termination
969 limited by 'n' bytes
970 **/
971 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
972 {
973         size_t len;
974
975         len = strnlen(src, n);
976         if (len+1 <= n) {
977                 len += 1;
978         }
979
980         return len;
981 }
982
983 struct anonymous_shared_header {
984         union {
985                 size_t length;
986                 uint8_t pad[16];
987         } u;
988 };
989
990 /* Map a shared memory buffer of at least nelem counters. */
991 void *anonymous_shared_allocate(size_t orig_bufsz)
992 {
993         void *ptr;
994         void *buf;
995         size_t pagesz = getpagesize();
996         size_t pagecnt;
997         size_t bufsz = orig_bufsz;
998         struct anonymous_shared_header *hdr;
999
1000         bufsz += sizeof(*hdr);
1001
1002         /* round up to full pages */
1003         pagecnt = bufsz / pagesz;
1004         if (bufsz % pagesz) {
1005                 pagecnt += 1;
1006         }
1007         bufsz = pagesz * pagecnt;
1008
1009         if (orig_bufsz >= bufsz) {
1010                 /* integer wrap */
1011                 errno = ENOMEM;
1012                 return NULL;
1013         }
1014
1015 #ifdef MAP_ANON
1016         /* BSD */
1017         buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1018                         -1 /* fd */, 0 /* offset */);
1019 #else
1020 {
1021         int saved_errno;
1022         int fd;
1023
1024         fd = open("/dev/zero", O_RDWR);
1025         if (fd == -1) {
1026                 return NULL;
1027         }
1028
1029         buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1030                    fd, 0 /* offset */);
1031         saved_errno = errno;
1032         close(fd);
1033         errno = saved_errno;
1034 }
1035 #endif
1036
1037         if (buf == MAP_FAILED) {
1038                 return NULL;
1039         }
1040
1041         hdr = (struct anonymous_shared_header *)buf;
1042         hdr->u.length = bufsz;
1043
1044         ptr = (void *)(&hdr[1]);
1045
1046         return ptr;
1047 }
1048
1049 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1050 {
1051 #ifdef HAVE_MREMAP
1052         void *buf;
1053         size_t pagesz = getpagesize();
1054         size_t pagecnt;
1055         size_t bufsz;
1056         struct anonymous_shared_header *hdr;
1057         int flags = 0;
1058
1059         if (ptr == NULL) {
1060                 errno = EINVAL;
1061                 return NULL;
1062         }
1063
1064         hdr = (struct anonymous_shared_header *)ptr;
1065         hdr--;
1066         if (hdr->u.length > (new_size + sizeof(*hdr))) {
1067                 errno = EINVAL;
1068                 return NULL;
1069         }
1070
1071         bufsz = new_size + sizeof(*hdr);
1072
1073         /* round up to full pages */
1074         pagecnt = bufsz / pagesz;
1075         if (bufsz % pagesz) {
1076                 pagecnt += 1;
1077         }
1078         bufsz = pagesz * pagecnt;
1079
1080         if (new_size >= bufsz) {
1081                 /* integer wrap */
1082                 errno = ENOSPC;
1083                 return NULL;
1084         }
1085
1086         if (bufsz <= hdr->u.length) {
1087                 return ptr;
1088         }
1089
1090         if (maymove) {
1091                 flags = MREMAP_MAYMOVE;
1092         }
1093
1094         buf = mremap(hdr, hdr->u.length, bufsz, flags);
1095
1096         if (buf == MAP_FAILED) {
1097                 errno = ENOSPC;
1098                 return NULL;
1099         }
1100
1101         hdr = (struct anonymous_shared_header *)buf;
1102         hdr->u.length = bufsz;
1103
1104         ptr = (void *)(&hdr[1]);
1105
1106         return ptr;
1107 #else
1108         errno = ENOSPC;
1109         return NULL;
1110 #endif
1111 }
1112
1113 void anonymous_shared_free(void *ptr)
1114 {
1115         struct anonymous_shared_header *hdr;
1116
1117         if (ptr == NULL) {
1118                 return;
1119         }
1120
1121         hdr = (struct anonymous_shared_header *)ptr;
1122
1123         hdr--;
1124
1125         munmap(hdr, hdr->u.length);
1126 }
1127
1128 #ifdef DEVELOPER
1129 /* used when you want a debugger started at a particular point in the
1130    code. Mostly useful in code that runs as a child process, where
1131    normal gdb attach is harder to organise.
1132 */
1133 void samba_start_debugger(void)
1134 {
1135         char *cmd = NULL;
1136         if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1137                 return;
1138         }
1139         if (system(cmd) == -1) {
1140                 free(cmd);
1141                 return;
1142         }
1143         free(cmd);
1144         sleep(2);
1145 }
1146 #endif