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 messages.
2490 ****************************************************************************/
2492 typedef struct _message_list {
2493 struct _message_list *msg_next;
2496 } pending_message_list;
2498 static pending_message_list *smb_msg_head = NULL;
2500 /****************************************************************************
2501 Function to push a linked list of local messages ready
2503 ****************************************************************************/
2505 static BOOL push_local_message(pending_message_list **pml, char *buf, int msg_len)
2507 pending_message_list *msg = (pending_message_list *)
2508 malloc(sizeof(pending_message_list));
2512 DEBUG(0,("push_message: malloc fail (1)\n"));
2516 msg->msg_buf = (char *)malloc(msg_len);
2517 if(msg->msg_buf == NULL)
2519 DEBUG(0,("push_local_message: malloc fail (2)\n"));
2524 memcpy(msg->msg_buf, buf, msg_len);
2525 msg->msg_len = msg_len;
2527 msg->msg_next = *pml;
2533 /****************************************************************************
2534 Function to push a linked list of local smb messages ready
2536 ****************************************************************************/
2538 BOOL push_smb_message(char *buf, int msg_len)
2540 return push_local_message(&smb_msg_head, buf, msg_len);
2543 /****************************************************************************
2544 Do a select on an two fd's - with timeout.
2546 If a local udp message has been pushed onto the
2547 queue (this can only happen during oplock break
2548 processing) return this first.
2550 If a pending smb message has been pushed onto the
2551 queue (this can only happen during oplock break
2552 processing) return this next.
2554 If the first smbfd is ready then read an smb from it.
2555 if the second (loopback UDP) fd is ready then read a message
2556 from it and setup the buffer header to identify the length
2558 Returns False on timeout or error.
2561 The timeout is in milli seconds
2562 ****************************************************************************/
2563 BOOL receive_message_or_smb(int smbfd, int oplock_fd,
2564 char *buffer, int buffer_len,
2565 int timeout, BOOL *got_smb)
2574 * Check to see if we already have a message on the smb queue.
2575 * If so - copy and return it.
2580 pending_message_list *msg = smb_msg_head;
2581 memcpy(buffer, msg->msg_buf, MIN(buffer_len, msg->msg_len));
2582 smb_msg_head = msg->msg_next;
2584 /* Free the message we just copied. */
2585 free((char *)msg->msg_buf);
2589 DEBUG(5,("receive_message_or_smb: returning queued smb message.\n"));
2595 FD_SET(oplock_fd,&fds);
2597 to.tv_sec = timeout / 1000;
2598 to.tv_usec = (timeout % 1000) * 1000;
2600 selrtn = sys_select(&fds,timeout>0?&to:NULL);
2602 /* Check if error */
2604 /* something is wrong. Maybe the socket is dead? */
2605 smb_read_error = READ_ERROR;
2609 /* Did we timeout ? */
2611 smb_read_error = READ_TIMEOUT;
2615 if (FD_ISSET(smbfd,&fds))
2618 return receive_smb(smbfd, buffer, 0);
2622 return receive_local_message(oplock_fd, buffer, buffer_len, 0);
2626 /****************************************************************************
2628 ****************************************************************************/
2629 BOOL send_smb(int fd,char *buffer)
2633 len = smb_len(buffer) + 4;
2635 while (nwritten < len)
2637 ret = write_socket(fd,buffer+nwritten,len - nwritten);
2640 DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
2652 /****************************************************************************
2653 find a pointer to a netbios name
2654 ****************************************************************************/
2655 char *name_ptr(char *buf,int ofs)
2657 unsigned char c = *(unsigned char *)(buf+ofs);
2659 if ((c & 0xC0) == 0xC0)
2663 memcpy(p,buf+ofs,2);
2666 DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
2673 /****************************************************************************
2674 extract a netbios name from a buf
2675 ****************************************************************************/
2676 int name_extract(char *buf,int ofs,char *name)
2678 char *p = name_ptr(buf,ofs);
2679 int d = PTR_DIFF(p,buf+ofs);
2681 if (d < -50 || d > 50) return(0);
2682 return(name_interpret(p,name));
2685 /****************************************************************************
2686 return the total storage length of a mangled name
2687 ****************************************************************************/
2688 int name_len( char *s )
2692 /* If the two high bits of the byte are set, return 2. */
2693 if( 0xC0 == (*(unsigned char *)s & 0xC0) )
2696 /* Add up the length bytes. */
2697 for( len = 1; (*s); s += (*s) + 1 )
2705 /****************************************************************************
2706 send a single packet to a port on another machine
2707 ****************************************************************************/
2708 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
2712 struct sockaddr_in sock_out;
2717 /* create a socket to write to */
2718 out_fd = socket(AF_INET, type, 0);
2721 DEBUG(0,("socket failed"));
2725 /* set the address and port */
2726 bzero((char *)&sock_out,sizeof(sock_out));
2727 putip((char *)&sock_out.sin_addr,(char *)&ip);
2728 sock_out.sin_port = htons( port );
2729 sock_out.sin_family = AF_INET;
2732 DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
2733 len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
2736 ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
2739 DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
2740 inet_ntoa(ip),port,strerror(errno)));
2746 /*******************************************************************
2747 sleep for a specified number of milliseconds
2748 ********************************************************************/
2752 struct timeval tval,t1,t2;
2759 tval.tv_sec = (t-tdiff)/1000;
2760 tval.tv_usec = 1000*((t-tdiff)%1000);
2764 sys_select(&fds,&tval);
2767 tdiff = TvalDiff(&t1,&t2);
2771 /****************************************************************************
2772 check if a string is part of a list
2773 ****************************************************************************/
2774 BOOL in_list(char *s,char *list,BOOL casesensitive)
2779 if (!list) return(False);
2781 while (next_token(&p,tok,LIST_SEP))
2783 if (casesensitive) {
2784 if (strcmp(tok,s) == 0)
2787 if (StrCaseCmp(tok,s) == 0)
2794 /* this is used to prevent lots of mallocs of size 1 */
2795 static char *null_string = NULL;
2797 /****************************************************************************
2798 set a string value, allocing the space for the string
2799 ****************************************************************************/
2800 BOOL string_init(char **dest,char *src)
2811 null_string = (char *)malloc(1);
2814 *dest = null_string;
2818 (*dest) = (char *)malloc(l+1);
2819 if ((*dest) == NULL) {
2820 DEBUG(0,("Out of memory in string_init\n"));
2829 /****************************************************************************
2831 ****************************************************************************/
2832 void string_free(char **s)
2834 if (!s || !(*s)) return;
2835 if (*s == null_string)
2841 /****************************************************************************
2842 set a string value, allocing the space for the string, and deallocating any
2844 ****************************************************************************/
2845 BOOL string_set(char **dest,char *src)
2849 return(string_init(dest,src));
2852 /****************************************************************************
2853 substitute a string for a pattern in another string. Make sure there is
2856 This routine looks for pattern in s and replaces it with
2857 insert. It may do multiple replacements.
2859 return True if a substitution was done.
2860 ****************************************************************************/
2861 BOOL string_sub(char *s,char *pattern,char *insert)
2867 if (!insert || !pattern || !s) return(False);
2870 lp = strlen(pattern);
2871 li = strlen(insert);
2873 if (!*pattern) return(False);
2875 while (lp <= ls && (p = strstr(s,pattern)))
2878 memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
2879 memcpy(p,insert,li);
2888 /*********************************************************
2889 * Recursive routine that is called by mask_match.
2890 * Does the actual matching.
2891 *********************************************************/
2892 BOOL do_match(char *str, char *regexp, int case_sig)
2896 for( p = regexp; *p && *str; ) {
2903 /* Look for a character matching
2904 the one after the '*' */
2907 return True; /* Automatic match */
2909 while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
2911 if(do_match(str,p,case_sig))
2925 if(toupper(*str) != toupper(*p))
2935 if (!*p && str[0] == '.' && str[1] == 0)
2938 if (!*str && *p == '?')
2940 while (*p == '?') p++;
2944 if(!*str && (*p == '*' && p[1] == '\0'))
2950 /*********************************************************
2951 * Routine to match a given string with a regexp - uses
2952 * simplified regexp that takes * and ? only. Case can be
2953 * significant or not.
2954 *********************************************************/
2955 BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
2959 fstring ebase,eext,sbase,sext;
2963 /* Make local copies of str and regexp */
2964 StrnCpy(p1,regexp,sizeof(pstring)-1);
2965 StrnCpy(p2,str,sizeof(pstring)-1);
2967 if (!strchr(p2,'.')) {
2972 if (!strchr(p1,'.')) {
2980 string_sub(p1,"*.*","*");
2981 string_sub(p1,".*","*");
2985 /* Remove any *? and ** as they are meaningless */
2986 for(p = p1; *p; p++)
2987 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2988 (void)strcpy( &p[1], &p[2]);
2990 if (strequal(p1,"*")) return(True);
2992 DEBUG(8,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", p2, p1, case_sig));
2998 if ((p=strrchr(p1,'.'))) {
3007 if (!strequal(p2,".") && !strequal(p2,"..") && (p=strrchr(p2,'.'))) {
3017 matched = do_match(sbase,ebase,case_sig) &&
3018 (trans2 || do_match(sext,eext,case_sig));
3020 DEBUG(8,("mask_match returning %d\n", matched));
3027 /****************************************************************************
3028 become a daemon, discarding the controlling terminal
3029 ****************************************************************************/
3030 void become_daemon(void)
3032 #ifndef NO_FORK_DEBUG
3036 /* detach from the terminal */
3039 #else /* USE_SETSID */
3042 int i = open("/dev/tty", O_RDWR);
3045 ioctl(i, (int) TIOCNOTTY, (char *)0);
3049 #endif /* TIOCNOTTY */
3050 #endif /* USE_SETSID */
3051 /* Close fd's 0,1,2. Needed if started by rsh */
3053 #endif /* NO_FORK_DEBUG */
3057 /****************************************************************************
3058 put up a yes/no prompt
3059 ****************************************************************************/
3065 if (!fgets(ans,sizeof(ans)-1,stdin))
3068 if (*ans == 'y' || *ans == 'Y')
3074 /****************************************************************************
3075 read a line from a file with possible \ continuation chars.
3076 Blanks at the start or end of a line are stripped.
3077 The string will be allocated if s2 is NULL
3078 ****************************************************************************/
3079 char *fgets_slash(char *s2,int maxlen,FILE *f)
3084 BOOL start_of_line = True;
3091 maxlen = MIN(maxlen,8);
3092 s = (char *)Realloc(s,maxlen);
3095 if (!s || maxlen < 2) return(NULL);
3099 while (len < maxlen-1)
3107 while (len > 0 && s[len-1] == ' ')
3111 if (len > 0 && s[len-1] == '\\')
3114 start_of_line = True;
3119 if (len <= 0 && !s2)
3121 return(len>0?s:NULL);
3126 start_of_line = False;
3130 if (!s2 && len > maxlen-3)
3133 s = (char *)Realloc(s,maxlen);
3134 if (!s) return(NULL);
3142 /****************************************************************************
3143 set the length of a file from a filedescriptor.
3144 Returns 0 on success, -1 on failure.
3145 ****************************************************************************/
3146 int set_filelen(int fd, long len)
3148 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
3149 extend a file with ftruncate. Provide alternate implementation
3152 #if FTRUNCATE_CAN_EXTEND
3153 return ftruncate(fd, len);
3157 long currpos = lseek(fd, 0L, SEEK_CUR);
3161 /* Do an fstat to see if the file is longer than
3162 the requested size (call ftruncate),
3163 or shorter, in which case seek to len - 1 and write 1
3165 if(fstat(fd, &st)<0)
3169 if (S_ISFIFO(st.st_mode)) return 0;
3172 if(st.st_size == len)
3174 if(st.st_size > len)
3175 return ftruncate(fd, len);
3177 if(lseek(fd, len-1, SEEK_SET) != len -1)
3179 if(write(fd, &c, 1)!=1)
3181 /* Seek to where we were */
3182 lseek(fd, currpos, SEEK_SET);
3188 /****************************************************************************
3189 return the byte checksum of some data
3190 ****************************************************************************/
3191 int byte_checksum(char *buf,int len)
3193 unsigned char *p = (unsigned char *)buf;
3203 /****************************************************************************
3204 this is a version of setbuffer() for those machines that only have setvbuf
3205 ****************************************************************************/
3206 void setbuffer(FILE *f,char *buf,int bufsize)
3208 setvbuf(f,buf,_IOFBF,bufsize);
3213 /****************************************************************************
3214 parse out a directory name from a path name. Assumes dos style filenames.
3215 ****************************************************************************/
3216 char *dirname_dos(char *path,char *buf)
3218 char *p = strrchr(path,'\\');
3233 /****************************************************************************
3234 parse out a filename from a path name. Assumes dos style filenames.
3235 ****************************************************************************/
3236 static char *filename_dos(char *path,char *buf)
3238 char *p = strrchr(path,'\\');
3250 /****************************************************************************
3251 expand a pointer to be a particular size
3252 ****************************************************************************/
3253 void *Realloc(void *p,int size)
3259 DEBUG(5,("Realloc asked for 0 bytes\n"));
3264 ret = (void *)malloc(size);
3266 ret = (void *)realloc(p,size);
3269 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
3275 /****************************************************************************
3277 ****************************************************************************/
3278 char *strdup(char *s)
3281 if (!s) return(NULL);
3282 ret = (char *)malloc(strlen(s)+1);
3283 if (!ret) return(NULL);
3290 /****************************************************************************
3291 Signal handler for SIGPIPE (write on a disconnected socket)
3292 ****************************************************************************/
3295 DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
3299 /****************************************************************************
3300 get my own name and IP
3301 ****************************************************************************/
3302 BOOL get_myname(char *my_name,struct in_addr *ip)
3309 /* get my host name */
3310 if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
3312 DEBUG(0,("gethostname failed\n"));
3317 if ((hp = Get_Hostbyname(hostname)) == 0)
3319 DEBUG(0,( "Get_Hostbyname: Unknown host %s.\n",hostname));
3325 /* split off any parts after an initial . */
3326 char *p = strchr(hostname,'.');
3329 fstrcpy(my_name,hostname);
3333 putip((char *)ip,(char *)hp->h_addr);
3339 /****************************************************************************
3340 true if two IP addresses are equal
3341 ****************************************************************************/
3342 BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
3345 a1 = ntohl(ip1.s_addr);
3346 a2 = ntohl(ip2.s_addr);
3351 /****************************************************************************
3352 open a socket of the specified type, port and address for incoming data
3353 ****************************************************************************/
3354 int open_socket_in(int type, int port, int dlevel,uint32 socket_addr)
3357 struct sockaddr_in sock;
3361 /* get my host name */
3362 if (gethostname(host_name, MAXHOSTNAMELEN) == -1)
3363 { DEBUG(0,("gethostname failed\n")); return -1; }
3366 if ((hp = Get_Hostbyname(host_name)) == 0)
3368 DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",host_name));
3372 bzero((char *)&sock,sizeof(sock));
3373 memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
3374 #if defined(__FreeBSD__) || defined(NETBSD) || defined(__OpenBSD__) /* XXX not the right ifdef */
3375 sock.sin_len = sizeof(sock);
3377 sock.sin_port = htons( port );
3378 sock.sin_family = hp->h_addrtype;
3379 sock.sin_addr.s_addr = socket_addr;
3380 res = socket(hp->h_addrtype, type, 0);
3382 { DEBUG(0,("socket failed\n")); return -1; }
3386 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
3389 /* now we've got a socket - we need to bind it */
3390 if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0)
3393 if (port == SMB_PORT || port == NMB_PORT)
3394 DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
3395 port,inet_ntoa(sock.sin_addr),strerror(errno)));
3398 if (dlevel > 0 && port < 1000)
3401 if (port >= 1000 && port < 9000)
3402 return(open_socket_in(type,port+1,dlevel,socket_addr));
3407 DEBUG(3,("bind succeeded on port %d\n",port));
3413 /****************************************************************************
3414 create an outgoing socket
3415 **************************************************************************/
3416 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
3418 struct sockaddr_in sock_out;
3420 int connect_loop = 250; /* 250 milliseconds */
3421 int loops = (timeout * 1000) / connect_loop;
3423 /* create a socket to write to */
3424 res = socket(PF_INET, type, 0);
3426 { DEBUG(0,("socket error\n")); return -1; }
3428 if (type != SOCK_STREAM) return(res);
3430 bzero((char *)&sock_out,sizeof(sock_out));
3431 putip((char *)&sock_out.sin_addr,(char *)addr);
3433 sock_out.sin_port = htons( port );
3434 sock_out.sin_family = PF_INET;
3436 /* set it non-blocking */
3437 set_blocking(res,False);
3439 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
3441 /* and connect it to the destination */
3443 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
3445 /* Some systems return EAGAIN when they mean EINPROGRESS */
3446 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3447 errno == EAGAIN) && loops--) {
3448 msleep(connect_loop);
3452 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3454 DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
3460 if (ret < 0 && errno == EISCONN) {
3467 DEBUG(1,("error connecting to %s:%d (%s)\n",
3468 inet_ntoa(*addr),port,strerror(errno)));
3472 /* set it blocking again */
3473 set_blocking(res,True);
3479 /****************************************************************************
3480 interpret a protocol description string, with a default
3481 ****************************************************************************/
3482 int interpret_protocol(char *str,int def)
3484 if (strequal(str,"NT1"))
3485 return(PROTOCOL_NT1);
3486 if (strequal(str,"LANMAN2"))
3487 return(PROTOCOL_LANMAN2);
3488 if (strequal(str,"LANMAN1"))
3489 return(PROTOCOL_LANMAN1);
3490 if (strequal(str,"CORE"))
3491 return(PROTOCOL_CORE);
3492 if (strequal(str,"COREPLUS"))
3493 return(PROTOCOL_COREPLUS);
3494 if (strequal(str,"CORE+"))
3495 return(PROTOCOL_COREPLUS);
3497 DEBUG(0,("Unrecognised protocol level %s\n",str));
3502 /****************************************************************************
3503 interpret a security level
3504 ****************************************************************************/
3505 int interpret_security(char *str,int def)
3507 if (strequal(str,"SERVER"))
3509 if (strequal(str,"USER"))
3511 if (strequal(str,"SHARE"))
3514 DEBUG(0,("Unrecognised security level %s\n",str));
3520 /****************************************************************************
3521 interpret an internet address or name into an IP address in 4 byte form
3522 ****************************************************************************/
3523 uint32 interpret_addr(char *str)
3528 BOOL pure_address = True;
3530 if (strcmp(str,"0.0.0.0") == 0) return(0);
3531 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
3533 for (i=0; pure_address && str[i]; i++)
3534 if (!(isdigit(str[i]) || str[i] == '.'))
3535 pure_address = False;
3537 /* if it's in the form of an IP address then get the lib to interpret it */
3539 res = inet_addr(str);
3541 /* otherwise assume it's a network name of some sort and use
3543 if ((hp = Get_Hostbyname(str)) == 0) {
3544 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
3547 if(hp->h_addr == NULL) {
3548 DEBUG(3,("Get_Hostbyname: host address is invalid for host %s.\n",str));
3551 putip((char *)&res,(char *)hp->h_addr);
3554 if (res == (uint32)-1) return(0);
3559 /*******************************************************************
3560 a convenient addition to interpret_addr()
3561 ******************************************************************/
3562 struct in_addr *interpret_addr2(char *str)
3564 static struct in_addr ret;
3565 uint32 a = interpret_addr(str);
3570 /*******************************************************************
3571 check if an IP is the 0.0.0.0
3572 ******************************************************************/
3573 BOOL zero_ip(struct in_addr ip)
3576 putip((char *)&a,(char *)&ip);
3581 /*******************************************************************
3582 matchname - determine if host name matches IP address
3583 ******************************************************************/
3584 static BOOL matchname(char *remotehost,struct in_addr addr)
3589 if ((hp = Get_Hostbyname(remotehost)) == 0) {
3590 DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
3595 * Make sure that gethostbyname() returns the "correct" host name.
3596 * Unfortunately, gethostbyname("localhost") sometimes yields
3597 * "localhost.domain". Since the latter host name comes from the
3598 * local DNS, we just have to trust it (all bets are off if the local
3599 * DNS is perverted). We always check the address list, though.
3602 if (strcasecmp(remotehost, hp->h_name)
3603 && strcasecmp(remotehost, "localhost")) {
3604 DEBUG(0,("host name/name mismatch: %s != %s",
3605 remotehost, hp->h_name));
3609 /* Look up the host address in the address list we just got. */
3610 for (i = 0; hp->h_addr_list[i]; i++) {
3611 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
3616 * The host name does not map to the original host address. Perhaps
3617 * someone has compromised a name server. More likely someone botched
3618 * it, but that could be dangerous, too.
3621 DEBUG(0,("host name/address mismatch: %s != %s",
3622 inet_ntoa(addr), hp->h_name));
3626 /*******************************************************************
3627 Reset the 'done' variables so after a client process is created
3628 from a fork call these calls will be re-done. This should be
3629 expanded if more variables need reseting.
3630 ******************************************************************/
3632 static BOOL global_client_name_done = False;
3633 static BOOL global_client_addr_done = False;
3635 void reset_globals_after_fork()
3637 global_client_name_done = False;
3638 global_client_addr_done = False;
3641 /*******************************************************************
3642 return the DNS name of the client
3643 ******************************************************************/
3644 char *client_name(void)
3648 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3649 int length = sizeof(sa);
3650 static pstring name_buf;
3653 if (global_client_name_done)
3656 strcpy(name_buf,"UNKNOWN");
3662 if (getpeername(Client, &sa, &length) < 0) {
3663 DEBUG(0,("getpeername failed\n"));
3667 /* Look up the remote host name. */
3668 if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
3669 sizeof(sockin->sin_addr),
3671 DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr()));
3672 StrnCpy(name_buf,client_addr(),sizeof(name_buf) - 1);
3674 StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
3675 if (!matchname(name_buf, sockin->sin_addr)) {
3676 DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr()));
3677 strcpy(name_buf,"UNKNOWN");
3680 global_client_name_done = True;
3684 /*******************************************************************
3685 return the IP addr of the client as a string
3686 ******************************************************************/
3687 char *client_addr(void)
3691 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3692 int length = sizeof(sa);
3693 static fstring addr_buf;
3695 if (global_client_addr_done)
3698 strcpy(addr_buf,"0.0.0.0");
3704 if (getpeername(Client, &sa, &length) < 0) {
3705 DEBUG(0,("getpeername failed\n"));
3709 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
3711 global_client_addr_done = True;
3715 char *automount_server(char *user_name)
3717 static pstring server_name;
3719 #if (defined(NETGROUP) && defined (AUTOMOUNT))
3720 int nis_error; /* returned by yp all functions */
3721 char *nis_result; /* yp_match inits this */
3722 int nis_result_len; /* and set this */
3723 char *nis_domain; /* yp_get_default_domain inits this */
3724 char *nis_map = (char *)lp_nis_home_map_name();
3725 int home_server_len;
3727 /* set to default of local machine */
3728 pstrcpy(server_name, local_machine);
3730 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0)
3732 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
3735 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
3737 if ((nis_error = yp_match(nis_domain, nis_map,
3738 user_name, strlen(user_name),
3739 &nis_result, &nis_result_len)) != 0)
3741 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
3744 if (!nis_error && lp_nis_home_map())
3746 home_server_len = strcspn(nis_result,":");
3747 DEBUG(5, ("NIS lookup succeeded. Home server length: %d\n",home_server_len));
3748 if (home_server_len > sizeof(pstring))
3750 home_server_len = sizeof(pstring);
3752 strncpy(server_name, nis_result, home_server_len);
3753 server_name[home_server_len] = '\0';
3756 /* use the local machine name instead of the auto-map server */
3757 pstrcpy(server_name, local_machine);
3760 DEBUG(4,("Home server: %s\n", server_name));
3765 /*******************************************************************
3766 sub strings with useful parameters
3767 Rewritten by Stefaan A Eeckels <Stefaan.Eeckels@ecc.lu> and
3768 Paul Rippin <pr3245@nopc.eurostat.cec.be>
3769 ********************************************************************/
3770 void standard_sub_basic(char *str)
3774 struct passwd *pass;
3775 char *username = sam_logon_in_ssb ? samlogon_user : sesssetup_user;
3777 for (s = str ; s && *s && (p = strchr(s,'%')); s = p )
3783 if ((pass = Get_Pwnam(sesssetup_user,False))!=NULL)
3785 string_sub(p,"%G",gidtoname(pass->pw_gid));
3793 case 'N' : string_sub(p,"%N", automount_server(username)); break;
3794 case 'I' : string_sub(p,"%I", client_addr()); break;
3795 case 'L' : string_sub(p,"%L", local_machine); break;
3796 case 'M' : string_sub(p,"%M", client_name()); break;
3797 case 'R' : string_sub(p,"%R", remote_proto); break;
3798 case 'T' : string_sub(p,"%T", timestring()); break;
3799 case 'U' : string_sub(p,"%U", username); break;
3800 case 'a' : string_sub(p,"%a", remote_arch); break;
3803 sprintf(pidstr,"%d",(int)getpid());
3804 string_sub(p,"%d", pidstr);
3807 case 'h' : string_sub(p,"%h", myhostname); break;
3808 case 'm' : string_sub(p,"%m", remote_machine); break;
3809 case 'v' : string_sub(p,"%v", VERSION); break;
3810 case '\0': p++; break; /* don't run off end if last character is % */
3811 default : p+=2; break;
3817 /*******************************************************************
3818 are two IPs on the same subnet?
3819 ********************************************************************/
3820 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
3822 uint32 net1,net2,nmask;
3824 nmask = ntohl(mask.s_addr);
3825 net1 = ntohl(ip1.s_addr);
3826 net2 = ntohl(ip2.s_addr);
3828 return((net1 & nmask) == (net2 & nmask));
3832 /*******************************************************************
3833 write a string in unicoode format
3834 ********************************************************************/
3835 int PutUniCode(char *dst,char *src)
3839 dst[ret++] = src[0];
3848 /****************************************************************************
3849 a wrapper for gethostbyname() that tries with all lower and all upper case
3850 if the initial name fails
3851 ****************************************************************************/
3852 struct hostent *Get_Hostbyname(char *name)
3854 char *name2 = strdup(name);
3855 struct hostent *ret;
3859 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
3863 if (!isalnum(*name2))
3869 ret = sys_gethostbyname(name2);
3876 /* try with all lowercase */
3878 ret = sys_gethostbyname(name2);
3885 /* try with all uppercase */
3887 ret = sys_gethostbyname(name2);
3894 /* nothing works :-( */
3900 /****************************************************************************
3901 check if a process exists. Does this work on all unixes?
3902 ****************************************************************************/
3903 BOOL process_exists(int pid)
3905 return(kill(pid,0) == 0 || errno != ESRCH);
3909 /*******************************************************************
3910 turn a uid into a user name
3911 ********************************************************************/
3912 char *uidtoname(int uid)
3914 static char name[40];
3915 struct passwd *pass = getpwuid(uid);
3916 if (pass) return(pass->pw_name);
3917 sprintf(name,"%d",uid);
3921 /*******************************************************************
3922 turn a gid into a group name
3923 ********************************************************************/
3924 char *gidtoname(int gid)
3926 static char name[40];
3927 struct group *grp = getgrgid(gid);
3928 if (grp) return(grp->gr_name);
3929 sprintf(name,"%d",gid);
3933 /*******************************************************************
3935 ********************************************************************/
3936 void BlockSignals(BOOL block,int signum)
3939 int block_mask = sigmask(signum);
3940 static int oldmask = 0;
3942 oldmask = sigblock(block_mask);
3944 sigsetmask(oldmask);
3945 #elif defined(USE_SIGPROCMASK)
3948 sigaddset(&set,signum);
3949 sigprocmask(block?SIG_BLOCK:SIG_UNBLOCK,&set,NULL);
3954 /*******************************************************************
3955 my own panic function - not suitable for general use
3956 ********************************************************************/
3957 void ajt_panic(void)
3959 system("/usr/bin/X11/xedit -display solen:0 /tmp/ERROR_FAULT");
3964 #define DIRECT direct
3966 #define DIRECT dirent
3969 /*******************************************************************
3970 a readdir wrapper which just returns the file name
3971 also return the inode number if requested
3972 ********************************************************************/
3973 char *readdirname(void *p)
3978 if (!p) return(NULL);
3980 ptr = (struct DIRECT *)readdir(p);
3981 if (!ptr) return(NULL);
3983 dname = ptr->d_name;
3986 if (telldir(p) < 0) return(NULL);
3990 /* this handles a broken compiler setup, causing a mixture
3991 of BSD and SYSV headers and libraries */
3993 static BOOL broken_readdir = False;
3994 if (!broken_readdir && !(*(dname)) && strequal("..",dname-2))
3996 DEBUG(0,("Your readdir() is broken. You have somehow mixed SYSV and BSD headers and libraries\n"));
3997 broken_readdir = True;
4006 pstrcpy(buf, dname);
4007 unix_to_dos(buf, True);
4014 /*******************************************************************
4015 Utility function used to decide if the last component
4016 of a path matches a (possibly wildcarded) entry in a namelist.
4017 ********************************************************************/
4019 BOOL is_in_path(char *name, name_compare_entry *namelist)
4021 pstring last_component;
4024 DEBUG(8, ("is_in_path: %s\n", name));
4026 /* if we have no list it's obviously not in the path */
4027 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
4029 DEBUG(8,("is_in_path: no name list.\n"));
4033 /* Get the last component of the unix name. */
4034 p = strrchr(name, '/');
4035 strncpy(last_component, p ? p : name, sizeof(last_component)-1);
4036 last_component[sizeof(last_component)-1] = '\0';
4038 for(; namelist->name != NULL; namelist++)
4040 if(namelist->is_wild)
4042 /* look for a wildcard match. */
4043 if (mask_match(last_component, namelist->name, case_sensitive, False))
4045 DEBUG(8,("is_in_path: mask match succeeded\n"));
4051 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
4052 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
4054 DEBUG(8,("is_in_path: match succeeded\n"));
4059 DEBUG(8,("is_in_path: match not found\n"));
4064 /*******************************************************************
4065 Strip a '/' separated list into an array of
4066 name_compare_enties structures suitable for
4067 passing to is_in_path(). We do this for
4068 speed so we can pre-parse all the names in the list
4069 and don't do it for each call to is_in_path().
4070 namelist is modified here and is assumed to be
4071 a copy owned by the caller.
4072 We also check if the entry contains a wildcard to
4073 remove a potentially expensive call to mask_match
4075 ********************************************************************/
4077 void set_namearray(name_compare_entry **ppname_array, char *namelist)
4080 char *nameptr = namelist;
4081 int num_entries = 0;
4084 (*ppname_array) = NULL;
4086 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
4089 /* We need to make two passes over the string. The
4090 first to count the number of elements, the second
4095 if ( *nameptr == '/' )
4097 /* cope with multiple (useless) /s) */
4101 /* find the next / */
4102 name_end = strchr(nameptr, '/');
4104 /* oops - the last check for a / didn't find one. */
4105 if (name_end == NULL)
4108 /* next segment please */
4109 nameptr = name_end + 1;
4113 if(num_entries == 0)
4116 if(( (*ppname_array) = (name_compare_entry *)malloc(
4117 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
4119 DEBUG(0,("set_namearray: malloc fail\n"));
4123 /* Now copy out the names */
4128 if ( *nameptr == '/' )
4130 /* cope with multiple (useless) /s) */
4134 /* find the next / */
4135 if ((name_end = strchr(nameptr, '/')) != NULL)
4140 /* oops - the last check for a / didn't find one. */
4141 if(name_end == NULL)
4144 (*ppname_array)[i].is_wild = ((strchr( nameptr, '?')!=NULL) ||
4145 (strchr( nameptr, '*')!=NULL));
4146 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
4148 DEBUG(0,("set_namearray: malloc fail (1)\n"));
4152 /* next segment please */
4153 nameptr = name_end + 1;
4157 (*ppname_array)[i].name = NULL;
4162 /****************************************************************************
4163 routine to free a namearray.
4164 ****************************************************************************/
4166 void free_namearray(name_compare_entry *name_array)
4171 if(name_array->name != NULL)
4172 free(name_array->name);
4174 free((char *)name_array);
4177 /****************************************************************************
4178 routine to do file locking
4179 ****************************************************************************/
4180 BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
4187 uint32 mask = 0xC0000000;
4189 /* make sure the count is reasonable, we might kill the lockd otherwise */
4192 /* the offset is often strange - remove 2 of its bits if either of
4193 the top two bits are set. Shift the top ones by two bits. This
4194 still allows OLE2 apps to operate, but should stop lockd from
4196 if ((offset & mask) != 0)
4197 offset = (offset & ~mask) | ((offset & mask) >> 2);
4199 uint32 mask = ((unsigned)1<<31);
4201 /* interpret negative counts as large numbers */
4205 /* no negative offsets */
4208 /* count + offset must be in range */
4209 while ((offset < 0 || (offset + count < 0)) && mask)
4217 DEBUG(8,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
4220 lock.l_whence = SEEK_SET;
4221 lock.l_start = (int)offset;
4222 lock.l_len = (int)count;
4227 ret = fcntl(fd,op,&lock);
4230 DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
4236 (lock.l_type != F_UNLCK) &&
4237 (lock.l_pid != 0) &&
4238 (lock.l_pid != getpid()))
4240 DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
4244 /* it must be not locked or locked by me */
4248 /* a lock set or unset */
4251 DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
4252 offset,count,op,type,strerror(errno)));
4254 /* perhaps it doesn't support this sort of locking?? */
4255 if (errno == EINVAL)
4257 DEBUG(3,("locking not supported? returning True\n"));
4264 /* everything went OK */
4265 DEBUG(8,("Lock call successful\n"));
4273 /*******************************************************************
4274 lock a file - returning a open file descriptor or -1 on failure
4275 The timeout is in seconds. 0 means no timeout
4276 ********************************************************************/
4277 int file_lock(char *name,int timeout)
4279 int fd = open(name,O_RDWR|O_CREAT,0666);
4281 if (fd < 0) return(-1);
4284 if (timeout) t = time(NULL);
4285 while (!timeout || (time(NULL)-t < timeout)) {
4286 if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);
4287 msleep(LOCK_RETRY_TIMEOUT);
4295 /*******************************************************************
4296 unlock a file locked by file_lock
4297 ********************************************************************/
4298 void file_unlock(int fd)
4302 fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
4307 /*******************************************************************
4308 is the name specified one of my netbios names
4309 returns true is it is equal, false otherwise
4310 ********************************************************************/
4311 BOOL is_myname(char *s)
4316 for (n=0; my_netbios_names[n]; n++) {
4317 if (strequal(my_netbios_names[n], s))
4320 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
4324 /*******************************************************************
4325 set the horrid remote_arch string based on an enum.
4326 ********************************************************************/
4327 void set_remote_arch(enum remote_arch_types type)
4333 strcpy(remote_arch, "WfWg");
4336 strcpy(remote_arch, "OS2");
4339 strcpy(remote_arch, "Win95");
4342 strcpy(remote_arch, "WinNT");
4345 strcpy(remote_arch,"Samba");
4348 ra_type = RA_UNKNOWN;
4349 strcpy(remote_arch, "UNKNOWN");
4354 /*******************************************************************
4355 Get the remote_arch type.
4356 ********************************************************************/
4357 enum remote_arch_types get_remote_arch()
4363 /*******************************************************************
4364 skip past some unicode strings in a buffer
4365 ********************************************************************/
4366 char *skip_unicode_string(char *buf,int n)
4377 /*******************************************************************
4378 Return a ascii version of a unicode string
4379 Hack alert: uses fixed buffer(s) and only handles ascii strings
4380 ********************************************************************/
4382 char *unistrn2(uint16 *buf, int len)
4384 static char lbufs[8][MAXUNI];
4386 char *lbuf = lbufs[nexti];
4389 nexti = (nexti+1)%8;
4391 DEBUG(10, ("unistrn2: "));
4393 for (p = lbuf; *buf && p-lbuf < MAXUNI-2 && len > 0; len--, p++, buf++)
4395 DEBUG(10, ("%4x ", *buf));
4405 /*******************************************************************
4406 Return a ascii version of a unicode string
4407 Hack alert: uses fixed buffer(s) and only handles ascii strings
4408 ********************************************************************/
4410 char *unistr2(uint16 *buf)
4412 static char lbufs[8][MAXUNI];
4414 char *lbuf = lbufs[nexti];
4417 nexti = (nexti+1)%8;
4419 DEBUG(10, ("unistr2: "));
4421 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf++)
4423 DEBUG(10, ("%4x ", *buf));
4433 /*******************************************************************
4434 create a null-terminated unicode string from a null-terminated ascii string.
4435 return number of unicode chars copied, excluding the null character.
4437 only handles ascii strings
4438 ********************************************************************/
4440 int struni2(uint16 *p, char *buf)
4444 if (p == NULL) return 0;
4446 DEBUG(10, ("struni2: "));
4450 for (; *buf && len < MAXUNI-2; len++, p++, buf++)
4452 DEBUG(10, ("%2x ", *buf));
4464 /*******************************************************************
4465 Return a ascii version of a unicode string
4466 Hack alert: uses fixed buffer(s) and only handles ascii strings
4467 ********************************************************************/
4469 char *unistr(char *buf)
4471 static char lbufs[8][MAXUNI];
4473 char *lbuf = lbufs[nexti];
4476 nexti = (nexti+1)%8;
4478 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf += 2)
4486 /*******************************************************************
4487 strncpy for unicode strings
4488 ********************************************************************/
4489 int unistrncpy(char *dst, char *src, int len)
4493 while (*src && len > 0)
4507 /*******************************************************************
4508 strcpy for unicode strings. returns length (in num of wide chars)
4509 ********************************************************************/
4510 int unistrcpy(char *dst, char *src)
4527 /*******************************************************************
4528 safe string copy into a fstring
4529 ********************************************************************/
4530 void fstrcpy(char *dest, char *src)
4532 int maxlength = sizeof(fstring) - 1;
4534 DEBUG(0,("ERROR: NULL dest in fstrcpy\n"));
4543 while (maxlength-- && *src)
4547 DEBUG(0,("ERROR: string overflow by %d in fstrcpy\n",
4552 /*******************************************************************
4553 safe string copy into a pstring
4554 ********************************************************************/
4555 void pstrcpy(char *dest, char *src)
4557 int maxlength = sizeof(pstring) - 1;
4559 DEBUG(0,("ERROR: NULL dest in pstrcpy\n"));
4568 while (maxlength-- && *src)
4572 DEBUG(0,("ERROR: string overflow by %d in pstrcpy\n",
4578 /*******************************************************************
4579 align a pointer to a multiple of 4 bytes
4580 ********************************************************************/
4581 char *align4(char *q, char *base)
4585 q += 4 - ((q - base) & 3);
4590 /*******************************************************************
4591 align a pointer to a multiple of 2 bytes
4592 ********************************************************************/
4593 char *align2(char *q, char *base)
4602 /*******************************************************************
4603 align a pointer to a multiple of align_offset bytes. looks like it
4604 will work for offsets of 0, 2 and 4...
4605 ********************************************************************/
4606 char *align_offset(char *q, char *base, int align_offset_len)
4608 int mod = ((q - base) & (align_offset_len-1));
4609 if (align_offset_len != 0 && mod != 0)
4611 q += align_offset_len - mod;
4616 void print_asc(int level, unsigned char *buf,int len)
4620 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
4623 void dump_data(int level,char *buf1,int len)
4625 unsigned char *buf = (unsigned char *)buf1;
4629 DEBUG(level,("[%03X] ",i));
4631 DEBUG(level,("%02X ",(int)buf[i]));
4633 if (i%8 == 0) DEBUG(level,(" "));
4635 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
4636 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
4637 if (i<len) DEBUG(level,("[%03X] ",i));
4645 if (n>8) DEBUG(level,(" "));
4646 while (n--) DEBUG(level,(" "));
4649 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
4651 if (n>0) print_asc(level,&buf[i-n],n);
4652 DEBUG(level,("\n"));
4656 char *tab_depth(int depth)
4658 static pstring spaces;
4659 memset(spaces, ' ', depth * 4);
4660 spaces[depth * 4] = 0;