few edits
[Samba.git] / source / lib / util.c
blobb6266cb9257a9bebf0a909074eab41aa57f84fa2
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
6 Copyright (C) Jeremy Allison 2001
7 Copyright (C) Simo Sorce 2001
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include "includes.h"
26 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
27 #ifdef WITH_NISPLUS_HOME
28 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
30 * The following lines are needed due to buggy include files
31 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
32 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
33 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
34 * an enum in /usr/include/rpcsvc/nis.h.
37 #if defined(GROUP)
38 #undef GROUP
39 #endif
41 #if defined(GROUP_OBJ)
42 #undef GROUP_OBJ
43 #endif
45 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
47 #include <rpcsvc/nis.h>
49 #endif /* WITH_NISPLUS_HOME */
50 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
52 #ifdef WITH_SSL
53 #include <openssl/ssl.h>
54 #undef Realloc /* SSLeay defines this and samba has a function of this name */
55 extern SSL *ssl;
56 extern int sslFd;
57 #endif /* WITH_SSL */
59 int Protocol = PROTOCOL_COREPLUS;
61 /* a default finfo structure to ensure all fields are sensible */
62 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
64 /* this is used by the chaining code */
65 int chain_size = 0;
67 int trans_num = 0;
70 case handling on filenames
72 int case_default = CASE_LOWER;
74 /* the following control case operations - they are put here so the
75 client can link easily */
76 BOOL case_sensitive;
77 BOOL case_preserve;
78 BOOL use_mangled_map = False;
79 BOOL short_case_preserve;
80 BOOL case_mangle;
82 static enum remote_arch_types ra_type = RA_UNKNOWN;
83 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
85 pstring global_myname = "";
86 fstring global_myworkgroup = "";
87 char **my_netbios_names;
90 /****************************************************************************
91 Find a suitable temporary directory. The result should be copied immediately
92 as it may be overwritten by a subsequent call.
93 ****************************************************************************/
95 char *tmpdir(void)
97 char *p;
98 if ((p = getenv("TMPDIR")))
99 return p;
100 return "/tmp";
103 /****************************************************************************
104 Determine whether we are in the specified group.
105 ****************************************************************************/
107 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
109 int i;
111 if (group == current_gid)
112 return(True);
114 for (i=0;i<ngroups;i++)
115 if (group == groups[i])
116 return(True);
118 return(False);
121 /****************************************************************************
122 Like atoi but gets the value up to the separator character.
123 ****************************************************************************/
125 char *Atoic(char *p, int *n, char *c)
127 if (!isdigit((int)*p)) {
128 DEBUG(5, ("Atoic: malformed number\n"));
129 return NULL;
132 (*n) = atoi(p);
134 while ((*p) && isdigit((int)*p))
135 p++;
137 if (strchr(c, *p) == NULL) {
138 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
139 return NULL;
142 return p;
145 /*************************************************************************
146 Reads a list of numbers.
147 *************************************************************************/
149 char *get_numlist(char *p, uint32 **num, int *count)
151 int val;
153 if (num == NULL || count == NULL)
154 return NULL;
156 (*count) = 0;
157 (*num ) = NULL;
159 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
160 uint32 *tn;
162 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
163 if (tn == NULL)
165 SAFE_FREE(*num);
166 return NULL;
167 } else
168 (*num) = tn;
169 (*num)[(*count)] = val;
170 (*count)++;
171 p++;
174 return p;
177 /*******************************************************************
178 Check if a file exists - call vfs_file_exist for samba files.
179 ********************************************************************/
181 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
183 SMB_STRUCT_STAT st;
184 if (!sbuf)
185 sbuf = &st;
187 if (sys_stat(fname,sbuf) != 0)
188 return(False);
190 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
193 /*******************************************************************
194 Check a files mod time.
195 ********************************************************************/
197 time_t file_modtime(char *fname)
199 SMB_STRUCT_STAT st;
201 if (sys_stat(fname,&st) != 0)
202 return(0);
204 return(st.st_mtime);
207 /*******************************************************************
208 Check if a directory exists.
209 ********************************************************************/
211 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
213 SMB_STRUCT_STAT st2;
214 BOOL ret;
216 if (!st) st = &st2;
218 if (sys_stat(dname,st) != 0)
219 return(False);
221 ret = S_ISDIR(st->st_mode);
222 if(!ret)
223 errno = ENOTDIR;
224 return ret;
227 /*******************************************************************
228 returns the size in bytes of the named file
229 ********************************************************************/
230 SMB_OFF_T get_file_size(char *file_name)
232 SMB_STRUCT_STAT buf;
233 buf.st_size = 0;
234 if(sys_stat(file_name,&buf) != 0)
235 return (SMB_OFF_T)-1;
236 return(buf.st_size);
239 /*******************************************************************
240 return a string representing an attribute for a file
241 ********************************************************************/
242 char *attrib_string(uint16 mode)
244 static fstring attrstr;
246 attrstr[0] = 0;
248 if (mode & aVOLID) fstrcat(attrstr,"V");
249 if (mode & aDIR) fstrcat(attrstr,"D");
250 if (mode & aARCH) fstrcat(attrstr,"A");
251 if (mode & aHIDDEN) fstrcat(attrstr,"H");
252 if (mode & aSYSTEM) fstrcat(attrstr,"S");
253 if (mode & aRONLY) fstrcat(attrstr,"R");
255 return(attrstr);
258 /*******************************************************************
259 show a smb message structure
260 ********************************************************************/
261 void show_msg(char *buf)
263 int i;
264 int bcc=0;
266 if (DEBUGLEVEL < 5) return;
268 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
269 smb_len(buf),
270 (int)CVAL(buf,smb_com),
271 (int)CVAL(buf,smb_rcls),
272 (int)CVAL(buf,smb_reh),
273 (int)SVAL(buf,smb_err),
274 (int)CVAL(buf,smb_flg),
275 (int)SVAL(buf,smb_flg2)));
276 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
277 (int)SVAL(buf,smb_tid),
278 (int)SVAL(buf,smb_pid),
279 (int)SVAL(buf,smb_uid),
280 (int)SVAL(buf,smb_mid),
281 (int)CVAL(buf,smb_wct)));
283 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
285 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
286 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
289 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
291 DEBUG(5,("smb_bcc=%d\n",bcc));
293 if (DEBUGLEVEL < 10) return;
295 if (DEBUGLEVEL < 50)
297 bcc = MIN(bcc, 512);
300 dump_data(10, smb_buf(buf), bcc);
303 /*******************************************************************
304 set the length and marker of an smb packet
305 ********************************************************************/
306 void smb_setlen(char *buf,int len)
308 _smb_setlen(buf,len);
310 SCVAL(buf,4,0xFF);
311 SCVAL(buf,5,'S');
312 SCVAL(buf,6,'M');
313 SCVAL(buf,7,'B');
316 /*******************************************************************
317 setup the word count and byte count for a smb message
318 ********************************************************************/
319 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
321 if (zero)
322 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
323 SCVAL(buf,smb_wct,num_words);
324 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
325 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
326 return (smb_size + num_words*2 + num_bytes);
329 /*******************************************************************
330 setup only the byte count for a smb message
331 ********************************************************************/
332 int set_message_bcc(char *buf,int num_bytes)
334 int num_words = CVAL(buf,smb_wct);
335 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
336 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
337 return (smb_size + num_words*2 + num_bytes);
340 /*******************************************************************
341 setup only the byte count for a smb message, using the end of the
342 message as a marker
343 ********************************************************************/
344 int set_message_end(void *outbuf,void *end_ptr)
346 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
349 /*******************************************************************
350 reduce a file name, removing .. elements.
351 ********************************************************************/
352 void dos_clean_name(char *s)
354 char *p=NULL;
356 DEBUG(3,("dos_clean_name [%s]\n",s));
358 /* remove any double slashes */
359 all_string_sub(s, "\\\\", "\\", 0);
361 while ((p = strstr(s,"\\..\\")) != NULL)
363 pstring s1;
365 *p = 0;
366 pstrcpy(s1,p+3);
368 if ((p=strrchr(s,'\\')) != NULL)
369 *p = 0;
370 else
371 *s = 0;
372 pstrcat(s,s1);
375 trim_string(s,NULL,"\\..");
377 all_string_sub(s, "\\.\\", "\\", 0);
380 /*******************************************************************
381 reduce a file name, removing .. elements.
382 ********************************************************************/
383 void unix_clean_name(char *s)
385 char *p=NULL;
387 DEBUG(3,("unix_clean_name [%s]\n",s));
389 /* remove any double slashes */
390 all_string_sub(s, "//","/", 0);
392 /* Remove leading ./ characters */
393 if(strncmp(s, "./", 2) == 0) {
394 trim_string(s, "./", NULL);
395 if(*s == 0)
396 pstrcpy(s,"./");
399 while ((p = strstr(s,"/../")) != NULL)
401 pstring s1;
403 *p = 0;
404 pstrcpy(s1,p+3);
406 if ((p=strrchr(s,'/')) != NULL)
407 *p = 0;
408 else
409 *s = 0;
410 pstrcat(s,s1);
413 trim_string(s,NULL,"/..");
416 /****************************************************************************
417 make a dir struct
418 ****************************************************************************/
419 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
421 char *p;
422 pstring mask2;
424 pstrcpy(mask2,mask);
426 if ((mode & aDIR) != 0)
427 size = 0;
429 memset(buf+1,' ',11);
430 if ((p = strchr(mask2,'.')) != NULL)
432 *p = 0;
433 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
434 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
435 *p = '.';
437 else
438 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
440 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
441 SCVAL(buf,21,mode);
442 put_dos_date(buf,22,date);
443 SSVAL(buf,26,size & 0xFFFF);
444 SSVAL(buf,28,(size >> 16)&0xFFFF);
445 StrnCpy(buf+30,fname,12);
446 if (!case_sensitive)
447 strupper(buf+30);
448 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
452 /*******************************************************************
453 close the low 3 fd's and open dev/null in their place
454 ********************************************************************/
455 void close_low_fds(void)
457 #ifndef VALGRIND
458 int fd;
459 int i;
460 close(0); close(1);
461 #ifndef __INSURE__
462 close(2);
463 #endif
464 /* try and use up these file descriptors, so silly
465 library routines writing to stdout etc won't cause havoc */
466 for (i=0;i<3;i++) {
467 fd = sys_open("/dev/null",O_RDWR,0);
468 if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
469 if (fd < 0) {
470 DEBUG(0,("Can't open /dev/null\n"));
471 return;
473 if (fd != i) {
474 DEBUG(0,("Didn't get file descriptor %d\n",i));
475 return;
478 #endif
481 /****************************************************************************
482 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
483 else
484 if SYSV use O_NDELAY
485 if BSD use FNDELAY
486 ****************************************************************************/
487 int set_blocking(int fd, BOOL set)
489 int val;
490 #ifdef O_NONBLOCK
491 #define FLAG_TO_SET O_NONBLOCK
492 #else
493 #ifdef SYSV
494 #define FLAG_TO_SET O_NDELAY
495 #else /* BSD */
496 #define FLAG_TO_SET FNDELAY
497 #endif
498 #endif
500 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
501 return -1;
502 if(set) /* Turn blocking on - ie. clear nonblock flag */
503 val &= ~FLAG_TO_SET;
504 else
505 val |= FLAG_TO_SET;
506 return sys_fcntl_long( fd, F_SETFL, val);
507 #undef FLAG_TO_SET
510 /****************************************************************************
511 Transfer some data between two fd's.
512 ****************************************************************************/
514 #ifndef TRANSFER_BUF_SIZE
515 #define TRANSFER_BUF_SIZE 65536
516 #endif
518 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
519 ssize_t (*write_fn)(int, const void *, size_t))
521 char *buf;
522 size_t total = 0;
523 ssize_t read_ret;
524 ssize_t write_ret;
525 size_t num_to_read_thistime;
526 size_t num_written = 0;
528 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
529 return -1;
531 while (total < n) {
532 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
534 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
535 if (read_ret == -1) {
536 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
537 SAFE_FREE(buf);
538 return -1;
540 if (read_ret == 0)
541 break;
543 num_written = 0;
545 while (num_written < read_ret) {
546 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
548 if (write_ret == -1) {
549 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
550 SAFE_FREE(buf);
551 return -1;
553 if (write_ret == 0)
554 return (ssize_t)total;
556 num_written += (size_t)write_ret;
559 total += (size_t)read_ret;
562 SAFE_FREE(buf);
563 return (ssize_t)total;
566 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
568 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
571 /*******************************************************************
572 Sleep for a specified number of milliseconds.
573 ********************************************************************/
575 void msleep(unsigned int t)
577 unsigned int tdiff=0;
578 struct timeval tval,t1,t2;
579 fd_set fds;
581 GetTimeOfDay(&t1);
582 GetTimeOfDay(&t2);
584 while (tdiff < t) {
585 tval.tv_sec = (t-tdiff)/1000;
586 tval.tv_usec = 1000*((t-tdiff)%1000);
588 /* Never wait for more than 1 sec. */
589 if (tval.tv_sec > 1) {
590 tval.tv_sec = 1;
591 tval.tv_usec = 0;
594 FD_ZERO(&fds);
595 errno = 0;
596 sys_select_intr(0,&fds,NULL,NULL,&tval);
598 GetTimeOfDay(&t2);
599 if (t2.tv_sec < t1.tv_sec) {
600 /* Someone adjusted time... */
601 t1 = t2;
604 tdiff = TvalDiff(&t1,&t2);
608 /****************************************************************************
609 Become a daemon, discarding the controlling terminal.
610 ****************************************************************************/
612 void become_daemon(void)
614 if (sys_fork()) {
615 _exit(0);
618 /* detach from the terminal */
619 #ifdef HAVE_SETSID
620 setsid();
621 #elif defined(TIOCNOTTY)
623 int i = sys_open("/dev/tty", O_RDWR, 0);
624 if (i != -1) {
625 ioctl(i, (int) TIOCNOTTY, (char *)0);
626 close(i);
629 #endif /* HAVE_SETSID */
631 /* Close fd's 0,1,2. Needed if started by rsh */
632 close_low_fds();
635 /****************************************************************************
636 Put up a yes/no prompt
637 ****************************************************************************/
639 BOOL yesno(char *p)
641 pstring ans;
642 printf("%s",p);
644 if (!fgets(ans,sizeof(ans)-1,stdin))
645 return(False);
647 if (*ans == 'y' || *ans == 'Y')
648 return(True);
650 return(False);
653 /****************************************************************************
654 Expand a pointer to be a particular size.
655 ****************************************************************************/
657 void *Realloc(void *p,size_t size)
659 void *ret=NULL;
661 if (size == 0) {
662 SAFE_FREE(p);
663 DEBUG(5,("Realloc asked for 0 bytes\n"));
664 return NULL;
667 if (!p)
668 ret = (void *)malloc(size);
669 else
670 ret = (void *)realloc(p,size);
672 if (!ret)
673 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
675 return(ret);
678 /****************************************************************************
679 Free memory, checks for NULL.
680 use directly SAFE_FREE()
681 exist only because we need to pass a function pointer somewhere --SSS
682 ****************************************************************************/
684 void safe_free(void *p)
686 SAFE_FREE(p);
689 /****************************************************************************
690 Get my own name and IP.
691 ****************************************************************************/
693 BOOL get_myname(char *my_name)
695 pstring hostname;
697 *hostname = 0;
699 /* get my host name */
700 if (gethostname(hostname, sizeof(hostname)) == -1) {
701 DEBUG(0,("gethostname failed\n"));
702 return False;
705 /* Ensure null termination. */
706 hostname[sizeof(hostname)-1] = '\0';
708 if (my_name) {
709 /* split off any parts after an initial . */
710 char *p = strchr(hostname,'.');
711 if (p)
712 *p = 0;
714 fstrcpy(my_name,hostname);
717 return(True);
720 /****************************************************************************
721 Interpret a protocol description string, with a default.
722 ****************************************************************************/
724 int interpret_protocol(char *str,int def)
726 if (strequal(str,"NT1"))
727 return(PROTOCOL_NT1);
728 if (strequal(str,"LANMAN2"))
729 return(PROTOCOL_LANMAN2);
730 if (strequal(str,"LANMAN1"))
731 return(PROTOCOL_LANMAN1);
732 if (strequal(str,"CORE"))
733 return(PROTOCOL_CORE);
734 if (strequal(str,"COREPLUS"))
735 return(PROTOCOL_COREPLUS);
736 if (strequal(str,"CORE+"))
737 return(PROTOCOL_COREPLUS);
739 DEBUG(0,("Unrecognised protocol level %s\n",str));
741 return(def);
744 /****************************************************************************
745 Return true if a string could be a pure IP address.
746 ****************************************************************************/
748 BOOL is_ipaddress(const char *str)
750 BOOL pure_address = True;
751 int i;
753 for (i=0; pure_address && str[i]; i++)
754 if (!(isdigit((int)str[i]) || str[i] == '.'))
755 pure_address = False;
757 /* Check that a pure number is not misinterpreted as an IP */
758 pure_address = pure_address && (strchr(str, '.') != NULL);
760 return pure_address;
763 /****************************************************************************
764 interpret an internet address or name into an IP address in 4 byte form
765 ****************************************************************************/
767 uint32 interpret_addr(const char *str)
769 struct hostent *hp;
770 uint32 res;
772 if (strcmp(str,"0.0.0.0") == 0) return(0);
773 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
775 /* if it's in the form of an IP address then get the lib to interpret it */
776 if (is_ipaddress(str)) {
777 res = inet_addr(str);
778 } else {
779 /* otherwise assume it's a network name of some sort and use
780 sys_gethostbyname */
781 if ((hp = sys_gethostbyname(str)) == 0) {
782 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
783 return 0;
785 if(hp->h_addr == NULL) {
786 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
787 return 0;
789 putip((char *)&res,(char *)hp->h_addr);
792 if (res == (uint32)-1) return(0);
794 return(res);
797 /*******************************************************************
798 a convenient addition to interpret_addr()
799 ******************************************************************/
800 struct in_addr *interpret_addr2(const char *str)
802 static struct in_addr ret;
803 uint32 a = interpret_addr(str);
804 ret.s_addr = a;
805 return(&ret);
808 /*******************************************************************
809 Check if an IP is the 0.0.0.0
810 ******************************************************************/
812 BOOL is_zero_ip(struct in_addr ip)
814 uint32 a;
815 putip((char *)&a,(char *)&ip);
816 return(a == 0);
819 /*******************************************************************
820 Set an IP to 0.0.0.0
821 ******************************************************************/
823 void zero_ip(struct in_addr *ip)
825 static BOOL init;
826 static struct in_addr ipzero;
828 if (!init) {
829 ipzero = *interpret_addr2("0.0.0.0");
830 init = True;
833 *ip = ipzero;
836 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
837 /******************************************************************
838 Remove any mount options such as -rsize=2048,wsize=2048 etc.
839 Based on a fix from <Thomas.Hepper@icem.de>.
840 *******************************************************************/
842 static void strip_mount_options( pstring *str)
844 if (**str == '-')
846 char *p = *str;
847 while(*p && !isspace(*p))
848 p++;
849 while(*p && isspace(*p))
850 p++;
851 if(*p) {
852 pstring tmp_str;
854 pstrcpy(tmp_str, p);
855 pstrcpy(*str, tmp_str);
860 /*******************************************************************
861 Patch from jkf@soton.ac.uk
862 Split Luke's automount_server into YP lookup and string splitter
863 so can easily implement automount_path().
864 As we may end up doing both, cache the last YP result.
865 *******************************************************************/
867 #ifdef WITH_NISPLUS_HOME
868 char *automount_lookup(char *user_name)
870 static fstring last_key = "";
871 static pstring last_value = "";
873 char *nis_map = (char *)lp_nis_home_map_name();
875 char buffer[NIS_MAXATTRVAL + 1];
876 nis_result *result;
877 nis_object *object;
878 entry_obj *entry;
880 if (strcmp(user_name, last_key))
882 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
883 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
885 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
887 if (result->status != NIS_SUCCESS)
889 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
890 fstrcpy(last_key, ""); pstrcpy(last_value, "");
892 else
894 object = result->objects.objects_val;
895 if (object->zo_data.zo_type == ENTRY_OBJ)
897 entry = &object->zo_data.objdata_u.en_data;
898 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
899 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
901 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
902 pstring_sub(last_value, "&", user_name);
903 fstrcpy(last_key, user_name);
907 nis_freeresult(result);
910 strip_mount_options(&last_value);
912 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
913 return last_value;
915 #else /* WITH_NISPLUS_HOME */
916 char *automount_lookup(char *user_name)
918 static fstring last_key = "";
919 static pstring last_value = "";
921 int nis_error; /* returned by yp all functions */
922 char *nis_result; /* yp_match inits this */
923 int nis_result_len; /* and set this */
924 char *nis_domain; /* yp_get_default_domain inits this */
925 char *nis_map = (char *)lp_nis_home_map_name();
927 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
928 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
929 return last_value;
932 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
934 if (!strcmp(user_name, last_key)) {
935 nis_result = last_value;
936 nis_result_len = strlen(last_value);
937 nis_error = 0;
939 } else {
941 if ((nis_error = yp_match(nis_domain, nis_map,
942 user_name, strlen(user_name),
943 &nis_result, &nis_result_len)) == 0) {
944 if (!nis_error && nis_result_len >= sizeof(pstring)) {
945 nis_result_len = sizeof(pstring)-1;
947 fstrcpy(last_key, user_name);
948 strncpy(last_value, nis_result, nis_result_len);
949 last_value[nis_result_len] = '\0';
950 strip_mount_options(&last_value);
952 } else if(nis_error == YPERR_KEY) {
954 /* If Key lookup fails user home server is not in nis_map
955 use default information for server, and home directory */
956 last_value[0] = 0;
957 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
958 user_name, nis_map));
959 DEBUG(3, ("using defaults for server and home directory\n"));
960 } else {
961 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
962 yperr_string(nis_error), user_name, nis_map));
967 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
968 return last_value;
970 #endif /* WITH_NISPLUS_HOME */
971 #endif
974 /*******************************************************************
975 are two IPs on the same subnet?
976 ********************************************************************/
977 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
979 uint32 net1,net2,nmask;
981 nmask = ntohl(mask.s_addr);
982 net1 = ntohl(ip1.s_addr);
983 net2 = ntohl(ip2.s_addr);
985 return((net1 & nmask) == (net2 & nmask));
989 /****************************************************************************
990 check if a process exists. Does this work on all unixes?
991 ****************************************************************************/
993 BOOL process_exists(pid_t pid)
995 return(kill(pid,0) == 0 || errno != ESRCH);
999 /*******************************************************************
1000 Convert a uid into a user name.
1001 ********************************************************************/
1003 char *uidtoname(uid_t uid)
1005 static fstring name;
1006 struct passwd *pass;
1008 if (winbind_uidtoname(name, uid))
1009 return name;
1011 pass = sys_getpwuid(uid);
1012 if (pass)
1013 return(pass->pw_name);
1014 slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1015 return(name);
1019 /*******************************************************************
1020 Convert a gid into a group name.
1021 ********************************************************************/
1023 char *gidtoname(gid_t gid)
1025 static fstring name;
1026 struct group *grp;
1028 if (winbind_gidtoname(name, gid))
1029 return name;
1031 grp = getgrgid(gid);
1032 if (grp)
1033 return(grp->gr_name);
1034 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1035 return(name);
1038 /*******************************************************************
1039 Convert a user name into a uid. If winbindd is present uses this.
1040 ********************************************************************/
1042 uid_t nametouid(char *name)
1044 struct passwd *pass;
1045 char *p;
1046 uid_t u;
1048 u = (uid_t)strtol(name, &p, 0);
1049 if ((p != name) && (*p == '\0'))
1050 return u;
1052 if (winbind_nametouid(&u, name))
1053 return u;
1055 pass = sys_getpwnam(name);
1056 if (pass)
1057 return(pass->pw_uid);
1058 return (uid_t)-1;
1061 /*******************************************************************
1062 Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1063 is present does a shortcut lookup...
1064 ********************************************************************/
1066 gid_t nametogid(char *name)
1068 struct group *grp;
1069 char *p;
1070 gid_t g;
1072 g = (gid_t)strtol(name, &p, 0);
1073 if ((p != name) && (*p == '\0'))
1074 return g;
1076 if (winbind_nametogid(&g, name))
1077 return g;
1079 grp = getgrnam(name);
1080 if (grp)
1081 return(grp->gr_gid);
1082 return (gid_t)-1;
1085 /*******************************************************************
1086 something really nasty happened - panic!
1087 ********************************************************************/
1088 void smb_panic(char *why)
1090 char *cmd = lp_panic_action();
1091 if (cmd && *cmd) {
1092 system(cmd);
1094 DEBUG(0,("PANIC: %s\n", why));
1095 dbgflush();
1096 abort();
1100 /*******************************************************************
1101 a readdir wrapper which just returns the file name
1102 ********************************************************************/
1103 char *readdirname(DIR *p)
1105 SMB_STRUCT_DIRENT *ptr;
1106 char *dname;
1108 if (!p) return(NULL);
1110 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1111 if (!ptr) return(NULL);
1113 dname = ptr->d_name;
1115 #ifdef NEXT2
1116 if (telldir(p) < 0) return(NULL);
1117 #endif
1119 #ifdef HAVE_BROKEN_READDIR
1120 /* using /usr/ucb/cc is BAD */
1121 dname = dname - 2;
1122 #endif
1125 static pstring buf;
1126 int len = NAMLEN(ptr);
1127 memcpy(buf, dname, len);
1128 buf[len] = 0;
1129 dname = buf;
1132 return(dname);
1135 /*******************************************************************
1136 Utility function used to decide if the last component
1137 of a path matches a (possibly wildcarded) entry in a namelist.
1138 ********************************************************************/
1140 BOOL is_in_path(char *name, name_compare_entry *namelist)
1142 pstring last_component;
1143 char *p;
1145 DEBUG(8, ("is_in_path: %s\n", name));
1147 /* if we have no list it's obviously not in the path */
1148 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
1150 DEBUG(8,("is_in_path: no name list.\n"));
1151 return False;
1154 /* Get the last component of the unix name. */
1155 p = strrchr(name, '/');
1156 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1157 last_component[sizeof(last_component)-1] = '\0';
1159 for(; namelist->name != NULL; namelist++)
1161 if(namelist->is_wild)
1163 if (mask_match(last_component, namelist->name, case_sensitive))
1165 DEBUG(8,("is_in_path: mask match succeeded\n"));
1166 return True;
1169 else
1171 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1172 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1174 DEBUG(8,("is_in_path: match succeeded\n"));
1175 return True;
1179 DEBUG(8,("is_in_path: match not found\n"));
1181 return False;
1184 /*******************************************************************
1185 Strip a '/' separated list into an array of
1186 name_compare_enties structures suitable for
1187 passing to is_in_path(). We do this for
1188 speed so we can pre-parse all the names in the list
1189 and don't do it for each call to is_in_path().
1190 namelist is modified here and is assumed to be
1191 a copy owned by the caller.
1192 We also check if the entry contains a wildcard to
1193 remove a potentially expensive call to mask_match
1194 if possible.
1195 ********************************************************************/
1197 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1199 char *name_end;
1200 char *nameptr = namelist;
1201 int num_entries = 0;
1202 int i;
1204 (*ppname_array) = NULL;
1206 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1207 return;
1209 /* We need to make two passes over the string. The
1210 first to count the number of elements, the second
1211 to split it.
1213 while(*nameptr)
1215 if ( *nameptr == '/' )
1217 /* cope with multiple (useless) /s) */
1218 nameptr++;
1219 continue;
1221 /* find the next / */
1222 name_end = strchr(nameptr, '/');
1224 /* oops - the last check for a / didn't find one. */
1225 if (name_end == NULL)
1226 break;
1228 /* next segment please */
1229 nameptr = name_end + 1;
1230 num_entries++;
1233 if(num_entries == 0)
1234 return;
1236 if(( (*ppname_array) = (name_compare_entry *)malloc(
1237 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1239 DEBUG(0,("set_namearray: malloc fail\n"));
1240 return;
1243 /* Now copy out the names */
1244 nameptr = namelist;
1245 i = 0;
1246 while(*nameptr)
1248 if ( *nameptr == '/' )
1250 /* cope with multiple (useless) /s) */
1251 nameptr++;
1252 continue;
1254 /* find the next / */
1255 if ((name_end = strchr(nameptr, '/')) != NULL)
1257 *name_end = 0;
1260 /* oops - the last check for a / didn't find one. */
1261 if(name_end == NULL)
1262 break;
1264 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1265 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1267 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1268 return;
1271 /* next segment please */
1272 nameptr = name_end + 1;
1273 i++;
1276 (*ppname_array)[i].name = NULL;
1278 return;
1281 /****************************************************************************
1282 routine to free a namearray.
1283 ****************************************************************************/
1285 void free_namearray(name_compare_entry *name_array)
1287 if(name_array == NULL)
1288 return;
1290 SAFE_FREE(name_array->name);
1291 SAFE_FREE(name_array);
1294 /****************************************************************************
1295 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1296 is dealt with in posix.c
1297 ****************************************************************************/
1299 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1301 SMB_STRUCT_FLOCK lock;
1302 int ret;
1304 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1306 lock.l_type = type;
1307 lock.l_whence = SEEK_SET;
1308 lock.l_start = offset;
1309 lock.l_len = count;
1310 lock.l_pid = 0;
1312 ret = sys_fcntl_ptr(fd,op,&lock);
1314 if (ret == -1 && errno != 0)
1315 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1317 /* a lock query */
1318 if (op == SMB_F_GETLK)
1320 if ((ret != -1) &&
1321 (lock.l_type != F_UNLCK) &&
1322 (lock.l_pid != 0) &&
1323 (lock.l_pid != sys_getpid()))
1325 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1326 return(True);
1329 /* it must be not locked or locked by me */
1330 return(False);
1333 /* a lock set or unset */
1334 if (ret == -1)
1336 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1337 (double)offset,(double)count,op,type,strerror(errno)));
1338 return(False);
1341 /* everything went OK */
1342 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1344 return(True);
1347 /*******************************************************************
1348 is the name specified one of my netbios names
1349 returns true is it is equal, false otherwise
1350 ********************************************************************/
1351 BOOL is_myname(char *s)
1353 int n;
1354 BOOL ret = False;
1356 for (n=0; my_netbios_names[n]; n++) {
1357 if (strequal(my_netbios_names[n], s))
1358 ret=True;
1360 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1361 return(ret);
1364 /********************************************************************
1365 Return only the first IP address of our configured interfaces
1366 as a string
1367 *******************************************************************/
1369 const char* get_my_primary_ip (void)
1371 static fstring ip_string;
1372 int n;
1373 struct iface_struct nics[MAX_INTERFACES];
1375 if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1376 return NULL;
1378 fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1379 return ip_string;
1383 BOOL is_myname_or_ipaddr(char *s)
1385 char *ptr;
1386 pstring nbname;
1388 /* optimize for the common case */
1389 if (strequal(s, global_myname))
1390 return True;
1392 /* maybe its an IP address? */
1393 if (is_ipaddress(s))
1395 struct iface_struct nics[MAX_INTERFACES];
1396 int i, n;
1397 uint32 ip;
1399 ip = interpret_addr(s);
1400 if ((ip==0) || (ip==0xffffffff))
1401 return False;
1403 n = get_interfaces(nics, MAX_INTERFACES);
1404 for (i=0; i<n; i++) {
1405 if (ip == nics[i].ip.s_addr)
1406 return True;
1410 /* check for an alias */
1411 ptr = lp_netbios_aliases();
1412 while ( next_token(&ptr, nbname, NULL, sizeof(nbname)) )
1414 if (StrCaseCmp(s, nbname) == 0)
1415 return True;
1419 /* no match */
1420 return False;
1425 /*******************************************************************
1426 set the horrid remote_arch string based on an enum.
1427 ********************************************************************/
1428 void set_remote_arch(enum remote_arch_types type)
1430 extern fstring remote_arch;
1431 ra_type = type;
1432 switch( type )
1434 case RA_WFWG:
1435 fstrcpy(remote_arch, "WfWg");
1436 return;
1437 case RA_OS2:
1438 fstrcpy(remote_arch, "OS2");
1439 return;
1440 case RA_WIN95:
1441 fstrcpy(remote_arch, "Win95");
1442 return;
1443 case RA_WINNT:
1444 fstrcpy(remote_arch, "WinNT");
1445 return;
1446 case RA_WIN2K:
1447 fstrcpy(remote_arch, "Win2K");
1448 return;
1449 case RA_SAMBA:
1450 fstrcpy(remote_arch,"Samba");
1451 return;
1452 default:
1453 ra_type = RA_UNKNOWN;
1454 fstrcpy(remote_arch, "UNKNOWN");
1455 break;
1459 /*******************************************************************
1460 Get the remote_arch type.
1461 ********************************************************************/
1462 enum remote_arch_types get_remote_arch(void)
1464 return ra_type;
1468 void out_ascii(FILE *f, unsigned char *buf,int len)
1470 int i;
1471 for (i=0;i<len;i++)
1473 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1477 void out_data(FILE *f,char *buf1,int len, int per_line)
1479 unsigned char *buf = (unsigned char *)buf1;
1480 int i=0;
1481 if (len<=0)
1483 return;
1486 fprintf(f, "[%03X] ",i);
1487 for (i=0;i<len;)
1489 fprintf(f, "%02X ",(int)buf[i]);
1490 i++;
1491 if (i%(per_line/2) == 0) fprintf(f, " ");
1492 if (i%per_line == 0)
1494 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1495 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1496 if (i<len) fprintf(f, "[%03X] ",i);
1499 if ((i%per_line) != 0)
1501 int n;
1503 n = per_line - (i%per_line);
1504 fprintf(f, " ");
1505 if (n>(per_line/2)) fprintf(f, " ");
1506 while (n--)
1508 fprintf(f, " ");
1510 n = MIN(per_line/2,i%per_line);
1511 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1512 n = (i%per_line) - n;
1513 if (n>0) out_ascii(f,&buf[i-n],n);
1514 fprintf(f, "\n");
1518 void print_asc(int level, unsigned char *buf,int len)
1520 int i;
1521 for (i=0;i<len;i++)
1522 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1525 void dump_data(int level,char *buf1,int len)
1527 unsigned char *buf = (unsigned char *)buf1;
1528 int i=0;
1529 if (len<=0) return;
1531 DEBUG(level,("[%03X] ",i));
1532 for (i=0;i<len;) {
1533 DEBUG(level,("%02X ",(int)buf[i]));
1534 i++;
1535 if (i%8 == 0) DEBUG(level,(" "));
1536 if (i%16 == 0) {
1537 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1538 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1539 if (i<len) DEBUG(level,("[%03X] ",i));
1542 if (i%16) {
1543 int n;
1545 n = 16 - (i%16);
1546 DEBUG(level,(" "));
1547 if (n>8) DEBUG(level,(" "));
1548 while (n--) DEBUG(level,(" "));
1550 n = MIN(8,i%16);
1551 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1552 n = (i%16) - n;
1553 if (n>0) print_asc(level,&buf[i-n],n);
1554 DEBUG(level,("\n"));
1558 char *tab_depth(int depth)
1560 static pstring spaces;
1561 memset(spaces, ' ', depth * 4);
1562 spaces[depth * 4] = 0;
1563 return spaces;
1566 /*****************************************************************************
1567 * Provide a checksum on a string
1569 * Input: s - the null-terminated character string for which the checksum
1570 * will be calculated.
1572 * Output: The checksum value calculated for s.
1574 * ****************************************************************************
1576 int str_checksum(const char *s)
1578 int res = 0;
1579 int c;
1580 int i=0;
1582 while(*s) {
1583 c = *s;
1584 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1585 s++;
1586 i++;
1588 return(res);
1589 } /* str_checksum */
1593 /*****************************************************************
1594 zero a memory area then free it. Used to catch bugs faster
1595 *****************************************************************/
1596 void zero_free(void *p, size_t size)
1598 memset(p, 0, size);
1599 SAFE_FREE(p);
1603 /*****************************************************************
1604 set our open file limit to a requested max and return the limit
1605 *****************************************************************/
1606 int set_maxfiles(int requested_max)
1608 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1609 struct rlimit rlp;
1610 int saved_current_limit;
1612 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1613 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1614 strerror(errno) ));
1615 /* just guess... */
1616 return requested_max;
1620 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1621 * account for the extra fd we need
1622 * as well as the log files and standard
1623 * handles etc. Save the limit we want to set in case
1624 * we are running on an OS that doesn't support this limit (AIX)
1625 * which always returns RLIM_INFINITY for rlp.rlim_max.
1628 /* Try raising the hard (max) limit to the requested amount. */
1630 #if defined(RLIM_INFINITY)
1631 if (rlp.rlim_max != RLIM_INFINITY) {
1632 int orig_max = rlp.rlim_max;
1634 if ( rlp.rlim_max < requested_max )
1635 rlp.rlim_max = requested_max;
1637 /* This failing is not an error - many systems (Linux) don't
1638 support our default request of 10,000 open files. JRA. */
1640 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1641 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1642 (int)rlp.rlim_max, strerror(errno) ));
1644 /* Set failed - restore original value from get. */
1645 rlp.rlim_max = orig_max;
1648 #endif
1650 /* Now try setting the soft (current) limit. */
1652 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1654 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1655 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1656 (int)rlp.rlim_cur, strerror(errno) ));
1657 /* just guess... */
1658 return saved_current_limit;
1661 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1662 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1663 strerror(errno) ));
1664 /* just guess... */
1665 return saved_current_limit;
1668 #if defined(RLIM_INFINITY)
1669 if(rlp.rlim_cur == RLIM_INFINITY)
1670 return saved_current_limit;
1671 #endif
1673 if((int)rlp.rlim_cur > saved_current_limit)
1674 return saved_current_limit;
1676 return rlp.rlim_cur;
1677 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1679 * No way to know - just guess...
1681 return requested_max;
1682 #endif
1685 /*****************************************************************
1686 splits out the start of the key (HKLM or HKU) and the rest of the key
1687 *****************************************************************/
1688 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1690 pstring tmp;
1692 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1694 return False;
1697 (*reg_type) = 0;
1699 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1701 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1703 (*reg_type) = HKEY_LOCAL_MACHINE;
1705 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1707 (*reg_type) = HKEY_USERS;
1709 else
1711 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1712 return False;
1715 if (next_token(NULL, tmp, "\n\r", sizeof(tmp)))
1717 fstrcpy(key_name, tmp);
1719 else
1721 key_name[0] = 0;
1724 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1726 return True;
1730 /*****************************************************************
1731 possibly replace mkstemp if it is broken
1732 *****************************************************************/
1733 int smb_mkstemp(char *template)
1735 #if HAVE_SECURE_MKSTEMP
1736 return mkstemp(template);
1737 #else
1738 /* have a reasonable go at emulating it. Hope that
1739 the system mktemp() isn't completly hopeless */
1740 char *p = mktemp(template);
1741 if (!p) return -1;
1742 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1743 #endif
1746 /*****************************************************************
1747 malloc that aborts with smb_panic on fail or zero size.
1748 *****************************************************************/
1750 void *smb_xmalloc(size_t size)
1752 void *p;
1753 if (size == 0)
1754 smb_panic("smb_xmalloc: called with zero size.\n");
1755 if ((p = malloc(size)) == NULL)
1756 smb_panic("smb_xmalloc: malloc fail.\n");
1757 return p;
1761 Memdup with smb_panic on fail.
1763 void *smb_xmemdup(const void *p, size_t size)
1765 void *p2;
1766 p2 = smb_xmalloc(size);
1767 memcpy(p2, p, size);
1768 return p2;
1772 strdup that aborts on malloc fail.
1774 char *smb_xstrdup(const char *s)
1776 char *s1 = strdup(s);
1777 if (!s1)
1778 smb_panic("smb_xstrdup: malloc fail\n");
1779 return s1;
1783 vasprintf that aborts on malloc fail
1785 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
1787 int n;
1788 va_list ap2;
1790 VA_COPY(ap2, ap);
1792 n = vasprintf(ptr, format, ap2);
1793 if (n == -1 || ! *ptr) {
1794 smb_panic("smb_xvasprintf: out of memory");
1796 return n;
1799 /*****************************************************************
1800 like strdup but for memory
1801 *****************************************************************/
1802 void *memdup(void *p, size_t size)
1804 void *p2;
1805 if (size == 0) return NULL;
1806 p2 = malloc(size);
1807 if (!p2) return NULL;
1808 memcpy(p2, p, size);
1809 return p2;
1812 /*****************************************************************
1813 get local hostname and cache result
1814 *****************************************************************/
1815 char *myhostname(void)
1817 static pstring ret;
1818 if (ret[0] == 0) {
1819 get_myname(ret);
1821 return ret;
1825 /*****************************************************************
1826 a useful function for returning a path in the Samba lock directory
1827 *****************************************************************/
1828 char *lock_path(char *name)
1830 static pstring fname;
1832 pstrcpy(fname,lp_lockdir());
1833 trim_string(fname,"","/");
1835 if (!directory_exist(fname,NULL)) {
1836 mkdir(fname,0755);
1839 pstrcat(fname,"/");
1840 pstrcat(fname,name);
1842 return fname;
1845 /*****************************************************************
1846 a useful function for returning a path in the Samba pid directory
1847 *****************************************************************/
1848 char *pid_path(char *name)
1850 static pstring fname;
1852 pstrcpy(fname,lp_piddir());
1853 trim_string(fname,"","/");
1855 if (!directory_exist(fname,NULL)) {
1856 mkdir(fname,0755);
1859 pstrcat(fname,"/");
1860 pstrcat(fname,name);
1862 return fname;
1865 /*******************************************************************
1866 Given a filename - get its directory name
1867 NB: Returned in static storage. Caveats:
1868 o Not safe in thread environment.
1869 o Caller must not free.
1870 o If caller wishes to preserve, they should copy.
1871 ********************************************************************/
1873 char *parent_dirname(const char *path)
1875 static pstring dirpath;
1876 char *p;
1878 if (!path)
1879 return(NULL);
1881 pstrcpy(dirpath, path);
1882 p = strrchr(dirpath, '/'); /* Find final '/', if any */
1883 if (!p) {
1884 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
1885 } else {
1886 if (p == dirpath)
1887 ++p; /* For root "/", leave "/" in place */
1888 *p = '\0';
1890 return dirpath;
1894 /*******************************************************************
1895 determine if a pattern contains any Microsoft wildcard characters
1896 *******************************************************************/
1897 BOOL ms_has_wild(char *s)
1899 char c;
1900 while ((c = *s++)) {
1901 switch (c) {
1902 case '*':
1903 case '?':
1904 case '<':
1905 case '>':
1906 case '"':
1907 return True;
1910 return False;
1913 /*******************************************************************
1914 a wrapper that handles case sensitivity and the special handling
1915 of the ".." name
1916 *******************************************************************/
1917 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1919 fstring p2, s2;
1920 if (strcmp(string,"..") == 0) string = ".";
1921 if (strcmp(pattern,".") == 0) return False;
1923 if (is_case_sensitive) {
1924 return ms_fnmatch(pattern, string) == 0;
1927 fstrcpy(p2, pattern);
1928 fstrcpy(s2, string);
1929 strlower(p2);
1930 strlower(s2);
1931 return ms_fnmatch(p2, s2) == 0;
1934 /*********************************************************
1935 Recursive routine that is called by unix_wild_match.
1936 *********************************************************/
1938 static BOOL unix_do_match(char *regexp, char *str)
1940 char *p;
1942 for( p = regexp; *p && *str; ) {
1944 switch(*p) {
1945 case '?':
1946 str++;
1947 p++;
1948 break;
1950 case '*':
1953 * Look for a character matching
1954 * the one after the '*'.
1956 p++;
1957 if(!*p)
1958 return True; /* Automatic match */
1959 while(*str) {
1961 while(*str && (*p != *str))
1962 str++;
1965 * Patch from weidel@multichart.de. In the case of the regexp
1966 * '*XX*' we want to ensure there are at least 2 'X' characters
1967 * in the string after the '*' for a match to be made.
1971 int matchcount=0;
1974 * Eat all the characters that match, but count how many there were.
1977 while(*str && (*p == *str)) {
1978 str++;
1979 matchcount++;
1983 * Now check that if the regexp had n identical characters that
1984 * matchcount had at least that many matches.
1987 while ( *(p+1) && (*(p+1) == *p)) {
1988 p++;
1989 matchcount--;
1992 if ( matchcount <= 0 )
1993 return False;
1996 str--; /* We've eaten the match char after the '*' */
1998 if(unix_do_match(p, str))
1999 return True;
2001 if(!*str)
2002 return False;
2003 else
2004 str++;
2006 return False;
2008 default:
2009 if(*str != *p)
2010 return False;
2011 str++;
2012 p++;
2013 break;
2017 if(!*p && !*str)
2018 return True;
2020 if (!*p && str[0] == '.' && str[1] == 0)
2021 return(True);
2023 if (!*str && *p == '?') {
2024 while (*p == '?')
2025 p++;
2026 return(!*p);
2029 if(!*str && (*p == '*' && p[1] == '\0'))
2030 return True;
2032 return False;
2035 /*******************************************************************
2036 Simple case insensitive interface to a UNIX wildcard matcher.
2037 *******************************************************************/
2039 BOOL unix_wild_match(char *pattern, char *string)
2041 pstring p2, s2;
2042 char *p;
2044 pstrcpy(p2, pattern);
2045 pstrcpy(s2, string);
2046 strlower(p2);
2047 strlower(s2);
2049 /* Remove any *? and ** from the pattern as they are meaningless */
2050 for(p = p2; *p; p++)
2051 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2052 pstrcpy( &p[1], &p[2]);
2054 if (strequal(p2,"*"))
2055 return True;
2057 return unix_do_match(p2, s2) == 0;
2060 /*******************************************************************
2061 free() a data blob
2062 *******************************************************************/
2064 static void free_data_blob(DATA_BLOB *d)
2066 if ((d) && (d->free)) {
2067 SAFE_FREE(d->data);
2071 /*******************************************************************
2072 construct a data blob, must be freed with data_blob_free()
2073 you can pass NULL for p and get a blank data blob
2074 *******************************************************************/
2076 DATA_BLOB data_blob(const void *p, size_t length)
2078 DATA_BLOB ret;
2080 if (!length) {
2081 ZERO_STRUCT(ret);
2082 return ret;
2085 if (p) {
2086 ret.data = smb_xmemdup(p, length);
2087 } else {
2088 ret.data = smb_xmalloc(length);
2090 ret.length = length;
2091 ret.free = free_data_blob;
2092 return ret;
2095 /*******************************************************************
2096 construct a data blob, using supplied TALLOC_CTX
2097 *******************************************************************/
2099 DATA_BLOB data_blob_talloc(TALLOC_CTX *mem_ctx, const void *p, size_t length)
2101 DATA_BLOB ret;
2103 if (!p || !length) {
2104 ZERO_STRUCT(ret);
2105 return ret;
2108 ret.data = talloc_memdup(mem_ctx, p, length);
2109 if (ret.data == NULL)
2110 smb_panic("data_blob_talloc: talloc_memdup failed.\n");
2112 ret.length = length;
2113 ret.free = NULL;
2114 return ret;
2117 /*******************************************************************
2118 free a data blob
2119 *******************************************************************/
2120 void data_blob_free(DATA_BLOB *d)
2122 if (d) {
2123 if (d->free) {
2124 (d->free)(d);
2126 ZERO_STRUCTP(d);
2130 /*******************************************************************
2131 clear a DATA_BLOB's contents
2132 *******************************************************************/
2133 void data_blob_clear(DATA_BLOB *d)
2135 if (d->data) {
2136 memset(d->data, 0, d->length);
2140 #ifdef __INSURE__
2142 /*******************************************************************
2143 This routine is a trick to immediately catch errors when debugging
2144 with insure. A xterm with a gdb is popped up when insure catches
2145 a error. It is Linux specific.
2146 ********************************************************************/
2147 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2149 static int (*fn)();
2150 int ret;
2151 char pidstr[10];
2152 pstring cmd = "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";
2154 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2155 pstring_sub(cmd, "%d", pidstr);
2157 if (!fn) {
2158 static void *h;
2159 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2160 fn = dlsym(h, "_Insure_trap_error");
2163 ret = fn(a1, a2, a3, a4, a5, a6);
2165 system(cmd);
2167 return ret;
2169 #endif