r6049: Ensure "dos filetime" checks file ACLs correctly. May fix Excel "read-only"
[Samba.git] / source / lib / util.c
blob8f6a381944293436f4ab106f5ff60fd474f86056
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
7 Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
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 /* Max allowable allococation - 256mb - 0x10000000 */
27 #define MAX_ALLOC_SIZE (1024*1024*256)
29 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
30 #ifdef WITH_NISPLUS_HOME
31 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
33 * The following lines are needed due to buggy include files
34 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
35 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
36 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
37 * an enum in /usr/include/rpcsvc/nis.h.
40 #if defined(GROUP)
41 #undef GROUP
42 #endif
44 #if defined(GROUP_OBJ)
45 #undef GROUP_OBJ
46 #endif
48 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
50 #include <rpcsvc/nis.h>
52 #endif /* WITH_NISPLUS_HOME */
53 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
55 enum protocol_types Protocol = PROTOCOL_COREPLUS;
57 /* a default finfo structure to ensure all fields are sensible */
58 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
60 /* this is used by the chaining code */
61 int chain_size = 0;
63 int trans_num = 0;
65 static enum remote_arch_types ra_type = RA_UNKNOWN;
66 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
68 /***********************************************************************
69 Definitions for all names.
70 ***********************************************************************/
72 static char *smb_myname;
73 static char *smb_myworkgroup;
74 static char *smb_scope;
75 static int smb_num_netbios_names;
76 static char **smb_my_netbios_names;
78 /***********************************************************************
79 Allocate and set myname. Ensure upper case.
80 ***********************************************************************/
82 BOOL set_global_myname(const char *myname)
84 SAFE_FREE(smb_myname);
85 smb_myname = SMB_STRDUP(myname);
86 if (!smb_myname)
87 return False;
88 strupper_m(smb_myname);
89 return True;
92 const char *global_myname(void)
94 return smb_myname;
97 /***********************************************************************
98 Allocate and set myworkgroup. Ensure upper case.
99 ***********************************************************************/
101 BOOL set_global_myworkgroup(const char *myworkgroup)
103 SAFE_FREE(smb_myworkgroup);
104 smb_myworkgroup = SMB_STRDUP(myworkgroup);
105 if (!smb_myworkgroup)
106 return False;
107 strupper_m(smb_myworkgroup);
108 return True;
111 const char *lp_workgroup(void)
113 return smb_myworkgroup;
116 /***********************************************************************
117 Allocate and set scope. Ensure upper case.
118 ***********************************************************************/
120 BOOL set_global_scope(const char *scope)
122 SAFE_FREE(smb_scope);
123 smb_scope = SMB_STRDUP(scope);
124 if (!smb_scope)
125 return False;
126 strupper_m(smb_scope);
127 return True;
130 /*********************************************************************
131 Ensure scope is never null string.
132 *********************************************************************/
134 const char *global_scope(void)
136 if (!smb_scope)
137 set_global_scope("");
138 return smb_scope;
141 static void free_netbios_names_array(void)
143 int i;
145 for (i = 0; i < smb_num_netbios_names; i++)
146 SAFE_FREE(smb_my_netbios_names[i]);
148 SAFE_FREE(smb_my_netbios_names);
149 smb_num_netbios_names = 0;
152 static BOOL allocate_my_netbios_names_array(size_t number)
154 free_netbios_names_array();
156 smb_num_netbios_names = number + 1;
157 smb_my_netbios_names = SMB_MALLOC_ARRAY( char *, smb_num_netbios_names );
159 if (!smb_my_netbios_names)
160 return False;
162 memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
163 return True;
166 static BOOL set_my_netbios_names(const char *name, int i)
168 SAFE_FREE(smb_my_netbios_names[i]);
170 smb_my_netbios_names[i] = SMB_STRDUP(name);
171 if (!smb_my_netbios_names[i])
172 return False;
173 strupper_m(smb_my_netbios_names[i]);
174 return True;
177 const char *my_netbios_names(int i)
179 return smb_my_netbios_names[i];
182 BOOL set_netbios_aliases(const char **str_array)
184 size_t namecount;
186 /* Work out the max number of netbios aliases that we have */
187 for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
190 if ( global_myname() && *global_myname())
191 namecount++;
193 /* Allocate space for the netbios aliases */
194 if (!allocate_my_netbios_names_array(namecount))
195 return False;
197 /* Use the global_myname string first */
198 namecount=0;
199 if ( global_myname() && *global_myname()) {
200 set_my_netbios_names( global_myname(), namecount );
201 namecount++;
204 if (str_array) {
205 size_t i;
206 for ( i = 0; str_array[i] != NULL; i++) {
207 size_t n;
208 BOOL duplicate = False;
210 /* Look for duplicates */
211 for( n=0; n<namecount; n++ ) {
212 if( strequal( str_array[i], my_netbios_names(n) ) ) {
213 duplicate = True;
214 break;
217 if (!duplicate) {
218 if (!set_my_netbios_names(str_array[i], namecount))
219 return False;
220 namecount++;
224 return True;
227 /****************************************************************************
228 Common name initialization code.
229 ****************************************************************************/
231 BOOL init_names(void)
233 extern fstring local_machine;
234 char *p;
235 int n;
237 if (global_myname() == NULL || *global_myname() == '\0') {
238 if (!set_global_myname(myhostname())) {
239 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
240 return False;
244 if (!set_netbios_aliases(lp_netbios_aliases())) {
245 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
246 return False;
249 fstrcpy( local_machine, global_myname() );
250 trim_char( local_machine, ' ', ' ' );
251 p = strchr( local_machine, ' ' );
252 if (p)
253 *p = 0;
254 strlower_m( local_machine );
256 DEBUG( 5, ("Netbios name list:-\n") );
257 for( n=0; my_netbios_names(n); n++ )
258 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
260 return( True );
263 /**************************************************************************n
264 Find a suitable temporary directory. The result should be copied immediately
265 as it may be overwritten by a subsequent call.
266 ****************************************************************************/
268 const char *tmpdir(void)
270 char *p;
271 if ((p = getenv("TMPDIR")))
272 return p;
273 return "/tmp";
276 /****************************************************************************
277 Add a gid to an array of gids if it's not already there.
278 ****************************************************************************/
280 void add_gid_to_array_unique(gid_t gid, gid_t **gids, int *num)
282 int i;
284 for (i=0; i<*num; i++) {
285 if ((*gids)[i] == gid)
286 return;
289 *gids = SMB_REALLOC_ARRAY(*gids, gid_t, *num+1);
291 if (*gids == NULL)
292 return;
294 (*gids)[*num] = gid;
295 *num += 1;
298 /****************************************************************************
299 Like atoi but gets the value up to the separator character.
300 ****************************************************************************/
302 static const char *Atoic(const char *p, int *n, const char *c)
304 if (!isdigit((int)*p)) {
305 DEBUG(5, ("Atoic: malformed number\n"));
306 return NULL;
309 (*n) = atoi(p);
311 while ((*p) && isdigit((int)*p))
312 p++;
314 if (strchr_m(c, *p) == NULL) {
315 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
316 return NULL;
319 return p;
322 /*************************************************************************
323 Reads a list of numbers.
324 *************************************************************************/
326 const char *get_numlist(const char *p, uint32 **num, int *count)
328 int val;
330 if (num == NULL || count == NULL)
331 return NULL;
333 (*count) = 0;
334 (*num ) = NULL;
336 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
337 uint32 *tn;
339 tn = SMB_REALLOC_ARRAY((*num), uint32, (*count)+1);
340 if (tn == NULL) {
341 SAFE_FREE(*num);
342 return NULL;
343 } else
344 (*num) = tn;
345 (*num)[(*count)] = val;
346 (*count)++;
347 p++;
350 return p;
353 /*******************************************************************
354 Check if a file exists - call vfs_file_exist for samba files.
355 ********************************************************************/
357 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
359 SMB_STRUCT_STAT st;
360 if (!sbuf)
361 sbuf = &st;
363 if (sys_stat(fname,sbuf) != 0)
364 return(False);
366 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
369 /*******************************************************************
370 Check a files mod time.
371 ********************************************************************/
373 time_t file_modtime(const char *fname)
375 SMB_STRUCT_STAT st;
377 if (sys_stat(fname,&st) != 0)
378 return(0);
380 return(st.st_mtime);
383 /*******************************************************************
384 Check if a directory exists.
385 ********************************************************************/
387 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
389 SMB_STRUCT_STAT st2;
390 BOOL ret;
392 if (!st)
393 st = &st2;
395 if (sys_stat(dname,st) != 0)
396 return(False);
398 ret = S_ISDIR(st->st_mode);
399 if(!ret)
400 errno = ENOTDIR;
401 return ret;
404 /*******************************************************************
405 Returns the size in bytes of the named file.
406 ********************************************************************/
408 SMB_OFF_T get_file_size(char *file_name)
410 SMB_STRUCT_STAT buf;
411 buf.st_size = 0;
412 if(sys_stat(file_name,&buf) != 0)
413 return (SMB_OFF_T)-1;
414 return(buf.st_size);
417 /*******************************************************************
418 Return a string representing an attribute for a file.
419 ********************************************************************/
421 char *attrib_string(uint16 mode)
423 static fstring attrstr;
425 attrstr[0] = 0;
427 if (mode & aVOLID) fstrcat(attrstr,"V");
428 if (mode & aDIR) fstrcat(attrstr,"D");
429 if (mode & aARCH) fstrcat(attrstr,"A");
430 if (mode & aHIDDEN) fstrcat(attrstr,"H");
431 if (mode & aSYSTEM) fstrcat(attrstr,"S");
432 if (mode & aRONLY) fstrcat(attrstr,"R");
434 return(attrstr);
437 /*******************************************************************
438 Show a smb message structure.
439 ********************************************************************/
441 void show_msg(char *buf)
443 int i;
444 int bcc=0;
446 if (!DEBUGLVL(5))
447 return;
449 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
450 smb_len(buf),
451 (int)CVAL(buf,smb_com),
452 (int)CVAL(buf,smb_rcls),
453 (int)CVAL(buf,smb_reh),
454 (int)SVAL(buf,smb_err),
455 (int)CVAL(buf,smb_flg),
456 (int)SVAL(buf,smb_flg2)));
457 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
458 (int)SVAL(buf,smb_tid),
459 (int)SVAL(buf,smb_pid),
460 (int)SVAL(buf,smb_uid),
461 (int)SVAL(buf,smb_mid)));
462 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
464 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
465 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
466 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
468 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
470 DEBUGADD(5,("smb_bcc=%d\n",bcc));
472 if (DEBUGLEVEL < 10)
473 return;
475 if (DEBUGLEVEL < 50)
476 bcc = MIN(bcc, 512);
478 dump_data(10, smb_buf(buf), bcc);
481 /*******************************************************************
482 Set the length and marker of an smb packet.
483 ********************************************************************/
485 void smb_setlen(char *buf,int len)
487 _smb_setlen(buf,len);
489 SCVAL(buf,4,0xFF);
490 SCVAL(buf,5,'S');
491 SCVAL(buf,6,'M');
492 SCVAL(buf,7,'B');
495 /*******************************************************************
496 Setup the word count and byte count for a smb message.
497 ********************************************************************/
499 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
501 if (zero)
502 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
503 SCVAL(buf,smb_wct,num_words);
504 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
505 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
506 return (smb_size + num_words*2 + num_bytes);
509 /*******************************************************************
510 Setup only the byte count for a smb message.
511 ********************************************************************/
513 int set_message_bcc(char *buf,int num_bytes)
515 int num_words = CVAL(buf,smb_wct);
516 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
517 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
518 return (smb_size + num_words*2 + num_bytes);
521 /*******************************************************************
522 Setup only the byte count for a smb message, using the end of the
523 message as a marker.
524 ********************************************************************/
526 int set_message_end(void *outbuf,void *end_ptr)
528 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
531 /*******************************************************************
532 Reduce a file name, removing .. elements.
533 ********************************************************************/
535 void dos_clean_name(char *s)
537 char *p=NULL;
539 DEBUG(3,("dos_clean_name [%s]\n",s));
541 /* remove any double slashes */
542 all_string_sub(s, "\\\\", "\\", 0);
544 while ((p = strstr_m(s,"\\..\\")) != NULL) {
545 pstring s1;
547 *p = 0;
548 pstrcpy(s1,p+3);
550 if ((p=strrchr_m(s,'\\')) != NULL)
551 *p = 0;
552 else
553 *s = 0;
554 pstrcat(s,s1);
557 trim_string(s,NULL,"\\..");
559 all_string_sub(s, "\\.\\", "\\", 0);
562 /*******************************************************************
563 Reduce a file name, removing .. elements.
564 ********************************************************************/
566 void unix_clean_name(char *s)
568 char *p=NULL;
570 DEBUG(3,("unix_clean_name [%s]\n",s));
572 /* remove any double slashes */
573 all_string_sub(s, "//","/", 0);
575 /* Remove leading ./ characters */
576 if(strncmp(s, "./", 2) == 0) {
577 trim_string(s, "./", NULL);
578 if(*s == 0)
579 pstrcpy(s,"./");
582 while ((p = strstr_m(s,"/../")) != NULL) {
583 pstring s1;
585 *p = 0;
586 pstrcpy(s1,p+3);
588 if ((p=strrchr_m(s,'/')) != NULL)
589 *p = 0;
590 else
591 *s = 0;
592 pstrcat(s,s1);
595 trim_string(s,NULL,"/..");
598 /****************************************************************************
599 Make a dir struct.
600 ****************************************************************************/
602 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date)
604 char *p;
605 pstring mask2;
607 pstrcpy(mask2,mask);
609 if ((mode & aDIR) != 0)
610 size = 0;
612 memset(buf+1,' ',11);
613 if ((p = strchr_m(mask2,'.')) != NULL) {
614 *p = 0;
615 push_ascii(buf+1,mask2,8, 0);
616 push_ascii(buf+9,p+1,3, 0);
617 *p = '.';
618 } else
619 push_ascii(buf+1,mask2,11, 0);
621 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
622 SCVAL(buf,21,mode);
623 put_dos_date(buf,22,date);
624 SSVAL(buf,26,size & 0xFFFF);
625 SSVAL(buf,28,(size >> 16)&0xFFFF);
626 /* We only uppercase if the protocol is downrev.
627 Strange, but verified on W2K3. Needed for OS/2. JRA. */
628 push_ascii(buf+30,fname,12,Protocol < PROTOCOL_NT1 ? STR_UPPER : 0);
629 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
632 /*******************************************************************
633 Close the low 3 fd's and open dev/null in their place.
634 ********************************************************************/
636 void close_low_fds(BOOL stderr_too)
638 #ifndef VALGRIND
639 int fd;
640 int i;
642 close(0);
643 close(1);
645 if (stderr_too)
646 close(2);
648 /* try and use up these file descriptors, so silly
649 library routines writing to stdout etc won't cause havoc */
650 for (i=0;i<3;i++) {
651 if (i == 2 && !stderr_too)
652 continue;
654 fd = sys_open("/dev/null",O_RDWR,0);
655 if (fd < 0)
656 fd = sys_open("/dev/null",O_WRONLY,0);
657 if (fd < 0) {
658 DEBUG(0,("Can't open /dev/null\n"));
659 return;
661 if (fd != i) {
662 DEBUG(0,("Didn't get file descriptor %d\n",i));
663 return;
666 #endif
669 /****************************************************************************
670 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
671 else
672 if SYSV use O_NDELAY
673 if BSD use FNDELAY
674 ****************************************************************************/
676 int set_blocking(int fd, BOOL set)
678 int val;
679 #ifdef O_NONBLOCK
680 #define FLAG_TO_SET O_NONBLOCK
681 #else
682 #ifdef SYSV
683 #define FLAG_TO_SET O_NDELAY
684 #else /* BSD */
685 #define FLAG_TO_SET FNDELAY
686 #endif
687 #endif
689 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
690 return -1;
691 if(set) /* Turn blocking on - ie. clear nonblock flag */
692 val &= ~FLAG_TO_SET;
693 else
694 val |= FLAG_TO_SET;
695 return sys_fcntl_long( fd, F_SETFL, val);
696 #undef FLAG_TO_SET
699 /****************************************************************************
700 Transfer some data between two fd's.
701 ****************************************************************************/
703 #ifndef TRANSFER_BUF_SIZE
704 #define TRANSFER_BUF_SIZE 65536
705 #endif
707 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
708 ssize_t (*write_fn)(int, const void *, size_t))
710 char *buf;
711 size_t total = 0;
712 ssize_t read_ret;
713 ssize_t write_ret;
714 size_t num_to_read_thistime;
715 size_t num_written = 0;
717 if ((buf = SMB_MALLOC(TRANSFER_BUF_SIZE)) == NULL)
718 return -1;
720 while (total < n) {
721 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
723 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
724 if (read_ret == -1) {
725 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
726 SAFE_FREE(buf);
727 return -1;
729 if (read_ret == 0)
730 break;
732 num_written = 0;
734 while (num_written < read_ret) {
735 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
737 if (write_ret == -1) {
738 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
739 SAFE_FREE(buf);
740 return -1;
742 if (write_ret == 0)
743 return (ssize_t)total;
745 num_written += (size_t)write_ret;
748 total += (size_t)read_ret;
751 SAFE_FREE(buf);
752 return (ssize_t)total;
755 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
757 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
760 /*******************************************************************
761 Sleep for a specified number of milliseconds.
762 ********************************************************************/
764 void smb_msleep(unsigned int t)
766 #if defined(HAVE_NANOSLEEP)
767 struct timespec tval;
768 int ret;
770 tval.tv_sec = t/1000;
771 tval.tv_nsec = 1000000*(t%1000);
773 do {
774 errno = 0;
775 ret = nanosleep(&tval, &tval);
776 } while (ret < 0 && errno == EINTR && (tval.tv_sec > 0 || tval.tv_nsec > 0));
777 #else
778 unsigned int tdiff=0;
779 struct timeval tval,t1,t2;
780 fd_set fds;
782 GetTimeOfDay(&t1);
783 t2 = t1;
785 while (tdiff < t) {
786 tval.tv_sec = (t-tdiff)/1000;
787 tval.tv_usec = 1000*((t-tdiff)%1000);
789 /* Never wait for more than 1 sec. */
790 if (tval.tv_sec > 1) {
791 tval.tv_sec = 1;
792 tval.tv_usec = 0;
795 FD_ZERO(&fds);
796 errno = 0;
797 sys_select_intr(0,&fds,NULL,NULL,&tval);
799 GetTimeOfDay(&t2);
800 if (t2.tv_sec < t1.tv_sec) {
801 /* Someone adjusted time... */
802 t1 = t2;
805 tdiff = TvalDiff(&t1,&t2);
807 #endif
810 /****************************************************************************
811 Become a daemon, discarding the controlling terminal.
812 ****************************************************************************/
814 void become_daemon(BOOL Fork)
816 if (Fork) {
817 if (sys_fork()) {
818 _exit(0);
822 /* detach from the terminal */
823 #ifdef HAVE_SETSID
824 setsid();
825 #elif defined(TIOCNOTTY)
827 int i = sys_open("/dev/tty", O_RDWR, 0);
828 if (i != -1) {
829 ioctl(i, (int) TIOCNOTTY, (char *)0);
830 close(i);
833 #endif /* HAVE_SETSID */
835 /* Close fd's 0,1,2. Needed if started by rsh */
836 close_low_fds(False); /* Don't close stderr, let the debug system
837 attach it to the logfile */
840 /****************************************************************************
841 Put up a yes/no prompt.
842 ****************************************************************************/
844 BOOL yesno(char *p)
846 pstring ans;
847 printf("%s",p);
849 if (!fgets(ans,sizeof(ans)-1,stdin))
850 return(False);
852 if (*ans == 'y' || *ans == 'Y')
853 return(True);
855 return(False);
858 #if defined(PARANOID_MALLOC_CHECKER)
860 /****************************************************************************
861 Internal malloc wrapper. Externally visible.
862 ****************************************************************************/
864 void *malloc_(size_t size)
866 #undef malloc
867 return malloc(size);
868 #define malloc(s) __ERROR_DONT_USE_MALLOC_DIRECTLY
871 /****************************************************************************
872 Internal calloc wrapper. Not externally visible.
873 ****************************************************************************/
875 static void *calloc_(size_t count, size_t size)
877 #undef calloc
878 return calloc(count, size);
879 #define calloc(n,s) __ERROR_DONT_USE_CALLOC_DIRECTLY
882 /****************************************************************************
883 Internal realloc wrapper. Not externally visible.
884 ****************************************************************************/
886 static void *realloc_(void *ptr, size_t size)
888 #undef realloc
889 return realloc(ptr, size);
890 #define realloc(p,s) __ERROR_DONT_USE_RELLOC_DIRECTLY
893 #endif /* PARANOID_MALLOC_CHECKER */
895 /****************************************************************************
896 Type-safe malloc.
897 ****************************************************************************/
899 void *malloc_array(size_t el_size, unsigned int count)
901 if (count >= MAX_ALLOC_SIZE/el_size) {
902 return NULL;
905 #if defined(PARANOID_MALLOC_CHECKER)
906 return malloc_(el_size*count);
907 #else
908 return malloc(el_size*count);
909 #endif
912 /****************************************************************************
913 Type-safe calloc.
914 ****************************************************************************/
916 void *calloc_array(size_t size, size_t nmemb)
918 if (nmemb >= MAX_ALLOC_SIZE/size) {
919 return NULL;
921 #if defined(PARANOID_MALLOC_CHECKER)
922 return calloc_(nmemb, size);
923 #else
924 return calloc(nmemb, size);
925 #endif
928 /****************************************************************************
929 Expand a pointer to be a particular size.
930 ****************************************************************************/
932 void *Realloc(void *p,size_t size)
934 void *ret=NULL;
936 if (size == 0) {
937 SAFE_FREE(p);
938 DEBUG(5,("Realloc asked for 0 bytes\n"));
939 return NULL;
942 #if defined(PARANOID_MALLOC_CHECKER)
943 if (!p)
944 ret = (void *)malloc_(size);
945 else
946 ret = (void *)realloc_(p,size);
947 #else
948 if (!p)
949 ret = (void *)malloc(size);
950 else
951 ret = (void *)realloc(p,size);
952 #endif
954 if (!ret)
955 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
957 return(ret);
960 /****************************************************************************
961 Type-safe realloc.
962 ****************************************************************************/
964 void *realloc_array(void *p,size_t el_size, unsigned int count)
966 if (count >= MAX_ALLOC_SIZE/el_size) {
967 return NULL;
969 return Realloc(p,el_size*count);
972 /****************************************************************************
973 Free memory, checks for NULL.
974 Use directly SAFE_FREE()
975 Exists only because we need to pass a function pointer somewhere --SSS
976 ****************************************************************************/
978 void safe_free(void *p)
980 SAFE_FREE(p);
983 /****************************************************************************
984 Get my own name and IP.
985 ****************************************************************************/
987 BOOL get_myname(char *my_name)
989 pstring hostname;
991 *hostname = 0;
993 /* get my host name */
994 if (gethostname(hostname, sizeof(hostname)) == -1) {
995 DEBUG(0,("gethostname failed\n"));
996 return False;
999 /* Ensure null termination. */
1000 hostname[sizeof(hostname)-1] = '\0';
1002 if (my_name) {
1003 /* split off any parts after an initial . */
1004 char *p = strchr_m(hostname,'.');
1006 if (p)
1007 *p = 0;
1009 fstrcpy(my_name,hostname);
1012 return(True);
1015 /****************************************************************************
1016 Get my own canonical name, including domain.
1017 ****************************************************************************/
1019 BOOL get_mydnsfullname(fstring my_dnsname)
1021 static fstring dnshostname;
1022 struct hostent *hp;
1024 if (!*dnshostname) {
1025 /* get my host name */
1026 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
1027 *dnshostname = '\0';
1028 DEBUG(0,("gethostname failed\n"));
1029 return False;
1032 /* Ensure null termination. */
1033 dnshostname[sizeof(dnshostname)-1] = '\0';
1035 /* Ensure we get the cannonical name. */
1036 if (!(hp = sys_gethostbyname(dnshostname))) {
1037 *dnshostname = '\0';
1038 return False;
1040 fstrcpy(dnshostname, hp->h_name);
1042 fstrcpy(my_dnsname, dnshostname);
1043 return True;
1046 /****************************************************************************
1047 Get my own domain name.
1048 ****************************************************************************/
1050 BOOL get_mydnsdomname(fstring my_domname)
1052 fstring domname;
1053 char *p;
1055 *my_domname = '\0';
1056 if (!get_mydnsfullname(domname)) {
1057 return False;
1059 p = strchr_m(domname, '.');
1060 if (p) {
1061 p++;
1062 fstrcpy(my_domname, p);
1065 return False;
1068 /****************************************************************************
1069 Interpret a protocol description string, with a default.
1070 ****************************************************************************/
1072 int interpret_protocol(const char *str,int def)
1074 if (strequal(str,"NT1"))
1075 return(PROTOCOL_NT1);
1076 if (strequal(str,"LANMAN2"))
1077 return(PROTOCOL_LANMAN2);
1078 if (strequal(str,"LANMAN1"))
1079 return(PROTOCOL_LANMAN1);
1080 if (strequal(str,"CORE"))
1081 return(PROTOCOL_CORE);
1082 if (strequal(str,"COREPLUS"))
1083 return(PROTOCOL_COREPLUS);
1084 if (strequal(str,"CORE+"))
1085 return(PROTOCOL_COREPLUS);
1087 DEBUG(0,("Unrecognised protocol level %s\n",str));
1089 return(def);
1092 /****************************************************************************
1093 Return true if a string could be a pure IP address.
1094 ****************************************************************************/
1096 BOOL is_ipaddress(const char *str)
1098 BOOL pure_address = True;
1099 int i;
1101 for (i=0; pure_address && str[i]; i++)
1102 if (!(isdigit((int)str[i]) || str[i] == '.'))
1103 pure_address = False;
1105 /* Check that a pure number is not misinterpreted as an IP */
1106 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1108 return pure_address;
1111 /****************************************************************************
1112 Interpret an internet address or name into an IP address in 4 byte form.
1113 ****************************************************************************/
1115 uint32 interpret_addr(const char *str)
1117 struct hostent *hp;
1118 uint32 res;
1120 if (strcmp(str,"0.0.0.0") == 0)
1121 return(0);
1122 if (strcmp(str,"255.255.255.255") == 0)
1123 return(0xFFFFFFFF);
1125 /* if it's in the form of an IP address then get the lib to interpret it */
1126 if (is_ipaddress(str)) {
1127 res = inet_addr(str);
1128 } else {
1129 /* otherwise assume it's a network name of some sort and use
1130 sys_gethostbyname */
1131 if ((hp = sys_gethostbyname(str)) == 0) {
1132 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1133 return 0;
1136 if(hp->h_addr == NULL) {
1137 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1138 return 0;
1140 putip((char *)&res,(char *)hp->h_addr);
1143 if (res == (uint32)-1)
1144 return(0);
1146 return(res);
1149 /*******************************************************************
1150 A convenient addition to interpret_addr().
1151 ******************************************************************/
1153 struct in_addr *interpret_addr2(const char *str)
1155 static struct in_addr ret;
1156 uint32 a = interpret_addr(str);
1157 ret.s_addr = a;
1158 return(&ret);
1161 /*******************************************************************
1162 Check if an IP is the 0.0.0.0.
1163 ******************************************************************/
1165 BOOL is_zero_ip(struct in_addr ip)
1167 uint32 a;
1168 putip((char *)&a,(char *)&ip);
1169 return(a == 0);
1172 /*******************************************************************
1173 Set an IP to 0.0.0.0.
1174 ******************************************************************/
1176 void zero_ip(struct in_addr *ip)
1178 static BOOL init;
1179 static struct in_addr ipzero;
1181 if (!init) {
1182 ipzero = *interpret_addr2("0.0.0.0");
1183 init = True;
1186 *ip = ipzero;
1189 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1190 /******************************************************************
1191 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1192 Based on a fix from <Thomas.Hepper@icem.de>.
1193 *******************************************************************/
1195 static void strip_mount_options( pstring *str)
1197 if (**str == '-') {
1198 char *p = *str;
1199 while(*p && !isspace(*p))
1200 p++;
1201 while(*p && isspace(*p))
1202 p++;
1203 if(*p) {
1204 pstring tmp_str;
1206 pstrcpy(tmp_str, p);
1207 pstrcpy(*str, tmp_str);
1212 /*******************************************************************
1213 Patch from jkf@soton.ac.uk
1214 Split Luke's automount_server into YP lookup and string splitter
1215 so can easily implement automount_path().
1216 As we may end up doing both, cache the last YP result.
1217 *******************************************************************/
1219 #ifdef WITH_NISPLUS_HOME
1220 char *automount_lookup( char *user_name)
1222 static fstring last_key = "";
1223 static pstring last_value = "";
1225 char *nis_map = (char *)lp_nis_home_map_name();
1227 char buffer[NIS_MAXATTRVAL + 1];
1228 nis_result *result;
1229 nis_object *object;
1230 entry_obj *entry;
1232 if (strcmp(user_name, last_key)) {
1233 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1234 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1236 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1237 if (result->status != NIS_SUCCESS) {
1238 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1239 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1240 } else {
1241 object = result->objects.objects_val;
1242 if (object->zo_data.zo_type == ENTRY_OBJ) {
1243 entry = &object->zo_data.objdata_u.en_data;
1244 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1245 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1247 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1248 pstring_sub(last_value, "&", user_name);
1249 fstrcpy(last_key, user_name);
1253 nis_freeresult(result);
1256 strip_mount_options(&last_value);
1258 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1259 return last_value;
1261 #else /* WITH_NISPLUS_HOME */
1263 char *automount_lookup( char *user_name)
1265 static fstring last_key = "";
1266 static pstring last_value = "";
1268 int nis_error; /* returned by yp all functions */
1269 char *nis_result; /* yp_match inits this */
1270 int nis_result_len; /* and set this */
1271 char *nis_domain; /* yp_get_default_domain inits this */
1272 char *nis_map = (char *)lp_nis_home_map_name();
1274 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1275 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1276 return last_value;
1279 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1281 if (!strcmp(user_name, last_key)) {
1282 nis_result = last_value;
1283 nis_result_len = strlen(last_value);
1284 nis_error = 0;
1285 } else {
1286 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1287 &nis_result, &nis_result_len)) == 0) {
1288 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1289 nis_result_len = sizeof(pstring)-1;
1291 fstrcpy(last_key, user_name);
1292 strncpy(last_value, nis_result, nis_result_len);
1293 last_value[nis_result_len] = '\0';
1294 strip_mount_options(&last_value);
1296 } else if(nis_error == YPERR_KEY) {
1298 /* If Key lookup fails user home server is not in nis_map
1299 use default information for server, and home directory */
1300 last_value[0] = 0;
1301 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1302 user_name, nis_map));
1303 DEBUG(3, ("using defaults for server and home directory\n"));
1304 } else {
1305 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1306 yperr_string(nis_error), user_name, nis_map));
1310 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1311 return last_value;
1313 #endif /* WITH_NISPLUS_HOME */
1314 #endif
1316 /*******************************************************************
1317 Are two IPs on the same subnet?
1318 ********************************************************************/
1320 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1322 uint32 net1,net2,nmask;
1324 nmask = ntohl(mask.s_addr);
1325 net1 = ntohl(ip1.s_addr);
1326 net2 = ntohl(ip2.s_addr);
1328 return((net1 & nmask) == (net2 & nmask));
1332 /****************************************************************************
1333 Check if a process exists. Does this work on all unixes?
1334 ****************************************************************************/
1336 BOOL process_exists(pid_t pid)
1338 /* Doing kill with a non-positive pid causes messages to be
1339 * sent to places we don't want. */
1340 SMB_ASSERT(pid > 0);
1341 return(kill(pid,0) == 0 || errno != ESRCH);
1344 /*******************************************************************
1345 Convert a uid into a user name.
1346 ********************************************************************/
1348 const char *uidtoname(uid_t uid)
1350 static fstring name;
1351 struct passwd *pass;
1353 pass = getpwuid_alloc(uid);
1354 if (pass) {
1355 fstrcpy(name, pass->pw_name);
1356 passwd_free(&pass);
1357 } else {
1358 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1360 return name;
1364 /*******************************************************************
1365 Convert a gid into a group name.
1366 ********************************************************************/
1368 char *gidtoname(gid_t gid)
1370 static fstring name;
1371 struct group *grp;
1373 grp = getgrgid(gid);
1374 if (grp)
1375 return(grp->gr_name);
1376 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1377 return(name);
1380 /*******************************************************************
1381 Convert a user name into a uid.
1382 ********************************************************************/
1384 uid_t nametouid(const char *name)
1386 struct passwd *pass;
1387 char *p;
1388 uid_t u;
1390 pass = getpwnam_alloc(name);
1391 if (pass) {
1392 u = pass->pw_uid;
1393 passwd_free(&pass);
1394 return u;
1397 u = (uid_t)strtol(name, &p, 0);
1398 if ((p != name) && (*p == '\0'))
1399 return u;
1401 return (uid_t)-1;
1404 /*******************************************************************
1405 Convert a name to a gid_t if possible. Return -1 if not a group.
1406 ********************************************************************/
1408 gid_t nametogid(const char *name)
1410 struct group *grp;
1411 char *p;
1412 gid_t g;
1414 g = (gid_t)strtol(name, &p, 0);
1415 if ((p != name) && (*p == '\0'))
1416 return g;
1418 grp = sys_getgrnam(name);
1419 if (grp)
1420 return(grp->gr_gid);
1421 return (gid_t)-1;
1424 /*******************************************************************
1425 legacy wrapper for smb_panic2()
1426 ********************************************************************/
1427 void smb_panic( const char *why )
1429 smb_panic2( why, True );
1432 /*******************************************************************
1433 Something really nasty happened - panic !
1434 ********************************************************************/
1436 #ifdef HAVE_LIBEXC_H
1437 #include <libexc.h>
1438 #endif
1440 void smb_panic2(const char *why, BOOL decrement_pid_count )
1442 char *cmd;
1443 int result;
1444 #ifdef HAVE_BACKTRACE_SYMBOLS
1445 void *backtrace_stack[BACKTRACE_STACK_SIZE];
1446 size_t backtrace_size;
1447 char **backtrace_strings;
1448 #endif
1450 #ifdef DEVELOPER
1452 extern char *global_clobber_region_function;
1453 extern unsigned int global_clobber_region_line;
1455 if (global_clobber_region_function) {
1456 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1457 global_clobber_region_function,
1458 global_clobber_region_line));
1461 #endif
1463 /* only smbd needs to decrement the smbd counter in connections.tdb */
1464 if ( decrement_pid_count )
1465 decrement_smbd_process_count();
1467 cmd = lp_panic_action();
1468 if (cmd && *cmd) {
1469 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1470 result = system(cmd);
1472 if (result == -1)
1473 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1474 strerror(errno)));
1475 else
1476 DEBUG(0, ("smb_panic(): action returned status %d\n",
1477 WEXITSTATUS(result)));
1479 DEBUG(0,("PANIC: %s\n", why));
1481 #ifdef HAVE_BACKTRACE_SYMBOLS
1482 /* get the backtrace (stack frames) */
1483 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1484 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1486 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
1487 (unsigned long)backtrace_size));
1489 if (backtrace_strings) {
1490 int i;
1492 for (i = 0; i < backtrace_size; i++)
1493 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1495 /* Leak the backtrace_strings, rather than risk what free() might do */
1498 #elif HAVE_LIBEXC
1500 #define NAMESIZE 32 /* Arbitrary */
1502 /* The IRIX libexc library provides an API for unwinding the stack. See
1503 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
1504 * since we are about to abort anyway, it hardly matters.
1506 * Note that if we paniced due to a SIGSEGV or SIGBUS (or similar) this
1507 * will fail with a nasty message upon failing to open the /proc entry.
1510 __uint64_t addrs[BACKTRACE_STACK_SIZE];
1511 char * names[BACKTRACE_STACK_SIZE];
1512 char namebuf[BACKTRACE_STACK_SIZE * NAMESIZE];
1514 int i;
1515 int levels;
1517 ZERO_ARRAY(addrs);
1518 ZERO_ARRAY(names);
1519 ZERO_ARRAY(namebuf);
1521 /* We need to be root so we can open our /proc entry to walk
1522 * our stack. It also helps when we want to dump core.
1524 become_root();
1526 for (i = 0; i < BACKTRACE_STACK_SIZE; i++) {
1527 names[i] = namebuf + (i * NAMESIZE);
1530 levels = trace_back_stack(0, addrs, names,
1531 BACKTRACE_STACK_SIZE, NAMESIZE);
1533 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels));
1534 for (i = 0; i < levels; i++) {
1535 DEBUGADD(0, (" #%d 0x%llx %s\n", i, addrs[i], names[i]));
1538 #undef NAMESIZE
1539 #endif
1541 dbgflush();
1542 #ifdef SIGABRT
1543 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
1544 #endif
1545 abort();
1548 /*******************************************************************
1549 A readdir wrapper which just returns the file name.
1550 ********************************************************************/
1552 const char *readdirname(DIR *p)
1554 SMB_STRUCT_DIRENT *ptr;
1555 char *dname;
1557 if (!p)
1558 return(NULL);
1560 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1561 if (!ptr)
1562 return(NULL);
1564 dname = ptr->d_name;
1566 #ifdef NEXT2
1567 if (telldir(p) < 0)
1568 return(NULL);
1569 #endif
1571 #ifdef HAVE_BROKEN_READDIR
1572 /* using /usr/ucb/cc is BAD */
1573 dname = dname - 2;
1574 #endif
1577 static pstring buf;
1578 int len = NAMLEN(ptr);
1579 memcpy(buf, dname, len);
1580 buf[len] = 0;
1581 dname = buf;
1584 return(dname);
1587 /*******************************************************************
1588 Utility function used to decide if the last component
1589 of a path matches a (possibly wildcarded) entry in a namelist.
1590 ********************************************************************/
1592 BOOL is_in_path(const char *name, name_compare_entry *namelist, BOOL case_sensitive)
1594 pstring last_component;
1595 char *p;
1597 /* if we have no list it's obviously not in the path */
1598 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1599 return False;
1602 DEBUG(8, ("is_in_path: %s\n", name));
1604 /* Get the last component of the unix name. */
1605 p = strrchr_m(name, '/');
1606 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1607 last_component[sizeof(last_component)-1] = '\0';
1609 for(; namelist->name != NULL; namelist++) {
1610 if(namelist->is_wild) {
1611 if (mask_match(last_component, namelist->name, case_sensitive)) {
1612 DEBUG(8,("is_in_path: mask match succeeded\n"));
1613 return True;
1615 } else {
1616 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1617 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1618 DEBUG(8,("is_in_path: match succeeded\n"));
1619 return True;
1623 DEBUG(8,("is_in_path: match not found\n"));
1625 return False;
1628 /*******************************************************************
1629 Strip a '/' separated list into an array of
1630 name_compare_enties structures suitable for
1631 passing to is_in_path(). We do this for
1632 speed so we can pre-parse all the names in the list
1633 and don't do it for each call to is_in_path().
1634 namelist is modified here and is assumed to be
1635 a copy owned by the caller.
1636 We also check if the entry contains a wildcard to
1637 remove a potentially expensive call to mask_match
1638 if possible.
1639 ********************************************************************/
1641 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1643 char *name_end;
1644 char *nameptr = namelist;
1645 int num_entries = 0;
1646 int i;
1648 (*ppname_array) = NULL;
1650 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1651 return;
1653 /* We need to make two passes over the string. The
1654 first to count the number of elements, the second
1655 to split it.
1658 while(*nameptr) {
1659 if ( *nameptr == '/' ) {
1660 /* cope with multiple (useless) /s) */
1661 nameptr++;
1662 continue;
1664 /* find the next / */
1665 name_end = strchr_m(nameptr, '/');
1667 /* oops - the last check for a / didn't find one. */
1668 if (name_end == NULL)
1669 break;
1671 /* next segment please */
1672 nameptr = name_end + 1;
1673 num_entries++;
1676 if(num_entries == 0)
1677 return;
1679 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
1680 DEBUG(0,("set_namearray: malloc fail\n"));
1681 return;
1684 /* Now copy out the names */
1685 nameptr = namelist;
1686 i = 0;
1687 while(*nameptr) {
1688 if ( *nameptr == '/' ) {
1689 /* cope with multiple (useless) /s) */
1690 nameptr++;
1691 continue;
1693 /* find the next / */
1694 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1695 *name_end = 0;
1697 /* oops - the last check for a / didn't find one. */
1698 if(name_end == NULL)
1699 break;
1701 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1702 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1703 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1704 return;
1707 /* next segment please */
1708 nameptr = name_end + 1;
1709 i++;
1712 (*ppname_array)[i].name = NULL;
1714 return;
1717 /****************************************************************************
1718 Routine to free a namearray.
1719 ****************************************************************************/
1721 void free_namearray(name_compare_entry *name_array)
1723 int i;
1725 if(name_array == NULL)
1726 return;
1728 for(i=0; name_array[i].name!=NULL; i++)
1729 SAFE_FREE(name_array[i].name);
1730 SAFE_FREE(name_array);
1733 /****************************************************************************
1734 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1735 is dealt with in posix.c
1736 ****************************************************************************/
1738 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1740 SMB_STRUCT_FLOCK lock;
1741 int ret;
1743 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1745 lock.l_type = type;
1746 lock.l_whence = SEEK_SET;
1747 lock.l_start = offset;
1748 lock.l_len = count;
1749 lock.l_pid = 0;
1751 ret = sys_fcntl_ptr(fd,op,&lock);
1753 if (ret == -1 && errno != 0)
1754 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1756 /* a lock query */
1757 if (op == SMB_F_GETLK) {
1758 if ((ret != -1) &&
1759 (lock.l_type != F_UNLCK) &&
1760 (lock.l_pid != 0) &&
1761 (lock.l_pid != sys_getpid())) {
1762 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1763 return(True);
1766 /* it must be not locked or locked by me */
1767 return(False);
1770 /* a lock set or unset */
1771 if (ret == -1) {
1772 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1773 (double)offset,(double)count,op,type,strerror(errno)));
1774 return(False);
1777 /* everything went OK */
1778 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1780 return(True);
1783 /*******************************************************************
1784 Is the name specified one of my netbios names.
1785 Returns true if it is equal, false otherwise.
1786 ********************************************************************/
1788 BOOL is_myname(const char *s)
1790 int n;
1791 BOOL ret = False;
1793 for (n=0; my_netbios_names(n); n++) {
1794 if (strequal(my_netbios_names(n), s)) {
1795 ret=True;
1796 break;
1799 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1800 return(ret);
1803 BOOL is_myname_or_ipaddr(const char *s)
1805 fstring name, dnsname;
1806 char *servername;
1808 if ( !s )
1809 return False;
1811 /* santize the string from '\\name' */
1813 fstrcpy( name, s );
1815 servername = strrchr_m( name, '\\' );
1816 if ( !servername )
1817 servername = name;
1818 else
1819 servername++;
1821 /* optimize for the common case */
1823 if (strequal(servername, global_myname()))
1824 return True;
1826 /* check for an alias */
1828 if (is_myname(servername))
1829 return True;
1831 /* check for loopback */
1833 if (strequal(servername, "localhost"))
1834 return True;
1836 /* maybe it's my dns name */
1838 if ( get_mydnsfullname( dnsname ) )
1839 if ( strequal( servername, dnsname ) )
1840 return True;
1842 /* handle possible CNAME records */
1844 if ( !is_ipaddress( servername ) ) {
1845 /* use DNS to resolve the name, but only the first address */
1846 struct hostent *hp;
1848 if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
1849 struct in_addr return_ip;
1850 putip( (char*)&return_ip, (char*)hp->h_addr );
1851 fstrcpy( name, inet_ntoa( return_ip ) );
1852 servername = name;
1856 /* maybe its an IP address? */
1857 if (is_ipaddress(servername)) {
1858 struct iface_struct nics[MAX_INTERFACES];
1859 int i, n;
1860 uint32 ip;
1862 ip = interpret_addr(servername);
1863 if ((ip==0) || (ip==0xffffffff))
1864 return False;
1866 n = get_interfaces(nics, MAX_INTERFACES);
1867 for (i=0; i<n; i++) {
1868 if (ip == nics[i].ip.s_addr)
1869 return True;
1873 /* no match */
1874 return False;
1877 /*******************************************************************
1878 Is the name specified our workgroup/domain.
1879 Returns true if it is equal, false otherwise.
1880 ********************************************************************/
1882 BOOL is_myworkgroup(const char *s)
1884 BOOL ret = False;
1886 if (strequal(s, lp_workgroup())) {
1887 ret=True;
1890 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1891 return(ret);
1894 /*******************************************************************
1895 we distinguish between 2K and XP by the "Native Lan Manager" string
1896 WinXP => "Windows 2002 5.1"
1897 Win2k => "Windows 2000 5.0"
1898 NT4 => "Windows NT 4.0"
1899 Win9x => "Windows 4.0"
1900 Windows 2003 doesn't set the native lan manager string but
1901 they do set the domain to "Windows 2003 5.2" (probably a bug).
1902 ********************************************************************/
1904 void ra_lanman_string( const char *native_lanman )
1906 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1907 set_remote_arch( RA_WINXP );
1908 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1909 set_remote_arch( RA_WIN2K3 );
1912 /*******************************************************************
1913 Set the horrid remote_arch string based on an enum.
1914 ********************************************************************/
1916 void set_remote_arch(enum remote_arch_types type)
1918 extern fstring remote_arch;
1919 ra_type = type;
1920 switch( type ) {
1921 case RA_WFWG:
1922 fstrcpy(remote_arch, "WfWg");
1923 break;
1924 case RA_OS2:
1925 fstrcpy(remote_arch, "OS2");
1926 break;
1927 case RA_WIN95:
1928 fstrcpy(remote_arch, "Win95");
1929 break;
1930 case RA_WINNT:
1931 fstrcpy(remote_arch, "WinNT");
1932 break;
1933 case RA_WIN2K:
1934 fstrcpy(remote_arch, "Win2K");
1935 break;
1936 case RA_WINXP:
1937 fstrcpy(remote_arch, "WinXP");
1938 break;
1939 case RA_WIN2K3:
1940 fstrcpy(remote_arch, "Win2K3");
1941 break;
1942 case RA_SAMBA:
1943 fstrcpy(remote_arch,"Samba");
1944 break;
1945 case RA_CIFSFS:
1946 fstrcpy(remote_arch,"CIFSFS");
1947 break;
1948 default:
1949 ra_type = RA_UNKNOWN;
1950 fstrcpy(remote_arch, "UNKNOWN");
1951 break;
1954 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n", remote_arch));
1957 /*******************************************************************
1958 Get the remote_arch type.
1959 ********************************************************************/
1961 enum remote_arch_types get_remote_arch(void)
1963 return ra_type;
1966 void print_asc(int level, const unsigned char *buf,int len)
1968 int i;
1969 for (i=0;i<len;i++)
1970 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1973 void dump_data(int level, const char *buf1,int len)
1975 const unsigned char *buf = (const unsigned char *)buf1;
1976 int i=0;
1977 if (len<=0) return;
1979 if (!DEBUGLVL(level)) return;
1981 DEBUGADD(level,("[%03X] ",i));
1982 for (i=0;i<len;) {
1983 DEBUGADD(level,("%02X ",(int)buf[i]));
1984 i++;
1985 if (i%8 == 0) DEBUGADD(level,(" "));
1986 if (i%16 == 0) {
1987 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1988 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1989 if (i<len) DEBUGADD(level,("[%03X] ",i));
1992 if (i%16) {
1993 int n;
1994 n = 16 - (i%16);
1995 DEBUGADD(level,(" "));
1996 if (n>8) DEBUGADD(level,(" "));
1997 while (n--) DEBUGADD(level,(" "));
1998 n = MIN(8,i%16);
1999 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
2000 n = (i%16) - n;
2001 if (n>0) print_asc(level,&buf[i-n],n);
2002 DEBUGADD(level,("\n"));
2006 void dump_data_pw(const char *msg, const uchar * data, size_t len)
2008 #ifdef DEBUG_PASSWORD
2009 DEBUG(11, ("%s", msg));
2010 if (data != NULL && len > 0)
2012 dump_data(11, data, len);
2014 #endif
2017 char *tab_depth(int depth)
2019 static pstring spaces;
2020 memset(spaces, ' ', depth * 4);
2021 spaces[depth * 4] = 0;
2022 return spaces;
2025 /*****************************************************************************
2026 Provide a checksum on a string
2028 Input: s - the null-terminated character string for which the checksum
2029 will be calculated.
2031 Output: The checksum value calculated for s.
2032 *****************************************************************************/
2034 int str_checksum(const char *s)
2036 int res = 0;
2037 int c;
2038 int i=0;
2040 while(*s) {
2041 c = *s;
2042 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
2043 s++;
2044 i++;
2046 return(res);
2049 /*****************************************************************
2050 Zero a memory area then free it. Used to catch bugs faster.
2051 *****************************************************************/
2053 void zero_free(void *p, size_t size)
2055 memset(p, 0, size);
2056 SAFE_FREE(p);
2059 /*****************************************************************
2060 Set our open file limit to a requested max and return the limit.
2061 *****************************************************************/
2063 int set_maxfiles(int requested_max)
2065 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
2066 struct rlimit rlp;
2067 int saved_current_limit;
2069 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2070 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
2071 strerror(errno) ));
2072 /* just guess... */
2073 return requested_max;
2077 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
2078 * account for the extra fd we need
2079 * as well as the log files and standard
2080 * handles etc. Save the limit we want to set in case
2081 * we are running on an OS that doesn't support this limit (AIX)
2082 * which always returns RLIM_INFINITY for rlp.rlim_max.
2085 /* Try raising the hard (max) limit to the requested amount. */
2087 #if defined(RLIM_INFINITY)
2088 if (rlp.rlim_max != RLIM_INFINITY) {
2089 int orig_max = rlp.rlim_max;
2091 if ( rlp.rlim_max < requested_max )
2092 rlp.rlim_max = requested_max;
2094 /* This failing is not an error - many systems (Linux) don't
2095 support our default request of 10,000 open files. JRA. */
2097 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2098 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
2099 (int)rlp.rlim_max, strerror(errno) ));
2101 /* Set failed - restore original value from get. */
2102 rlp.rlim_max = orig_max;
2105 #endif
2107 /* Now try setting the soft (current) limit. */
2109 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
2111 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2112 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
2113 (int)rlp.rlim_cur, strerror(errno) ));
2114 /* just guess... */
2115 return saved_current_limit;
2118 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2119 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
2120 strerror(errno) ));
2121 /* just guess... */
2122 return saved_current_limit;
2125 #if defined(RLIM_INFINITY)
2126 if(rlp.rlim_cur == RLIM_INFINITY)
2127 return saved_current_limit;
2128 #endif
2130 if((int)rlp.rlim_cur > saved_current_limit)
2131 return saved_current_limit;
2133 return rlp.rlim_cur;
2134 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
2136 * No way to know - just guess...
2138 return requested_max;
2139 #endif
2142 /*****************************************************************
2143 Splits out the start of the key (HKLM or HKU) and the rest of the key.
2144 *****************************************************************/
2146 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
2148 pstring tmp;
2150 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
2151 return False;
2153 (*reg_type) = 0;
2155 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
2157 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2158 (*reg_type) = HKEY_LOCAL_MACHINE;
2159 else if (strequal(tmp, "HKCR") || strequal(tmp, "HKEY_CLASSES_ROOT"))
2160 (*reg_type) = HKEY_CLASSES_ROOT;
2161 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2162 (*reg_type) = HKEY_USERS;
2163 else if (strequal(tmp, "HKPD")||strequal(tmp, "HKEY_PERFORMANCE_DATA"))
2164 (*reg_type) = HKEY_PERFORMANCE_DATA;
2165 else {
2166 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2167 return False;
2170 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2171 fstrcpy(key_name, tmp);
2172 else
2173 key_name[0] = 0;
2175 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2177 return True;
2180 /*****************************************************************
2181 Possibly replace mkstemp if it is broken.
2182 *****************************************************************/
2184 int smb_mkstemp(char *template)
2186 #if HAVE_SECURE_MKSTEMP
2187 return mkstemp(template);
2188 #else
2189 /* have a reasonable go at emulating it. Hope that
2190 the system mktemp() isn't completly hopeless */
2191 char *p = mktemp(template);
2192 if (!p)
2193 return -1;
2194 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2195 #endif
2198 /*****************************************************************
2199 malloc that aborts with smb_panic on fail or zero size.
2200 *****************************************************************/
2202 void *smb_xmalloc_array(size_t size, unsigned int count)
2204 void *p;
2205 if (size == 0)
2206 smb_panic("smb_xmalloc_array: called with zero size.\n");
2207 if (count >= MAX_ALLOC_SIZE/size) {
2208 smb_panic("smb_xmalloc: alloc size too large.\n");
2210 if ((p = SMB_MALLOC(size*count)) == NULL) {
2211 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
2212 (unsigned long)size, (unsigned long)count));
2213 smb_panic("smb_xmalloc_array: malloc fail.\n");
2215 return p;
2219 Memdup with smb_panic on fail.
2222 void *smb_xmemdup(const void *p, size_t size)
2224 void *p2;
2225 p2 = SMB_XMALLOC_ARRAY(unsigned char,size);
2226 memcpy(p2, p, size);
2227 return p2;
2231 strdup that aborts on malloc fail.
2234 char *smb_xstrdup(const char *s)
2236 #if defined(PARANOID_MALLOC_CHECKER)
2237 #ifdef strdup
2238 #undef strdup
2239 #endif
2240 #endif
2241 char *s1 = strdup(s);
2242 #if defined(PARANOID_MALLOC_CHECKER)
2243 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
2244 #endif
2245 if (!s1)
2246 smb_panic("smb_xstrdup: malloc fail\n");
2247 return s1;
2252 strndup that aborts on malloc fail.
2255 char *smb_xstrndup(const char *s, size_t n)
2257 #if defined(PARANOID_MALLOC_CHECKER)
2258 #ifdef strndup
2259 #undef strndup
2260 #endif
2261 #endif
2262 char *s1 = strndup(s, n);
2263 #if defined(PARANOID_MALLOC_CHECKER)
2264 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
2265 #endif
2266 if (!s1)
2267 smb_panic("smb_xstrndup: malloc fail\n");
2268 return s1;
2272 vasprintf that aborts on malloc fail
2275 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2277 int n;
2278 va_list ap2;
2280 VA_COPY(ap2, ap);
2282 n = vasprintf(ptr, format, ap2);
2283 if (n == -1 || ! *ptr)
2284 smb_panic("smb_xvasprintf: out of memory");
2285 return n;
2288 /*****************************************************************
2289 Like strdup but for memory.
2290 *****************************************************************/
2292 void *memdup(const void *p, size_t size)
2294 void *p2;
2295 if (size == 0)
2296 return NULL;
2297 p2 = SMB_MALLOC(size);
2298 if (!p2)
2299 return NULL;
2300 memcpy(p2, p, size);
2301 return p2;
2304 /*****************************************************************
2305 Get local hostname and cache result.
2306 *****************************************************************/
2308 char *myhostname(void)
2310 static pstring ret;
2311 if (ret[0] == 0)
2312 get_myname(ret);
2313 return ret;
2316 /*****************************************************************
2317 A useful function for returning a path in the Samba lock directory.
2318 *****************************************************************/
2320 char *lock_path(const char *name)
2322 static pstring fname;
2324 pstrcpy(fname,lp_lockdir());
2325 trim_char(fname,'\0','/');
2327 if (!directory_exist(fname,NULL))
2328 mkdir(fname,0755);
2330 pstrcat(fname,"/");
2331 pstrcat(fname,name);
2333 return fname;
2336 /*****************************************************************
2337 A useful function for returning a path in the Samba pid directory.
2338 *****************************************************************/
2340 char *pid_path(const char *name)
2342 static pstring fname;
2344 pstrcpy(fname,lp_piddir());
2345 trim_char(fname,'\0','/');
2347 if (!directory_exist(fname,NULL))
2348 mkdir(fname,0755);
2350 pstrcat(fname,"/");
2351 pstrcat(fname,name);
2353 return fname;
2357 * @brief Returns an absolute path to a file in the Samba lib directory.
2359 * @param name File to find, relative to LIBDIR.
2361 * @retval Pointer to a static #pstring containing the full path.
2364 char *lib_path(const char *name)
2366 static pstring fname;
2367 fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2368 return fname;
2372 * @brief Returns the platform specific shared library extension.
2374 * @retval Pointer to a static #fstring containing the extension.
2377 const char *shlib_ext(void)
2379 return dyn_SHLIBEXT;
2382 /*******************************************************************
2383 Given a filename - get its directory name
2384 NB: Returned in static storage. Caveats:
2385 o Not safe in thread environment.
2386 o Caller must not free.
2387 o If caller wishes to preserve, they should copy.
2388 ********************************************************************/
2390 char *parent_dirname(const char *path)
2392 static pstring dirpath;
2393 char *p;
2395 if (!path)
2396 return(NULL);
2398 pstrcpy(dirpath, path);
2399 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2400 if (!p) {
2401 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2402 } else {
2403 if (p == dirpath)
2404 ++p; /* For root "/", leave "/" in place */
2405 *p = '\0';
2407 return dirpath;
2411 /*******************************************************************
2412 Determine if a pattern contains any Microsoft wildcard characters.
2413 *******************************************************************/
2415 BOOL ms_has_wild(const char *s)
2417 char c;
2418 while ((c = *s++)) {
2419 switch (c) {
2420 case '*':
2421 case '?':
2422 case '<':
2423 case '>':
2424 case '"':
2425 return True;
2428 return False;
2431 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2433 smb_ucs2_t c;
2434 if (!s) return False;
2435 while ((c = *s++)) {
2436 switch (c) {
2437 case UCS2_CHAR('*'):
2438 case UCS2_CHAR('?'):
2439 case UCS2_CHAR('<'):
2440 case UCS2_CHAR('>'):
2441 case UCS2_CHAR('"'):
2442 return True;
2445 return False;
2448 /*******************************************************************
2449 A wrapper that handles case sensitivity and the special handling
2450 of the ".." name.
2451 *******************************************************************/
2453 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2455 if (strcmp(string,"..") == 0)
2456 string = ".";
2457 if (strcmp(pattern,".") == 0)
2458 return False;
2460 return ms_fnmatch(pattern, string, Protocol <= PROTOCOL_LANMAN2, is_case_sensitive) == 0;
2463 /*******************************************************************
2464 A wrapper that handles case sensitivity and the special handling
2465 of the ".." name. Varient that is only called by old search code which requires
2466 pattern translation.
2467 *******************************************************************/
2469 BOOL mask_match_search(const char *string, char *pattern, BOOL is_case_sensitive)
2471 if (strcmp(string,"..") == 0)
2472 string = ".";
2473 if (strcmp(pattern,".") == 0)
2474 return False;
2476 return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
2479 /*******************************************************************
2480 A wrapper that handles a list of patters and calls mask_match()
2481 on each. Returns True if any of the patterns match.
2482 *******************************************************************/
2484 BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_sensitive)
2486 while (listLen-- > 0) {
2487 if (mask_match(string, *list++, is_case_sensitive))
2488 return True;
2490 return False;
2493 /*********************************************************
2494 Recursive routine that is called by unix_wild_match.
2495 *********************************************************/
2497 static BOOL unix_do_match(const char *regexp, const char *str)
2499 const char *p;
2501 for( p = regexp; *p && *str; ) {
2503 switch(*p) {
2504 case '?':
2505 str++;
2506 p++;
2507 break;
2509 case '*':
2512 * Look for a character matching
2513 * the one after the '*'.
2515 p++;
2516 if(!*p)
2517 return True; /* Automatic match */
2518 while(*str) {
2520 while(*str && (*p != *str))
2521 str++;
2524 * Patch from weidel@multichart.de. In the case of the regexp
2525 * '*XX*' we want to ensure there are at least 2 'X' characters
2526 * in the string after the '*' for a match to be made.
2530 int matchcount=0;
2533 * Eat all the characters that match, but count how many there were.
2536 while(*str && (*p == *str)) {
2537 str++;
2538 matchcount++;
2542 * Now check that if the regexp had n identical characters that
2543 * matchcount had at least that many matches.
2546 while ( *(p+1) && (*(p+1) == *p)) {
2547 p++;
2548 matchcount--;
2551 if ( matchcount <= 0 )
2552 return False;
2555 str--; /* We've eaten the match char after the '*' */
2557 if(unix_do_match(p, str))
2558 return True;
2560 if(!*str)
2561 return False;
2562 else
2563 str++;
2565 return False;
2567 default:
2568 if(*str != *p)
2569 return False;
2570 str++;
2571 p++;
2572 break;
2576 if(!*p && !*str)
2577 return True;
2579 if (!*p && str[0] == '.' && str[1] == 0)
2580 return(True);
2582 if (!*str && *p == '?') {
2583 while (*p == '?')
2584 p++;
2585 return(!*p);
2588 if(!*str && (*p == '*' && p[1] == '\0'))
2589 return True;
2591 return False;
2594 /*******************************************************************
2595 Simple case insensitive interface to a UNIX wildcard matcher.
2596 *******************************************************************/
2598 BOOL unix_wild_match(const char *pattern, const char *string)
2600 pstring p2, s2;
2601 char *p;
2603 pstrcpy(p2, pattern);
2604 pstrcpy(s2, string);
2605 strlower_m(p2);
2606 strlower_m(s2);
2608 /* Remove any *? and ** from the pattern as they are meaningless */
2609 for(p = p2; *p; p++)
2610 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2611 pstrcpy( &p[1], &p[2]);
2613 if (strequal(p2,"*"))
2614 return True;
2616 return unix_do_match(p2, s2) == 0;
2619 /**********************************************************************
2620 Converts a name to a fully qalified domain name.
2621 ***********************************************************************/
2623 void name_to_fqdn(fstring fqdn, const char *name)
2625 struct hostent *hp = sys_gethostbyname(name);
2626 if ( hp && hp->h_name && *hp->h_name ) {
2627 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
2628 fstrcpy(fqdn,hp->h_name);
2629 } else {
2630 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
2631 fstrcpy(fqdn, name);
2635 #ifdef __INSURE__
2637 /*******************************************************************
2638 This routine is a trick to immediately catch errors when debugging
2639 with insure. A xterm with a gdb is popped up when insure catches
2640 a error. It is Linux specific.
2641 ********************************************************************/
2643 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2645 static int (*fn)();
2646 int ret;
2647 char pidstr[10];
2648 /* you can get /usr/bin/backtrace from
2649 http://samba.org/ftp/unpacked/junkcode/backtrace */
2650 pstring cmd = "/usr/bin/backtrace %d";
2652 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2653 pstring_sub(cmd, "%d", pidstr);
2655 if (!fn) {
2656 static void *h;
2657 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2658 fn = dlsym(h, "_Insure_trap_error");
2660 if (!h || h == _Insure_trap_error) {
2661 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2662 fn = dlsym(h, "_Insure_trap_error");
2666 ret = fn(a1, a2, a3, a4, a5, a6);
2668 system(cmd);
2670 return ret;
2672 #endif