filled in 'change share command' parameter in smb.conf. Also regenerated
[Samba.git] / source / lib / util.c
blob3bee53abbcca39bf49a1e147b792fb908c7e18d1
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "includes.h"
24 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
25 #ifdef WITH_NISPLUS_HOME
26 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
28 * The following lines are needed due to buggy include files
29 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
30 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
31 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
32 * an enum in /usr/include/rpcsvc/nis.h.
35 #if defined(GROUP)
36 #undef GROUP
37 #endif
39 #if defined(GROUP_OBJ)
40 #undef GROUP_OBJ
41 #endif
43 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
45 #include <rpcsvc/nis.h>
47 #else /* !WITH_NISPLUS_HOME */
49 #include "rpcsvc/ypclnt.h"
51 #endif /* WITH_NISPLUS_HOME */
52 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
54 #ifdef WITH_SSL
55 #include <ssl.h>
56 #undef Realloc /* SSLeay defines this and samba has a function of this name */
57 extern SSL *ssl;
58 extern int sslFd;
59 #endif /* WITH_SSL */
61 extern int DEBUGLEVEL;
63 int Protocol = PROTOCOL_COREPLUS;
65 /* a default finfo structure to ensure all fields are sensible */
66 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
68 /* this is used by the chaining code */
69 int chain_size = 0;
71 int trans_num = 0;
74 case handling on filenames
76 int case_default = CASE_LOWER;
78 /* the following control case operations - they are put here so the
79 client can link easily */
80 BOOL case_sensitive;
81 BOOL case_preserve;
82 BOOL use_mangled_map = False;
83 BOOL short_case_preserve;
84 BOOL case_mangle;
86 static enum remote_arch_types ra_type = RA_UNKNOWN;
87 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
89 pstring global_myname = "";
90 fstring global_myworkgroup = "";
91 char **my_netbios_names;
94 /****************************************************************************
95 find a suitable temporary directory. The result should be copied immediately
96 as it may be overwritten by a subsequent call
97 ****************************************************************************/
98 char *tmpdir(void)
100 char *p;
101 if ((p = getenv("TMPDIR"))) {
102 return p;
104 return "/tmp";
107 /****************************************************************************
108 determine whether we are in the specified group
109 ****************************************************************************/
111 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
113 int i;
115 if (group == current_gid) return(True);
117 for (i=0;i<ngroups;i++)
118 if (group == groups[i])
119 return(True);
121 return(False);
125 /****************************************************************************
126 like atoi but gets the value up to the separater character
127 ****************************************************************************/
128 char *Atoic(char *p, int *n, char *c)
130 if (!isdigit((int)*p))
132 DEBUG(5, ("Atoic: malformed number\n"));
133 return NULL;
136 (*n) = atoi(p);
138 while ((*p) && isdigit((int)*p))
140 p++;
143 if (strchr(c, *p) == NULL)
145 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
146 return NULL;
149 return p;
152 /*************************************************************************
153 reads a list of numbers
154 *************************************************************************/
155 char *get_numlist(char *p, uint32 **num, int *count)
157 int val;
159 if (num == NULL || count == NULL)
161 return NULL;
164 (*count) = 0;
165 (*num ) = NULL;
167 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':')
169 (*num) = Realloc((*num), ((*count)+1) * sizeof(uint32));
170 if ((*num) == NULL)
172 return NULL;
174 (*num)[(*count)] = val;
175 (*count)++;
176 p++;
179 return p;
183 /*******************************************************************
184 check if a file exists - call vfs_file_exist for samba files
185 ********************************************************************/
186 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
188 SMB_STRUCT_STAT st;
189 if (!sbuf) sbuf = &st;
191 if (sys_stat(fname,sbuf) != 0)
192 return(False);
194 return(S_ISREG(sbuf->st_mode));
197 /*******************************************************************
198 rename a unix file
199 ********************************************************************/
200 int file_rename(char *from, char *to)
202 int rcode = rename (from, to);
204 if (errno == EXDEV)
206 /* Rename across filesystems needed. */
207 rcode = copy_reg (from, to);
209 return rcode;
212 /*******************************************************************
213 check a files mod time
214 ********************************************************************/
215 time_t file_modtime(char *fname)
217 SMB_STRUCT_STAT st;
219 if (sys_stat(fname,&st) != 0)
220 return(0);
222 return(st.st_mtime);
225 /*******************************************************************
226 check if a directory exists
227 ********************************************************************/
228 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
230 SMB_STRUCT_STAT st2;
231 BOOL ret;
233 if (!st) st = &st2;
235 if (sys_stat(dname,st) != 0)
236 return(False);
238 ret = S_ISDIR(st->st_mode);
239 if(!ret)
240 errno = ENOTDIR;
241 return ret;
244 /*******************************************************************
245 returns the size in bytes of the named file
246 ********************************************************************/
247 SMB_OFF_T get_file_size(char *file_name)
249 SMB_STRUCT_STAT buf;
250 buf.st_size = 0;
251 if(sys_stat(file_name,&buf) != 0)
252 return (SMB_OFF_T)-1;
253 return(buf.st_size);
256 /*******************************************************************
257 return a string representing an attribute for a file
258 ********************************************************************/
259 char *attrib_string(uint16 mode)
261 static fstring attrstr;
263 attrstr[0] = 0;
265 if (mode & aVOLID) fstrcat(attrstr,"V");
266 if (mode & aDIR) fstrcat(attrstr,"D");
267 if (mode & aARCH) fstrcat(attrstr,"A");
268 if (mode & aHIDDEN) fstrcat(attrstr,"H");
269 if (mode & aSYSTEM) fstrcat(attrstr,"S");
270 if (mode & aRONLY) fstrcat(attrstr,"R");
272 return(attrstr);
275 /*******************************************************************
276 show a smb message structure
277 ********************************************************************/
278 void show_msg(char *buf)
280 int i;
281 int bcc=0;
283 if (DEBUGLEVEL < 5) return;
285 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
286 smb_len(buf),
287 (int)CVAL(buf,smb_com),
288 (int)CVAL(buf,smb_rcls),
289 (int)CVAL(buf,smb_reh),
290 (int)SVAL(buf,smb_err),
291 (int)CVAL(buf,smb_flg),
292 (int)SVAL(buf,smb_flg2)));
293 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
294 (int)SVAL(buf,smb_tid),
295 (int)SVAL(buf,smb_pid),
296 (int)SVAL(buf,smb_uid),
297 (int)SVAL(buf,smb_mid),
298 (int)CVAL(buf,smb_wct)));
300 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
302 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
303 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
306 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
308 DEBUG(5,("smb_bcc=%d\n",bcc));
310 if (DEBUGLEVEL < 10) return;
312 if (DEBUGLEVEL < 50)
314 bcc = MIN(bcc, 512);
317 dump_data(10, smb_buf(buf), bcc);
320 /*******************************************************************
321 set the length and marker of an smb packet
322 ********************************************************************/
323 void smb_setlen(char *buf,int len)
325 _smb_setlen(buf,len);
327 CVAL(buf,4) = 0xFF;
328 CVAL(buf,5) = 'S';
329 CVAL(buf,6) = 'M';
330 CVAL(buf,7) = 'B';
333 /*******************************************************************
334 setup the word count and byte count for a smb message
335 ********************************************************************/
336 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
338 if (zero)
339 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
340 CVAL(buf,smb_wct) = num_words;
341 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
342 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
343 return (smb_size + num_words*2 + num_bytes);
346 /*******************************************************************
347 setup only the byte count for a smb message
348 ********************************************************************/
349 void set_message_bcc(char *buf,int num_bytes)
351 int num_words = CVAL(buf,smb_wct);
352 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
353 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
356 /*******************************************************************
357 setup only the byte count for a smb message, using the end of the
358 message as a marker
359 ********************************************************************/
360 void set_message_end(void *outbuf,void *end_ptr)
362 set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
365 /*******************************************************************
366 reduce a file name, removing .. elements.
367 ********************************************************************/
368 void dos_clean_name(char *s)
370 char *p=NULL;
372 DEBUG(3,("dos_clean_name [%s]\n",s));
374 /* remove any double slashes */
375 all_string_sub(s, "\\\\", "\\", 0);
377 while ((p = strstr(s,"\\..\\")) != NULL)
379 pstring s1;
381 *p = 0;
382 pstrcpy(s1,p+3);
384 if ((p=strrchr(s,'\\')) != NULL)
385 *p = 0;
386 else
387 *s = 0;
388 pstrcat(s,s1);
391 trim_string(s,NULL,"\\..");
393 all_string_sub(s, "\\.\\", "\\", 0);
396 /*******************************************************************
397 reduce a file name, removing .. elements.
398 ********************************************************************/
399 void unix_clean_name(char *s)
401 char *p=NULL;
403 DEBUG(3,("unix_clean_name [%s]\n",s));
405 /* remove any double slashes */
406 all_string_sub(s, "//","/", 0);
408 /* Remove leading ./ characters */
409 if(strncmp(s, "./", 2) == 0) {
410 trim_string(s, "./", NULL);
411 if(*s == 0)
412 pstrcpy(s,"./");
415 while ((p = strstr(s,"/../")) != NULL)
417 pstring s1;
419 *p = 0;
420 pstrcpy(s1,p+3);
422 if ((p=strrchr(s,'/')) != NULL)
423 *p = 0;
424 else
425 *s = 0;
426 pstrcat(s,s1);
429 trim_string(s,NULL,"/..");
432 /****************************************************************************
433 make a dir struct
434 ****************************************************************************/
435 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
437 char *p;
438 pstring mask2;
440 pstrcpy(mask2,mask);
442 if ((mode & aDIR) != 0)
443 size = 0;
445 memset(buf+1,' ',11);
446 if ((p = strchr(mask2,'.')) != NULL)
448 *p = 0;
449 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
450 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
451 *p = '.';
453 else
454 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
456 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
457 CVAL(buf,21) = mode;
458 put_dos_date(buf,22,date);
459 SSVAL(buf,26,size & 0xFFFF);
460 SSVAL(buf,28,(size >> 16)&0xFFFF);
461 StrnCpy(buf+30,fname,12);
462 if (!case_sensitive)
463 strupper(buf+30);
464 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
468 /*******************************************************************
469 close the low 3 fd's and open dev/null in their place
470 ********************************************************************/
471 void close_low_fds(void)
473 int fd;
474 int i;
475 close(0); close(1);
476 #ifndef __INSURE__
477 close(2);
478 #endif
479 /* try and use up these file descriptors, so silly
480 library routines writing to stdout etc won't cause havoc */
481 for (i=0;i<3;i++) {
482 fd = sys_open("/dev/null",O_RDWR,0);
483 if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
484 if (fd < 0) {
485 DEBUG(0,("Can't open /dev/null\n"));
486 return;
488 if (fd != i) {
489 DEBUG(0,("Didn't get file descriptor %d\n",i));
490 return;
495 /****************************************************************************
496 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
497 else
498 if SYSV use O_NDELAY
499 if BSD use FNDELAY
500 ****************************************************************************/
501 int set_blocking(int fd, BOOL set)
503 int val;
504 #ifdef O_NONBLOCK
505 #define FLAG_TO_SET O_NONBLOCK
506 #else
507 #ifdef SYSV
508 #define FLAG_TO_SET O_NDELAY
509 #else /* BSD */
510 #define FLAG_TO_SET FNDELAY
511 #endif
512 #endif
514 if((val = fcntl(fd, F_GETFL, 0)) == -1)
515 return -1;
516 if(set) /* Turn blocking on - ie. clear nonblock flag */
517 val &= ~FLAG_TO_SET;
518 else
519 val |= FLAG_TO_SET;
520 return fcntl( fd, F_SETFL, val);
521 #undef FLAG_TO_SET
524 /****************************************************************************
525 transfer some data between two fd's
526 ****************************************************************************/
527 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n,char *header,int headlen,int align)
529 static char *buf=NULL;
530 static int size=0;
531 char *buf1,*abuf;
532 SMB_OFF_T total = 0;
534 DEBUG(4,("transfer_file n=%.0f (head=%d) called\n",(double)n,headlen));
536 if (size == 0) {
537 size = lp_readsize();
538 size = MAX(size,1024);
541 while (!buf && size>0) {
542 buf = (char *)Realloc(buf,size+8);
543 if (!buf) size /= 2;
546 if (!buf) {
547 DEBUG(0,("Can't allocate transfer buffer!\n"));
548 exit(1);
551 abuf = buf + (align%8);
553 if (header)
554 n += headlen;
556 while (n > 0)
558 int s = (int)MIN(n,(SMB_OFF_T)size);
559 int ret,ret2=0;
561 ret = 0;
563 if (header && (headlen >= MIN(s,1024))) {
564 buf1 = header;
565 s = headlen;
566 ret = headlen;
567 headlen = 0;
568 header = NULL;
569 } else {
570 buf1 = abuf;
573 if (header && headlen > 0)
575 ret = MIN(headlen,size);
576 memcpy(buf1,header,ret);
577 headlen -= ret;
578 header += ret;
579 if (headlen <= 0) header = NULL;
582 if (s > ret)
583 ret += read(infd,buf1+ret,s-ret);
585 if (ret > 0)
587 ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
588 if (ret2 > 0) total += ret2;
589 /* if we can't write then dump excess data */
590 if (ret2 != ret)
591 transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
593 if (ret <= 0 || ret2 != ret)
594 return(total);
595 n -= ret;
597 return(total);
601 /*******************************************************************
602 sleep for a specified number of milliseconds
603 ********************************************************************/
604 void msleep(int t)
606 int tdiff=0;
607 struct timeval tval,t1,t2;
608 fd_set fds;
610 GetTimeOfDay(&t1);
611 GetTimeOfDay(&t2);
613 while (tdiff < t) {
614 tval.tv_sec = (t-tdiff)/1000;
615 tval.tv_usec = 1000*((t-tdiff)%1000);
617 FD_ZERO(&fds);
618 errno = 0;
619 sys_select_intr(0,&fds,&tval);
621 GetTimeOfDay(&t2);
622 tdiff = TvalDiff(&t1,&t2);
627 /****************************************************************************
628 become a daemon, discarding the controlling terminal
629 ****************************************************************************/
630 void become_daemon(void)
632 if (sys_fork()) {
633 _exit(0);
636 /* detach from the terminal */
637 #ifdef HAVE_SETSID
638 setsid();
639 #elif defined(TIOCNOTTY)
641 int i = sys_open("/dev/tty", O_RDWR, 0);
642 if (i != -1) {
643 ioctl(i, (int) TIOCNOTTY, (char *)0);
644 close(i);
647 #endif /* HAVE_SETSID */
649 /* Close fd's 0,1,2. Needed if started by rsh */
650 close_low_fds();
654 /****************************************************************************
655 put up a yes/no prompt
656 ****************************************************************************/
657 BOOL yesno(char *p)
659 pstring ans;
660 printf("%s",p);
662 if (!fgets(ans,sizeof(ans)-1,stdin))
663 return(False);
665 if (*ans == 'y' || *ans == 'Y')
666 return(True);
668 return(False);
671 #ifdef HPUX
672 /****************************************************************************
673 this is a version of setbuffer() for those machines that only have setvbuf
674 ****************************************************************************/
675 void setbuffer(FILE *f,char *buf,int bufsize)
677 setvbuf(f,buf,_IOFBF,bufsize);
679 #endif
681 /****************************************************************************
682 expand a pointer to be a particular size
683 ****************************************************************************/
684 void *Realloc(void *p,size_t size)
686 void *ret=NULL;
688 if (size == 0) {
689 if (p) free(p);
690 DEBUG(5,("Realloc asked for 0 bytes\n"));
691 return NULL;
694 if (!p)
695 ret = (void *)malloc(size);
696 else
697 ret = (void *)realloc(p,size);
699 if (!ret)
700 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
702 return(ret);
706 /****************************************************************************
707 free memory, checks for NULL
708 ****************************************************************************/
709 void safe_free(void *p)
711 if (p != NULL)
713 free(p);
718 /****************************************************************************
719 get my own name and IP
720 ****************************************************************************/
721 BOOL get_myname(char *my_name)
723 pstring hostname;
725 *hostname = 0;
727 /* get my host name */
728 if (gethostname(hostname, sizeof(hostname)) == -1) {
729 DEBUG(0,("gethostname failed\n"));
730 return False;
733 /* Ensure null termination. */
734 hostname[sizeof(hostname)-1] = '\0';
736 if (my_name) {
737 /* split off any parts after an initial . */
738 char *p = strchr(hostname,'.');
739 if (p) *p = 0;
741 fstrcpy(my_name,hostname);
744 return(True);
747 /****************************************************************************
748 interpret a protocol description string, with a default
749 ****************************************************************************/
750 int interpret_protocol(char *str,int def)
752 if (strequal(str,"NT1"))
753 return(PROTOCOL_NT1);
754 if (strequal(str,"LANMAN2"))
755 return(PROTOCOL_LANMAN2);
756 if (strequal(str,"LANMAN1"))
757 return(PROTOCOL_LANMAN1);
758 if (strequal(str,"CORE"))
759 return(PROTOCOL_CORE);
760 if (strequal(str,"COREPLUS"))
761 return(PROTOCOL_COREPLUS);
762 if (strequal(str,"CORE+"))
763 return(PROTOCOL_COREPLUS);
765 DEBUG(0,("Unrecognised protocol level %s\n",str));
767 return(def);
770 /****************************************************************************
771 Return true if a string could be a pure IP address.
772 ****************************************************************************/
774 BOOL is_ipaddress(const char *str)
776 BOOL pure_address = True;
777 int i;
779 for (i=0; pure_address && str[i]; i++)
780 if (!(isdigit((int)str[i]) || str[i] == '.'))
781 pure_address = False;
783 /* Check that a pure number is not misinterpreted as an IP */
784 pure_address = pure_address && (strchr(str, '.') != NULL);
786 return pure_address;
789 /****************************************************************************
790 interpret an internet address or name into an IP address in 4 byte form
791 ****************************************************************************/
793 uint32 interpret_addr(char *str)
795 struct hostent *hp;
796 uint32 res;
798 if (strcmp(str,"0.0.0.0") == 0) return(0);
799 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
801 /* if it's in the form of an IP address then get the lib to interpret it */
802 if (is_ipaddress(str)) {
803 res = inet_addr(str);
804 } else {
805 /* otherwise assume it's a network name of some sort and use
806 Get_Hostbyname */
807 if ((hp = Get_Hostbyname(str)) == 0) {
808 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
809 return 0;
811 if(hp->h_addr == NULL) {
812 DEBUG(3,("Get_Hostbyname: host address is invalid for host %s\n",str));
813 return 0;
815 putip((char *)&res,(char *)hp->h_addr);
818 if (res == (uint32)-1) return(0);
820 return(res);
823 /*******************************************************************
824 a convenient addition to interpret_addr()
825 ******************************************************************/
826 struct in_addr *interpret_addr2(char *str)
828 static struct in_addr ret;
829 uint32 a = interpret_addr(str);
830 ret.s_addr = a;
831 return(&ret);
834 /*******************************************************************
835 check if an IP is the 0.0.0.0
836 ******************************************************************/
837 BOOL zero_ip(struct in_addr ip)
839 uint32 a;
840 putip((char *)&a,(char *)&ip);
841 return(a == 0);
845 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
846 /******************************************************************
847 Remove any mount options such as -rsize=2048,wsize=2048 etc.
848 Based on a fix from <Thomas.Hepper@icem.de>.
849 *******************************************************************/
851 static void strip_mount_options( pstring *str)
853 if (**str == '-')
855 char *p = *str;
856 while(*p && !isspace(*p))
857 p++;
858 while(*p && isspace(*p))
859 p++;
860 if(*p) {
861 pstring tmp_str;
863 pstrcpy(tmp_str, p);
864 pstrcpy(*str, tmp_str);
869 /*******************************************************************
870 Patch from jkf@soton.ac.uk
871 Split Luke's automount_server into YP lookup and string splitter
872 so can easily implement automount_path().
873 As we may end up doing both, cache the last YP result.
874 *******************************************************************/
876 #ifdef WITH_NISPLUS_HOME
877 char *automount_lookup(char *user_name)
879 static fstring last_key = "";
880 static pstring last_value = "";
882 char *nis_map = (char *)lp_nis_home_map_name();
884 char buffer[NIS_MAXATTRVAL + 1];
885 nis_result *result;
886 nis_object *object;
887 entry_obj *entry;
889 if (strcmp(user_name, last_key))
891 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
892 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
894 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
896 if (result->status != NIS_SUCCESS)
898 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
899 fstrcpy(last_key, ""); pstrcpy(last_value, "");
901 else
903 object = result->objects.objects_val;
904 if (object->zo_data.zo_type == ENTRY_OBJ)
906 entry = &object->zo_data.objdata_u.en_data;
907 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
908 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
910 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
911 pstring_sub(last_value, "&", user_name);
912 fstrcpy(last_key, user_name);
916 nis_freeresult(result);
919 strip_mount_options(&last_value);
921 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
922 return last_value;
924 #else /* WITH_NISPLUS_HOME */
925 char *automount_lookup(char *user_name)
927 static fstring last_key = "";
928 static pstring last_value = "";
930 int nis_error; /* returned by yp all functions */
931 char *nis_result; /* yp_match inits this */
932 int nis_result_len; /* and set this */
933 char *nis_domain; /* yp_get_default_domain inits this */
934 char *nis_map = (char *)lp_nis_home_map_name();
936 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
937 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
938 return last_value;
941 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
943 if (!strcmp(user_name, last_key)) {
944 nis_result = last_value;
945 nis_result_len = strlen(last_value);
946 nis_error = 0;
948 } else {
950 if ((nis_error = yp_match(nis_domain, nis_map,
951 user_name, strlen(user_name),
952 &nis_result, &nis_result_len)) == 0) {
953 if (!nis_error && nis_result_len >= sizeof(pstring)) {
954 nis_result_len = sizeof(pstring)-1;
956 fstrcpy(last_key, user_name);
957 strncpy(last_value, nis_result, nis_result_len);
958 last_value[nis_result_len] = '\0';
959 strip_mount_options(&last_value);
961 } else if(nis_error == YPERR_KEY) {
963 /* If Key lookup fails user home server is not in nis_map
964 use default information for server, and home directory */
965 last_value[0] = 0;
966 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
967 user_name, nis_map));
968 DEBUG(3, ("using defaults for server and home directory\n"));
969 } else {
970 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
971 yperr_string(nis_error), user_name, nis_map));
976 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
977 return last_value;
979 #endif /* WITH_NISPLUS_HOME */
980 #endif
983 /*******************************************************************
984 are two IPs on the same subnet?
985 ********************************************************************/
986 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
988 uint32 net1,net2,nmask;
990 nmask = ntohl(mask.s_addr);
991 net1 = ntohl(ip1.s_addr);
992 net2 = ntohl(ip2.s_addr);
994 return((net1 & nmask) == (net2 & nmask));
998 /****************************************************************************
999 a wrapper for gethostbyname() that tries with all lower and all upper case
1000 if the initial name fails
1001 ****************************************************************************/
1002 struct hostent *Get_Hostbyname(const char *name)
1004 char *name2 = strdup(name);
1005 struct hostent *ret;
1007 if (!name2)
1009 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
1010 exit(0);
1015 * This next test is redundent and causes some systems (with
1016 * broken isalnum() calls) problems.
1017 * JRA.
1020 #if 0
1021 if (!isalnum(*name2))
1023 free(name2);
1024 return(NULL);
1026 #endif /* 0 */
1028 ret = sys_gethostbyname(name2);
1029 if (ret != NULL)
1031 free(name2);
1032 return(ret);
1035 /* try with all lowercase */
1036 strlower(name2);
1037 ret = sys_gethostbyname(name2);
1038 if (ret != NULL)
1040 free(name2);
1041 return(ret);
1044 /* try with all uppercase */
1045 strupper(name2);
1046 ret = sys_gethostbyname(name2);
1047 if (ret != NULL)
1049 free(name2);
1050 return(ret);
1053 /* nothing works :-( */
1054 free(name2);
1055 return(NULL);
1059 /****************************************************************************
1060 check if a process exists. Does this work on all unixes?
1061 ****************************************************************************/
1063 BOOL process_exists(pid_t pid)
1065 return(kill(pid,0) == 0 || errno != ESRCH);
1069 /*******************************************************************
1070 Convert a uid into a user name.
1071 ********************************************************************/
1073 char *uidtoname(uid_t uid)
1075 static fstring name;
1076 struct passwd *pass;
1078 if (winbind_uidtoname(name, uid))
1079 return name;
1081 pass = sys_getpwuid(uid);
1082 if (pass) return(pass->pw_name);
1083 slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1084 return(name);
1088 /*******************************************************************
1089 Convert a gid into a group name.
1090 ********************************************************************/
1092 char *gidtoname(gid_t gid)
1094 static fstring name;
1095 struct group *grp;
1097 if (winbind_gidtoname(name, gid))
1098 return name;
1100 grp = getgrgid(gid);
1101 if (grp) return(grp->gr_name);
1102 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1103 return(name);
1106 /*******************************************************************
1107 Convert a user name into a uid. If winbindd is present uses this.
1108 ********************************************************************/
1110 uid_t nametouid(char *name)
1112 struct passwd *pass;
1113 char *p;
1114 uid_t u;
1116 u = (uid_t)strtol(name, &p, 0);
1117 if (p != name) return u;
1119 if (winbind_nametouid(&u, name))
1120 return u;
1122 pass = sys_getpwnam(name);
1123 if (pass) return(pass->pw_uid);
1124 return (uid_t)-1;
1127 /*******************************************************************
1128 Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1129 is present does a shortcut lookup...
1130 ********************************************************************/
1132 gid_t nametogid(char *name)
1134 struct group *grp;
1135 char *p;
1136 gid_t g;
1138 g = (gid_t)strtol(name, &p, 0);
1139 if (p != name) return g;
1141 if (winbind_nametogid(&g, name))
1142 return g;
1144 grp = getgrnam(name);
1145 if (grp) return(grp->gr_gid);
1146 return (gid_t)-1;
1149 /*******************************************************************
1150 something really nasty happened - panic!
1151 ********************************************************************/
1152 void smb_panic(char *why)
1154 char *cmd = lp_panic_action();
1155 if (cmd && *cmd) {
1156 system(cmd);
1158 DEBUG(0,("PANIC: %s\n", why));
1159 dbgflush();
1160 abort();
1164 /*******************************************************************
1165 a readdir wrapper which just returns the file name
1166 ********************************************************************/
1167 char *readdirname(DIR *p)
1169 SMB_STRUCT_DIRENT *ptr;
1170 char *dname;
1172 if (!p) return(NULL);
1174 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1175 if (!ptr) return(NULL);
1177 dname = ptr->d_name;
1179 #ifdef NEXT2
1180 if (telldir(p) < 0) return(NULL);
1181 #endif
1183 #ifdef HAVE_BROKEN_READDIR
1184 /* using /usr/ucb/cc is BAD */
1185 dname = dname - 2;
1186 #endif
1189 static pstring buf;
1190 memcpy(buf, dname, NAMLEN(ptr)+1);
1191 dname = buf;
1194 return(dname);
1197 /*******************************************************************
1198 Utility function used to decide if the last component
1199 of a path matches a (possibly wildcarded) entry in a namelist.
1200 ********************************************************************/
1202 BOOL is_in_path(char *name, name_compare_entry *namelist)
1204 pstring last_component;
1205 char *p;
1207 DEBUG(8, ("is_in_path: %s\n", name));
1209 /* if we have no list it's obviously not in the path */
1210 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
1212 DEBUG(8,("is_in_path: no name list.\n"));
1213 return False;
1216 /* Get the last component of the unix name. */
1217 p = strrchr(name, '/');
1218 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1219 last_component[sizeof(last_component)-1] = '\0';
1221 for(; namelist->name != NULL; namelist++)
1223 if(namelist->is_wild)
1225 if (mask_match(last_component, namelist->name, case_sensitive))
1227 DEBUG(8,("is_in_path: mask match succeeded\n"));
1228 return True;
1231 else
1233 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1234 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1236 DEBUG(8,("is_in_path: match succeeded\n"));
1237 return True;
1241 DEBUG(8,("is_in_path: match not found\n"));
1243 return False;
1246 /*******************************************************************
1247 Strip a '/' separated list into an array of
1248 name_compare_enties structures suitable for
1249 passing to is_in_path(). We do this for
1250 speed so we can pre-parse all the names in the list
1251 and don't do it for each call to is_in_path().
1252 namelist is modified here and is assumed to be
1253 a copy owned by the caller.
1254 We also check if the entry contains a wildcard to
1255 remove a potentially expensive call to mask_match
1256 if possible.
1257 ********************************************************************/
1259 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1261 char *name_end;
1262 char *nameptr = namelist;
1263 int num_entries = 0;
1264 int i;
1266 (*ppname_array) = NULL;
1268 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1269 return;
1271 /* We need to make two passes over the string. The
1272 first to count the number of elements, the second
1273 to split it.
1275 while(*nameptr)
1277 if ( *nameptr == '/' )
1279 /* cope with multiple (useless) /s) */
1280 nameptr++;
1281 continue;
1283 /* find the next / */
1284 name_end = strchr(nameptr, '/');
1286 /* oops - the last check for a / didn't find one. */
1287 if (name_end == NULL)
1288 break;
1290 /* next segment please */
1291 nameptr = name_end + 1;
1292 num_entries++;
1295 if(num_entries == 0)
1296 return;
1298 if(( (*ppname_array) = (name_compare_entry *)malloc(
1299 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1301 DEBUG(0,("set_namearray: malloc fail\n"));
1302 return;
1305 /* Now copy out the names */
1306 nameptr = namelist;
1307 i = 0;
1308 while(*nameptr)
1310 if ( *nameptr == '/' )
1312 /* cope with multiple (useless) /s) */
1313 nameptr++;
1314 continue;
1316 /* find the next / */
1317 if ((name_end = strchr(nameptr, '/')) != NULL)
1319 *name_end = 0;
1322 /* oops - the last check for a / didn't find one. */
1323 if(name_end == NULL)
1324 break;
1326 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1327 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1329 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1330 return;
1333 /* next segment please */
1334 nameptr = name_end + 1;
1335 i++;
1338 (*ppname_array)[i].name = NULL;
1340 return;
1343 /****************************************************************************
1344 routine to free a namearray.
1345 ****************************************************************************/
1347 void free_namearray(name_compare_entry *name_array)
1349 if(name_array == 0)
1350 return;
1352 if(name_array->name != NULL)
1353 free(name_array->name);
1355 free((char *)name_array);
1358 /****************************************************************************
1359 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1360 is dealt with in posix.c
1361 ****************************************************************************/
1363 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1365 SMB_STRUCT_FLOCK lock;
1366 int ret;
1368 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1370 lock.l_type = type;
1371 lock.l_whence = SEEK_SET;
1372 lock.l_start = offset;
1373 lock.l_len = count;
1374 lock.l_pid = 0;
1376 errno = 0;
1378 ret = fcntl(fd,op,&lock);
1380 if (errno != 0)
1381 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1383 /* a lock query */
1384 if (op == SMB_F_GETLK)
1386 if ((ret != -1) &&
1387 (lock.l_type != F_UNLCK) &&
1388 (lock.l_pid != 0) &&
1389 (lock.l_pid != sys_getpid()))
1391 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1392 return(True);
1395 /* it must be not locked or locked by me */
1396 return(False);
1399 /* a lock set or unset */
1400 if (ret == -1)
1402 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1403 (double)offset,(double)count,op,type,strerror(errno)));
1404 return(False);
1407 /* everything went OK */
1408 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1410 return(True);
1413 /*******************************************************************
1414 is the name specified one of my netbios names
1415 returns true is it is equal, false otherwise
1416 ********************************************************************/
1417 BOOL is_myname(char *s)
1419 int n;
1420 BOOL ret = False;
1422 for (n=0; my_netbios_names[n]; n++) {
1423 if (strequal(my_netbios_names[n], s))
1424 ret=True;
1426 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1427 return(ret);
1430 /*******************************************************************
1431 set the horrid remote_arch string based on an enum.
1432 ********************************************************************/
1433 void set_remote_arch(enum remote_arch_types type)
1435 extern fstring remote_arch;
1436 ra_type = type;
1437 switch( type )
1439 case RA_WFWG:
1440 fstrcpy(remote_arch, "WfWg");
1441 return;
1442 case RA_OS2:
1443 fstrcpy(remote_arch, "OS2");
1444 return;
1445 case RA_WIN95:
1446 fstrcpy(remote_arch, "Win95");
1447 return;
1448 case RA_WINNT:
1449 fstrcpy(remote_arch, "WinNT");
1450 return;
1451 case RA_WIN2K:
1452 fstrcpy(remote_arch, "Win2K");
1453 return;
1454 case RA_SAMBA:
1455 fstrcpy(remote_arch,"Samba");
1456 return;
1457 default:
1458 ra_type = RA_UNKNOWN;
1459 fstrcpy(remote_arch, "UNKNOWN");
1460 break;
1464 /*******************************************************************
1465 Get the remote_arch type.
1466 ********************************************************************/
1467 enum remote_arch_types get_remote_arch(void)
1469 return ra_type;
1473 void out_ascii(FILE *f, unsigned char *buf,int len)
1475 int i;
1476 for (i=0;i<len;i++)
1478 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1482 void out_data(FILE *f,char *buf1,int len, int per_line)
1484 unsigned char *buf = (unsigned char *)buf1;
1485 int i=0;
1486 if (len<=0)
1488 return;
1491 fprintf(f, "[%03X] ",i);
1492 for (i=0;i<len;)
1494 fprintf(f, "%02X ",(int)buf[i]);
1495 i++;
1496 if (i%(per_line/2) == 0) fprintf(f, " ");
1497 if (i%per_line == 0)
1499 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1500 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1501 if (i<len) fprintf(f, "[%03X] ",i);
1504 if ((i%per_line) != 0)
1506 int n;
1508 n = per_line - (i%per_line);
1509 fprintf(f, " ");
1510 if (n>(per_line/2)) fprintf(f, " ");
1511 while (n--)
1513 fprintf(f, " ");
1515 n = MIN(per_line/2,i%per_line);
1516 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1517 n = (i%per_line) - n;
1518 if (n>0) out_ascii(f,&buf[i-n],n);
1519 fprintf(f, "\n");
1523 void print_asc(int level, unsigned char *buf,int len)
1525 int i;
1526 for (i=0;i<len;i++)
1527 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1530 void dump_data(int level,char *buf1,int len)
1532 unsigned char *buf = (unsigned char *)buf1;
1533 int i=0;
1534 if (len<=0) return;
1536 DEBUG(level,("[%03X] ",i));
1537 for (i=0;i<len;) {
1538 DEBUG(level,("%02X ",(int)buf[i]));
1539 i++;
1540 if (i%8 == 0) DEBUG(level,(" "));
1541 if (i%16 == 0) {
1542 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1543 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1544 if (i<len) DEBUG(level,("[%03X] ",i));
1547 if (i%16) {
1548 int n;
1550 n = 16 - (i%16);
1551 DEBUG(level,(" "));
1552 if (n>8) DEBUG(level,(" "));
1553 while (n--) DEBUG(level,(" "));
1555 n = MIN(8,i%16);
1556 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1557 n = (i%16) - n;
1558 if (n>0) print_asc(level,&buf[i-n],n);
1559 DEBUG(level,("\n"));
1563 char *tab_depth(int depth)
1565 static pstring spaces;
1566 memset(spaces, ' ', depth * 4);
1567 spaces[depth * 4] = 0;
1568 return spaces;
1571 /*****************************************************************************
1572 * Provide a checksum on a string
1574 * Input: s - the null-terminated character string for which the checksum
1575 * will be calculated.
1577 * Output: The checksum value calculated for s.
1579 * ****************************************************************************
1581 int str_checksum(const char *s)
1583 int res = 0;
1584 int c;
1585 int i=0;
1587 while(*s) {
1588 c = *s;
1589 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1590 s++;
1591 i++;
1593 return(res);
1594 } /* str_checksum */
1598 /*****************************************************************
1599 zero a memory area then free it. Used to catch bugs faster
1600 *****************************************************************/
1601 void zero_free(void *p, size_t size)
1603 memset(p, 0, size);
1604 free(p);
1608 /*****************************************************************
1609 set our open file limit to a requested max and return the limit
1610 *****************************************************************/
1611 int set_maxfiles(int requested_max)
1613 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1614 struct rlimit rlp;
1615 int saved_current_limit;
1617 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1618 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1619 strerror(errno) ));
1620 /* just guess... */
1621 return requested_max;
1625 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1626 * account for the extra fd we need
1627 * as well as the log files and standard
1628 * handles etc. Save the limit we want to set in case
1629 * we are running on an OS that doesn't support this limit (AIX)
1630 * which always returns RLIM_INFINITY for rlp.rlim_max.
1633 /* Try raising the hard (max) limit to the requested amount. */
1635 #if defined(RLIM_INFINITY)
1636 if (rlp.rlim_max != RLIM_INFINITY) {
1637 int orig_max = rlp.rlim_max;
1639 if ( rlp.rlim_max < requested_max )
1640 rlp.rlim_max = requested_max;
1642 /* This failing is not an error - many systems (Linux) don't
1643 support our default request of 10,000 open files. JRA. */
1645 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1646 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1647 (int)rlp.rlim_max, strerror(errno) ));
1649 /* Set failed - restore original value from get. */
1650 rlp.rlim_max = orig_max;
1653 #endif
1655 /* Now try setting the soft (current) limit. */
1657 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1659 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1660 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1661 (int)rlp.rlim_cur, strerror(errno) ));
1662 /* just guess... */
1663 return saved_current_limit;
1666 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1667 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1668 strerror(errno) ));
1669 /* just guess... */
1670 return saved_current_limit;
1673 #if defined(RLIM_INFINITY)
1674 if(rlp.rlim_cur == RLIM_INFINITY)
1675 return saved_current_limit;
1676 #endif
1678 if((int)rlp.rlim_cur > saved_current_limit)
1679 return saved_current_limit;
1681 return rlp.rlim_cur;
1682 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1684 * No way to know - just guess...
1686 return requested_max;
1687 #endif
1690 /*****************************************************************
1691 splits out the start of the key (HKLM or HKU) and the rest of the key
1692 *****************************************************************/
1693 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1695 pstring tmp;
1697 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1699 return False;
1702 (*reg_type) = 0;
1704 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1706 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1708 (*reg_type) = HKEY_LOCAL_MACHINE;
1710 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1712 (*reg_type) = HKEY_USERS;
1714 else
1716 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1717 return False;
1720 if (next_token(NULL, tmp, "\n\r", sizeof(tmp)))
1722 fstrcpy(key_name, tmp);
1724 else
1726 key_name[0] = 0;
1729 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1731 return True;
1735 /*****************************************************************
1736 possibly replace mkstemp if it is broken
1737 *****************************************************************/
1738 int smb_mkstemp(char *template)
1740 #if HAVE_SECURE_MKSTEMP
1741 return mkstemp(template);
1742 #else
1743 /* have a reasonable go at emulating it. Hope that
1744 the system mktemp() isn't completly hopeless */
1745 char *p = mktemp(template);
1746 if (!p) return -1;
1747 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1748 #endif
1751 /*****************************************************************
1752 like strdup but for memory
1753 *****************************************************************/
1754 void *memdup(void *p, size_t size)
1756 void *p2;
1757 if (size == 0) return NULL;
1758 p2 = malloc(size);
1759 if (!p2) return NULL;
1760 memcpy(p2, p, size);
1761 return p2;
1764 /*****************************************************************
1765 get local hostname and cache result
1766 *****************************************************************/
1767 char *myhostname(void)
1769 static pstring ret;
1770 if (ret[0] == 0) {
1771 get_myname(ret);
1773 return ret;
1777 /*****************************************************************
1778 a useful function for returning a path in the Samba lock directory
1779 *****************************************************************/
1780 char *lock_path(char *name)
1782 static pstring fname;
1784 pstrcpy(fname,lp_lockdir());
1785 trim_string(fname,"","/");
1787 if (!directory_exist(fname,NULL)) {
1788 mkdir(fname,0755);
1791 pstrcat(fname,"/");
1792 pstrcat(fname,name);
1794 return fname;
1797 /*******************************************************************
1798 Given a filename - get its directory name
1799 NB: Returned in static storage. Caveats:
1800 o Not safe in thread environment.
1801 o Caller must not free.
1802 o If caller wishes to preserve, they should copy.
1803 ********************************************************************/
1805 char *parent_dirname(const char *path)
1807 static pstring dirpath;
1808 char *p;
1810 if (!path)
1811 return(NULL);
1813 pstrcpy(dirpath, path);
1814 p = strrchr(dirpath, '/'); /* Find final '/', if any */
1815 if (!p) {
1816 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
1817 } else {
1818 if (p == dirpath)
1819 ++p; /* For root "/", leave "/" in place */
1820 *p = '\0';
1822 return dirpath;
1826 /*******************************************************************
1827 determine if a pattern contains any Microsoft wildcard characters
1828 *******************************************************************/
1829 BOOL ms_has_wild(char *s)
1831 char c;
1832 while ((c = *s++)) {
1833 switch (c) {
1834 case '*':
1835 case '?':
1836 case '<':
1837 case '>':
1838 case '"':
1839 return True;
1842 return False;
1845 /*******************************************************************
1846 a wrapper that handles case sensitivity and the special handling
1847 of the ".." name
1848 *******************************************************************/
1849 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1851 fstring p2, s2;
1852 if (strcmp(string,"..") == 0) string = ".";
1853 if (strcmp(pattern,".") == 0) return False;
1855 if (is_case_sensitive) {
1856 return ms_fnmatch(pattern, string) == 0;
1859 fstrcpy(p2, pattern);
1860 fstrcpy(s2, string);
1861 strlower(p2);
1862 strlower(s2);
1863 return ms_fnmatch(p2, s2) == 0;
1868 #ifdef __INSURE__
1870 /*******************************************************************
1871 This routine is a trick to immediately catch errors when debugging
1872 with insure. A xterm with a gdb is popped up when insure catches
1873 a error. It is Linux specific.
1874 ********************************************************************/
1875 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1877 static int (*fn)();
1878 int ret;
1879 char pidstr[10];
1880 pstring cmd = "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";
1882 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
1883 pstring_sub(cmd, "%d", pidstr);
1885 if (!fn) {
1886 static void *h;
1887 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1888 fn = dlsym(h, "_Insure_trap_error");
1891 ret = fn(a1, a2, a3, a4, a5, a6);
1893 system(cmd);
1895 return ret;
1897 #endif