2 Unix SMB/Netbios implementation.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1997
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.
24 #if (defined(NETGROUP) && defined (AUTOMOUNT))
25 #include "rpcsvc/ypclnt.h"
34 int Protocol = PROTOCOL_COREPLUS;
36 /* a default finfo structure to ensure all fields are sensible */
37 file_info def_finfo = {-1,0,0,0,0,0,0,""};
39 /* these are some file handles where debug info will be stored */
42 /* the client file descriptor */
45 /* the last IP received from */
46 struct in_addr lastip;
48 /* the last port received from */
51 /* this is used by the chaining code */
57 case handling on filenames
59 int case_default = CASE_LOWER;
64 /* the following control case operations - they are put here so the
65 client can link easily */
68 BOOL use_mangled_map = False;
69 BOOL short_case_preserve;
72 fstring remote_machine="";
73 fstring local_machine="";
74 fstring remote_arch="UNKNOWN";
75 static enum remote_arch_types ra_type = RA_UNKNOWN;
76 fstring remote_proto="UNKNOWN";
77 pstring myhostname="";
78 pstring user_socket_options="";
80 pstring sesssetup_user="";
81 pstring samlogon_user="";
83 BOOL sam_logon_in_ssb = False;
86 fstring myworkgroup = "";
87 char **my_netbios_names;
89 int smb_read_error = 0;
91 static BOOL stdout_logging = False;
93 static char *filename_dos(char *path,char *buf);
96 /**************************************************************************** **
97 catch a sigusr2 - decrease the debug log level.
98 **************************************************************************** */
101 BlockSignals( True, SIGUSR2);
108 DEBUG( 0, ( "Got SIGUSR2 set debug level to %d.\n", DEBUGLEVEL ) );
110 BlockSignals( False, SIGUSR2);
111 #ifndef DONT_REINSTALL_SIG
112 signal(SIGUSR2, SIGNAL_CAST sig_usr2);
119 /**************************************************************************** **
120 catch a sigusr1 - increase the debug log level.
121 **************************************************************************** */
124 BlockSignals( True, SIGUSR1);
131 DEBUG( 0, ( "Got SIGUSR1 set debug level to %d.\n", DEBUGLEVEL ) );
133 BlockSignals( False, SIGUSR1);
134 #ifndef DONT_REINSTALL_SIG
135 signal(SIGUSR1, SIGNAL_CAST sig_usr1);
142 /*******************************************************************
143 get ready for syslog stuff
144 ******************************************************************/
145 void setup_logging(char *pname,BOOL interactive)
149 char *p = strrchr(pname,'/');
152 openlog(pname, LOG_PID, SYSLOG_FACILITY);
153 #else /* for old systems that have no facility codes. */
154 openlog(pname, LOG_PID);
159 stdout_logging = True;
165 BOOL append_log=False;
168 /****************************************************************************
170 ****************************************************************************/
171 void reopen_logs(void)
178 strcpy(fname,debugf);
179 if (lp_loaded() && (*lp_logfile()))
180 strcpy(fname,lp_logfile());
182 if (!strcsequal(fname,debugf) || !dbf || !file_exist(debugf,NULL))
184 int oldumask = umask(022);
185 strcpy(debugf,fname);
186 if (dbf) fclose(dbf);
188 dbf = fopen(debugf,"a");
190 dbf = fopen(debugf,"w");
191 if (dbf) setbuf(dbf,NULL);
206 /*******************************************************************
207 check if the log has grown too big
208 ********************************************************************/
209 static void check_log_size(void)
211 static int debug_count=0;
215 if (debug_count++ < 100 || getuid() != 0) return;
217 maxlog = lp_max_log_size() * 1024;
218 if (!dbf || maxlog <= 0) return;
220 if (fstat(fileno(dbf),&st) == 0 && st.st_size > maxlog) {
221 fclose(dbf); dbf = NULL;
223 if (dbf && file_size(debugf) > maxlog) {
225 fclose(dbf); dbf = NULL;
226 sprintf(name,"%s.old",debugf);
227 sys_rename(debugf,name);
235 /*******************************************************************
236 write an debug message on the debugfile. This is called by the DEBUG
238 ********************************************************************/
240 int Debug1(char *format_str, ...)
249 int old_errno = errno;
251 if (stdout_logging) {
253 va_start(ap, format_str);
256 format_str = va_arg(ap,char *);
258 vfprintf(dbf,format_str,ap);
265 if (!lp_syslog_only())
269 int oldumask = umask(022);
270 dbf = fopen(debugf,"w");
282 if (syslog_level < lp_syslog())
285 * map debug levels to syslog() priorities
286 * note that not all DEBUG(0, ...) calls are
289 static int priority_map[] = {
298 if (syslog_level >= sizeof(priority_map) / sizeof(priority_map[0]) ||
300 priority = LOG_DEBUG;
302 priority = priority_map[syslog_level];
305 va_start(ap, format_str);
308 format_str = va_arg(ap,char *);
310 vsprintf(msgbuf, format_str, ap);
314 syslog(priority, "%s", msgbuf);
319 if (!lp_syslog_only())
323 va_start(ap, format_str);
326 format_str = va_arg(ap,char *);
328 vfprintf(dbf,format_str,ap);
340 /****************************************************************************
341 find a suitable temporary directory. The result should be copied immediately
342 as it may be overwritten by a subsequent call
343 ****************************************************************************/
347 if ((p = getenv("TMPDIR"))) {
355 /****************************************************************************
356 determine if a file descriptor is in fact a socket
357 ****************************************************************************/
358 BOOL is_a_socket(int fd)
362 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
366 static char *last_ptr=NULL;
368 /****************************************************************************
369 Get the next token from a string, return False if none found
370 handles double-quotes.
371 Based on a routine by GJC@VILLAGE.COM.
372 Extensively modified by Andrew.Tridgell@anu.edu.au
373 ****************************************************************************/
374 BOOL next_token(char **ptr,char *buff,char *sep)
379 if (!ptr) ptr = &last_ptr;
380 if (!ptr) return(False);
384 /* default to simple separators */
385 if (!sep) sep = " \t\n\r";
387 /* find the first non sep char */
388 while(*s && strchr(sep,*s)) s++;
391 if (! *s) return(False);
393 /* copy over the token */
394 for (quoted = False; *s && (quoted || !strchr(sep,*s)); s++)
402 *ptr = (*s) ? s+1 : s;
409 /****************************************************************************
410 Convert list of tokens to array; dependent on above routine.
411 Uses last_ptr from above - bit of a hack.
412 ****************************************************************************/
413 char **toktocliplist(int *ctok, char *sep)
419 if (!sep) sep = " \t\n\r";
421 while(*s && strchr(sep,*s)) s++;
424 if (!*s) return(NULL);
428 while(*s && (!strchr(sep,*s))) s++;
429 while(*s && strchr(sep,*s)) *s++=0;
435 if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
447 /*******************************************************************
448 safely copies memory, ensuring no overlap problems.
449 this is only used if the machine does not have it's own memmove().
450 this is not the fastest algorithm in town, but it will do for our
452 ********************************************************************/
453 void *MemMove(void *dest,void *src,int size)
457 if (dest==src || !size) return(dest);
459 d = (unsigned long)dest;
460 s = (unsigned long)src;
462 if ((d >= (s+size)) || (s >= (d+size))) {
464 memcpy(dest,src,size);
470 /* we can forward copy */
471 if (s-d >= sizeof(int) &&
472 !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
473 /* do it all as words */
474 int *idest = (int *)dest;
475 int *isrc = (int *)src;
477 for (i=0;i<size;i++) idest[i] = isrc[i];
480 char *cdest = (char *)dest;
481 char *csrc = (char *)src;
482 for (i=0;i<size;i++) cdest[i] = csrc[i];
487 /* must backward copy */
488 if (d-s >= sizeof(int) &&
489 !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
490 /* do it all as words */
491 int *idest = (int *)dest;
492 int *isrc = (int *)src;
494 for (i=size-1;i>=0;i--) idest[i] = isrc[i];
497 char *cdest = (char *)dest;
498 char *csrc = (char *)src;
499 for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
507 /****************************************************************************
508 prompte a dptr (to make it recently used)
509 ****************************************************************************/
510 void array_promote(char *array,int elsize,int element)
516 p = (char *)malloc(elsize);
520 DEBUG(5,("Ahh! Can't malloc\n"));
523 memcpy(p,array + element * elsize, elsize);
524 memmove(array + elsize,array,elsize*element);
525 memcpy(array,p,elsize);
529 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
538 } socket_options[] = {
539 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
540 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
541 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
543 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
545 #ifdef IPTOS_LOWDELAY
546 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
548 #ifdef IPTOS_THROUGHPUT
549 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
552 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
555 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
558 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
561 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
564 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
567 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
573 /****************************************************************************
574 set user socket options
575 ****************************************************************************/
576 void set_socket_options(int fd, char *options)
580 while (next_token(&options,tok," \t,"))
585 BOOL got_value = False;
587 if ((p = strchr(tok,'=')))
594 for (i=0;socket_options[i].name;i++)
595 if (strequal(socket_options[i].name,tok))
598 if (!socket_options[i].name)
600 DEBUG(0,("Unknown socket option %s\n",tok));
604 switch (socket_options[i].opttype)
608 ret = setsockopt(fd,socket_options[i].level,
609 socket_options[i].option,(char *)&value,sizeof(int));
614 DEBUG(0,("syntax error - %s does not take a value\n",tok));
617 int on = socket_options[i].value;
618 ret = setsockopt(fd,socket_options[i].level,
619 socket_options[i].option,(char *)&on,sizeof(int));
625 DEBUG(0,("Failed to set socket option %s\n",tok));
631 /****************************************************************************
632 close the socket communication
633 ****************************************************************************/
634 void close_sockets(void )
640 /****************************************************************************
641 determine whether we are in the specified group
642 ****************************************************************************/
643 BOOL in_group(gid_t group, int current_gid, int ngroups, int *groups)
647 if (group == current_gid) return(True);
649 for (i=0;i<ngroups;i++)
650 if (group == groups[i])
656 /****************************************************************************
657 this is a safer strcpy(), meant to prevent core dumps when nasty things happen
658 ****************************************************************************/
659 char *StrCpy(char *dest,char *src)
664 /* I don't want to get lazy with these ... */
666 DEBUG(0,("ERROR: NULL StrCpy() called!\n"));
671 if (!dest) return(NULL);
676 while ((*d++ = *src++)) ;
680 /****************************************************************************
681 line strncpy but always null terminates. Make sure there is room!
682 ****************************************************************************/
683 char *StrnCpy(char *dest,char *src,int n)
686 if (!dest) return(NULL);
691 while (n-- && (*d++ = *src++)) ;
697 /*******************************************************************
698 copy an IP address from one buffer to another
699 ********************************************************************/
700 void putip(void *dest,void *src)
706 /****************************************************************************
707 interpret the weird netbios "name". Return the name type
708 ****************************************************************************/
709 static int name_interpret(char *in,char *out)
712 int len = (*in++) / 2;
716 if (len > 30 || len<1) return(0);
720 if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
724 *out = ((in[0]-'A')<<4) + (in[1]-'A');
732 /* Handle any scope names */
735 *out++ = '.'; /* Scope names are separated by periods */
736 len = *(unsigned char *)in++;
737 StrnCpy(out, in, len);
746 /****************************************************************************
747 mangle a name into netbios format
749 Note: <Out> must be (33 + strlen(scope) + 2) bytes long, at minimum.
750 ****************************************************************************/
751 int name_mangle( char *In, char *Out, char name_type )
759 /* Safely copy the input string, In, into buf[]. */
760 (void)memset( buf, 0, 20 );
764 (void)sprintf( buf, "%-15.15s%c", In, name_type );
766 /* Place the length of the first field into the output buffer. */
770 /* Now convert the name to the rfc1001/1002 format. */
771 for( i = 0; i < 16; i++ )
773 c = toupper( buf[i] );
774 p[i*2] = ( (c >> 4) & 0x000F ) + 'A';
775 p[(i*2)+1] = (c & 0x000F) + 'A';
780 /* Add the scope string. */
781 for( i = 0, len = 0; NULL != scope; i++, len++ )
789 return( name_len(Out) );
801 return( name_len(Out) );
804 /*******************************************************************
805 check if a file exists
806 ********************************************************************/
807 BOOL file_exist(char *fname,struct stat *sbuf)
810 if (!sbuf) sbuf = &st;
812 if (sys_stat(fname,sbuf) != 0)
815 return(S_ISREG(sbuf->st_mode));
818 /*******************************************************************
819 check a files mod time
820 ********************************************************************/
821 time_t file_modtime(char *fname)
825 if (sys_stat(fname,&st) != 0)
831 /*******************************************************************
832 check if a directory exists
833 ********************************************************************/
834 BOOL directory_exist(char *dname,struct stat *st)
841 if (sys_stat(dname,st) != 0)
844 ret = S_ISDIR(st->st_mode);
850 /*******************************************************************
851 returns the size in bytes of the named file
852 ********************************************************************/
853 uint32 file_size(char *file_name)
857 sys_stat(file_name,&buf);
861 /*******************************************************************
862 return a string representing an attribute for a file
863 ********************************************************************/
864 char *attrib_string(int mode)
866 static char attrstr[10];
870 if (mode & aVOLID) strcat(attrstr,"V");
871 if (mode & aDIR) strcat(attrstr,"D");
872 if (mode & aARCH) strcat(attrstr,"A");
873 if (mode & aHIDDEN) strcat(attrstr,"H");
874 if (mode & aSYSTEM) strcat(attrstr,"S");
875 if (mode & aRONLY) strcat(attrstr,"R");
881 /*******************************************************************
882 case insensitive string compararison
883 ********************************************************************/
884 int StrCaseCmp(char *s, char *t)
886 /* compare until we run out of string, either t or s, or find a difference */
887 /* We *must* use toupper rather than tolower here due to the
888 asynchronous upper to lower mapping.
890 #if !defined(KANJI_WIN95_COMPATIBILITY)
891 if(lp_client_code_page() == KANJI_CODEPAGE)
893 /* Win95 treats full width ascii characters as case sensitive. */
898 return toupper (*s) - toupper (*t);
899 else if (is_sj_alph (*s) && is_sj_alph (*t))
901 diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
907 else if (is_shift_jis (*s) && is_shift_jis (*t))
909 diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
912 diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
918 else if (is_shift_jis (*s))
920 else if (is_shift_jis (*t))
924 diff = toupper (*s) - toupper (*t);
933 #endif /* KANJI_WIN95_COMPATIBILITY */
935 while (*s && *t && toupper(*s) == toupper(*t))
941 return(toupper(*s) - toupper(*t));
945 /*******************************************************************
946 case insensitive string compararison, length limited
947 ********************************************************************/
948 int StrnCaseCmp(char *s, char *t, int n)
950 /* compare until we run out of string, either t or s, or chars */
951 /* We *must* use toupper rather than tolower here due to the
952 asynchronous upper to lower mapping.
954 #if !defined(KANJI_WIN95_COMPATIBILITY)
955 if(lp_client_code_page() == KANJI_CODEPAGE)
957 /* Win95 treats full width ascii characters as case sensitive. */
962 return toupper (*s) - toupper (*t);
963 else if (is_sj_alph (*s) && is_sj_alph (*t))
965 diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
972 else if (is_shift_jis (*s) && is_shift_jis (*t))
974 diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
977 diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
984 else if (is_shift_jis (*s))
986 else if (is_shift_jis (*t))
990 diff = toupper (*s) - toupper (*t);
1001 #endif /* KANJI_WIN95_COMPATIBILITY */
1003 while (n && *s && *t && toupper(*s) == toupper(*t))
1010 /* not run out of chars - strings are different lengths */
1012 return(toupper(*s) - toupper(*t));
1014 /* identical up to where we run out of chars,
1015 and strings are same length */
1020 /*******************************************************************
1022 ********************************************************************/
1023 BOOL strequal(char *s1, char *s2)
1025 if (s1 == s2) return(True);
1026 if (!s1 || !s2) return(False);
1028 return(StrCaseCmp(s1,s2)==0);
1031 /*******************************************************************
1032 compare 2 strings up to and including the nth char.
1033 ******************************************************************/
1034 BOOL strnequal(char *s1,char *s2,int n)
1036 if (s1 == s2) return(True);
1037 if (!s1 || !s2 || !n) return(False);
1039 return(StrnCaseCmp(s1,s2,n)==0);
1042 /*******************************************************************
1043 compare 2 strings (case sensitive)
1044 ********************************************************************/
1045 BOOL strcsequal(char *s1,char *s2)
1047 if (s1 == s2) return(True);
1048 if (!s1 || !s2) return(False);
1050 return(strcmp(s1,s2)==0);
1054 /*******************************************************************
1055 convert a string to lower case
1056 ********************************************************************/
1057 void strlower(char *s)
1061 #if !defined(KANJI_WIN95_COMPATIBILITY)
1062 if(lp_client_code_page() == KANJI_CODEPAGE)
1064 /* Win95 treats full width ascii characters as case sensitive. */
1065 if (is_shift_jis (*s))
1067 if (is_sj_upper (s[0], s[1]))
1068 s[1] = sj_tolower2 (s[1]);
1071 else if (is_kana (*s))
1083 #endif /* KANJI_WIN95_COMPATIBILITY */
1092 /*******************************************************************
1093 convert a string to upper case
1094 ********************************************************************/
1095 void strupper(char *s)
1099 #if !defined(KANJI_WIN95_COMPATIBILITY)
1100 if(lp_client_code_page() == KANJI_CODEPAGE)
1102 /* Win95 treats full width ascii characters as case sensitive. */
1103 if (is_shift_jis (*s))
1105 if (is_sj_lower (s[0], s[1]))
1106 s[1] = sj_toupper2 (s[1]);
1109 else if (is_kana (*s))
1121 #endif /* KANJI_WIN95_COMPATIBILITY */
1130 /*******************************************************************
1131 convert a string to "normal" form
1132 ********************************************************************/
1133 void strnorm(char *s)
1135 if (case_default == CASE_UPPER)
1141 /*******************************************************************
1142 check if a string is in "normal" case
1143 ********************************************************************/
1144 BOOL strisnormal(char *s)
1146 if (case_default == CASE_UPPER)
1147 return(!strhaslower(s));
1149 return(!strhasupper(s));
1153 /****************************************************************************
1155 ****************************************************************************/
1156 void string_replace(char *s,char oldc,char newc)
1160 #if !defined(KANJI_WIN95_COMPATIBILITY)
1161 if(lp_client_code_page() == KANJI_CODEPAGE)
1163 /* Win95 treats full width ascii characters as case sensitive. */
1164 if (is_shift_jis (*s))
1166 else if (is_kana (*s))
1176 #endif /* KANJI_WIN95_COMPATIBILITY */
1185 /****************************************************************************
1186 make a file into unix format
1187 ****************************************************************************/
1188 void unix_format(char *fname)
1191 string_replace(fname,'\\','/');
1195 pstrcpy(namecopy,fname);
1197 strcat(fname,namecopy);
1201 /****************************************************************************
1202 make a file into dos format
1203 ****************************************************************************/
1204 void dos_format(char *fname)
1206 string_replace(fname,'/','\\');
1210 /*******************************************************************
1211 show a smb message structure
1212 ********************************************************************/
1213 void show_msg(char *buf)
1218 if (DEBUGLEVEL < 5) return;
1220 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
1222 (int)CVAL(buf,smb_com),
1223 (int)CVAL(buf,smb_rcls),
1224 (int)CVAL(buf,smb_reh),
1225 (int)SVAL(buf,smb_err),
1226 (int)CVAL(buf,smb_flg),
1227 (int)SVAL(buf,smb_flg2)));
1228 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
1229 (int)SVAL(buf,smb_tid),
1230 (int)SVAL(buf,smb_pid),
1231 (int)SVAL(buf,smb_uid),
1232 (int)SVAL(buf,smb_mid),
1233 (int)CVAL(buf,smb_wct)));
1235 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
1236 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
1237 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
1239 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
1240 DEBUG(5,("smb_bcc=%d\n",bcc));
1242 if (DEBUGLEVEL < 10) return;
1244 dump_data(10, smb_buf(buf), MIN(bcc, 512));
1247 /*******************************************************************
1248 return the length of an smb packet
1249 ********************************************************************/
1250 int smb_len(char *buf)
1252 return( PVAL(buf,3) | (PVAL(buf,2)<<8) | ((PVAL(buf,1)&1)<<16) );
1255 /*******************************************************************
1256 set the length of an smb packet
1257 ********************************************************************/
1258 void _smb_setlen(char *buf,int len)
1261 buf[1] = (len&0x10000)>>16;
1262 buf[2] = (len&0xFF00)>>8;
1266 /*******************************************************************
1267 set the length and marker of an smb packet
1268 ********************************************************************/
1269 void smb_setlen(char *buf,int len)
1271 _smb_setlen(buf,len);
1279 /*******************************************************************
1280 setup the word count and byte count for a smb message
1281 ********************************************************************/
1282 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
1285 bzero(buf + smb_size,num_words*2 + num_bytes);
1286 CVAL(buf,smb_wct) = num_words;
1287 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
1288 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
1289 return (smb_size + num_words*2 + num_bytes);
1292 /*******************************************************************
1293 return the number of smb words
1294 ********************************************************************/
1295 int smb_numwords(char *buf)
1297 return (CVAL(buf,smb_wct));
1300 /*******************************************************************
1301 return the size of the smb_buf region of a message
1302 ********************************************************************/
1303 int smb_buflen(char *buf)
1305 return(SVAL(buf,smb_vwv0 + smb_numwords(buf)*2));
1308 /*******************************************************************
1309 return a pointer to the smb_buf data area
1310 ********************************************************************/
1311 int smb_buf_ofs(char *buf)
1313 return (smb_size + CVAL(buf,smb_wct)*2);
1316 /*******************************************************************
1317 return a pointer to the smb_buf data area
1318 ********************************************************************/
1319 char *smb_buf(char *buf)
1321 return (buf + smb_buf_ofs(buf));
1324 /*******************************************************************
1325 return the SMB offset into an SMB buffer
1326 ********************************************************************/
1327 int smb_offset(char *p,char *buf)
1329 return(PTR_DIFF(p,buf+4) + chain_size);
1333 /*******************************************************************
1334 skip past some strings in a buffer
1335 ********************************************************************/
1336 char *skip_string(char *buf,int n)
1339 buf += strlen(buf) + 1;
1343 /*******************************************************************
1344 trim the specified elements off the front and back of a string
1345 ********************************************************************/
1346 BOOL trim_string(char *s,char *front,char *back)
1349 while (front && *front && strncmp(s,front,strlen(front)) == 0)
1355 if (!(*p = p[strlen(front)]))
1360 while (back && *back && strlen(s) >= strlen(back) &&
1361 (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0))
1364 s[strlen(s)-strlen(back)] = 0;
1370 /*******************************************************************
1371 reduce a file name, removing .. elements.
1372 ********************************************************************/
1373 void dos_clean_name(char *s)
1377 DEBUG(3,("dos_clean_name [%s]\n",s));
1379 /* remove any double slashes */
1380 string_sub(s, "\\\\", "\\");
1382 while ((p = strstr(s,"\\..\\")) != NULL)
1389 if ((p=strrchr(s,'\\')) != NULL)
1396 trim_string(s,NULL,"\\..");
1398 string_sub(s, "\\.\\", "\\");
1401 /*******************************************************************
1402 reduce a file name, removing .. elements.
1403 ********************************************************************/
1404 void unix_clean_name(char *s)
1408 DEBUG(3,("unix_clean_name [%s]\n",s));
1410 /* remove any double slashes */
1411 string_sub(s, "//","/");
1413 /* Remove leading ./ characters */
1414 if(strncmp(s, "./", 2) == 0) {
1415 trim_string(s, "./", NULL);
1420 while ((p = strstr(s,"/../")) != NULL)
1427 if ((p=strrchr(s,'/')) != NULL)
1434 trim_string(s,NULL,"/..");
1438 /*******************************************************************
1439 a wrapper for the normal chdir() function
1440 ********************************************************************/
1441 int ChDir(char *path)
1444 static pstring LastDir="";
1446 if (strcsequal(path,".")) return(0);
1448 if (*path == '/' && strcsequal(LastDir,path)) return(0);
1449 DEBUG(3,("chdir to %s\n",path));
1450 res = sys_chdir(path);
1452 pstrcpy(LastDir,path);
1456 /* number of list structures for a caching GetWd function. */
1457 #define MAX_GETWDCACHE (50)
1465 } ino_list[MAX_GETWDCACHE];
1467 BOOL use_getwd_cache=True;
1469 /*******************************************************************
1470 return the absolute current directory path
1471 ********************************************************************/
1472 char *GetWd(char *str)
1475 static BOOL getwd_cache_init = False;
1476 struct stat st, st2;
1481 if (!use_getwd_cache)
1482 return(sys_getwd(str));
1484 /* init the cache */
1485 if (!getwd_cache_init)
1487 getwd_cache_init = True;
1488 for (i=0;i<MAX_GETWDCACHE;i++)
1490 string_init(&ino_list[i].text,"");
1491 ino_list[i].valid = False;
1495 /* Get the inode of the current directory, if this doesn't work we're
1498 if (stat(".",&st) == -1)
1500 DEBUG(0,("Very strange, couldn't stat \".\"\n"));
1501 return(sys_getwd(str));
1505 for (i=0; i<MAX_GETWDCACHE; i++)
1506 if (ino_list[i].valid)
1509 /* If we have found an entry with a matching inode and dev number
1510 then find the inode number for the directory in the cached string.
1511 If this agrees with that returned by the stat for the current
1512 directory then all is o.k. (but make sure it is a directory all
1515 if (st.st_ino == ino_list[i].inode &&
1516 st.st_dev == ino_list[i].dev)
1518 if (stat(ino_list[i].text,&st2) == 0)
1520 if (st.st_ino == st2.st_ino &&
1521 st.st_dev == st2.st_dev &&
1522 (st2.st_mode & S_IFMT) == S_IFDIR)
1524 strcpy (str, ino_list[i].text);
1526 /* promote it for future use */
1527 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1532 /* If the inode is different then something's changed,
1533 scrub the entry and start from scratch. */
1534 ino_list[i].valid = False;
1541 /* We don't have the information to hand so rely on traditional methods.
1542 The very slow getcwd, which spawns a process on some systems, or the
1543 not quite so bad getwd. */
1547 DEBUG(0,("Getwd failed, errno %s\n",strerror(errno)));
1553 DEBUG(5,("GetWd %s, inode %d, dev %x\n",s,(int)st.st_ino,(int)st.st_dev));
1555 /* add it to the cache */
1556 i = MAX_GETWDCACHE - 1;
1557 string_set(&ino_list[i].text,s);
1558 ino_list[i].dev = st.st_dev;
1559 ino_list[i].inode = st.st_ino;
1560 ino_list[i].valid = True;
1562 /* put it at the top of the list */
1563 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1570 /*******************************************************************
1571 reduce a file name, removing .. elements and checking that
1572 it is below dir in the heirachy. This uses GetWd() and so must be run
1573 on the system that has the referenced file system.
1575 widelinks are allowed if widelinks is true
1576 ********************************************************************/
1577 BOOL reduce_name(char *s,char *dir,BOOL widelinks)
1579 #ifndef REDUCE_PATHS
1587 BOOL relative = (*s != '/');
1589 *dir2 = *wd = *basename = *newname = 0;
1594 /* can't have a leading .. */
1595 if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
1597 DEBUG(3,("Illegal file name? (%s)\n",s));
1607 DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
1609 /* remove any double slashes */
1610 string_sub(s,"//","/");
1612 pstrcpy(basename,s);
1613 p = strrchr(basename,'/');
1620 DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
1624 if (ChDir(dir) != 0)
1626 DEBUG(0,("couldn't chdir to %s\n",dir));
1632 DEBUG(0,("couldn't getwd for %s\n",dir));
1638 if (p && (p != basename))
1641 if (strcmp(p+1,".")==0)
1643 if (strcmp(p+1,"..")==0)
1647 if (ChDir(basename) != 0)
1650 DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,basename));
1654 if (!GetWd(newname))
1657 DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
1661 if (p && (p != basename))
1663 strcat(newname,"/");
1664 strcat(newname,p+1);
1668 int l = strlen(dir2);
1669 if (dir2[l-1] == '/')
1672 if (strncmp(newname,dir2,l) != 0)
1675 DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,l));
1681 if (newname[l] == '/')
1682 pstrcpy(s,newname + l + 1);
1684 pstrcpy(s,newname+l);
1695 DEBUG(3,("reduced to %s\n",s));
1700 /****************************************************************************
1702 ****************************************************************************/
1703 static void expand_one(char *Mask,int len)
1706 while ((p1 = strchr(Mask,'*')) != NULL)
1708 int lfill = (len+1) - strlen(Mask);
1709 int l1= (p1 - Mask);
1712 memset(tmp+l1,'?',lfill);
1713 pstrcpy(tmp + l1 + lfill,Mask + l1 + 1);
1718 /****************************************************************************
1719 expand a wildcard expression, replacing *s with ?s
1720 ****************************************************************************/
1721 void expand_mask(char *Mask,BOOL doext)
1726 BOOL hasdot = False;
1728 BOOL absolute = (*Mask == '\\');
1730 *mbeg = *mext = *dirpart = *filepart = 0;
1732 /* parse the directory and filename */
1733 if (strchr(Mask,'\\'))
1734 dirname_dos(Mask,dirpart);
1736 filename_dos(Mask,filepart);
1738 pstrcpy(mbeg,filepart);
1739 if ((p1 = strchr(mbeg,'.')) != NULL)
1749 if (strlen(mbeg) > 8)
1751 pstrcpy(mext,mbeg + 8);
1757 strcpy(mbeg,"????????");
1758 if ((*mext == 0) && doext && !hasdot)
1761 if (strequal(mbeg,"*") && *mext==0)
1769 pstrcpy(Mask,dirpart);
1770 if (*dirpart || absolute) strcat(Mask,"\\");
1775 DEBUG(6,("Mask expanded to [%s]\n",Mask));
1779 /****************************************************************************
1780 does a string have any uppercase chars in it?
1781 ****************************************************************************/
1782 BOOL strhasupper(char *s)
1786 #if !defined(KANJI_WIN95_COMPATIBILITY)
1787 if(lp_client_code_page() == KANJI_CODEPAGE)
1789 /* Win95 treats full width ascii characters as case sensitive. */
1790 if (is_shift_jis (*s))
1792 else if (is_kana (*s))
1802 #endif /* KANJI_WIN95_COMPATIBILITY */
1812 /****************************************************************************
1813 does a string have any lowercase chars in it?
1814 ****************************************************************************/
1815 BOOL strhaslower(char *s)
1819 #if !defined(KANJI_WIN95_COMPATIBILITY)
1820 if(lp_client_code_page() == KANJI_CODEPAGE)
1822 /* Win95 treats full width ascii characters as case sensitive. */
1823 if (is_shift_jis (*s))
1825 if (is_sj_upper (s[0], s[1]))
1827 if (is_sj_lower (s[0], s[1]))
1831 else if (is_kana (*s))
1843 #endif /* KANJI_WIN95_COMPATIBILITY */
1853 /****************************************************************************
1854 find the number of chars in a string
1855 ****************************************************************************/
1856 int count_chars(char *s,char c)
1860 #if !defined(KANJI_WIN95_COMPATIBILITY)
1861 if(lp_client_code_page() == KANJI_CODEPAGE)
1863 /* Win95 treats full width ascii characters as case sensitive. */
1866 if (is_shift_jis (*s))
1877 #endif /* KANJI_WIN95_COMPATIBILITY */
1890 /****************************************************************************
1892 ****************************************************************************/
1893 void make_dir_struct(char *buf,char *mask,char *fname,unsigned int size,int mode,time_t date)
1898 pstrcpy(mask2,mask);
1900 if ((mode & aDIR) != 0)
1903 memset(buf+1,' ',11);
1904 if ((p = strchr(mask2,'.')) != NULL)
1907 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
1908 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
1912 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
1914 bzero(buf+21,DIR_STRUCT_SIZE-21);
1915 CVAL(buf,21) = mode;
1916 put_dos_date(buf,22,date);
1917 SSVAL(buf,26,size & 0xFFFF);
1918 SSVAL(buf,28,size >> 16);
1919 StrnCpy(buf+30,fname,12);
1920 if (!case_sensitive)
1922 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
1926 /*******************************************************************
1927 close the low 3 fd's and open dev/null in their place
1928 ********************************************************************/
1929 void close_low_fds(void)
1933 close(0); close(1); close(2);
1934 /* try and use up these file descriptors, so silly
1935 library routines writing to stdout etc won't cause havoc */
1937 fd = open("/dev/null",O_RDWR,0);
1938 if (fd < 0) fd = open("/dev/null",O_WRONLY,0);
1940 DEBUG(0,("Can't open /dev/null\n"));
1944 DEBUG(0,("Didn't get file descriptor %d\n",i));
1950 /****************************************************************************
1951 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
1953 if SYSV use O_NDELAY
1955 ****************************************************************************/
1956 int set_blocking(int fd, BOOL set)
1960 #define FLAG_TO_SET O_NONBLOCK
1963 #define FLAG_TO_SET O_NDELAY
1965 #define FLAG_TO_SET FNDELAY
1969 if((val = fcntl(fd, F_GETFL, 0)) == -1)
1971 if(set) /* Turn blocking on - ie. clear nonblock flag */
1972 val &= ~FLAG_TO_SET;
1975 return fcntl( fd, F_SETFL, val);
1980 /****************************************************************************
1982 ****************************************************************************/
1983 int write_socket(int fd,char *buf,int len)
1989 DEBUG(6,("write_socket(%d,%d)\n",fd,len));
1990 ret = write_data(fd,buf,len);
1992 DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,len,ret));
1996 /****************************************************************************
1998 ****************************************************************************/
1999 int read_udp_socket(int fd,char *buf,int len)
2002 struct sockaddr sock;
2005 socklen = sizeof(sock);
2006 bzero((char *)&sock,socklen);
2007 bzero((char *)&lastip,sizeof(lastip));
2008 ret = recvfrom(fd,buf,len,0,&sock,&socklen);
2010 DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
2014 lastip = *(struct in_addr *) &sock.sa_data[2];
2015 lastport = ntohs(((struct sockaddr_in *)&sock)->sin_port);
2017 DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
2018 inet_ntoa(lastip), lastport, ret));
2023 /****************************************************************************
2024 read data from a device with a timout in msec.
2025 mincount = if timeout, minimum to read before returning
2026 maxcount = number to be read.
2027 ****************************************************************************/
2028 int read_with_timeout(int fd,char *buf,int mincnt,int maxcnt,long time_out)
2034 struct timeval timeout;
2036 /* just checking .... */
2037 if (maxcnt <= 0) return(0);
2042 if (time_out <= 0) {
2043 if (mincnt == 0) mincnt = maxcnt;
2045 while (nread < mincnt) {
2046 readret = read(fd, buf + nread, maxcnt - nread);
2048 smb_read_error = READ_EOF;
2052 if (readret == -1) {
2053 smb_read_error = READ_ERROR;
2061 /* Most difficult - timeout read */
2062 /* If this is ever called on a disk file and
2063 mincnt is greater then the filesize then
2064 system performance will suffer severely as
2065 select always return true on disk files */
2067 /* Set initial timeout */
2068 timeout.tv_sec = time_out / 1000;
2069 timeout.tv_usec = 1000 * (time_out % 1000);
2071 for (nread=0; nread<mincnt; )
2076 selrtn = sys_select(&fds,&timeout);
2078 /* Check if error */
2080 /* something is wrong. Maybe the socket is dead? */
2081 smb_read_error = READ_ERROR;
2085 /* Did we timeout ? */
2087 smb_read_error = READ_TIMEOUT;
2091 readret = read(fd, buf+nread, maxcnt-nread);
2093 /* we got EOF on the file descriptor */
2094 smb_read_error = READ_EOF;
2098 if (readret == -1) {
2099 /* the descriptor is probably dead */
2100 smb_read_error = READ_ERROR;
2107 /* Return the number we got */
2111 /****************************************************************************
2112 read data from the client. Maxtime is in milliseconds
2113 ****************************************************************************/
2114 int read_max_udp(int fd,char *buffer,int bufsize,int maxtime)
2119 struct timeval timeout;
2124 timeout.tv_sec = maxtime / 1000;
2125 timeout.tv_usec = (maxtime % 1000) * 1000;
2127 selrtn = sys_select(&fds,maxtime>0?&timeout:NULL);
2129 if (!FD_ISSET(fd,&fds))
2132 nread = read_udp_socket(fd, buffer, bufsize);
2134 /* return the number got */
2138 /*******************************************************************
2139 find the difference in milliseconds between two struct timeval
2141 ********************************************************************/
2142 int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
2144 return((tvalnew->tv_sec - tvalold->tv_sec)*1000 +
2145 ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);
2148 /****************************************************************************
2149 send a keepalive packet (rfc1002)
2150 ****************************************************************************/
2151 BOOL send_keepalive(int client)
2153 unsigned char buf[4];
2156 buf[1] = buf[2] = buf[3] = 0;
2158 return(write_data(client,(char *)buf,4) == 4);
2163 /****************************************************************************
2164 read data from the client, reading exactly N bytes.
2165 ****************************************************************************/
2166 int read_data(int fd,char *buffer,int N)
2175 ret = read(fd,buffer + total,N - total);
2177 smb_read_error = READ_EOF;
2181 smb_read_error = READ_ERROR;
2190 /****************************************************************************
2192 ****************************************************************************/
2193 int write_data(int fd,char *buffer,int N)
2200 ret = write(fd,buffer + total,N - total);
2202 if (ret == -1) return -1;
2203 if (ret == 0) return total;
2211 /****************************************************************************
2212 transfer some data between two fd's
2213 ****************************************************************************/
2214 int transfer_file(int infd,int outfd,int n,char *header,int headlen,int align)
2216 static char *buf=NULL;
2221 DEBUG(4,("transfer_file %d (head=%d) called\n",n,headlen));
2224 size = lp_readsize();
2225 size = MAX(size,1024);
2228 while (!buf && size>0) {
2229 buf = (char *)Realloc(buf,size+8);
2230 if (!buf) size /= 2;
2234 DEBUG(0,("Can't allocate transfer buffer!\n"));
2238 abuf = buf + (align%8);
2245 int s = MIN(n,size);
2250 if (header && (headlen >= MIN(s,1024))) {
2260 if (header && headlen > 0)
2262 ret = MIN(headlen,size);
2263 memcpy(buf1,header,ret);
2266 if (headlen <= 0) header = NULL;
2270 ret += read(infd,buf1+ret,s-ret);
2274 ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
2275 if (ret2 > 0) total += ret2;
2276 /* if we can't write then dump excess data */
2278 transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
2280 if (ret <= 0 || ret2 != ret)
2288 /****************************************************************************
2289 read 4 bytes of a smb packet and return the smb length of the packet
2290 store the result in the buffer
2291 This version of the function will return a length of zero on receiving
2293 ****************************************************************************/
2294 static int read_smb_length_return_keepalive(int fd,char *inbuf,int timeout)
2296 int len=0, msg_type;
2302 ok = (read_with_timeout(fd,inbuf,4,4,timeout) == 4);
2304 ok = (read_data(fd,inbuf,4) == 4);
2309 len = smb_len(inbuf);
2310 msg_type = CVAL(inbuf,0);
2312 if (msg_type == 0x85)
2313 DEBUG(5,("Got keepalive packet\n"));
2316 DEBUG(10,("got smb length of %d\n",len));
2321 /****************************************************************************
2322 read 4 bytes of a smb packet and return the smb length of the packet
2323 store the result in the buffer. This version of the function will
2324 never return a session keepalive (length of zero).
2325 ****************************************************************************/
2326 int read_smb_length(int fd,char *inbuf,int timeout)
2332 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
2337 /* Ignore session keepalives. */
2338 if(CVAL(inbuf,0) != 0x85)
2345 /****************************************************************************
2346 read an smb from a fd. Note that the buffer *MUST* be of size
2347 BUFFER_SIZE+SAFETY_MARGIN.
2348 The timeout is in milli seconds.
2350 This function will return on a
2351 receipt of a session keepalive packet.
2352 ****************************************************************************/
2353 BOOL receive_smb(int fd,char *buffer, int timeout)
2359 bzero(buffer,smb_size + 100);
2361 len = read_smb_length_return_keepalive(fd,buffer,timeout);
2365 if (len > BUFFER_SIZE) {
2366 DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
2367 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
2372 ret = read_data(fd,buffer+4,len);
2374 smb_read_error = READ_ERROR;
2381 /****************************************************************************
2382 read an smb from a fd ignoring all keepalive packets. Note that the buffer
2383 *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
2384 The timeout is in milli seconds
2386 This is exactly the same as receive_smb except that it never returns
2387 a session keepalive packet (just as receive_smb used to do).
2388 receive_smb was changed to return keepalives as the oplock processing means this call
2389 should never go into a blocking read.
2390 ****************************************************************************/
2392 BOOL client_receive_smb(int fd,char *buffer, int timeout)
2398 ret = receive_smb(fd, buffer, timeout);
2403 /* Ignore session keepalive packets. */
2404 if(CVAL(buffer,0) != 0x85)
2410 /****************************************************************************
2411 read a message from a udp fd.
2412 The timeout is in milli seconds
2413 ****************************************************************************/
2414 BOOL receive_local_message(int fd, char *buffer, int buffer_len, int timeout)
2416 struct sockaddr_in from;
2417 int fromlen = sizeof(from);
2429 to.tv_sec = timeout / 1000;
2430 to.tv_usec = (timeout % 1000) * 1000;
2432 selrtn = sys_select(&fds,&to);
2434 /* Check if error */
2437 /* something is wrong. Maybe the socket is dead? */
2438 smb_read_error = READ_ERROR;
2442 /* Did we timeout ? */
2445 smb_read_error = READ_TIMEOUT;
2451 * Read a loopback udp message.
2453 msg_len = recvfrom(fd, &buffer[UDP_CMD_HEADER_LEN],
2454 buffer_len - UDP_CMD_HEADER_LEN, 0,
2455 (struct sockaddr *)&from, &fromlen);
2459 DEBUG(0,("receive_local_message. Error in recvfrom. (%s).\n",strerror(errno)));
2463 /* Validate message length. */
2464 if(msg_len > (buffer_len - UDP_CMD_HEADER_LEN))
2466 DEBUG(0,("receive_local_message: invalid msg_len (%d) max can be %d\n",
2468 buffer_len - UDP_CMD_HEADER_LEN));
2472 /* Validate message from address (must be localhost). */
2473 if(from.sin_addr.s_addr != htonl(INADDR_LOOPBACK))
2475 DEBUG(0,("receive_local_message: invalid 'from' address \
2476 (was %x should be 127.0.0.1\n", from.sin_addr.s_addr));
2480 /* Setup the message header */
2481 SIVAL(buffer,UDP_CMD_LEN_OFFSET,msg_len);
2482 SSVAL(buffer,UDP_CMD_PORT_OFFSET,ntohs(from.sin_port));
2487 /****************************************************************************
2488 structure to hold a linked list of local udp messages.
2490 ****************************************************************************/
2492 typedef struct _udp_message_list {
2493 struct _udp_message_list *msg_next;
2498 static udp_message_list *udp_msg_head = NULL;
2500 /****************************************************************************
2501 Function to push a linked list of local udp messages ready
2503 ****************************************************************************/
2504 BOOL push_local_message(char *buf, int msg_len)
2506 udp_message_list *msg = (udp_message_list *)malloc(sizeof(udp_message_list));
2510 DEBUG(0,("push_local_message: malloc fail (1)\n"));
2514 msg->msg_buf = (char *)malloc(msg_len);
2515 if(msg->msg_buf == NULL)
2517 DEBUG(0,("push_local_message: malloc fail (2)\n"));
2522 memcpy(msg->msg_buf, buf, msg_len);
2523 msg->msg_len = msg_len;
2525 msg->msg_next = udp_msg_head;
2531 /****************************************************************************
2532 Do a select on an two fd's - with timeout.
2534 If a local udp message has been pushed onto the
2535 queue (this can only happen during oplock break
2536 processing) return this first.
2538 If the first smbfd is ready then read an smb from it.
2539 if the second (loopback UDP) fd is ready then read a message
2540 from it and setup the buffer header to identify the length
2542 Returns False on timeout or error.
2545 The timeout is in milli seconds
2546 ****************************************************************************/
2547 BOOL receive_message_or_smb(int smbfd, int oplock_fd,
2548 char *buffer, int buffer_len,
2549 int timeout, BOOL *got_smb)
2558 * Check to see if we already have a message on the udp queue.
2559 * If so - copy and return it.
2564 udp_message_list *msg = udp_msg_head;
2565 memcpy(buffer, msg->msg_buf, MIN(buffer_len, msg->msg_len));
2566 udp_msg_head = msg->msg_next;
2568 /* Free the message we just copied. */
2569 free((char *)msg->msg_buf);
2576 FD_SET(oplock_fd,&fds);
2578 to.tv_sec = timeout / 1000;
2579 to.tv_usec = (timeout % 1000) * 1000;
2581 selrtn = sys_select(&fds,timeout>0?&to:NULL);
2583 /* Check if error */
2585 /* something is wrong. Maybe the socket is dead? */
2586 smb_read_error = READ_ERROR;
2590 /* Did we timeout ? */
2592 smb_read_error = READ_TIMEOUT;
2596 if (FD_ISSET(smbfd,&fds))
2599 return receive_smb(smbfd, buffer, 0);
2603 return receive_local_message(oplock_fd, buffer, buffer_len, 0);
2607 /****************************************************************************
2609 ****************************************************************************/
2610 BOOL send_smb(int fd,char *buffer)
2614 len = smb_len(buffer) + 4;
2616 while (nwritten < len)
2618 ret = write_socket(fd,buffer+nwritten,len - nwritten);
2621 DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
2633 /****************************************************************************
2634 find a pointer to a netbios name
2635 ****************************************************************************/
2636 char *name_ptr(char *buf,int ofs)
2638 unsigned char c = *(unsigned char *)(buf+ofs);
2640 if ((c & 0xC0) == 0xC0)
2644 memcpy(p,buf+ofs,2);
2647 DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
2654 /****************************************************************************
2655 extract a netbios name from a buf
2656 ****************************************************************************/
2657 int name_extract(char *buf,int ofs,char *name)
2659 char *p = name_ptr(buf,ofs);
2660 int d = PTR_DIFF(p,buf+ofs);
2662 if (d < -50 || d > 50) return(0);
2663 return(name_interpret(p,name));
2666 /****************************************************************************
2667 return the total storage length of a mangled name
2668 ****************************************************************************/
2669 int name_len( char *s )
2673 /* If the two high bits of the byte are set, return 2. */
2674 if( 0xC0 == (*(unsigned char *)s & 0xC0) )
2677 /* Add up the length bytes. */
2678 for( len = 1; (*s); s += (*s) + 1 )
2686 /****************************************************************************
2687 send a single packet to a port on another machine
2688 ****************************************************************************/
2689 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
2693 struct sockaddr_in sock_out;
2698 /* create a socket to write to */
2699 out_fd = socket(AF_INET, type, 0);
2702 DEBUG(0,("socket failed"));
2706 /* set the address and port */
2707 bzero((char *)&sock_out,sizeof(sock_out));
2708 putip((char *)&sock_out.sin_addr,(char *)&ip);
2709 sock_out.sin_port = htons( port );
2710 sock_out.sin_family = AF_INET;
2713 DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
2714 len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
2717 ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
2720 DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
2721 inet_ntoa(ip),port,strerror(errno)));
2727 /*******************************************************************
2728 sleep for a specified number of milliseconds
2729 ********************************************************************/
2733 struct timeval tval,t1,t2;
2740 tval.tv_sec = (t-tdiff)/1000;
2741 tval.tv_usec = 1000*((t-tdiff)%1000);
2745 sys_select(&fds,&tval);
2748 tdiff = TvalDiff(&t1,&t2);
2752 /****************************************************************************
2753 check if a string is part of a list
2754 ****************************************************************************/
2755 BOOL in_list(char *s,char *list,BOOL casesensitive)
2760 if (!list) return(False);
2762 while (next_token(&p,tok,LIST_SEP))
2764 if (casesensitive) {
2765 if (strcmp(tok,s) == 0)
2768 if (StrCaseCmp(tok,s) == 0)
2775 /* this is used to prevent lots of mallocs of size 1 */
2776 static char *null_string = NULL;
2778 /****************************************************************************
2779 set a string value, allocing the space for the string
2780 ****************************************************************************/
2781 BOOL string_init(char **dest,char *src)
2792 null_string = (char *)malloc(1);
2795 *dest = null_string;
2799 (*dest) = (char *)malloc(l+1);
2800 if ((*dest) == NULL) {
2801 DEBUG(0,("Out of memory in string_init\n"));
2810 /****************************************************************************
2812 ****************************************************************************/
2813 void string_free(char **s)
2815 if (!s || !(*s)) return;
2816 if (*s == null_string)
2822 /****************************************************************************
2823 set a string value, allocing the space for the string, and deallocating any
2825 ****************************************************************************/
2826 BOOL string_set(char **dest,char *src)
2830 return(string_init(dest,src));
2833 /****************************************************************************
2834 substitute a string for a pattern in another string. Make sure there is
2837 This routine looks for pattern in s and replaces it with
2838 insert. It may do multiple replacements.
2840 return True if a substitution was done.
2841 ****************************************************************************/
2842 BOOL string_sub(char *s,char *pattern,char *insert)
2848 if (!insert || !pattern || !s) return(False);
2851 lp = strlen(pattern);
2852 li = strlen(insert);
2854 if (!*pattern) return(False);
2856 while (lp <= ls && (p = strstr(s,pattern)))
2859 memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
2860 memcpy(p,insert,li);
2869 /*********************************************************
2870 * Recursive routine that is called by mask_match.
2871 * Does the actual matching.
2872 *********************************************************/
2873 BOOL do_match(char *str, char *regexp, int case_sig)
2877 for( p = regexp; *p && *str; ) {
2884 /* Look for a character matching
2885 the one after the '*' */
2888 return True; /* Automatic match */
2890 while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
2892 if(do_match(str,p,case_sig))
2906 if(toupper(*str) != toupper(*p))
2916 if (!*p && str[0] == '.' && str[1] == 0)
2919 if (!*str && *p == '?')
2921 while (*p == '?') p++;
2925 if(!*str && (*p == '*' && p[1] == '\0'))
2931 /*********************************************************
2932 * Routine to match a given string with a regexp - uses
2933 * simplified regexp that takes * and ? only. Case can be
2934 * significant or not.
2935 *********************************************************/
2936 BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
2940 fstring ebase,eext,sbase,sext;
2944 /* Make local copies of str and regexp */
2945 StrnCpy(p1,regexp,sizeof(pstring)-1);
2946 StrnCpy(p2,str,sizeof(pstring)-1);
2948 if (!strchr(p2,'.')) {
2953 if (!strchr(p1,'.')) {
2961 string_sub(p1,"*.*","*");
2962 string_sub(p1,".*","*");
2966 /* Remove any *? and ** as they are meaningless */
2967 for(p = p1; *p; p++)
2968 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2969 (void)strcpy( &p[1], &p[2]);
2971 if (strequal(p1,"*")) return(True);
2973 DEBUG(8,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", p2, p1, case_sig));
2979 if ((p=strrchr(p1,'.'))) {
2988 if (!strequal(p2,".") && !strequal(p2,"..") && (p=strrchr(p2,'.'))) {
2998 matched = do_match(sbase,ebase,case_sig) &&
2999 (trans2 || do_match(sext,eext,case_sig));
3001 DEBUG(8,("mask_match returning %d\n", matched));
3008 /****************************************************************************
3009 become a daemon, discarding the controlling terminal
3010 ****************************************************************************/
3011 void become_daemon(void)
3013 #ifndef NO_FORK_DEBUG
3017 /* detach from the terminal */
3020 #else /* USE_SETSID */
3023 int i = open("/dev/tty", O_RDWR);
3026 ioctl(i, (int) TIOCNOTTY, (char *)0);
3030 #endif /* TIOCNOTTY */
3031 #endif /* USE_SETSID */
3032 /* Close fd's 0,1,2. Needed if started by rsh */
3034 #endif /* NO_FORK_DEBUG */
3038 /****************************************************************************
3039 put up a yes/no prompt
3040 ****************************************************************************/
3046 if (!fgets(ans,sizeof(ans)-1,stdin))
3049 if (*ans == 'y' || *ans == 'Y')
3055 /****************************************************************************
3056 read a line from a file with possible \ continuation chars.
3057 Blanks at the start or end of a line are stripped.
3058 The string will be allocated if s2 is NULL
3059 ****************************************************************************/
3060 char *fgets_slash(char *s2,int maxlen,FILE *f)
3065 BOOL start_of_line = True;
3072 maxlen = MIN(maxlen,8);
3073 s = (char *)Realloc(s,maxlen);
3076 if (!s || maxlen < 2) return(NULL);
3080 while (len < maxlen-1)
3088 while (len > 0 && s[len-1] == ' ')
3092 if (len > 0 && s[len-1] == '\\')
3095 start_of_line = True;
3100 if (len <= 0 && !s2)
3102 return(len>0?s:NULL);
3107 start_of_line = False;
3111 if (!s2 && len > maxlen-3)
3114 s = (char *)Realloc(s,maxlen);
3115 if (!s) return(NULL);
3123 /****************************************************************************
3124 set the length of a file from a filedescriptor.
3125 Returns 0 on success, -1 on failure.
3126 ****************************************************************************/
3127 int set_filelen(int fd, long len)
3129 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
3130 extend a file with ftruncate. Provide alternate implementation
3133 #if FTRUNCATE_CAN_EXTEND
3134 return ftruncate(fd, len);
3138 long currpos = lseek(fd, 0L, SEEK_CUR);
3142 /* Do an fstat to see if the file is longer than
3143 the requested size (call ftruncate),
3144 or shorter, in which case seek to len - 1 and write 1
3146 if(fstat(fd, &st)<0)
3150 if (S_ISFIFO(st.st_mode)) return 0;
3153 if(st.st_size == len)
3155 if(st.st_size > len)
3156 return ftruncate(fd, len);
3158 if(lseek(fd, len-1, SEEK_SET) != len -1)
3160 if(write(fd, &c, 1)!=1)
3162 /* Seek to where we were */
3163 lseek(fd, currpos, SEEK_SET);
3169 /****************************************************************************
3170 return the byte checksum of some data
3171 ****************************************************************************/
3172 int byte_checksum(char *buf,int len)
3174 unsigned char *p = (unsigned char *)buf;
3184 /****************************************************************************
3185 this is a version of setbuffer() for those machines that only have setvbuf
3186 ****************************************************************************/
3187 void setbuffer(FILE *f,char *buf,int bufsize)
3189 setvbuf(f,buf,_IOFBF,bufsize);
3194 /****************************************************************************
3195 parse out a directory name from a path name. Assumes dos style filenames.
3196 ****************************************************************************/
3197 char *dirname_dos(char *path,char *buf)
3199 char *p = strrchr(path,'\\');
3214 /****************************************************************************
3215 parse out a filename from a path name. Assumes dos style filenames.
3216 ****************************************************************************/
3217 static char *filename_dos(char *path,char *buf)
3219 char *p = strrchr(path,'\\');
3231 /****************************************************************************
3232 expand a pointer to be a particular size
3233 ****************************************************************************/
3234 void *Realloc(void *p,int size)
3240 DEBUG(5,("Realloc asked for 0 bytes\n"));
3245 ret = (void *)malloc(size);
3247 ret = (void *)realloc(p,size);
3250 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
3256 /****************************************************************************
3258 ****************************************************************************/
3259 char *strdup(char *s)
3262 if (!s) return(NULL);
3263 ret = (char *)malloc(strlen(s)+1);
3264 if (!ret) return(NULL);
3271 /****************************************************************************
3272 Signal handler for SIGPIPE (write on a disconnected socket)
3273 ****************************************************************************/
3276 DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
3280 /****************************************************************************
3281 get my own name and IP
3282 ****************************************************************************/
3283 BOOL get_myname(char *my_name,struct in_addr *ip)
3290 /* get my host name */
3291 if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
3293 DEBUG(0,("gethostname failed\n"));
3298 if ((hp = Get_Hostbyname(hostname)) == 0)
3300 DEBUG(0,( "Get_Hostbyname: Unknown host %s.\n",hostname));
3306 /* split off any parts after an initial . */
3307 char *p = strchr(hostname,'.');
3310 fstrcpy(my_name,hostname);
3314 putip((char *)ip,(char *)hp->h_addr);
3320 /****************************************************************************
3321 true if two IP addresses are equal
3322 ****************************************************************************/
3323 BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
3326 a1 = ntohl(ip1.s_addr);
3327 a2 = ntohl(ip2.s_addr);
3332 /****************************************************************************
3333 open a socket of the specified type, port and address for incoming data
3334 ****************************************************************************/
3335 int open_socket_in(int type, int port, int dlevel,uint32 socket_addr)
3338 struct sockaddr_in sock;
3342 /* get my host name */
3343 if (gethostname(host_name, MAXHOSTNAMELEN) == -1)
3344 { DEBUG(0,("gethostname failed\n")); return -1; }
3347 if ((hp = Get_Hostbyname(host_name)) == 0)
3349 DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",host_name));
3353 bzero((char *)&sock,sizeof(sock));
3354 memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
3355 #if defined(__FreeBSD__) || defined(NETBSD) || defined(__OpenBSD__) /* XXX not the right ifdef */
3356 sock.sin_len = sizeof(sock);
3358 sock.sin_port = htons( port );
3359 sock.sin_family = hp->h_addrtype;
3360 sock.sin_addr.s_addr = socket_addr;
3361 res = socket(hp->h_addrtype, type, 0);
3363 { DEBUG(0,("socket failed\n")); return -1; }
3367 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
3370 /* now we've got a socket - we need to bind it */
3371 if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0)
3374 if (port == SMB_PORT || port == NMB_PORT)
3375 DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
3376 port,inet_ntoa(sock.sin_addr),strerror(errno)));
3379 if (dlevel > 0 && port < 1000)
3382 if (port >= 1000 && port < 9000)
3383 return(open_socket_in(type,port+1,dlevel,socket_addr));
3388 DEBUG(3,("bind succeeded on port %d\n",port));
3394 /****************************************************************************
3395 create an outgoing socket
3396 **************************************************************************/
3397 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
3399 struct sockaddr_in sock_out;
3401 int connect_loop = 250; /* 250 milliseconds */
3402 int loops = (timeout * 1000) / connect_loop;
3404 /* create a socket to write to */
3405 res = socket(PF_INET, type, 0);
3407 { DEBUG(0,("socket error\n")); return -1; }
3409 if (type != SOCK_STREAM) return(res);
3411 bzero((char *)&sock_out,sizeof(sock_out));
3412 putip((char *)&sock_out.sin_addr,(char *)addr);
3414 sock_out.sin_port = htons( port );
3415 sock_out.sin_family = PF_INET;
3417 /* set it non-blocking */
3418 set_blocking(res,False);
3420 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
3422 /* and connect it to the destination */
3424 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
3426 /* Some systems return EAGAIN when they mean EINPROGRESS */
3427 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3428 errno == EAGAIN) && loops--) {
3429 msleep(connect_loop);
3433 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3435 DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
3441 if (ret < 0 && errno == EISCONN) {
3448 DEBUG(1,("error connecting to %s:%d (%s)\n",
3449 inet_ntoa(*addr),port,strerror(errno)));
3453 /* set it blocking again */
3454 set_blocking(res,True);
3460 /****************************************************************************
3461 interpret a protocol description string, with a default
3462 ****************************************************************************/
3463 int interpret_protocol(char *str,int def)
3465 if (strequal(str,"NT1"))
3466 return(PROTOCOL_NT1);
3467 if (strequal(str,"LANMAN2"))
3468 return(PROTOCOL_LANMAN2);
3469 if (strequal(str,"LANMAN1"))
3470 return(PROTOCOL_LANMAN1);
3471 if (strequal(str,"CORE"))
3472 return(PROTOCOL_CORE);
3473 if (strequal(str,"COREPLUS"))
3474 return(PROTOCOL_COREPLUS);
3475 if (strequal(str,"CORE+"))
3476 return(PROTOCOL_COREPLUS);
3478 DEBUG(0,("Unrecognised protocol level %s\n",str));
3483 /****************************************************************************
3484 interpret a security level
3485 ****************************************************************************/
3486 int interpret_security(char *str,int def)
3488 if (strequal(str,"SERVER"))
3490 if (strequal(str,"USER"))
3492 if (strequal(str,"SHARE"))
3495 DEBUG(0,("Unrecognised security level %s\n",str));
3501 /****************************************************************************
3502 interpret an internet address or name into an IP address in 4 byte form
3503 ****************************************************************************/
3504 uint32 interpret_addr(char *str)
3509 BOOL pure_address = True;
3511 if (strcmp(str,"0.0.0.0") == 0) return(0);
3512 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
3514 for (i=0; pure_address && str[i]; i++)
3515 if (!(isdigit(str[i]) || str[i] == '.'))
3516 pure_address = False;
3518 /* if it's in the form of an IP address then get the lib to interpret it */
3520 res = inet_addr(str);
3522 /* otherwise assume it's a network name of some sort and use
3524 if ((hp = Get_Hostbyname(str)) == 0) {
3525 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
3528 if(hp->h_addr == NULL) {
3529 DEBUG(3,("Get_Hostbyname: host address is invalid for host %s.\n",str));
3532 putip((char *)&res,(char *)hp->h_addr);
3535 if (res == (uint32)-1) return(0);
3540 /*******************************************************************
3541 a convenient addition to interpret_addr()
3542 ******************************************************************/
3543 struct in_addr *interpret_addr2(char *str)
3545 static struct in_addr ret;
3546 uint32 a = interpret_addr(str);
3551 /*******************************************************************
3552 check if an IP is the 0.0.0.0
3553 ******************************************************************/
3554 BOOL zero_ip(struct in_addr ip)
3557 putip((char *)&a,(char *)&ip);
3562 /*******************************************************************
3563 matchname - determine if host name matches IP address
3564 ******************************************************************/
3565 static BOOL matchname(char *remotehost,struct in_addr addr)
3570 if ((hp = Get_Hostbyname(remotehost)) == 0) {
3571 DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
3576 * Make sure that gethostbyname() returns the "correct" host name.
3577 * Unfortunately, gethostbyname("localhost") sometimes yields
3578 * "localhost.domain". Since the latter host name comes from the
3579 * local DNS, we just have to trust it (all bets are off if the local
3580 * DNS is perverted). We always check the address list, though.
3583 if (strcasecmp(remotehost, hp->h_name)
3584 && strcasecmp(remotehost, "localhost")) {
3585 DEBUG(0,("host name/name mismatch: %s != %s",
3586 remotehost, hp->h_name));
3590 /* Look up the host address in the address list we just got. */
3591 for (i = 0; hp->h_addr_list[i]; i++) {
3592 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
3597 * The host name does not map to the original host address. Perhaps
3598 * someone has compromised a name server. More likely someone botched
3599 * it, but that could be dangerous, too.
3602 DEBUG(0,("host name/address mismatch: %s != %s",
3603 inet_ntoa(addr), hp->h_name));
3607 /*******************************************************************
3608 Reset the 'done' variables so after a client process is created
3609 from a fork call these calls will be re-done. This should be
3610 expanded if more variables need reseting.
3611 ******************************************************************/
3613 static BOOL global_client_name_done = False;
3614 static BOOL global_client_addr_done = False;
3616 void reset_globals_after_fork()
3618 global_client_name_done = False;
3619 global_client_addr_done = False;
3622 /*******************************************************************
3623 return the DNS name of the client
3624 ******************************************************************/
3625 char *client_name(void)
3629 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3630 int length = sizeof(sa);
3631 static pstring name_buf;
3634 if (global_client_name_done)
3637 strcpy(name_buf,"UNKNOWN");
3643 if (getpeername(Client, &sa, &length) < 0) {
3644 DEBUG(0,("getpeername failed\n"));
3648 /* Look up the remote host name. */
3649 if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
3650 sizeof(sockin->sin_addr),
3652 DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr()));
3653 StrnCpy(name_buf,client_addr(),sizeof(name_buf) - 1);
3655 StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
3656 if (!matchname(name_buf, sockin->sin_addr)) {
3657 DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr()));
3658 strcpy(name_buf,"UNKNOWN");
3661 global_client_name_done = True;
3665 /*******************************************************************
3666 return the IP addr of the client as a string
3667 ******************************************************************/
3668 char *client_addr(void)
3672 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3673 int length = sizeof(sa);
3674 static fstring addr_buf;
3676 if (global_client_addr_done)
3679 strcpy(addr_buf,"0.0.0.0");
3685 if (getpeername(Client, &sa, &length) < 0) {
3686 DEBUG(0,("getpeername failed\n"));
3690 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
3692 global_client_addr_done = True;
3696 char *automount_server(char *user_name)
3698 static pstring server_name;
3700 #if (defined(NETGROUP) && defined (AUTOMOUNT))
3701 int nis_error; /* returned by yp all functions */
3702 char *nis_result; /* yp_match inits this */
3703 int nis_result_len; /* and set this */
3704 char *nis_domain; /* yp_get_default_domain inits this */
3705 char *nis_map = (char *)lp_nis_home_map_name();
3706 int home_server_len;
3708 /* set to default of local machine */
3709 pstrcpy(server_name, local_machine);
3711 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0)
3713 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
3716 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
3718 if ((nis_error = yp_match(nis_domain, nis_map,
3719 user_name, strlen(user_name),
3720 &nis_result, &nis_result_len)) != 0)
3722 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
3725 if (!nis_error && lp_nis_home_map())
3727 home_server_len = strcspn(nis_result,":");
3728 DEBUG(5, ("NIS lookup succeeded. Home server length: %d\n",home_server_len));
3729 if (home_server_len > sizeof(pstring))
3731 home_server_len = sizeof(pstring);
3733 strncpy(server_name, nis_result, home_server_len);
3736 /* use the local machine name instead of the auto-map server */
3737 pstrcpy(server_name, local_machine);
3740 DEBUG(4,("Home server: %s\n", server_name));
3745 /*******************************************************************
3746 sub strings with useful parameters
3747 Rewritten by Stefaan A Eeckels <Stefaan.Eeckels@ecc.lu> and
3748 Paul Rippin <pr3245@nopc.eurostat.cec.be>
3749 ********************************************************************/
3750 void standard_sub_basic(char *str)
3754 struct passwd *pass;
3755 char *username = sam_logon_in_ssb ? samlogon_user : sesssetup_user;
3757 for (s = str ; s && *s && (p = strchr(s,'%')); s = p )
3763 if ((pass = Get_Pwnam(sesssetup_user,False))!=NULL)
3765 string_sub(p,"%G",gidtoname(pass->pw_gid));
3773 case 'N' : string_sub(p,"%N", automount_server(username)); break;
3774 case 'I' : string_sub(p,"%I", client_addr()); break;
3775 case 'L' : string_sub(p,"%L", local_machine); break;
3776 case 'M' : string_sub(p,"%M", client_name()); break;
3777 case 'R' : string_sub(p,"%R", remote_proto); break;
3778 case 'T' : string_sub(p,"%T", timestring()); break;
3779 case 'U' : string_sub(p,"%U", username); break;
3780 case 'a' : string_sub(p,"%a", remote_arch); break;
3783 sprintf(pidstr,"%d",(int)getpid());
3784 string_sub(p,"%d", pidstr);
3787 case 'h' : string_sub(p,"%h", myhostname); break;
3788 case 'm' : string_sub(p,"%m", remote_machine); break;
3789 case 'v' : string_sub(p,"%v", VERSION); break;
3790 case '\0': p++; break; /* don't run off end if last character is % */
3791 default : p+=2; break;
3797 /*******************************************************************
3798 are two IPs on the same subnet?
3799 ********************************************************************/
3800 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
3802 uint32 net1,net2,nmask;
3804 nmask = ntohl(mask.s_addr);
3805 net1 = ntohl(ip1.s_addr);
3806 net2 = ntohl(ip2.s_addr);
3808 return((net1 & nmask) == (net2 & nmask));
3812 /*******************************************************************
3813 write a string in unicoode format
3814 ********************************************************************/
3815 int PutUniCode(char *dst,char *src)
3819 dst[ret++] = src[0];
3828 /****************************************************************************
3829 a wrapper for gethostbyname() that tries with all lower and all upper case
3830 if the initial name fails
3831 ****************************************************************************/
3832 struct hostent *Get_Hostbyname(char *name)
3834 char *name2 = strdup(name);
3835 struct hostent *ret;
3839 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
3843 if (!isalnum(*name2))
3849 ret = sys_gethostbyname(name2);
3856 /* try with all lowercase */
3858 ret = sys_gethostbyname(name2);
3865 /* try with all uppercase */
3867 ret = sys_gethostbyname(name2);
3874 /* nothing works :-( */
3880 /****************************************************************************
3881 check if a process exists. Does this work on all unixes?
3882 ****************************************************************************/
3883 BOOL process_exists(int pid)
3885 return(kill(pid,0) == 0 || errno != ESRCH);
3889 /*******************************************************************
3890 turn a uid into a user name
3891 ********************************************************************/
3892 char *uidtoname(int uid)
3894 static char name[40];
3895 struct passwd *pass = getpwuid(uid);
3896 if (pass) return(pass->pw_name);
3897 sprintf(name,"%d",uid);
3901 /*******************************************************************
3902 turn a gid into a group name
3903 ********************************************************************/
3904 char *gidtoname(int gid)
3906 static char name[40];
3907 struct group *grp = getgrgid(gid);
3908 if (grp) return(grp->gr_name);
3909 sprintf(name,"%d",gid);
3913 /*******************************************************************
3915 ********************************************************************/
3916 void BlockSignals(BOOL block,int signum)
3919 int block_mask = sigmask(signum);
3920 static int oldmask = 0;
3922 oldmask = sigblock(block_mask);
3924 sigsetmask(oldmask);
3925 #elif defined(USE_SIGPROCMASK)
3928 sigaddset(&set,signum);
3929 sigprocmask(block?SIG_BLOCK:SIG_UNBLOCK,&set,NULL);
3934 /*******************************************************************
3935 my own panic function - not suitable for general use
3936 ********************************************************************/
3937 void ajt_panic(void)
3939 system("/usr/bin/X11/xedit -display solen:0 /tmp/ERROR_FAULT");
3944 #define DIRECT direct
3946 #define DIRECT dirent
3949 /*******************************************************************
3950 a readdir wrapper which just returns the file name
3951 also return the inode number if requested
3952 ********************************************************************/
3953 char *readdirname(void *p)
3958 if (!p) return(NULL);
3960 ptr = (struct DIRECT *)readdir(p);
3961 if (!ptr) return(NULL);
3963 dname = ptr->d_name;
3966 if (telldir(p) < 0) return(NULL);
3970 /* this handles a broken compiler setup, causing a mixture
3971 of BSD and SYSV headers and libraries */
3973 static BOOL broken_readdir = False;
3974 if (!broken_readdir && !(*(dname)) && strequal("..",dname-2))
3976 DEBUG(0,("Your readdir() is broken. You have somehow mixed SYSV and BSD headers and libraries\n"));
3977 broken_readdir = True;
3986 pstrcpy(buf, dname);
3987 unix_to_dos(buf, True);
3994 /*******************************************************************
3995 Utility function used to decide if the last component
3996 of a path matches a (possibly wildcarded) entry in a namelist.
3997 ********************************************************************/
3999 BOOL is_in_path(char *name, name_compare_entry *namelist)
4001 pstring last_component;
4004 DEBUG(8, ("is_in_path: %s\n", name));
4006 /* if we have no list it's obviously not in the path */
4007 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
4009 DEBUG(8,("is_in_path: no name list.\n"));
4013 /* Get the last component of the unix name. */
4014 p = strrchr(name, '/');
4015 strncpy(last_component, p ? p : name, sizeof(last_component)-1);
4016 last_component[sizeof(last_component)-1] = '\0';
4018 for(; namelist->name != NULL; namelist++)
4020 if(namelist->is_wild)
4022 /* look for a wildcard match. */
4023 if (mask_match(last_component, namelist->name, case_sensitive, False))
4025 DEBUG(8,("is_in_path: mask match succeeded\n"));
4031 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
4032 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
4034 DEBUG(8,("is_in_path: match succeeded\n"));
4039 DEBUG(8,("is_in_path: match not found\n"));
4044 /*******************************************************************
4045 Strip a '/' separated list into an array of
4046 name_compare_enties structures suitable for
4047 passing to is_in_path(). We do this for
4048 speed so we can pre-parse all the names in the list
4049 and don't do it for each call to is_in_path().
4050 namelist is modified here and is assumed to be
4051 a copy owned by the caller.
4052 We also check if the entry contains a wildcard to
4053 remove a potentially expensive call to mask_match
4055 ********************************************************************/
4057 void set_namearray(name_compare_entry **ppname_array, char *namelist)
4060 char *nameptr = namelist;
4061 int num_entries = 0;
4064 (*ppname_array) = NULL;
4066 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
4069 /* We need to make two passes over the string. The
4070 first to count the number of elements, the second
4075 if ( *nameptr == '/' )
4077 /* cope with multiple (useless) /s) */
4081 /* find the next / */
4082 name_end = strchr(nameptr, '/');
4084 /* oops - the last check for a / didn't find one. */
4085 if (name_end == NULL)
4088 /* next segment please */
4089 nameptr = name_end + 1;
4093 if(num_entries == 0)
4096 if(( (*ppname_array) = (name_compare_entry *)malloc(
4097 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
4099 DEBUG(0,("set_namearray: malloc fail\n"));
4103 /* Now copy out the names */
4108 if ( *nameptr == '/' )
4110 /* cope with multiple (useless) /s) */
4114 /* find the next / */
4115 if ((name_end = strchr(nameptr, '/')) != NULL)
4120 /* oops - the last check for a / didn't find one. */
4121 if(name_end == NULL)
4124 (*ppname_array)[i].is_wild = ((strchr( nameptr, '?')!=NULL) ||
4125 (strchr( nameptr, '*')!=NULL));
4126 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
4128 DEBUG(0,("set_namearray: malloc fail (1)\n"));
4132 /* next segment please */
4133 nameptr = name_end + 1;
4137 (*ppname_array)[i].name = NULL;
4142 /****************************************************************************
4143 routine to free a namearray.
4144 ****************************************************************************/
4146 void free_namearray(name_compare_entry *name_array)
4151 if(name_array->name != NULL)
4152 free(name_array->name);
4154 free((char *)name_array);
4157 /****************************************************************************
4158 routine to do file locking
4159 ****************************************************************************/
4160 BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
4167 uint32 mask = 0xC0000000;
4169 /* make sure the count is reasonable, we might kill the lockd otherwise */
4172 /* the offset is often strange - remove 2 of its bits if either of
4173 the top two bits are set. Shift the top ones by two bits. This
4174 still allows OLE2 apps to operate, but should stop lockd from
4176 if ((offset & mask) != 0)
4177 offset = (offset & ~mask) | ((offset & mask) >> 2);
4179 uint32 mask = ((unsigned)1<<31);
4181 /* interpret negative counts as large numbers */
4185 /* no negative offsets */
4188 /* count + offset must be in range */
4189 while ((offset < 0 || (offset + count < 0)) && mask)
4197 DEBUG(8,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
4200 lock.l_whence = SEEK_SET;
4201 lock.l_start = (int)offset;
4202 lock.l_len = (int)count;
4207 ret = fcntl(fd,op,&lock);
4210 DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
4216 (lock.l_type != F_UNLCK) &&
4217 (lock.l_pid != 0) &&
4218 (lock.l_pid != getpid()))
4220 DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
4224 /* it must be not locked or locked by me */
4228 /* a lock set or unset */
4231 DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
4232 offset,count,op,type,strerror(errno)));
4234 /* perhaps it doesn't support this sort of locking?? */
4235 if (errno == EINVAL)
4237 DEBUG(3,("locking not supported? returning True\n"));
4244 /* everything went OK */
4245 DEBUG(8,("Lock call successful\n"));
4253 /*******************************************************************
4254 lock a file - returning a open file descriptor or -1 on failure
4255 The timeout is in seconds. 0 means no timeout
4256 ********************************************************************/
4257 int file_lock(char *name,int timeout)
4259 int fd = open(name,O_RDWR|O_CREAT,0666);
4261 if (fd < 0) return(-1);
4264 if (timeout) t = time(NULL);
4265 while (!timeout || (time(NULL)-t < timeout)) {
4266 if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);
4267 msleep(LOCK_RETRY_TIMEOUT);
4275 /*******************************************************************
4276 unlock a file locked by file_lock
4277 ********************************************************************/
4278 void file_unlock(int fd)
4282 fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
4287 /*******************************************************************
4288 is the name specified one of my netbios names
4289 returns true is it is equal, false otherwise
4290 ********************************************************************/
4291 BOOL is_myname(char *s)
4296 for (n=0; my_netbios_names[n]; n++) {
4297 if (strequal(my_netbios_names[n], s))
4300 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
4304 /*******************************************************************
4305 set the horrid remote_arch string based on an enum.
4306 ********************************************************************/
4307 void set_remote_arch(enum remote_arch_types type)
4313 strcpy(remote_arch, "WfWg");
4316 strcpy(remote_arch, "OS2");
4319 strcpy(remote_arch, "Win95");
4322 strcpy(remote_arch, "WinNT");
4325 strcpy(remote_arch,"Samba");
4328 ra_type = RA_UNKNOWN;
4329 strcpy(remote_arch, "UNKNOWN");
4334 /*******************************************************************
4335 Get the remote_arch type.
4336 ********************************************************************/
4337 enum remote_arch_types get_remote_arch()
4343 /*******************************************************************
4344 skip past some unicode strings in a buffer
4345 ********************************************************************/
4346 char *skip_unicode_string(char *buf,int n)
4357 /*******************************************************************
4358 Return a ascii version of a unicode string
4359 Hack alert: uses fixed buffer(s) and only handles ascii strings
4360 ********************************************************************/
4362 char *unistrn2(uint16 *buf, int len)
4364 static char lbufs[8][MAXUNI];
4366 char *lbuf = lbufs[nexti];
4369 nexti = (nexti+1)%8;
4371 DEBUG(10, ("unistrn2: "));
4373 for (p = lbuf; *buf && p-lbuf < MAXUNI-2 && len > 0; len--, p++, buf++)
4375 DEBUG(10, ("%4x ", *buf));
4385 /*******************************************************************
4386 Return a ascii version of a unicode string
4387 Hack alert: uses fixed buffer(s) and only handles ascii strings
4388 ********************************************************************/
4390 char *unistr2(uint16 *buf)
4392 static char lbufs[8][MAXUNI];
4394 char *lbuf = lbufs[nexti];
4397 nexti = (nexti+1)%8;
4399 DEBUG(10, ("unistr2: "));
4401 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf++)
4403 DEBUG(10, ("%4x ", *buf));
4413 /*******************************************************************
4414 create a null-terminated unicode string from a null-terminated ascii string.
4415 return number of unicode chars copied, excluding the null character.
4417 only handles ascii strings
4418 ********************************************************************/
4420 int struni2(uint16 *p, char *buf)
4424 if (p == NULL) return 0;
4426 DEBUG(10, ("struni2: "));
4430 for (; *buf && len < MAXUNI-2; len++, p++, buf++)
4432 DEBUG(10, ("%2x ", *buf));
4444 /*******************************************************************
4445 Return a ascii version of a unicode string
4446 Hack alert: uses fixed buffer(s) and only handles ascii strings
4447 ********************************************************************/
4449 char *unistr(char *buf)
4451 static char lbufs[8][MAXUNI];
4453 char *lbuf = lbufs[nexti];
4456 nexti = (nexti+1)%8;
4458 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf += 2)
4466 /*******************************************************************
4467 strncpy for unicode strings
4468 ********************************************************************/
4469 int unistrncpy(char *dst, char *src, int len)
4473 while (*src && len > 0)
4487 /*******************************************************************
4488 strcpy for unicode strings. returns length (in num of wide chars)
4489 ********************************************************************/
4490 int unistrcpy(char *dst, char *src)
4507 /*******************************************************************
4508 safe string copy into a fstring
4509 ********************************************************************/
4510 void fstrcpy(char *dest, char *src)
4512 int maxlength = sizeof(fstring) - 1;
4514 DEBUG(0,("ERROR: NULL dest in fstrcpy\n"));
4523 while (maxlength-- && *src)
4527 DEBUG(0,("ERROR: string overflow by %d in fstrcpy\n",
4532 /*******************************************************************
4533 safe string copy into a pstring
4534 ********************************************************************/
4535 void pstrcpy(char *dest, char *src)
4537 int maxlength = sizeof(pstring) - 1;
4539 DEBUG(0,("ERROR: NULL dest in pstrcpy\n"));
4548 while (maxlength-- && *src)
4552 DEBUG(0,("ERROR: string overflow by %d in pstrcpy\n",
4558 /*******************************************************************
4559 align a pointer to a multiple of 4 bytes
4560 ********************************************************************/
4561 char *align4(char *q, char *base)
4565 q += 4 - ((q - base) & 3);
4570 /*******************************************************************
4571 align a pointer to a multiple of 2 bytes
4572 ********************************************************************/
4573 char *align2(char *q, char *base)
4582 /*******************************************************************
4583 align a pointer to a multiple of align_offset bytes. looks like it
4584 will work for offsets of 0, 2 and 4...
4585 ********************************************************************/
4586 char *align_offset(char *q, char *base, int align_offset_len)
4588 int mod = ((q - base) & (align_offset_len-1));
4589 if (align_offset_len != 0 && mod != 0)
4591 q += align_offset_len - mod;
4596 void print_asc(int level, unsigned char *buf,int len)
4600 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
4603 void dump_data(int level,char *buf1,int len)
4605 unsigned char *buf = (unsigned char *)buf1;
4609 DEBUG(level,("[%03X] ",i));
4611 DEBUG(level,("%02X ",(int)buf[i]));
4613 if (i%8 == 0) DEBUG(level,(" "));
4615 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
4616 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
4617 if (i<len) DEBUG(level,("[%03X] ",i));
4625 if (n>8) DEBUG(level,(" "));
4626 while (n--) DEBUG(level,(" "));
4629 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
4631 if (n>0) print_asc(level,&buf[i-n],n);
4632 DEBUG(level,("\n"));
4636 char *tab_depth(int depth)
4638 static pstring spaces;
4639 memset(spaces, ' ', depth * 4);
4640 spaces[depth * 4] = 0;