r1427: getting nmbd to build; still missing NetServerEnum() client call; i know this...
[Samba.git] / SAMBA_3_2_MERGE / source / lib / util.c
blob95edf5482b73f8d3d714a39365b593b5f50141ef
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 #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 #else /* !WITH_NISPLUS_HOME */
51 #include "rpcsvc/ypclnt.h"
53 #endif /* WITH_NISPLUS_HOME */
54 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
56 int Protocol = PROTOCOL_COREPLUS;
58 /* a default finfo structure to ensure all fields are sensible */
59 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
61 /* this is used by the chaining code */
62 int chain_size = 0;
64 int trans_num = 0;
66 static enum remote_arch_types ra_type = RA_UNKNOWN;
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 = 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 = 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 = 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 = (char **)malloc( sizeof(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] = 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 Determine whether we are in the specified group.
278 ****************************************************************************/
280 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
282 int i;
284 if (group == current_gid)
285 return(True);
287 for (i=0;i<ngroups;i++)
288 if (group == groups[i])
289 return(True);
291 return(False);
294 /****************************************************************************
295 Like atoi but gets the value up to the separator character.
296 ****************************************************************************/
298 static const char *Atoic(const char *p, int *n, const char *c)
300 if (!isdigit((int)*p)) {
301 DEBUG(5, ("Atoic: malformed number\n"));
302 return NULL;
305 (*n) = atoi(p);
307 while ((*p) && isdigit((int)*p))
308 p++;
310 if (strchr_m(c, *p) == NULL) {
311 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
312 return NULL;
315 return p;
318 /*************************************************************************
319 Reads a list of numbers.
320 *************************************************************************/
322 const char *get_numlist(const char *p, uint32 **num, int *count)
324 int val;
326 if (num == NULL || count == NULL)
327 return NULL;
329 (*count) = 0;
330 (*num ) = NULL;
332 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
333 uint32 *tn;
335 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
336 if (tn == NULL) {
337 SAFE_FREE(*num);
338 return NULL;
339 } else
340 (*num) = tn;
341 (*num)[(*count)] = val;
342 (*count)++;
343 p++;
346 return p;
349 /*******************************************************************
350 Check if a file exists - call vfs_file_exist for samba files.
351 ********************************************************************/
353 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
355 SMB_STRUCT_STAT st;
356 if (!sbuf)
357 sbuf = &st;
359 if (sys_stat(fname,sbuf) != 0)
360 return(False);
362 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
365 /*******************************************************************
366 Check a files mod time.
367 ********************************************************************/
369 time_t file_modtime(const char *fname)
371 SMB_STRUCT_STAT st;
373 if (sys_stat(fname,&st) != 0)
374 return(0);
376 return(st.st_mtime);
379 /*******************************************************************
380 Check if a directory exists.
381 ********************************************************************/
383 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
385 SMB_STRUCT_STAT st2;
386 BOOL ret;
388 if (!st)
389 st = &st2;
391 if (sys_stat(dname,st) != 0)
392 return(False);
394 ret = S_ISDIR(st->st_mode);
395 if(!ret)
396 errno = ENOTDIR;
397 return ret;
400 /*******************************************************************
401 Returns the size in bytes of the named file.
402 ********************************************************************/
404 SMB_OFF_T get_file_size(char *file_name)
406 SMB_STRUCT_STAT buf;
407 buf.st_size = 0;
408 if(sys_stat(file_name,&buf) != 0)
409 return (SMB_OFF_T)-1;
410 return(buf.st_size);
413 /*******************************************************************
414 Show a smb message structure.
415 ********************************************************************/
417 void show_msg(char *buf)
419 int i;
420 int bcc=0;
422 if (!DEBUGLVL(5))
423 return;
425 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
426 smb_len(buf),
427 (int)CVAL(buf,smb_com),
428 (int)CVAL(buf,smb_rcls),
429 (int)CVAL(buf,smb_reh),
430 (int)SVAL(buf,smb_err),
431 (int)CVAL(buf,smb_flg),
432 (int)SVAL(buf,smb_flg2)));
433 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
434 (int)SVAL(buf,smb_tid),
435 (int)SVAL(buf,smb_pid),
436 (int)SVAL(buf,smb_uid),
437 (int)SVAL(buf,smb_mid)));
438 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
440 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
441 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
442 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
444 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
446 DEBUGADD(5,("smb_bcc=%d\n",bcc));
448 if (DEBUGLEVEL < 10)
449 return;
451 if (DEBUGLEVEL < 50)
452 bcc = MIN(bcc, 512);
454 dump_data(10, smb_buf(buf), bcc);
457 /*******************************************************************
458 Set the length and marker of an smb packet.
459 ********************************************************************/
461 void smb_setlen(char *buf,int len)
463 _smb_setlen(buf,len);
465 SCVAL(buf,4,0xFF);
466 SCVAL(buf,5,'S');
467 SCVAL(buf,6,'M');
468 SCVAL(buf,7,'B');
471 /*******************************************************************
472 Setup the word count and byte count for a smb message.
473 ********************************************************************/
475 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
477 if (zero)
478 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
479 SCVAL(buf,smb_wct,num_words);
480 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
481 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
482 return (smb_size + num_words*2 + num_bytes);
485 /*******************************************************************
486 Setup only the byte count for a smb message.
487 ********************************************************************/
489 int set_message_bcc(char *buf,int num_bytes)
491 int num_words = CVAL(buf,smb_wct);
492 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
493 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
494 return (smb_size + num_words*2 + num_bytes);
497 /*******************************************************************
498 Setup only the byte count for a smb message, using the end of the
499 message as a marker.
500 ********************************************************************/
502 int set_message_end(void *outbuf,void *end_ptr)
504 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
507 /*******************************************************************
508 Reduce a file name, removing .. elements.
509 ********************************************************************/
511 void unix_clean_name(char *s)
513 char *p=NULL;
515 DEBUG(3,("unix_clean_name [%s]\n",s));
517 /* remove any double slashes */
518 all_string_sub(s, "//","/", 0);
520 /* Remove leading ./ characters */
521 if(strncmp(s, "./", 2) == 0) {
522 trim_string(s, "./", NULL);
523 if(*s == 0)
524 pstrcpy(s,"./");
527 while ((p = strstr_m(s,"/../")) != NULL) {
528 pstring s1;
530 *p = 0;
531 pstrcpy(s1,p+3);
533 if ((p=strrchr_m(s,'/')) != NULL)
534 *p = 0;
535 else
536 *s = 0;
537 pstrcat(s,s1);
540 trim_string(s,NULL,"/..");
543 /****************************************************************************
544 Make a dir struct.
545 ****************************************************************************/
547 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date, BOOL case_sensitive)
549 char *p;
550 pstring mask2;
552 pstrcpy(mask2,mask);
554 if ((mode & aDIR) != 0)
555 size = 0;
557 memset(buf+1,' ',11);
558 if ((p = strchr_m(mask2,'.')) != NULL) {
559 *p = 0;
560 push_ascii(buf+1,mask2,8, 0);
561 push_ascii(buf+9,p+1,3, 0);
562 *p = '.';
563 } else
564 push_ascii(buf+1,mask2,11, 0);
566 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
567 SCVAL(buf,21,mode);
568 put_dos_date(buf,22,date);
569 SSVAL(buf,26,size & 0xFFFF);
570 SSVAL(buf,28,(size >> 16)&0xFFFF);
571 push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
572 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
575 /*******************************************************************
576 Close the low 3 fd's and open dev/null in their place.
577 ********************************************************************/
579 void close_low_fds(BOOL stderr_too)
581 #ifndef VALGRIND
582 int fd;
583 int i;
585 close(0);
586 close(1);
588 if (stderr_too)
589 close(2);
591 /* try and use up these file descriptors, so silly
592 library routines writing to stdout etc won't cause havoc */
593 for (i=0;i<3;i++) {
594 if (i == 2 && !stderr_too)
595 continue;
597 fd = sys_open("/dev/null",O_RDWR,0);
598 if (fd < 0)
599 fd = sys_open("/dev/null",O_WRONLY,0);
600 if (fd < 0) {
601 DEBUG(0,("Can't open /dev/null\n"));
602 return;
604 if (fd != i) {
605 DEBUG(0,("Didn't get file descriptor %d\n",i));
606 return;
609 #endif
612 /****************************************************************************
613 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
614 else
615 if SYSV use O_NDELAY
616 if BSD use FNDELAY
617 ****************************************************************************/
619 int set_blocking(int fd, BOOL set)
621 int val;
622 #ifdef O_NONBLOCK
623 #define FLAG_TO_SET O_NONBLOCK
624 #else
625 #ifdef SYSV
626 #define FLAG_TO_SET O_NDELAY
627 #else /* BSD */
628 #define FLAG_TO_SET FNDELAY
629 #endif
630 #endif
632 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
633 return -1;
634 if(set) /* Turn blocking on - ie. clear nonblock flag */
635 val &= ~FLAG_TO_SET;
636 else
637 val |= FLAG_TO_SET;
638 return sys_fcntl_long( fd, F_SETFL, val);
639 #undef FLAG_TO_SET
642 /****************************************************************************
643 Transfer some data between two fd's.
644 ****************************************************************************/
646 #ifndef TRANSFER_BUF_SIZE
647 #define TRANSFER_BUF_SIZE 65536
648 #endif
650 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
651 ssize_t (*write_fn)(int, const void *, size_t))
653 char *buf;
654 size_t total = 0;
655 ssize_t read_ret;
656 ssize_t write_ret;
657 size_t num_to_read_thistime;
658 size_t num_written = 0;
660 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
661 return -1;
663 while (total < n) {
664 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
666 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
667 if (read_ret == -1) {
668 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
669 SAFE_FREE(buf);
670 return -1;
672 if (read_ret == 0)
673 break;
675 num_written = 0;
677 while (num_written < read_ret) {
678 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
680 if (write_ret == -1) {
681 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
682 SAFE_FREE(buf);
683 return -1;
685 if (write_ret == 0)
686 return (ssize_t)total;
688 num_written += (size_t)write_ret;
691 total += (size_t)read_ret;
694 SAFE_FREE(buf);
695 return (ssize_t)total;
698 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
700 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
703 /*******************************************************************
704 Sleep for a specified number of milliseconds.
705 ********************************************************************/
707 void smb_msleep(unsigned int t)
709 unsigned int tdiff=0;
710 struct timeval tval,t1,t2;
711 fd_set fds;
713 GetTimeOfDay(&t1);
714 GetTimeOfDay(&t2);
716 while (tdiff < t) {
717 tval.tv_sec = (t-tdiff)/1000;
718 tval.tv_usec = 1000*((t-tdiff)%1000);
720 /* Never wait for more than 1 sec. */
721 if (tval.tv_sec > 1) {
722 tval.tv_sec = 1;
723 tval.tv_usec = 0;
726 FD_ZERO(&fds);
727 errno = 0;
728 sys_select_intr(0,&fds,NULL,NULL,&tval);
730 GetTimeOfDay(&t2);
731 if (t2.tv_sec < t1.tv_sec) {
732 /* Someone adjusted time... */
733 t1 = t2;
736 tdiff = TvalDiff(&t1,&t2);
740 /****************************************************************************
741 Become a daemon, discarding the controlling terminal.
742 ****************************************************************************/
744 void become_daemon(BOOL Fork)
746 if (Fork) {
747 if (sys_fork()) {
748 _exit(0);
752 /* detach from the terminal */
753 #ifdef HAVE_SETSID
754 setsid();
755 #elif defined(TIOCNOTTY)
757 int i = sys_open("/dev/tty", O_RDWR, 0);
758 if (i != -1) {
759 ioctl(i, (int) TIOCNOTTY, (char *)0);
760 close(i);
763 #endif /* HAVE_SETSID */
765 /* Close fd's 0,1,2. Needed if started by rsh */
766 close_low_fds(False); /* Don't close stderr, let the debug system
767 attach it to the logfile */
771 /****************************************************************************
772 Expand a pointer to be a particular size.
773 ****************************************************************************/
775 void *Realloc(void *p,size_t size)
777 void *ret=NULL;
779 if (size == 0) {
780 SAFE_FREE(p);
781 DEBUG(5,("Realloc asked for 0 bytes\n"));
782 return NULL;
785 if (!p)
786 ret = (void *)malloc(size);
787 else
788 ret = (void *)realloc(p,size);
790 if (!ret)
791 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
793 return(ret);
796 void *Realloc_zero(void *ptr, size_t size)
798 void *tptr = NULL;
800 tptr = Realloc(ptr, size);
801 if(tptr == NULL)
802 return NULL;
804 memset((char *)tptr,'\0',size);
806 return tptr;
809 /****************************************************************************
810 Free memory, checks for NULL.
811 Use directly SAFE_FREE()
812 Exists only because we need to pass a function pointer somewhere --SSS
813 ****************************************************************************/
815 void safe_free(void *p)
817 SAFE_FREE(p);
820 /****************************************************************************
821 Get my own name and IP.
822 ****************************************************************************/
824 BOOL get_myname(char *my_name)
826 pstring hostname;
828 *hostname = 0;
830 /* get my host name */
831 if (gethostname(hostname, sizeof(hostname)) == -1) {
832 DEBUG(0,("gethostname failed\n"));
833 return False;
836 /* Ensure null termination. */
837 hostname[sizeof(hostname)-1] = '\0';
839 if (my_name) {
840 /* split off any parts after an initial . */
841 char *p = strchr_m(hostname,'.');
843 if (p)
844 *p = 0;
846 fstrcpy(my_name,hostname);
849 return(True);
853 /****************************************************************************
854 Get my own name, including domain.
855 ****************************************************************************/
857 BOOL get_myfullname(char *my_name)
859 pstring hostname;
861 *hostname = 0;
863 /* get my host name */
864 if (gethostname(hostname, sizeof(hostname)) == -1) {
865 DEBUG(0,("gethostname failed\n"));
866 return False;
869 /* Ensure null termination. */
870 hostname[sizeof(hostname)-1] = '\0';
872 if (my_name)
873 fstrcpy(my_name, hostname);
874 return True;
877 /****************************************************************************
878 Get my own domain name.
879 ****************************************************************************/
881 BOOL get_mydomname(fstring my_domname)
883 pstring hostname;
884 char *p;
886 *hostname = 0;
887 /* get my host name */
888 if (gethostname(hostname, sizeof(hostname)) == -1) {
889 DEBUG(0,("gethostname failed\n"));
890 return False;
893 /* Ensure null termination. */
894 hostname[sizeof(hostname)-1] = '\0';
896 p = strchr_m(hostname, '.');
898 if (!p)
899 return False;
901 p++;
903 if (my_domname)
904 fstrcpy(my_domname, p);
906 return True;
909 /****************************************************************************
910 Get my own canonical name, including domain.
911 ****************************************************************************/
913 BOOL get_mydnsfullname(fstring my_dnsname)
915 static fstring dnshostname;
916 struct hostent *hp;
918 if (!*dnshostname) {
919 /* get my host name */
920 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
921 *dnshostname = '\0';
922 DEBUG(0,("gethostname failed\n"));
923 return False;
926 /* Ensure null termination. */
927 dnshostname[sizeof(dnshostname)-1] = '\0';
929 /* Ensure we get the cannonical name. */
930 if (!(hp = sys_gethostbyname(dnshostname))) {
931 *dnshostname = '\0';
932 return False;
934 fstrcpy(dnshostname, hp->h_name);
936 fstrcpy(my_dnsname, dnshostname);
937 return True;
940 /****************************************************************************
941 Get my own domain name.
942 ****************************************************************************/
944 BOOL get_mydnsdomname(fstring my_domname)
946 fstring domname;
947 char *p;
949 *my_domname = '\0';
950 if (!get_mydnsfullname(domname)) {
951 return False;
953 p = strchr_m(domname, '.');
954 if (p) {
955 p++;
956 fstrcpy(my_domname, p);
959 return False;
962 /****************************************************************************
963 Interpret a protocol description string, with a default.
964 ****************************************************************************/
966 int interpret_protocol(const char *str,int def)
968 if (strequal(str,"NT1"))
969 return(PROTOCOL_NT1);
970 if (strequal(str,"LANMAN2"))
971 return(PROTOCOL_LANMAN2);
972 if (strequal(str,"LANMAN1"))
973 return(PROTOCOL_LANMAN1);
974 if (strequal(str,"CORE"))
975 return(PROTOCOL_CORE);
976 if (strequal(str,"COREPLUS"))
977 return(PROTOCOL_COREPLUS);
978 if (strequal(str,"CORE+"))
979 return(PROTOCOL_COREPLUS);
981 DEBUG(0,("Unrecognised protocol level %s\n",str));
983 return(def);
986 /****************************************************************************
987 Return true if a string could be a pure IP address.
988 ****************************************************************************/
990 BOOL is_ipaddress(const char *str)
992 BOOL pure_address = True;
993 int i;
995 for (i=0; pure_address && str[i]; i++)
996 if (!(isdigit((int)str[i]) || str[i] == '.'))
997 pure_address = False;
999 /* Check that a pure number is not misinterpreted as an IP */
1000 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1002 return pure_address;
1005 /****************************************************************************
1006 Interpret an internet address or name into an IP address in 4 byte form.
1007 ****************************************************************************/
1009 uint32 interpret_addr(const char *str)
1011 struct hostent *hp;
1012 uint32 res;
1014 if (strcmp(str,"0.0.0.0") == 0)
1015 return(0);
1016 if (strcmp(str,"255.255.255.255") == 0)
1017 return(0xFFFFFFFF);
1019 /* if it's in the form of an IP address then get the lib to interpret it */
1020 if (is_ipaddress(str)) {
1021 res = inet_addr(str);
1022 } else {
1023 /* otherwise assume it's a network name of some sort and use
1024 sys_gethostbyname */
1025 if ((hp = sys_gethostbyname(str)) == 0) {
1026 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1027 return 0;
1030 if(hp->h_addr == NULL) {
1031 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1032 return 0;
1034 putip((char *)&res,(char *)hp->h_addr);
1037 if (res == (uint32)-1)
1038 return(0);
1040 return(res);
1043 /*******************************************************************
1044 A convenient addition to interpret_addr().
1045 ******************************************************************/
1047 struct in_addr *interpret_addr2(TALLOC_CTX *mem_ctx, const char *str)
1049 struct in_addr *ret;
1050 uint32_t a = interpret_addr(str);
1052 ret = talloc(mem_ctx, sizeof(struct in_addr));
1053 if (!ret) return NULL;
1054 ret->s_addr = a;
1055 return(ret);
1058 /*******************************************************************
1059 Check if an IP is the 0.0.0.0.
1060 ******************************************************************/
1062 BOOL is_zero_ip(struct in_addr ip)
1064 uint32 a;
1065 putip((char *)&a,(char *)&ip);
1066 return(a == 0);
1069 /*******************************************************************
1070 Set an IP to 0.0.0.0.
1071 ******************************************************************/
1073 void zero_ip(struct in_addr *ip)
1075 *ip = inet_makeaddr(0,0);
1076 return;
1079 /*******************************************************************
1080 Set an IP to 255.255.255.255
1081 ******************************************************************/
1083 void one_ip(struct in_addr *ip)
1085 *ip = inet_makeaddr(0xffffffff,0xffffffff);
1086 return;
1089 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1090 /******************************************************************
1091 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1092 Based on a fix from <Thomas.Hepper@icem.de>.
1093 *******************************************************************/
1095 static void strip_mount_options( pstring *str)
1097 if (**str == '-') {
1098 char *p = *str;
1099 while(*p && !isspace(*p))
1100 p++;
1101 while(*p && isspace(*p))
1102 p++;
1103 if(*p) {
1104 pstring tmp_str;
1106 pstrcpy(tmp_str, p);
1107 pstrcpy(*str, tmp_str);
1112 /*******************************************************************
1113 Patch from jkf@soton.ac.uk
1114 Split Luke's automount_server into YP lookup and string splitter
1115 so can easily implement automount_path().
1116 As we may end up doing both, cache the last YP result.
1117 *******************************************************************/
1119 #ifdef WITH_NISPLUS_HOME
1120 char *automount_lookup(const char *user_name)
1122 static fstring last_key = "";
1123 static pstring last_value = "";
1125 char *nis_map = (char *)lp_nis_home_map_name();
1127 char buffer[NIS_MAXATTRVAL + 1];
1128 nis_result *result;
1129 nis_object *object;
1130 entry_obj *entry;
1132 if (strcmp(user_name, last_key)) {
1133 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1134 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1136 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1137 if (result->status != NIS_SUCCESS) {
1138 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1139 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1140 } else {
1141 object = result->objects.objects_val;
1142 if (object->zo_data.zo_type == ENTRY_OBJ) {
1143 entry = &object->zo_data.objdata_u.en_data;
1144 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1145 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1147 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1148 pstring_sub(last_value, "&", user_name);
1149 fstrcpy(last_key, user_name);
1153 nis_freeresult(result);
1156 strip_mount_options(&last_value);
1158 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1159 return last_value;
1161 #else /* WITH_NISPLUS_HOME */
1163 char *automount_lookup(const char *user_name)
1165 static fstring last_key = "";
1166 static pstring last_value = "";
1168 int nis_error; /* returned by yp all functions */
1169 char *nis_result; /* yp_match inits this */
1170 int nis_result_len; /* and set this */
1171 char *nis_domain; /* yp_get_default_domain inits this */
1172 char *nis_map = (char *)lp_nis_home_map_name();
1174 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1175 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1176 return last_value;
1179 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1181 if (!strcmp(user_name, last_key)) {
1182 nis_result = last_value;
1183 nis_result_len = strlen(last_value);
1184 nis_error = 0;
1185 } else {
1186 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1187 &nis_result, &nis_result_len)) == 0) {
1188 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1189 nis_result_len = sizeof(pstring)-1;
1191 fstrcpy(last_key, user_name);
1192 strncpy(last_value, nis_result, nis_result_len);
1193 last_value[nis_result_len] = '\0';
1194 strip_mount_options(&last_value);
1196 } else if(nis_error == YPERR_KEY) {
1198 /* If Key lookup fails user home server is not in nis_map
1199 use default information for server, and home directory */
1200 last_value[0] = 0;
1201 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1202 user_name, nis_map));
1203 DEBUG(3, ("using defaults for server and home directory\n"));
1204 } else {
1205 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1206 yperr_string(nis_error), user_name, nis_map));
1210 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1211 return last_value;
1213 #endif /* WITH_NISPLUS_HOME */
1214 #endif
1216 /*******************************************************************
1217 Are two IPs on the same subnet?
1218 ********************************************************************/
1220 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1222 uint32 net1,net2,nmask;
1224 nmask = ntohl(mask.s_addr);
1225 net1 = ntohl(ip1.s_addr);
1226 net2 = ntohl(ip2.s_addr);
1228 return((net1 & nmask) == (net2 & nmask));
1232 /****************************************************************************
1233 Check if a process exists. Does this work on all unixes?
1234 ****************************************************************************/
1236 BOOL process_exists(pid_t pid)
1238 /* Doing kill with a non-positive pid causes messages to be
1239 * sent to places we don't want. */
1240 SMB_ASSERT(pid > 0);
1241 return(kill(pid,0) == 0 || errno != ESRCH);
1244 /*******************************************************************
1245 Convert a uid into a user name.
1246 ********************************************************************/
1248 const char *uidtoname(uid_t uid)
1250 static fstring name;
1251 struct passwd *pass;
1253 pass = getpwuid_alloc(uid);
1254 if (pass) {
1255 fstrcpy(name, pass->pw_name);
1256 passwd_free(&pass);
1257 } else {
1258 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1260 return name;
1264 /*******************************************************************
1265 Convert a gid into a group name.
1266 ********************************************************************/
1268 char *gidtoname(gid_t gid)
1270 static fstring name;
1271 struct group *grp;
1273 grp = getgrgid(gid);
1274 if (grp)
1275 return(grp->gr_name);
1276 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1277 return(name);
1280 /*******************************************************************
1281 Convert a user name into a uid.
1282 ********************************************************************/
1284 uid_t nametouid(const char *name)
1286 struct passwd *pass;
1287 char *p;
1288 uid_t u;
1290 pass = getpwnam_alloc(name);
1291 if (pass) {
1292 u = pass->pw_uid;
1293 passwd_free(&pass);
1294 return u;
1297 u = (uid_t)strtol(name, &p, 0);
1298 if ((p != name) && (*p == '\0'))
1299 return u;
1301 return (uid_t)-1;
1304 /*******************************************************************
1305 Convert a name to a gid_t if possible. Return -1 if not a group.
1306 ********************************************************************/
1308 gid_t nametogid(const char *name)
1310 struct group *grp;
1311 char *p;
1312 gid_t g;
1314 g = (gid_t)strtol(name, &p, 0);
1315 if ((p != name) && (*p == '\0'))
1316 return g;
1318 grp = sys_getgrnam(name);
1319 if (grp)
1320 return(grp->gr_gid);
1321 return (gid_t)-1;
1324 /*******************************************************************
1325 legacy wrapper for smb_panic2()
1326 ********************************************************************/
1327 void smb_panic( const char *why )
1329 smb_panic2( why, True );
1332 /*******************************************************************
1333 Something really nasty happened - panic !
1334 ********************************************************************/
1336 #ifdef HAVE_LIBEXC_H
1337 #include <libexc.h>
1338 #endif
1340 void smb_panic2(const char *why, BOOL decrement_pid_count )
1342 char *cmd;
1343 int result;
1344 #ifdef HAVE_BACKTRACE_SYMBOLS
1345 void *backtrace_stack[BACKTRACE_STACK_SIZE];
1346 size_t backtrace_size;
1347 char **backtrace_strings;
1348 #endif
1350 #ifdef DEVELOPER
1352 extern char *global_clobber_region_function;
1353 extern unsigned int global_clobber_region_line;
1355 if (global_clobber_region_function) {
1356 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1357 global_clobber_region_function,
1358 global_clobber_region_line));
1361 #endif
1363 /* only smbd needs to decrement the smbd counter in connections.tdb */
1364 if ( decrement_pid_count )
1365 decrement_smbd_process_count();
1367 cmd = lp_panic_action();
1368 if (cmd && *cmd) {
1369 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1370 result = system(cmd);
1372 if (result == -1)
1373 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1374 strerror(errno)));
1375 else
1376 DEBUG(0, ("smb_panic(): action returned status %d\n",
1377 WEXITSTATUS(result)));
1379 DEBUG(0,("PANIC: %s\n", why));
1381 #ifdef HAVE_BACKTRACE_SYMBOLS
1382 /* get the backtrace (stack frames) */
1383 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1384 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1386 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
1387 (unsigned long)backtrace_size));
1389 if (backtrace_strings) {
1390 int i;
1392 for (i = 0; i < backtrace_size; i++)
1393 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1395 /* Leak the backtrace_strings, rather than risk what free() might do */
1398 #elif HAVE_LIBEXC
1400 #define NAMESIZE 32 /* Arbitrary */
1402 /* The IRIX libexc library provides an API for unwinding the stack. See
1403 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
1404 * since we are about to abort anyway, it hardly matters.
1406 * Note that if we paniced due to a SIGSEGV or SIGBUS (or similar) this
1407 * will fail with a nasty message upon failing to open the /proc entry.
1410 __uint64_t addrs[BACKTRACE_STACK_SIZE];
1411 char * names[BACKTRACE_STACK_SIZE];
1412 char namebuf[BACKTRACE_STACK_SIZE * NAMESIZE];
1414 int i;
1415 int levels;
1417 ZERO_ARRAY(addrs);
1418 ZERO_ARRAY(names);
1419 ZERO_ARRAY(namebuf);
1421 for (i = 0; i < BACKTRACE_STACK_SIZE; i++) {
1422 names[i] = namebuf + (i * NAMESIZE);
1425 levels = trace_back_stack(0, addrs, names,
1426 BACKTRACE_STACK_SIZE, NAMESIZE);
1428 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels));
1429 for (i = 0; i < levels; i++) {
1430 DEBUGADD(0, (" #%d 0x%llx %s\n", i, addrs[i], names[i]));
1433 #undef NAMESIZE
1434 #endif
1436 #ifdef SIGABRT
1437 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
1438 #endif
1439 abort();
1443 /*******************************************************************
1444 Utility function used to decide if the last component
1445 of a path matches a (possibly wildcarded) entry in a namelist.
1446 ********************************************************************/
1448 BOOL is_in_path(const char *name, name_compare_entry *namelist, BOOL case_sensitive)
1450 pstring last_component;
1451 char *p;
1453 DEBUG(8, ("is_in_path: %s\n", name));
1455 /* if we have no list it's obviously not in the path */
1456 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1457 DEBUG(8,("is_in_path: no name list.\n"));
1458 return False;
1461 /* Get the last component of the unix name. */
1462 p = strrchr_m(name, '/');
1463 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1464 last_component[sizeof(last_component)-1] = '\0';
1466 for(; namelist->name != NULL; namelist++) {
1467 if(namelist->is_wild) {
1468 if (mask_match_x(last_component, namelist->name, case_sensitive)) {
1469 DEBUG(8,("is_in_path: mask match succeeded\n"));
1470 return True;
1472 } else {
1473 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1474 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1475 DEBUG(8,("is_in_path: match succeeded\n"));
1476 return True;
1480 DEBUG(8,("is_in_path: match not found\n"));
1482 return False;
1485 /*******************************************************************
1486 Strip a '/' separated list into an array of
1487 name_compare_enties structures suitable for
1488 passing to is_in_path(). We do this for
1489 speed so we can pre-parse all the names in the list
1490 and don't do it for each call to is_in_path().
1491 namelist is modified here and is assumed to be
1492 a copy owned by the caller.
1493 We also check if the entry contains a wildcard to
1494 remove a potentially expensive call to mask_match
1495 if possible.
1496 ********************************************************************/
1498 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1500 char *name_end;
1501 char *nameptr = namelist;
1502 int num_entries = 0;
1503 int i;
1505 (*ppname_array) = NULL;
1507 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1508 return;
1510 /* We need to make two passes over the string. The
1511 first to count the number of elements, the second
1512 to split it.
1515 while(*nameptr) {
1516 if ( *nameptr == '/' ) {
1517 /* cope with multiple (useless) /s) */
1518 nameptr++;
1519 continue;
1521 /* find the next / */
1522 name_end = strchr_m(nameptr, '/');
1524 /* oops - the last check for a / didn't find one. */
1525 if (name_end == NULL)
1526 break;
1528 /* next segment please */
1529 nameptr = name_end + 1;
1530 num_entries++;
1533 if(num_entries == 0)
1534 return;
1536 if(( (*ppname_array) = (name_compare_entry *)malloc(
1537 (num_entries + 1) * sizeof(name_compare_entry))) == NULL) {
1538 DEBUG(0,("set_namearray: malloc fail\n"));
1539 return;
1542 /* Now copy out the names */
1543 nameptr = namelist;
1544 i = 0;
1545 while(*nameptr) {
1546 if ( *nameptr == '/' ) {
1547 /* cope with multiple (useless) /s) */
1548 nameptr++;
1549 continue;
1551 /* find the next / */
1552 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1553 *name_end = 0;
1555 /* oops - the last check for a / didn't find one. */
1556 if(name_end == NULL)
1557 break;
1559 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1560 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL) {
1561 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1562 return;
1565 /* next segment please */
1566 nameptr = name_end + 1;
1567 i++;
1570 (*ppname_array)[i].name = NULL;
1572 return;
1575 /****************************************************************************
1576 Routine to free a namearray.
1577 ****************************************************************************/
1579 void free_namearray(name_compare_entry *name_array)
1581 int i;
1583 if(name_array == NULL)
1584 return;
1586 for(i=0; name_array[i].name!=NULL; i++)
1587 SAFE_FREE(name_array[i].name);
1588 SAFE_FREE(name_array);
1591 /****************************************************************************
1592 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1593 is dealt with in posix.c
1594 ****************************************************************************/
1596 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1598 SMB_STRUCT_FLOCK lock;
1599 int ret;
1601 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1603 lock.l_type = type;
1604 lock.l_whence = SEEK_SET;
1605 lock.l_start = offset;
1606 lock.l_len = count;
1607 lock.l_pid = 0;
1609 ret = sys_fcntl_ptr(fd,op,&lock);
1611 if (ret == -1 && errno != 0)
1612 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1614 /* a lock query */
1615 if (op == SMB_F_GETLK) {
1616 if ((ret != -1) &&
1617 (lock.l_type != F_UNLCK) &&
1618 (lock.l_pid != 0) &&
1619 (lock.l_pid != sys_getpid())) {
1620 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1621 return(True);
1624 /* it must be not locked or locked by me */
1625 return(False);
1628 /* a lock set or unset */
1629 if (ret == -1) {
1630 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1631 (double)offset,(double)count,op,type,strerror(errno)));
1632 return(False);
1635 /* everything went OK */
1636 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1638 return(True);
1641 /*******************************************************************
1642 Is the name specified one of my netbios names.
1643 Returns true if it is equal, false otherwise.
1644 ********************************************************************/
1646 BOOL is_myname(const char *s)
1648 int n;
1649 BOOL ret = False;
1651 for (n=0; my_netbios_names(n); n++) {
1652 if (strequal(my_netbios_names(n), s)) {
1653 ret=True;
1654 break;
1657 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1658 return(ret);
1661 BOOL is_myname_or_ipaddr(const char *s)
1663 /* optimize for the common case */
1664 if (strequal(s, global_myname()))
1665 return True;
1667 /* maybe its an IP address? */
1668 if (is_ipaddress(s)) {
1669 struct iface_struct nics[MAX_INTERFACES];
1670 int i, n;
1671 uint32 ip;
1673 ip = interpret_addr(s);
1674 if ((ip==0) || (ip==0xffffffff))
1675 return False;
1677 n = get_interfaces(nics, MAX_INTERFACES);
1678 for (i=0; i<n; i++) {
1679 if (ip == nics[i].ip.s_addr)
1680 return True;
1684 /* check for an alias */
1685 if (is_myname(s))
1686 return True;
1688 /* no match */
1689 return False;
1692 /*******************************************************************
1693 Is the name specified our workgroup/domain.
1694 Returns true if it is equal, false otherwise.
1695 ********************************************************************/
1697 BOOL is_myworkgroup(const char *s)
1699 BOOL ret = False;
1701 if (strequal(s, lp_workgroup())) {
1702 ret=True;
1705 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1706 return(ret);
1709 /*******************************************************************
1710 we distinguish between 2K and XP by the "Native Lan Manager" string
1711 WinXP => "Windows 2002 5.1"
1712 Win2k => "Windows 2000 5.0"
1713 NT4 => "Windows NT 4.0"
1714 Win9x => "Windows 4.0"
1715 Windows 2003 doesn't set the native lan manager string but
1716 they do set the domain to "Windows 2003 5.2" (probably a bug).
1717 ********************************************************************/
1719 void ra_lanman_string( const char *native_lanman )
1721 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1722 set_remote_arch( RA_WINXP );
1723 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1724 set_remote_arch( RA_WIN2K3 );
1727 /*******************************************************************
1728 Set the horrid remote_arch string based on an enum.
1729 ********************************************************************/
1731 void set_remote_arch(enum remote_arch_types type)
1733 extern fstring remote_arch;
1734 ra_type = type;
1735 switch( type ) {
1736 case RA_WFWG:
1737 fstrcpy(remote_arch, "WfWg");
1738 break;
1739 case RA_OS2:
1740 fstrcpy(remote_arch, "OS2");
1741 break;
1742 case RA_WIN95:
1743 fstrcpy(remote_arch, "Win95");
1744 break;
1745 case RA_WINNT:
1746 fstrcpy(remote_arch, "WinNT");
1747 break;
1748 case RA_WIN2K:
1749 fstrcpy(remote_arch, "Win2K");
1750 break;
1751 case RA_WINXP:
1752 fstrcpy(remote_arch, "WinXP");
1753 break;
1754 case RA_WIN2K3:
1755 fstrcpy(remote_arch, "Win2K3");
1756 break;
1757 case RA_SAMBA:
1758 fstrcpy(remote_arch,"Samba");
1759 break;
1760 case RA_CIFSFS:
1761 fstrcpy(remote_arch,"CIFSFS");
1762 break;
1763 default:
1764 ra_type = RA_UNKNOWN;
1765 fstrcpy(remote_arch, "UNKNOWN");
1766 break;
1769 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n", remote_arch));
1772 /*******************************************************************
1773 Get the remote_arch type.
1774 ********************************************************************/
1776 enum remote_arch_types get_remote_arch(void)
1778 return ra_type;
1781 void print_asc(int level, const unsigned char *buf,int len)
1783 int i;
1784 for (i=0;i<len;i++)
1785 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1788 void dump_data(int level, const char *buf1,int len)
1790 const unsigned char *buf = (const unsigned char *)buf1;
1791 int i=0;
1792 if (len<=0) return;
1794 if (!DEBUGLVL(level)) return;
1796 DEBUGADD(level,("[%03X] ",i));
1797 for (i=0;i<len;) {
1798 DEBUGADD(level,("%02X ",(int)buf[i]));
1799 i++;
1800 if (i%8 == 0) DEBUGADD(level,(" "));
1801 if (i%16 == 0) {
1802 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1803 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1804 if (i<len) DEBUGADD(level,("[%03X] ",i));
1807 if (i%16) {
1808 int n;
1809 n = 16 - (i%16);
1810 DEBUGADD(level,(" "));
1811 if (n>8) DEBUGADD(level,(" "));
1812 while (n--) DEBUGADD(level,(" "));
1813 n = MIN(8,i%16);
1814 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1815 n = (i%16) - n;
1816 if (n>0) print_asc(level,&buf[i-n],n);
1817 DEBUGADD(level,("\n"));
1821 void dump_data_pw(const char *msg, const uchar * data, size_t len)
1823 #ifdef DEBUG_PASSWORD
1824 DEBUG(11, ("%s", msg));
1825 if (data != NULL && len > 0)
1827 dump_data(11, data, len);
1829 #endif
1832 char *tab_depth(int depth)
1834 static pstring spaces;
1835 memset(spaces, ' ', depth * 4);
1836 spaces[depth * 4] = 0;
1837 return spaces;
1840 /*****************************************************************************
1841 Provide a checksum on a string
1843 Input: s - the null-terminated character string for which the checksum
1844 will be calculated.
1846 Output: The checksum value calculated for s.
1847 *****************************************************************************/
1849 int str_checksum(const char *s)
1851 int res = 0;
1852 int c;
1853 int i=0;
1855 while(*s) {
1856 c = *s;
1857 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1858 s++;
1859 i++;
1861 return(res);
1864 /*****************************************************************
1865 Zero a memory area then free it. Used to catch bugs faster.
1866 *****************************************************************/
1868 void zero_free(void *p, size_t size)
1870 memset(p, 0, size);
1871 SAFE_FREE(p);
1874 /*****************************************************************
1875 Set our open file limit to a requested max and return the limit.
1876 *****************************************************************/
1878 int set_maxfiles(int requested_max)
1880 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1881 struct rlimit rlp;
1882 int saved_current_limit;
1884 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1885 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1886 strerror(errno) ));
1887 /* just guess... */
1888 return requested_max;
1892 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1893 * account for the extra fd we need
1894 * as well as the log files and standard
1895 * handles etc. Save the limit we want to set in case
1896 * we are running on an OS that doesn't support this limit (AIX)
1897 * which always returns RLIM_INFINITY for rlp.rlim_max.
1900 /* Try raising the hard (max) limit to the requested amount. */
1902 #if defined(RLIM_INFINITY)
1903 if (rlp.rlim_max != RLIM_INFINITY) {
1904 int orig_max = rlp.rlim_max;
1906 if ( rlp.rlim_max < requested_max )
1907 rlp.rlim_max = requested_max;
1909 /* This failing is not an error - many systems (Linux) don't
1910 support our default request of 10,000 open files. JRA. */
1912 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1913 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1914 (int)rlp.rlim_max, strerror(errno) ));
1916 /* Set failed - restore original value from get. */
1917 rlp.rlim_max = orig_max;
1920 #endif
1922 /* Now try setting the soft (current) limit. */
1924 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1926 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1927 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1928 (int)rlp.rlim_cur, strerror(errno) ));
1929 /* just guess... */
1930 return saved_current_limit;
1933 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1934 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1935 strerror(errno) ));
1936 /* just guess... */
1937 return saved_current_limit;
1940 #if defined(RLIM_INFINITY)
1941 if(rlp.rlim_cur == RLIM_INFINITY)
1942 return saved_current_limit;
1943 #endif
1945 if((int)rlp.rlim_cur > saved_current_limit)
1946 return saved_current_limit;
1948 return rlp.rlim_cur;
1949 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1951 * No way to know - just guess...
1953 return requested_max;
1954 #endif
1957 /*****************************************************************
1958 Splits out the start of the key (HKLM or HKU) and the rest of the key.
1959 *****************************************************************/
1961 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
1963 pstring tmp;
1965 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1966 return False;
1968 (*reg_type) = 0;
1970 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1972 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1973 (*reg_type) = HKEY_LOCAL_MACHINE;
1974 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1975 (*reg_type) = HKEY_USERS;
1976 else {
1977 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1978 return False;
1981 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
1982 fstrcpy(key_name, tmp);
1983 else
1984 key_name[0] = 0;
1986 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1988 return True;
1991 /*****************************************************************
1992 Possibly replace mkstemp if it is broken.
1993 *****************************************************************/
1995 int smb_mkstemp(char *template)
1997 #if HAVE_SECURE_MKSTEMP
1998 return mkstemp(template);
1999 #else
2000 /* have a reasonable go at emulating it. Hope that
2001 the system mktemp() isn't completly hopeless */
2002 char *p = mktemp(template);
2003 if (!p)
2004 return -1;
2005 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2006 #endif
2009 /*****************************************************************
2010 malloc that aborts with smb_panic on fail or zero size.
2011 *****************************************************************/
2013 void *smb_xmalloc(size_t size)
2015 void *p;
2016 if (size == 0)
2017 smb_panic("smb_xmalloc: called with zero size.\n");
2018 if ((p = malloc(size)) == NULL) {
2019 DEBUG(0, ("smb_xmalloc() failed to allocate %lu bytes\n", (unsigned long)size));
2020 smb_panic("smb_xmalloc: malloc fail.\n");
2022 return p;
2026 Memdup with smb_panic on fail.
2029 void *smb_xmemdup(const void *p, size_t size)
2031 void *p2;
2032 p2 = smb_xmalloc(size);
2033 memcpy(p2, p, size);
2034 return p2;
2038 strdup that aborts on malloc fail.
2041 char *smb_xstrdup(const char *s)
2043 char *s1 = strdup(s);
2044 if (!s1)
2045 smb_panic("smb_xstrdup: malloc fail\n");
2046 return s1;
2050 strndup that aborts on malloc fail.
2053 char *smb_xstrndup(const char *s, size_t n)
2055 char *s1 = strndup(s, n);
2056 if (!s1)
2057 smb_panic("smb_xstrndup: malloc fail\n");
2058 return s1;
2062 vasprintf that aborts on malloc fail
2065 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2067 int n;
2068 va_list ap2;
2070 VA_COPY(ap2, ap);
2072 n = vasprintf(ptr, format, ap2);
2073 if (n == -1 || ! *ptr)
2074 smb_panic("smb_xvasprintf: out of memory");
2075 return n;
2078 /*****************************************************************
2079 Like strdup but for memory.
2080 *****************************************************************/
2082 void *memdup(const void *p, size_t size)
2084 void *p2;
2085 if (size == 0)
2086 return NULL;
2087 p2 = malloc(size);
2088 if (!p2)
2089 return NULL;
2090 memcpy(p2, p, size);
2091 return p2;
2094 /*****************************************************************
2095 Get local hostname and cache result.
2096 *****************************************************************/
2098 char *myhostname(void)
2100 static pstring ret;
2101 if (ret[0] == 0)
2102 get_myname(ret);
2103 return ret;
2106 /*****************************************************************
2107 A useful function for returning a path in the Samba lock directory.
2108 *****************************************************************/
2110 char *lock_path(const char *name)
2112 static pstring fname;
2114 pstrcpy(fname,lp_lockdir());
2115 trim_char(fname,'\0','/');
2117 if (!directory_exist(fname,NULL))
2118 mkdir(fname,0755);
2120 pstrcat(fname,"/");
2121 pstrcat(fname,name);
2123 return fname;
2126 /*****************************************************************
2127 A useful function for returning a path in the Samba pid directory.
2128 *****************************************************************/
2130 char *pid_path(const char *name)
2132 static pstring fname;
2134 pstrcpy(fname,lp_piddir());
2135 trim_char(fname,'\0','/');
2137 if (!directory_exist(fname,NULL))
2138 mkdir(fname,0755);
2140 pstrcat(fname,"/");
2141 pstrcat(fname,name);
2143 return fname;
2147 * @brief Returns an absolute path to a file in the Samba lib directory.
2149 * @param name File to find, relative to LIBDIR.
2151 * @retval Pointer to a static #pstring containing the full path.
2154 char *lib_path(const char *name)
2156 static pstring fname;
2157 fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2158 return fname;
2162 * @brief Returns the platform specific shared library extension.
2164 * @retval Pointer to a static #fstring containing the extension.
2167 const char *shlib_ext(void)
2169 return dyn_SHLIBEXT;
2172 /*******************************************************************
2173 Given a filename - get its directory name
2174 NB: Returned in static storage. Caveats:
2175 o Not safe in thread environment.
2176 o Caller must not free.
2177 o If caller wishes to preserve, they should copy.
2178 ********************************************************************/
2180 char *parent_dirname(const char *path)
2182 static pstring dirpath;
2183 char *p;
2185 if (!path)
2186 return(NULL);
2188 pstrcpy(dirpath, path);
2189 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2190 if (!p) {
2191 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2192 } else {
2193 if (p == dirpath)
2194 ++p; /* For root "/", leave "/" in place */
2195 *p = '\0';
2197 return dirpath;
2201 /*******************************************************************
2202 Determine if a pattern contains any Microsoft wildcard characters.
2203 *******************************************************************/
2205 BOOL ms_has_wild(const char *s)
2207 char c;
2208 while ((c = *s++)) {
2209 switch (c) {
2210 case '*':
2211 case '?':
2212 case '<':
2213 case '>':
2214 case '"':
2215 return True;
2218 return False;
2221 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2223 smb_ucs2_t c;
2224 if (!s) return False;
2225 while ((c = *s++)) {
2226 switch (c) {
2227 case UCS2_CHAR('*'):
2228 case UCS2_CHAR('?'):
2229 case UCS2_CHAR('<'):
2230 case UCS2_CHAR('>'):
2231 case UCS2_CHAR('"'):
2232 return True;
2235 return False;
2238 /*******************************************************************
2239 A wrapper that handles case sensitivity and the special handling
2240 of the ".." name.
2241 *******************************************************************/
2243 BOOL mask_match_x(const char *string, char *pattern, BOOL is_case_sensitive)
2245 if (strcmp(string,"..") == 0)
2246 string = ".";
2247 if (strcmp(pattern,".") == 0)
2248 return False;
2250 return ms_fnmatch_x(pattern, string, Protocol, is_case_sensitive) == 0;
2253 /*******************************************************************
2254 A wrapper that handles a list of patters and calls mask_match()
2255 on each. Returns True if any of the patterns match.
2256 *******************************************************************/
2258 BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_sensitive)
2260 while (listLen-- > 0) {
2261 if (mask_match_x(string, *list++, is_case_sensitive))
2262 return True;
2264 return False;
2267 /*********************************************************
2268 Recursive routine that is called by unix_wild_match.
2269 *********************************************************/
2271 static BOOL unix_do_match(const char *regexp, const char *str)
2273 const char *p;
2275 for( p = regexp; *p && *str; ) {
2277 switch(*p) {
2278 case '?':
2279 str++;
2280 p++;
2281 break;
2283 case '*':
2286 * Look for a character matching
2287 * the one after the '*'.
2289 p++;
2290 if(!*p)
2291 return True; /* Automatic match */
2292 while(*str) {
2294 while(*str && (*p != *str))
2295 str++;
2298 * Patch from weidel@multichart.de. In the case of the regexp
2299 * '*XX*' we want to ensure there are at least 2 'X' characters
2300 * in the string after the '*' for a match to be made.
2304 int matchcount=0;
2307 * Eat all the characters that match, but count how many there were.
2310 while(*str && (*p == *str)) {
2311 str++;
2312 matchcount++;
2316 * Now check that if the regexp had n identical characters that
2317 * matchcount had at least that many matches.
2320 while ( *(p+1) && (*(p+1) == *p)) {
2321 p++;
2322 matchcount--;
2325 if ( matchcount <= 0 )
2326 return False;
2329 str--; /* We've eaten the match char after the '*' */
2331 if(unix_do_match(p, str))
2332 return True;
2334 if(!*str)
2335 return False;
2336 else
2337 str++;
2339 return False;
2341 default:
2342 if(*str != *p)
2343 return False;
2344 str++;
2345 p++;
2346 break;
2350 if(!*p && !*str)
2351 return True;
2353 if (!*p && str[0] == '.' && str[1] == 0)
2354 return(True);
2356 if (!*str && *p == '?') {
2357 while (*p == '?')
2358 p++;
2359 return(!*p);
2362 if(!*str && (*p == '*' && p[1] == '\0'))
2363 return True;
2365 return False;
2368 /*******************************************************************
2369 Simple case insensitive interface to a UNIX wildcard matcher.
2370 *******************************************************************/
2372 BOOL unix_wild_match(const char *pattern, const char *string)
2374 pstring p2, s2;
2375 char *p;
2377 pstrcpy(p2, pattern);
2378 pstrcpy(s2, string);
2379 strlower_m(p2);
2380 strlower_m(s2);
2382 /* Remove any *? and ** from the pattern as they are meaningless */
2383 for(p = p2; *p; p++)
2384 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2385 pstrcpy( &p[1], &p[2]);
2387 if (strequal(p2,"*"))
2388 return True;
2390 return unix_do_match(p2, s2) == 0;
2393 /**********************************************************************
2394 Converts a name to a fully qalified domain name.
2395 ***********************************************************************/
2397 void name_to_fqdn(fstring fqdn, const char *name)
2399 struct hostent *hp = sys_gethostbyname(name);
2400 if ( hp && hp->h_name && *hp->h_name ) {
2401 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
2402 fstrcpy(fqdn,hp->h_name);
2403 } else {
2404 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
2405 fstrcpy(fqdn, name);
2409 #ifdef __INSURE__
2411 /*******************************************************************
2412 This routine is a trick to immediately catch errors when debugging
2413 with insure. A xterm with a gdb is popped up when insure catches
2414 a error. It is Linux specific.
2415 ********************************************************************/
2417 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2419 static int (*fn)();
2420 int ret;
2421 char pidstr[10];
2422 /* you can get /usr/bin/backtrace from
2423 http://samba.org/ftp/unpacked/junkcode/backtrace */
2424 pstring cmd = "/usr/bin/backtrace %d";
2426 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2427 pstring_sub(cmd, "%d", pidstr);
2429 if (!fn) {
2430 static void *h;
2431 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2432 fn = dlsym(h, "_Insure_trap_error");
2434 if (!h || h == _Insure_trap_error) {
2435 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2436 fn = dlsym(h, "_Insure_trap_error");
2440 ret = fn(a1, a2, a3, a4, a5, a6);
2442 system(cmd);
2444 return ret;
2446 #endif