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"
31 * @brief Misc utility functions
35 Find a suitable temporary directory. The result should be copied immediately
36 as it may be overwritten by a subsequent call.
38 _PUBLIC_ const char *tmpdir(void)
41 if ((p = getenv("TMPDIR")))
48 Check if a file exists - call vfs_file_exist for samba files.
50 _PUBLIC_ bool file_exist(const char *fname)
54 if (stat(fname, &st) != 0) {
58 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
62 Check a files mod time.
65 _PUBLIC_ time_t file_modtime(const char *fname)
69 if (stat(fname,&st) != 0)
76 Check if a directory exists.
79 _PUBLIC_ bool directory_exist(const char *dname)
84 if (stat(dname,&st) != 0) {
88 ret = S_ISDIR(st.st_mode);
95 * Try to create the specified directory if it didn't exist.
97 * @retval true if the directory already existed and has the right permissions
98 * or was successfully created.
100 _PUBLIC_ bool directory_create_or_exist(const char *dname, uid_t uid,
106 old_umask = umask(0);
107 if (lstat(dname, &st) == -1) {
108 if (errno == ENOENT) {
109 /* Create directory */
110 if (mkdir(dname, dir_perms) == -1) {
111 DEBUG(0, ("error creating directory "
118 DEBUG(0, ("lstat failed on directory %s: %s\n",
119 dname, strerror(errno)));
124 /* Check ownership and permission on existing directory */
125 if (!S_ISDIR(st.st_mode)) {
126 DEBUG(0, ("directory %s isn't a directory\n",
131 if ((st.st_uid != uid) ||
132 ((st.st_mode & 0777) != dir_perms)) {
133 DEBUG(0, ("invalid permissions on directory "
144 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
150 _PUBLIC_ int set_blocking(int fd, bool set)
154 #define FLAG_TO_SET O_NONBLOCK
157 #define FLAG_TO_SET O_NDELAY
159 #define FLAG_TO_SET FNDELAY
163 if((val = fcntl(fd, F_GETFL, 0)) == -1)
165 if(set) /* Turn blocking on - ie. clear nonblock flag */
169 return fcntl( fd, F_SETFL, val);
175 Sleep for a specified number of milliseconds.
178 _PUBLIC_ void msleep(unsigned int t)
182 tval.tv_sec = t/1000;
183 tval.tv_usec = 1000*(t%1000);
184 /* this should be the real select - do NOT replace
186 select(0,NULL,NULL,NULL,&tval);
190 Get my own name, return in malloc'ed storage.
193 _PUBLIC_ char *get_myname(void)
198 hostname = (char *)malloc(MAXHOSTNAMELEN+1);
201 /* get my host name */
202 if (gethostname(hostname, MAXHOSTNAMELEN+1) == -1) {
203 DEBUG(0,("gethostname failed\n"));
207 /* Ensure null termination. */
208 hostname[MAXHOSTNAMELEN] = '\0';
210 /* split off any parts after an initial . */
211 p = strchr(hostname, '.');
220 Return true if a string could be a pure IP address.
223 _PUBLIC_ bool is_ipaddress(const char *str)
225 bool pure_address = true;
228 if (str == NULL) return false;
230 for (i=0; pure_address && str[i]; i++)
231 if (!(isdigit((int)str[i]) || str[i] == '.'))
232 pure_address = false;
234 /* Check that a pure number is not misinterpreted as an IP */
235 pure_address = pure_address && (strchr(str, '.') != NULL);
241 Interpret an internet address or name into an IP address in 4 byte form.
243 _PUBLIC_ uint32_t interpret_addr(const char *str)
248 if (str == NULL || *str == 0 ||
249 strcmp(str,"0.0.0.0") == 0) {
252 if (strcmp(str,"255.255.255.255") == 0) {
255 /* recognise 'localhost' as a special name. This fixes problems with
256 some hosts that don't have localhost in /etc/hosts */
257 if (strcasecmp(str,"localhost") == 0) {
261 /* if it's in the form of an IP address then get the lib to interpret it */
262 if (is_ipaddress(str)) {
263 res = inet_addr(str);
265 /* otherwise assume it's a network name of some sort and use
267 if ((hp = sys_gethostbyname(str)) == 0) {
268 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
272 if(hp->h_addr == NULL) {
273 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
276 memcpy((char *)&res,(char *)hp->h_addr, 4);
279 if (res == (uint32_t)-1)
286 A convenient addition to interpret_addr().
288 _PUBLIC_ struct in_addr interpret_addr2(const char *str)
291 uint32_t a = interpret_addr(str);
297 Check if an IP is the 0.0.0.0.
300 _PUBLIC_ bool is_zero_ip(struct in_addr ip)
302 return ip.s_addr == 0;
306 Are two IPs on the same subnet?
309 _PUBLIC_ bool same_net(struct in_addr ip1, struct in_addr ip2, struct in_addr mask)
311 uint32_t net1,net2,nmask;
313 nmask = ntohl(mask.s_addr);
314 net1 = ntohl(ip1.s_addr);
315 net2 = ntohl(ip2.s_addr);
317 return((net1 & nmask) == (net2 & nmask));
322 Check if a process exists. Does this work on all unixes?
325 _PUBLIC_ bool process_exists(pid_t pid)
327 /* Doing kill with a non-positive pid causes messages to be
328 * sent to places we don't want. */
330 return(kill(pid,0) == 0 || errno != ESRCH);
334 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
335 is dealt with in posix.c
338 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
343 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
346 lock.l_whence = SEEK_SET;
347 lock.l_start = offset;
351 ret = fcntl(fd,op,&lock);
353 if (ret == -1 && errno != 0)
354 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
359 (lock.l_type != F_UNLCK) &&
361 (lock.l_pid != getpid())) {
362 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
366 /* it must be not locked or locked by me */
370 /* a lock set or unset */
372 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
373 (double)offset,(double)count,op,type,strerror(errno)));
377 /* everything went OK */
378 DEBUG(8,("fcntl_lock: Lock call successful\n"));
384 static void print_asc(int level, const uint8_t *buf,int len)
388 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
392 * Write dump of binary data to the log file.
394 * The data is only written if the log level is at least level.
396 static void _dump_data(int level, const uint8_t *buf, int len,
397 bool omit_zero_bytes)
400 const uint8_t empty[16];
401 bool skipped = false;
405 if (!DEBUGLVL(level)) return;
407 memset(&empty, '\0', 16);
412 if ((omit_zero_bytes == true) &&
415 (memcmp(&buf[i], &empty, 16) == 0))
422 DEBUGADD(level,("[%04X] ",i));
426 DEBUGADD(level,("%02X ",(int)buf[i]));
428 if (i%8 == 0) DEBUGADD(level,(" "));
431 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
432 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
434 if ((omit_zero_bytes == true) &&
436 (memcmp(&buf[i], &empty, 16) == 0)) {
438 DEBUGADD(level,("skipping zero buffer bytes\n"));
448 DEBUGADD(level,(" "));
449 if (n>8) DEBUGADD(level,(" "));
450 while (n--) DEBUGADD(level,(" "));
452 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
454 if (n>0) print_asc(level,&buf[i-n],n);
455 DEBUGADD(level,("\n"));
461 * Write dump of binary data to the log file.
463 * The data is only written if the log level is at least level.
465 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
467 _dump_data(level, buf, len, false);
471 * Write dump of binary data to the log file.
473 * The data is only written if the log level is at least level.
474 * 16 zero bytes in a row are ommited
476 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
478 _dump_data(level, buf, len, true);
483 malloc that aborts with smb_panic on fail or zero size.
486 _PUBLIC_ void *smb_xmalloc(size_t size)
490 smb_panic("smb_xmalloc: called with zero size.\n");
491 if ((p = malloc(size)) == NULL)
492 smb_panic("smb_xmalloc: malloc fail.\n");
497 Memdup with smb_panic on fail.
500 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
503 p2 = smb_xmalloc(size);
509 strdup that aborts on malloc fail.
512 _PUBLIC_ char *smb_xstrdup(const char *s)
514 char *s1 = strdup(s);
516 smb_panic("smb_xstrdup: malloc fail\n");
522 Like strdup but for memory.
525 _PUBLIC_ void *memdup(const void *p, size_t size)
538 * Write a password to the log file.
540 * @note Only actually does something if DEBUG_PASSWORD was defined during
543 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
545 #ifdef DEBUG_PASSWORD
546 DEBUG(11, ("%s", msg));
547 if (data != NULL && len > 0)
549 dump_data(11, data, len);
556 * see if a range of memory is all zero. A NULL pointer is considered
559 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
562 if (!ptr) return true;
563 for (i=0;i<size;i++) {
564 if (ptr[i]) return false;
570 realloc an array, checking for integer overflow in the array size
572 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count)
574 #define MAX_MALLOC_SIZE 0x7fffffff
576 count >= MAX_MALLOC_SIZE/el_size) {
580 return malloc(el_size * count);
582 return realloc(ptr, el_size * count);
585 /****************************************************************************
587 ****************************************************************************/
589 void *malloc_array(size_t el_size, unsigned int count)
591 return realloc_array(NULL, el_size, count);
594 _PUBLIC_ void *talloc_check_name_abort(const void *ptr, const char *name)
598 result = talloc_check_name(ptr, name);
602 DEBUG(0, ("Talloc type mismatch, expected %s, got %s\n",
603 name, talloc_get_name(ptr)));
604 smb_panic("talloc type mismatch");
605 /* Keep the compiler happy */