2 Unix SMB/Netbios implementation.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
26 #include <rpcsvc/nis.h>
28 #include "rpcsvc/ypclnt.h"
34 #undef Realloc /* SSLeay defines this and samba has a function of this name */
45 int Protocol = PROTOCOL_COREPLUS;
47 /* a default finfo structure to ensure all fields are sensible */
48 file_info def_finfo = {-1,0,0,0,0,0,0,""};
50 /* these are some file handles where debug info will be stored */
53 /* the client file descriptor */
56 /* the last IP received from */
57 struct in_addr lastip;
59 /* the last port received from */
62 /* this is used by the chaining code */
68 case handling on filenames
70 int case_default = CASE_LOWER;
75 /* the following control case operations - they are put here so the
76 client can link easily */
79 BOOL use_mangled_map = False;
80 BOOL short_case_preserve;
83 fstring remote_machine="";
84 fstring local_machine="";
85 fstring remote_arch="UNKNOWN";
86 static enum remote_arch_types ra_type = RA_UNKNOWN;
87 fstring remote_proto="UNKNOWN";
88 pstring myhostname="";
89 pstring user_socket_options="";
91 pstring sesssetup_user="";
92 pstring samlogon_user="";
94 BOOL sam_logon_in_ssb = False;
96 pstring global_myname = "";
97 fstring global_myworkgroup = "";
98 char **my_netbios_names;
100 int smb_read_error = 0;
102 static BOOL stdout_logging = False;
104 static char *filename_dos(char *path,char *buf);
107 /******************************************************************************
108 catch a sigusr2 - decrease the debug log level.
109 *****************************************************************************/
112 BlockSignals( True, SIGUSR2);
119 DEBUG( 0, ( "Got SIGUSR2 set debug level to %d.\n", DEBUGLEVEL ) );
121 BlockSignals( False, SIGUSR2);
122 CatchSignal(SIGUSR2, SIGNAL_CAST sig_usr2);
129 /******************************************************************************
130 catch a sigusr1 - increase the debug log level.
131 *****************************************************************************/
134 BlockSignals( True, SIGUSR1);
141 DEBUG( 0, ( "Got SIGUSR1 set debug level to %d.\n", DEBUGLEVEL ) );
143 BlockSignals( False, SIGUSR1);
144 CatchSignal(SIGUSR1, SIGNAL_CAST sig_usr1);
150 /*******************************************************************
151 get ready for syslog stuff
152 ******************************************************************/
153 void setup_logging(char *pname,BOOL interactive)
157 char *p = strrchr(pname,'/');
160 openlog(pname, LOG_PID, SYSLOG_FACILITY);
161 #else /* for old systems that have no facility codes. */
162 openlog(pname, LOG_PID);
167 stdout_logging = True;
173 BOOL append_log=False;
176 /****************************************************************************
178 ****************************************************************************/
179 void reopen_logs(void)
185 pstrcpy(fname,debugf);
186 if (lp_loaded() && (*lp_logfile()))
187 pstrcpy(fname,lp_logfile());
189 if (!strcsequal(fname,debugf) || !dbf || !file_exist(debugf,NULL))
191 int oldumask = umask(022);
192 pstrcpy(debugf,fname);
196 dbf = fopen(debugf,"a");
198 dbf = fopen(debugf,"w");
200 * Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
201 * to fix problem where smbd's that generate less
202 * than 100 messages keep growing the log.
204 force_check_log_size();
220 /*******************************************************************
221 Number of debug messages that have been output.
222 Used to check log size.
223 ********************************************************************/
225 static int debug_count=0;
227 /*******************************************************************
228 Force a check of the log size.
229 ********************************************************************/
231 void force_check_log_size(void)
236 /*******************************************************************
237 Check if the log has grown too big
238 ********************************************************************/
240 static void check_log_size(void)
245 if (debug_count++ < 100 || getuid() != 0)
248 maxlog = lp_max_log_size() * 1024;
249 if (!dbf || maxlog <= 0)
252 if (fstat(fileno(dbf),&st) == 0 && st.st_size > maxlog) {
256 if (dbf && file_size(debugf) > maxlog) {
260 slprintf(name,sizeof(name)-1,"%s.old",debugf);
269 /*******************************************************************
270 write an debug message on the debugfile. This is called by the DEBUG
272 ********************************************************************/
274 int Debug1(char *format_str, ...)
283 int old_errno = errno;
285 if (stdout_logging) {
287 va_start(ap, format_str);
290 format_str = va_arg(ap,char *);
292 vfprintf(dbf,format_str,ap);
299 if (!lp_syslog_only())
303 int oldumask = umask(022);
305 dbf = fopen(debugf,"a");
307 dbf = fopen(debugf,"w");
319 if (syslog_level < lp_syslog())
322 * map debug levels to syslog() priorities
323 * note that not all DEBUG(0, ...) calls are
326 static int priority_map[] = {
335 if (syslog_level >= sizeof(priority_map) / sizeof(priority_map[0]) ||
337 priority = LOG_DEBUG;
339 priority = priority_map[syslog_level];
342 va_start(ap, format_str);
345 format_str = va_arg(ap,char *);
347 vslprintf(msgbuf, sizeof(msgbuf)-1,format_str, ap);
351 syslog(priority, "%s", msgbuf);
356 if (!lp_syslog_only())
360 va_start(ap, format_str);
363 format_str = va_arg(ap,char *);
365 vfprintf(dbf,format_str,ap);
377 /****************************************************************************
378 find a suitable temporary directory. The result should be copied immediately
379 as it may be overwritten by a subsequent call
380 ****************************************************************************/
384 if ((p = getenv("TMPDIR"))) {
392 /****************************************************************************
393 determine if a file descriptor is in fact a socket
394 ****************************************************************************/
395 BOOL is_a_socket(int fd)
399 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
403 static char *last_ptr=NULL;
405 /****************************************************************************
406 Get the next token from a string, return False if none found
407 handles double-quotes.
408 Based on a routine by GJC@VILLAGE.COM.
409 Extensively modified by Andrew.Tridgell@anu.edu.au
410 ****************************************************************************/
411 BOOL next_token(char **ptr,char *buff,char *sep)
416 if (!ptr) ptr = &last_ptr;
417 if (!ptr) return(False);
421 /* default to simple separators */
422 if (!sep) sep = " \t\n\r";
424 /* find the first non sep char */
425 while(*s && strchr(sep,*s)) s++;
428 if (! *s) return(False);
430 /* copy over the token */
431 for (quoted = False; *s && (quoted || !strchr(sep,*s)); s++)
439 *ptr = (*s) ? s+1 : s;
446 /****************************************************************************
447 Convert list of tokens to array; dependent on above routine.
448 Uses last_ptr from above - bit of a hack.
449 ****************************************************************************/
450 char **toktocliplist(int *ctok, char *sep)
456 if (!sep) sep = " \t\n\r";
458 while(*s && strchr(sep,*s)) s++;
461 if (!*s) return(NULL);
465 while(*s && (!strchr(sep,*s))) s++;
466 while(*s && strchr(sep,*s)) *s++=0;
472 if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
484 /* ************************************************************************* **
485 * Duplicate a block of memory.
486 * ************************************************************************* **
488 void *mem_dup( void *from, int size )
492 tmp = malloc( size );
494 (void)memcpy( tmp, from, size );
498 /****************************************************************************
499 prompte a dptr (to make it recently used)
500 ****************************************************************************/
501 void array_promote(char *array,int elsize,int element)
507 p = (char *)malloc(elsize);
511 DEBUG(5,("Ahh! Can't malloc\n"));
514 memcpy(p,array + element * elsize, elsize);
515 memmove(array + elsize,array,elsize*element);
516 memcpy(array,p,elsize);
520 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
529 } socket_options[] = {
530 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
531 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
532 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
534 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
536 #ifdef IPTOS_LOWDELAY
537 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
539 #ifdef IPTOS_THROUGHPUT
540 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
543 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
546 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
549 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
552 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
555 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
558 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
564 /****************************************************************************
565 set user socket options
566 ****************************************************************************/
567 void set_socket_options(int fd, char *options)
571 while (next_token(&options,tok," \t,"))
576 BOOL got_value = False;
578 if ((p = strchr(tok,'=')))
585 for (i=0;socket_options[i].name;i++)
586 if (strequal(socket_options[i].name,tok))
589 if (!socket_options[i].name)
591 DEBUG(0,("Unknown socket option %s\n",tok));
595 switch (socket_options[i].opttype)
599 ret = setsockopt(fd,socket_options[i].level,
600 socket_options[i].option,(char *)&value,sizeof(int));
605 DEBUG(0,("syntax error - %s does not take a value\n",tok));
608 int on = socket_options[i].value;
609 ret = setsockopt(fd,socket_options[i].level,
610 socket_options[i].option,(char *)&on,sizeof(int));
616 DEBUG(0,("Failed to set socket option %s\n",tok));
622 /****************************************************************************
623 close the socket communication
624 ****************************************************************************/
625 void close_sockets(void )
628 sslutil_disconnect(Client);
629 #endif /* WITH_SSL */
635 /****************************************************************************
636 determine whether we are in the specified group
637 ****************************************************************************/
638 BOOL in_group(gid_t group, int current_gid, int ngroups, int *groups)
642 if (group == current_gid) return(True);
644 for (i=0;i<ngroups;i++)
645 if (group == groups[i])
651 /****************************************************************************
652 this is a safer strcpy(), meant to prevent core dumps when nasty things happen
653 ****************************************************************************/
654 char *StrCpy(char *dest,char *src)
659 /* I don't want to get lazy with these ... */
661 DEBUG(0,("ERROR: NULL StrCpy() called!\n"));
666 if (!dest) return(NULL);
671 while ((*d++ = *src++)) ;
675 /****************************************************************************
676 line strncpy but always null terminates. Make sure there is room!
677 ****************************************************************************/
678 char *StrnCpy(char *dest,char *src,int n)
681 if (!dest) return(NULL);
686 while (n-- && (*d++ = *src++)) ;
692 /*******************************************************************
693 copy an IP address from one buffer to another
694 ********************************************************************/
695 void putip(void *dest,void *src)
701 /****************************************************************************
702 interpret the weird netbios "name". Return the name type
703 ****************************************************************************/
704 static int name_interpret(char *in,char *out)
707 int len = (*in++) / 2;
711 if (len > 30 || len<1) return(0);
715 if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
719 *out = ((in[0]-'A')<<4) + (in[1]-'A');
727 /* Handle any scope names */
730 *out++ = '.'; /* Scope names are separated by periods */
731 len = *(unsigned char *)in++;
732 StrnCpy(out, in, len);
741 /****************************************************************************
742 mangle a name into netbios format
744 Note: <Out> must be (33 + strlen(scope) + 2) bytes long, at minimum.
745 ****************************************************************************/
746 int name_mangle( char *In, char *Out, char name_type )
754 /* Safely copy the input string, In, into buf[]. */
755 (void)memset( buf, 0, 20 );
759 (void)slprintf( buf, sizeof(buf) - 1, "%-15.15s%c", In, name_type );
761 /* Place the length of the first field into the output buffer. */
765 /* Now convert the name to the rfc1001/1002 format. */
766 for( i = 0; i < 16; i++ )
768 c = toupper( buf[i] );
769 p[i*2] = ( (c >> 4) & 0x000F ) + 'A';
770 p[(i*2)+1] = (c & 0x000F) + 'A';
775 /* Add the scope string. */
776 for( i = 0, len = 0; NULL != scope; i++, len++ )
784 return( name_len(Out) );
796 return( name_len(Out) );
799 /*******************************************************************
800 check if a file exists
801 ********************************************************************/
802 BOOL file_exist(char *fname,struct stat *sbuf)
805 if (!sbuf) sbuf = &st;
807 if (sys_stat(fname,sbuf) != 0)
810 return(S_ISREG(sbuf->st_mode));
813 /*******************************************************************
814 check a files mod time
815 ********************************************************************/
816 time_t file_modtime(char *fname)
820 if (sys_stat(fname,&st) != 0)
826 /*******************************************************************
827 check if a directory exists
828 ********************************************************************/
829 BOOL directory_exist(char *dname,struct stat *st)
836 if (sys_stat(dname,st) != 0)
839 ret = S_ISDIR(st->st_mode);
845 /*******************************************************************
846 returns the size in bytes of the named file
847 ********************************************************************/
848 uint32 file_size(char *file_name)
852 sys_stat(file_name,&buf);
856 /*******************************************************************
857 return a string representing an attribute for a file
858 ********************************************************************/
859 char *attrib_string(int mode)
861 static fstring attrstr;
865 if (mode & aVOLID) fstrcat(attrstr,"V");
866 if (mode & aDIR) fstrcat(attrstr,"D");
867 if (mode & aARCH) fstrcat(attrstr,"A");
868 if (mode & aHIDDEN) fstrcat(attrstr,"H");
869 if (mode & aSYSTEM) fstrcat(attrstr,"S");
870 if (mode & aRONLY) fstrcat(attrstr,"R");
876 /*******************************************************************
877 case insensitive string compararison
878 ********************************************************************/
879 int StrCaseCmp(char *s, char *t)
881 /* compare until we run out of string, either t or s, or find a difference */
882 /* We *must* use toupper rather than tolower here due to the
883 asynchronous upper to lower mapping.
885 #if !defined(KANJI_WIN95_COMPATIBILITY)
887 * For completeness we should put in equivalent code for code pages
888 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
889 * doubt anyone wants Samba to behave differently from Win95 and WinNT
890 * here. They both treat full width ascii characters as case senstive
891 * filenames (ie. they don't do the work we do here).
895 if(lp_client_code_page() == KANJI_CODEPAGE)
897 /* Win95 treats full width ascii characters as case sensitive. */
902 return toupper (*s) - toupper (*t);
903 else if (is_sj_alph (*s) && is_sj_alph (*t))
905 diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
911 else if (is_shift_jis (*s) && is_shift_jis (*t))
913 diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
916 diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
922 else if (is_shift_jis (*s))
924 else if (is_shift_jis (*t))
928 diff = toupper (*s) - toupper (*t);
937 #endif /* KANJI_WIN95_COMPATIBILITY */
939 while (*s && *t && toupper(*s) == toupper(*t))
945 return(toupper(*s) - toupper(*t));
949 /*******************************************************************
950 case insensitive string compararison, length limited
951 ********************************************************************/
952 int StrnCaseCmp(char *s, char *t, int n)
954 /* compare until we run out of string, either t or s, or chars */
955 /* We *must* use toupper rather than tolower here due to the
956 asynchronous upper to lower mapping.
958 #if !defined(KANJI_WIN95_COMPATIBILITY)
960 * For completeness we should put in equivalent code for code pages
961 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
962 * doubt anyone wants Samba to behave differently from Win95 and WinNT
963 * here. They both treat full width ascii characters as case senstive
964 * filenames (ie. they don't do the work we do here).
968 if(lp_client_code_page() == KANJI_CODEPAGE)
970 /* Win95 treats full width ascii characters as case sensitive. */
975 return toupper (*s) - toupper (*t);
976 else if (is_sj_alph (*s) && is_sj_alph (*t))
978 diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
985 else if (is_shift_jis (*s) && is_shift_jis (*t))
987 diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
990 diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
997 else if (is_shift_jis (*s))
999 else if (is_shift_jis (*t))
1003 diff = toupper (*s) - toupper (*t);
1014 #endif /* KANJI_WIN95_COMPATIBILITY */
1016 while (n && *s && *t && toupper(*s) == toupper(*t))
1023 /* not run out of chars - strings are different lengths */
1025 return(toupper(*s) - toupper(*t));
1027 /* identical up to where we run out of chars,
1028 and strings are same length */
1033 /*******************************************************************
1035 ********************************************************************/
1036 BOOL strequal(char *s1, char *s2)
1038 if (s1 == s2) return(True);
1039 if (!s1 || !s2) return(False);
1041 return(StrCaseCmp(s1,s2)==0);
1044 /*******************************************************************
1045 compare 2 strings up to and including the nth char.
1046 ******************************************************************/
1047 BOOL strnequal(char *s1,char *s2,int n)
1049 if (s1 == s2) return(True);
1050 if (!s1 || !s2 || !n) return(False);
1052 return(StrnCaseCmp(s1,s2,n)==0);
1055 /*******************************************************************
1056 compare 2 strings (case sensitive)
1057 ********************************************************************/
1058 BOOL strcsequal(char *s1,char *s2)
1060 if (s1 == s2) return(True);
1061 if (!s1 || !s2) return(False);
1063 return(strcmp(s1,s2)==0);
1067 /*******************************************************************
1068 convert a string to lower case
1069 ********************************************************************/
1070 void strlower(char *s)
1074 #if !defined(KANJI_WIN95_COMPATIBILITY)
1076 * For completeness we should put in equivalent code for code pages
1077 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
1078 * doubt anyone wants Samba to behave differently from Win95 and WinNT
1079 * here. They both treat full width ascii characters as case senstive
1080 * filenames (ie. they don't do the work we do here).
1084 if(lp_client_code_page() == KANJI_CODEPAGE)
1086 /* Win95 treats full width ascii characters as case sensitive. */
1087 if (is_shift_jis (*s))
1089 if (is_sj_upper (s[0], s[1]))
1090 s[1] = sj_tolower2 (s[1]);
1093 else if (is_kana (*s))
1105 #endif /* KANJI_WIN95_COMPATIBILITY */
1107 int skip = skip_multibyte_char( *s );
1120 /*******************************************************************
1121 convert a string to upper case
1122 ********************************************************************/
1123 void strupper(char *s)
1127 #if !defined(KANJI_WIN95_COMPATIBILITY)
1129 * For completeness we should put in equivalent code for code pages
1130 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
1131 * doubt anyone wants Samba to behave differently from Win95 and WinNT
1132 * here. They both treat full width ascii characters as case senstive
1133 * filenames (ie. they don't do the work we do here).
1137 if(lp_client_code_page() == KANJI_CODEPAGE)
1139 /* Win95 treats full width ascii characters as case sensitive. */
1140 if (is_shift_jis (*s))
1142 if (is_sj_lower (s[0], s[1]))
1143 s[1] = sj_toupper2 (s[1]);
1146 else if (is_kana (*s))
1158 #endif /* KANJI_WIN95_COMPATIBILITY */
1160 int skip = skip_multibyte_char( *s );
1173 /*******************************************************************
1174 convert a string to "normal" form
1175 ********************************************************************/
1176 void strnorm(char *s)
1178 if (case_default == CASE_UPPER)
1184 /*******************************************************************
1185 check if a string is in "normal" case
1186 ********************************************************************/
1187 BOOL strisnormal(char *s)
1189 if (case_default == CASE_UPPER)
1190 return(!strhaslower(s));
1192 return(!strhasupper(s));
1196 /****************************************************************************
1198 ****************************************************************************/
1199 void string_replace(char *s,char oldc,char newc)
1204 skip = skip_multibyte_char( *s );
1216 /****************************************************************************
1217 make a file into unix format
1218 ****************************************************************************/
1219 void unix_format(char *fname)
1222 string_replace(fname,'\\','/');
1226 pstrcpy(namecopy,fname);
1228 pstrcat(fname,namecopy);
1232 /****************************************************************************
1233 make a file into dos format
1234 ****************************************************************************/
1235 void dos_format(char *fname)
1237 string_replace(fname,'/','\\');
1240 /*******************************************************************
1241 show a smb message structure
1242 ********************************************************************/
1243 void show_msg(char *buf)
1248 if (DEBUGLEVEL < 5) return;
1250 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
1252 (int)CVAL(buf,smb_com),
1253 (int)CVAL(buf,smb_rcls),
1254 (int)CVAL(buf,smb_reh),
1255 (int)SVAL(buf,smb_err),
1256 (int)CVAL(buf,smb_flg),
1257 (int)SVAL(buf,smb_flg2)));
1258 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
1259 (int)SVAL(buf,smb_tid),
1260 (int)SVAL(buf,smb_pid),
1261 (int)SVAL(buf,smb_uid),
1262 (int)SVAL(buf,smb_mid),
1263 (int)CVAL(buf,smb_wct)));
1265 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
1267 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
1268 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
1271 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
1273 DEBUG(5,("smb_bcc=%d\n",bcc));
1275 if (DEBUGLEVEL < 10) return;
1277 if (DEBUGLEVEL < 50)
1279 bcc = MIN(bcc, 512);
1282 dump_data(10, smb_buf(buf), bcc);
1284 /*******************************************************************
1285 return the length of an smb packet
1286 ********************************************************************/
1287 int smb_len(char *buf)
1289 return( PVAL(buf,3) | (PVAL(buf,2)<<8) | ((PVAL(buf,1)&1)<<16) );
1292 /*******************************************************************
1293 set the length of an smb packet
1294 ********************************************************************/
1295 void _smb_setlen(char *buf,int len)
1298 buf[1] = (len&0x10000)>>16;
1299 buf[2] = (len&0xFF00)>>8;
1303 /*******************************************************************
1304 set the length and marker of an smb packet
1305 ********************************************************************/
1306 void smb_setlen(char *buf,int len)
1308 _smb_setlen(buf,len);
1316 /*******************************************************************
1317 setup the word count and byte count for a smb message
1318 ********************************************************************/
1319 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
1322 bzero(buf + smb_size,num_words*2 + num_bytes);
1323 CVAL(buf,smb_wct) = num_words;
1324 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
1325 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
1326 return (smb_size + num_words*2 + num_bytes);
1329 /*******************************************************************
1330 return the number of smb words
1331 ********************************************************************/
1332 int smb_numwords(char *buf)
1334 return (CVAL(buf,smb_wct));
1337 /*******************************************************************
1338 return the size of the smb_buf region of a message
1339 ********************************************************************/
1340 int smb_buflen(char *buf)
1342 return(SVAL(buf,smb_vwv0 + smb_numwords(buf)*2));
1345 /*******************************************************************
1346 return a pointer to the smb_buf data area
1347 ********************************************************************/
1348 int smb_buf_ofs(char *buf)
1350 return (smb_size + CVAL(buf,smb_wct)*2);
1353 /*******************************************************************
1354 return a pointer to the smb_buf data area
1355 ********************************************************************/
1356 char *smb_buf(char *buf)
1358 return (buf + smb_buf_ofs(buf));
1361 /*******************************************************************
1362 return the SMB offset into an SMB buffer
1363 ********************************************************************/
1364 int smb_offset(char *p,char *buf)
1366 return(PTR_DIFF(p,buf+4) + chain_size);
1370 /*******************************************************************
1371 skip past some strings in a buffer
1372 ********************************************************************/
1373 char *skip_string(char *buf,int n)
1376 buf += strlen(buf) + 1;
1380 /*******************************************************************
1381 trim the specified elements off the front and back of a string
1382 ********************************************************************/
1383 BOOL trim_string(char *s,char *front,char *back)
1386 while (front && *front && strncmp(s,front,strlen(front)) == 0)
1392 if (!(*p = p[strlen(front)]))
1397 while (back && *back && strlen(s) >= strlen(back) &&
1398 (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0))
1401 s[strlen(s)-strlen(back)] = 0;
1407 /*******************************************************************
1408 reduce a file name, removing .. elements.
1409 ********************************************************************/
1410 void dos_clean_name(char *s)
1414 DEBUG(3,("dos_clean_name [%s]\n",s));
1416 /* remove any double slashes */
1417 string_sub(s, "\\\\", "\\");
1419 while ((p = strstr(s,"\\..\\")) != NULL)
1426 if ((p=strrchr(s,'\\')) != NULL)
1433 trim_string(s,NULL,"\\..");
1435 string_sub(s, "\\.\\", "\\");
1438 /*******************************************************************
1439 reduce a file name, removing .. elements.
1440 ********************************************************************/
1441 void unix_clean_name(char *s)
1445 DEBUG(3,("unix_clean_name [%s]\n",s));
1447 /* remove any double slashes */
1448 string_sub(s, "//","/");
1450 /* Remove leading ./ characters */
1451 if(strncmp(s, "./", 2) == 0) {
1452 trim_string(s, "./", NULL);
1457 while ((p = strstr(s,"/../")) != NULL)
1464 if ((p=strrchr(s,'/')) != NULL)
1471 trim_string(s,NULL,"/..");
1475 /*******************************************************************
1476 a wrapper for the normal chdir() function
1477 ********************************************************************/
1478 int ChDir(char *path)
1481 static pstring LastDir="";
1483 if (strcsequal(path,".")) return(0);
1485 if (*path == '/' && strcsequal(LastDir,path)) return(0);
1486 DEBUG(3,("chdir to %s\n",path));
1487 res = sys_chdir(path);
1489 pstrcpy(LastDir,path);
1493 /* number of list structures for a caching GetWd function. */
1494 #define MAX_GETWDCACHE (50)
1502 } ino_list[MAX_GETWDCACHE];
1504 BOOL use_getwd_cache=True;
1506 /*******************************************************************
1507 return the absolute current directory path
1508 ********************************************************************/
1509 char *GetWd(char *str)
1512 static BOOL getwd_cache_init = False;
1513 struct stat st, st2;
1518 if (!use_getwd_cache)
1519 return(sys_getwd(str));
1521 /* init the cache */
1522 if (!getwd_cache_init)
1524 getwd_cache_init = True;
1525 for (i=0;i<MAX_GETWDCACHE;i++)
1527 string_init(&ino_list[i].text,"");
1528 ino_list[i].valid = False;
1532 /* Get the inode of the current directory, if this doesn't work we're
1535 if (stat(".",&st) == -1)
1537 DEBUG(0,("Very strange, couldn't stat \".\"\n"));
1538 return(sys_getwd(str));
1542 for (i=0; i<MAX_GETWDCACHE; i++)
1543 if (ino_list[i].valid)
1546 /* If we have found an entry with a matching inode and dev number
1547 then find the inode number for the directory in the cached string.
1548 If this agrees with that returned by the stat for the current
1549 directory then all is o.k. (but make sure it is a directory all
1552 if (st.st_ino == ino_list[i].inode &&
1553 st.st_dev == ino_list[i].dev)
1555 if (stat(ino_list[i].text,&st2) == 0)
1557 if (st.st_ino == st2.st_ino &&
1558 st.st_dev == st2.st_dev &&
1559 (st2.st_mode & S_IFMT) == S_IFDIR)
1561 pstrcpy (str, ino_list[i].text);
1563 /* promote it for future use */
1564 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1569 /* If the inode is different then something's changed,
1570 scrub the entry and start from scratch. */
1571 ino_list[i].valid = False;
1578 /* We don't have the information to hand so rely on traditional methods.
1579 The very slow getcwd, which spawns a process on some systems, or the
1580 not quite so bad getwd. */
1584 DEBUG(0,("Getwd failed, errno %s\n",strerror(errno)));
1590 DEBUG(5,("GetWd %s, inode %d, dev %x\n",s,(int)st.st_ino,(int)st.st_dev));
1592 /* add it to the cache */
1593 i = MAX_GETWDCACHE - 1;
1594 string_set(&ino_list[i].text,s);
1595 ino_list[i].dev = st.st_dev;
1596 ino_list[i].inode = st.st_ino;
1597 ino_list[i].valid = True;
1599 /* put it at the top of the list */
1600 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1607 /*******************************************************************
1608 reduce a file name, removing .. elements and checking that
1609 it is below dir in the heirachy. This uses GetWd() and so must be run
1610 on the system that has the referenced file system.
1612 widelinks are allowed if widelinks is true
1613 ********************************************************************/
1614 BOOL reduce_name(char *s,char *dir,BOOL widelinks)
1616 #ifndef REDUCE_PATHS
1624 BOOL relative = (*s != '/');
1626 *dir2 = *wd = *base_name = *newname = 0;
1631 /* can't have a leading .. */
1632 if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
1634 DEBUG(3,("Illegal file name? (%s)\n",s));
1644 DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
1646 /* remove any double slashes */
1647 string_sub(s,"//","/");
1649 pstrcpy(base_name,s);
1650 p = strrchr(base_name,'/');
1657 DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
1661 if (ChDir(dir) != 0)
1663 DEBUG(0,("couldn't chdir to %s\n",dir));
1669 DEBUG(0,("couldn't getwd for %s\n",dir));
1675 if (p && (p != base_name))
1678 if (strcmp(p+1,".")==0)
1680 if (strcmp(p+1,"..")==0)
1684 if (ChDir(base_name) != 0)
1687 DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,base_name));
1691 if (!GetWd(newname))
1694 DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
1698 if (p && (p != base_name))
1700 pstrcat(newname,"/");
1701 pstrcat(newname,p+1);
1705 int l = strlen(dir2);
1706 if (dir2[l-1] == '/')
1709 if (strncmp(newname,dir2,l) != 0)
1712 DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,l));
1718 if (newname[l] == '/')
1719 pstrcpy(s,newname + l + 1);
1721 pstrcpy(s,newname+l);
1732 DEBUG(3,("reduced to %s\n",s));
1737 /****************************************************************************
1739 ****************************************************************************/
1740 static void expand_one(char *Mask,int len)
1743 while ((p1 = strchr(Mask,'*')) != NULL)
1745 int lfill = (len+1) - strlen(Mask);
1746 int l1= (p1 - Mask);
1749 memset(tmp+l1,'?',lfill);
1750 pstrcpy(tmp + l1 + lfill,Mask + l1 + 1);
1755 /****************************************************************************
1756 expand a wildcard expression, replacing *s with ?s
1757 ****************************************************************************/
1758 void expand_mask(char *Mask,BOOL doext)
1763 BOOL hasdot = False;
1765 BOOL absolute = (*Mask == '\\');
1767 *mbeg = *mext = *dirpart = *filepart = 0;
1769 /* parse the directory and filename */
1770 if (strchr(Mask,'\\'))
1771 dirname_dos(Mask,dirpart);
1773 filename_dos(Mask,filepart);
1775 pstrcpy(mbeg,filepart);
1776 if ((p1 = strchr(mbeg,'.')) != NULL)
1786 if (strlen(mbeg) > 8)
1788 pstrcpy(mext,mbeg + 8);
1794 pstrcpy(mbeg,"????????");
1795 if ((*mext == 0) && doext && !hasdot)
1796 pstrcpy(mext,"???");
1798 if (strequal(mbeg,"*") && *mext==0)
1806 pstrcpy(Mask,dirpart);
1807 if (*dirpart || absolute) pstrcat(Mask,"\\");
1812 DEBUG(6,("Mask expanded to [%s]\n",Mask));
1816 /****************************************************************************
1817 does a string have any uppercase chars in it?
1818 ****************************************************************************/
1819 BOOL strhasupper(char *s)
1823 #if !defined(KANJI_WIN95_COMPATIBILITY)
1825 * For completeness we should put in equivalent code for code pages
1826 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
1827 * doubt anyone wants Samba to behave differently from Win95 and WinNT
1828 * here. They both treat full width ascii characters as case senstive
1829 * filenames (ie. they don't do the work we do here).
1833 if(lp_client_code_page() == KANJI_CODEPAGE)
1835 /* Win95 treats full width ascii characters as case sensitive. */
1836 if (is_shift_jis (*s))
1838 else if (is_kana (*s))
1848 #endif /* KANJI_WIN95_COMPATIBILITY */
1850 int skip = skip_multibyte_char( *s );
1863 /****************************************************************************
1864 does a string have any lowercase chars in it?
1865 ****************************************************************************/
1866 BOOL strhaslower(char *s)
1870 #if !defined(KANJI_WIN95_COMPATIBILITY)
1872 * For completeness we should put in equivalent code for code pages
1873 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
1874 * doubt anyone wants Samba to behave differently from Win95 and WinNT
1875 * here. They both treat full width ascii characters as case senstive
1876 * filenames (ie. they don't do the work we do here).
1880 if(lp_client_code_page() == KANJI_CODEPAGE)
1882 /* Win95 treats full width ascii characters as case sensitive. */
1883 if (is_shift_jis (*s))
1885 if (is_sj_upper (s[0], s[1]))
1887 if (is_sj_lower (s[0], s[1]))
1891 else if (is_kana (*s))
1903 #endif /* KANJI_WIN95_COMPATIBILITY */
1905 int skip = skip_multibyte_char( *s );
1918 /****************************************************************************
1919 find the number of chars in a string
1920 ****************************************************************************/
1921 int count_chars(char *s,char c)
1925 #if !defined(KANJI_WIN95_COMPATIBILITY)
1927 * For completeness we should put in equivalent code for code pages
1928 * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
1929 * doubt anyone wants Samba to behave differently from Win95 and WinNT
1930 * here. They both treat full width ascii characters as case senstive
1931 * filenames (ie. they don't do the work we do here).
1935 if(lp_client_code_page() == KANJI_CODEPAGE)
1937 /* Win95 treats full width ascii characters as case sensitive. */
1940 if (is_shift_jis (*s))
1951 #endif /* KANJI_WIN95_COMPATIBILITY */
1955 int skip = skip_multibyte_char( *s );
1969 /****************************************************************************
1971 ****************************************************************************/
1972 void make_dir_struct(char *buf,char *mask,char *fname,unsigned int size,int mode,time_t date)
1977 pstrcpy(mask2,mask);
1979 if ((mode & aDIR) != 0)
1982 memset(buf+1,' ',11);
1983 if ((p = strchr(mask2,'.')) != NULL)
1986 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
1987 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
1991 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
1993 bzero(buf+21,DIR_STRUCT_SIZE-21);
1994 CVAL(buf,21) = mode;
1995 put_dos_date(buf,22,date);
1996 SSVAL(buf,26,size & 0xFFFF);
1997 SSVAL(buf,28,size >> 16);
1998 StrnCpy(buf+30,fname,12);
1999 if (!case_sensitive)
2001 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
2005 /*******************************************************************
2006 close the low 3 fd's and open dev/null in their place
2007 ********************************************************************/
2008 void close_low_fds(void)
2012 close(0); close(1); close(2);
2013 /* try and use up these file descriptors, so silly
2014 library routines writing to stdout etc won't cause havoc */
2016 fd = open("/dev/null",O_RDWR,0);
2017 if (fd < 0) fd = open("/dev/null",O_WRONLY,0);
2019 DEBUG(0,("Can't open /dev/null\n"));
2023 DEBUG(0,("Didn't get file descriptor %d\n",i));
2029 /****************************************************************************
2030 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
2032 if SYSV use O_NDELAY
2034 ****************************************************************************/
2035 int set_blocking(int fd, BOOL set)
2039 #define FLAG_TO_SET O_NONBLOCK
2042 #define FLAG_TO_SET O_NDELAY
2044 #define FLAG_TO_SET FNDELAY
2048 if((val = fcntl(fd, F_GETFL, 0)) == -1)
2050 if(set) /* Turn blocking on - ie. clear nonblock flag */
2051 val &= ~FLAG_TO_SET;
2054 return fcntl( fd, F_SETFL, val);
2059 /****************************************************************************
2061 ****************************************************************************/
2062 int write_socket(int fd,char *buf,int len)
2068 DEBUG(6,("write_socket(%d,%d)\n",fd,len));
2069 ret = write_data(fd,buf,len);
2071 DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,len,ret));
2073 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
2074 len, fd, strerror(errno) ));
2079 /****************************************************************************
2081 ****************************************************************************/
2082 int read_udp_socket(int fd,char *buf,int len)
2085 struct sockaddr_in sock;
2088 socklen = sizeof(sock);
2089 bzero((char *)&sock,socklen);
2090 bzero((char *)&lastip,sizeof(lastip));
2091 ret = recvfrom(fd,buf,len,0,(struct sockaddr *)&sock,&socklen);
2093 DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
2097 lastip = sock.sin_addr;
2098 lastport = ntohs(sock.sin_port);
2100 DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
2101 inet_ntoa(lastip), lastport, ret));
2106 /****************************************************************************
2107 read data from a device with a timout in msec.
2108 mincount = if timeout, minimum to read before returning
2109 maxcount = number to be read.
2110 ****************************************************************************/
2111 int read_with_timeout(int fd,char *buf,int mincnt,int maxcnt,long time_out)
2117 struct timeval timeout;
2119 /* just checking .... */
2120 if (maxcnt <= 0) return(0);
2125 if (time_out <= 0) {
2126 if (mincnt == 0) mincnt = maxcnt;
2128 while (nread < mincnt) {
2131 readret = SSL_read(ssl, buf + nread, maxcnt - nread);
2133 readret = read(fd, buf + nread, maxcnt - nread);
2135 #else /* WITH_SSL */
2136 readret = read(fd, buf + nread, maxcnt - nread);
2137 #endif /* WITH_SSL */
2140 smb_read_error = READ_EOF;
2144 if (readret == -1) {
2145 smb_read_error = READ_ERROR;
2153 /* Most difficult - timeout read */
2154 /* If this is ever called on a disk file and
2155 mincnt is greater then the filesize then
2156 system performance will suffer severely as
2157 select always return true on disk files */
2159 /* Set initial timeout */
2160 timeout.tv_sec = time_out / 1000;
2161 timeout.tv_usec = 1000 * (time_out % 1000);
2163 for (nread=0; nread<mincnt; )
2168 selrtn = sys_select(&fds,&timeout);
2170 /* Check if error */
2172 /* something is wrong. Maybe the socket is dead? */
2173 smb_read_error = READ_ERROR;
2177 /* Did we timeout ? */
2179 smb_read_error = READ_TIMEOUT;
2185 readret = SSL_read(ssl, buf + nread, maxcnt - nread);
2187 readret = read(fd, buf + nread, maxcnt - nread);
2189 #else /* WITH_SSL */
2190 readret = read(fd, buf+nread, maxcnt-nread);
2191 #endif /* WITH_SSL */
2194 /* we got EOF on the file descriptor */
2195 smb_read_error = READ_EOF;
2199 if (readret == -1) {
2200 /* the descriptor is probably dead */
2201 smb_read_error = READ_ERROR;
2208 /* Return the number we got */
2212 /****************************************************************************
2213 read data from the client. Maxtime is in milliseconds
2214 ****************************************************************************/
2215 int read_max_udp(int fd,char *buffer,int bufsize,int maxtime)
2220 struct timeval timeout;
2225 timeout.tv_sec = maxtime / 1000;
2226 timeout.tv_usec = (maxtime % 1000) * 1000;
2228 selrtn = sys_select(&fds,maxtime>0?&timeout:NULL);
2230 if (!FD_ISSET(fd,&fds))
2233 nread = read_udp_socket(fd, buffer, bufsize);
2235 /* return the number got */
2239 /*******************************************************************
2240 find the difference in milliseconds between two struct timeval
2242 ********************************************************************/
2243 int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
2245 return((tvalnew->tv_sec - tvalold->tv_sec)*1000 +
2246 ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);
2249 /****************************************************************************
2250 send a keepalive packet (rfc1002)
2251 ****************************************************************************/
2252 BOOL send_keepalive(int client)
2254 unsigned char buf[4];
2257 buf[1] = buf[2] = buf[3] = 0;
2259 return(write_data(client,(char *)buf,4) == 4);
2264 /****************************************************************************
2265 read data from the client, reading exactly N bytes.
2266 ****************************************************************************/
2267 int read_data(int fd,char *buffer,int N)
2278 ret = SSL_read(ssl, buffer + total, N - total);
2280 ret = read(fd,buffer + total,N - total);
2282 #else /* WITH_SSL */
2283 ret = read(fd,buffer + total,N - total);
2284 #endif /* WITH_SSL */
2288 smb_read_error = READ_EOF;
2293 smb_read_error = READ_ERROR;
2302 /****************************************************************************
2304 ****************************************************************************/
2305 int write_data(int fd,char *buffer,int N)
2314 ret = SSL_write(ssl,buffer + total,N - total);
2316 ret = write(fd,buffer + total,N - total);
2318 #else /* WITH_SSL */
2319 ret = write(fd,buffer + total,N - total);
2320 #endif /* WITH_SSL */
2322 if (ret == -1) return -1;
2323 if (ret == 0) return total;
2331 /****************************************************************************
2332 transfer some data between two fd's
2333 ****************************************************************************/
2334 int transfer_file(int infd,int outfd,int n,char *header,int headlen,int align)
2336 static char *buf=NULL;
2341 DEBUG(4,("transfer_file %d (head=%d) called\n",n,headlen));
2344 size = lp_readsize();
2345 size = MAX(size,1024);
2348 while (!buf && size>0) {
2349 buf = (char *)Realloc(buf,size+8);
2350 if (!buf) size /= 2;
2354 DEBUG(0,("Can't allocate transfer buffer!\n"));
2358 abuf = buf + (align%8);
2365 int s = MIN(n,size);
2370 if (header && (headlen >= MIN(s,1024))) {
2380 if (header && headlen > 0)
2382 ret = MIN(headlen,size);
2383 memcpy(buf1,header,ret);
2386 if (headlen <= 0) header = NULL;
2390 ret += read(infd,buf1+ret,s-ret);
2394 ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
2395 if (ret2 > 0) total += ret2;
2396 /* if we can't write then dump excess data */
2398 transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
2400 if (ret <= 0 || ret2 != ret)
2408 /****************************************************************************
2409 read 4 bytes of a smb packet and return the smb length of the packet
2410 store the result in the buffer
2411 This version of the function will return a length of zero on receiving
2413 ****************************************************************************/
2414 static int read_smb_length_return_keepalive(int fd,char *inbuf,int timeout)
2416 int len=0, msg_type;
2422 ok = (read_with_timeout(fd,inbuf,4,4,timeout) == 4);
2424 ok = (read_data(fd,inbuf,4) == 4);
2429 len = smb_len(inbuf);
2430 msg_type = CVAL(inbuf,0);
2432 if (msg_type == 0x85)
2433 DEBUG(5,("Got keepalive packet\n"));
2436 DEBUG(10,("got smb length of %d\n",len));
2441 /****************************************************************************
2442 read 4 bytes of a smb packet and return the smb length of the packet
2443 store the result in the buffer. This version of the function will
2444 never return a session keepalive (length of zero).
2445 ****************************************************************************/
2446 int read_smb_length(int fd,char *inbuf,int timeout)
2452 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
2457 /* Ignore session keepalives. */
2458 if(CVAL(inbuf,0) != 0x85)
2465 /****************************************************************************
2466 read an smb from a fd. Note that the buffer *MUST* be of size
2467 BUFFER_SIZE+SAFETY_MARGIN.
2468 The timeout is in milli seconds.
2470 This function will return on a
2471 receipt of a session keepalive packet.
2472 ****************************************************************************/
2473 BOOL receive_smb(int fd,char *buffer, int timeout)
2479 bzero(buffer,smb_size + 100);
2481 len = read_smb_length_return_keepalive(fd,buffer,timeout);
2485 if (len > BUFFER_SIZE) {
2486 DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
2487 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
2492 ret = read_data(fd,buffer+4,len);
2494 smb_read_error = READ_ERROR;
2501 /****************************************************************************
2502 read an smb from a fd ignoring all keepalive packets. Note that the buffer
2503 *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
2504 The timeout is in milli seconds
2506 This is exactly the same as receive_smb except that it never returns
2507 a session keepalive packet (just as receive_smb used to do).
2508 receive_smb was changed to return keepalives as the oplock processing means this call
2509 should never go into a blocking read.
2510 ****************************************************************************/
2512 BOOL client_receive_smb(int fd,char *buffer, int timeout)
2518 ret = receive_smb(fd, buffer, timeout);
2523 /* Ignore session keepalive packets. */
2524 if(CVAL(buffer,0) != 0x85)
2530 /****************************************************************************
2531 read a message from a udp fd.
2532 The timeout is in milli seconds
2533 ****************************************************************************/
2534 BOOL receive_local_message(int fd, char *buffer, int buffer_len, int timeout)
2536 struct sockaddr_in from;
2537 int fromlen = sizeof(from);
2551 to.tv_sec = timeout / 1000;
2552 to.tv_usec = (timeout % 1000) * 1000;
2554 selrtn = sys_select(&fds,&to);
2556 /* Check if error */
2559 /* something is wrong. Maybe the socket is dead? */
2560 smb_read_error = READ_ERROR;
2564 /* Did we timeout ? */
2567 smb_read_error = READ_TIMEOUT;
2573 * Read a loopback udp message.
2575 msg_len = recvfrom(fd, &buffer[UDP_CMD_HEADER_LEN],
2576 buffer_len - UDP_CMD_HEADER_LEN, 0,
2577 (struct sockaddr *)&from, &fromlen);
2581 DEBUG(0,("receive_local_message. Error in recvfrom. (%s).\n",strerror(errno)));
2585 /* Validate message length. */
2586 if(msg_len > (buffer_len - UDP_CMD_HEADER_LEN))
2588 DEBUG(0,("receive_local_message: invalid msg_len (%d) max can be %d\n",
2590 buffer_len - UDP_CMD_HEADER_LEN));
2594 /* Validate message from address (must be localhost). */
2595 if(from.sin_addr.s_addr != htonl(INADDR_LOOPBACK))
2597 DEBUG(0,("receive_local_message: invalid 'from' address \
2598 (was %x should be 127.0.0.1\n", from.sin_addr.s_addr));
2602 /* Setup the message header */
2603 SIVAL(buffer,UDP_CMD_LEN_OFFSET,msg_len);
2604 SSVAL(buffer,UDP_CMD_PORT_OFFSET,ntohs(from.sin_port));
2609 /****************************************************************************
2610 structure to hold a linked list of local messages.
2612 ****************************************************************************/
2614 typedef struct _message_list {
2615 struct _message_list *msg_next;
2618 } pending_message_list;
2620 static pending_message_list *smb_msg_head = NULL;
2622 /****************************************************************************
2623 Function to push a linked list of local messages ready
2625 ****************************************************************************/
2627 static BOOL push_local_message(pending_message_list **pml, char *buf, int msg_len)
2629 pending_message_list *msg = (pending_message_list *)
2630 malloc(sizeof(pending_message_list));
2634 DEBUG(0,("push_message: malloc fail (1)\n"));
2638 msg->msg_buf = (char *)malloc(msg_len);
2639 if(msg->msg_buf == NULL)
2641 DEBUG(0,("push_local_message: malloc fail (2)\n"));
2646 memcpy(msg->msg_buf, buf, msg_len);
2647 msg->msg_len = msg_len;
2649 msg->msg_next = *pml;
2655 /****************************************************************************
2656 Function to push a linked list of local smb messages ready
2658 ****************************************************************************/
2660 BOOL push_smb_message(char *buf, int msg_len)
2662 return push_local_message(&smb_msg_head, buf, msg_len);
2665 /****************************************************************************
2666 Do a select on an two fd's - with timeout.
2668 If a local udp message has been pushed onto the
2669 queue (this can only happen during oplock break
2670 processing) return this first.
2672 If a pending smb message has been pushed onto the
2673 queue (this can only happen during oplock break
2674 processing) return this next.
2676 If the first smbfd is ready then read an smb from it.
2677 if the second (loopback UDP) fd is ready then read a message
2678 from it and setup the buffer header to identify the length
2680 Returns False on timeout or error.
2683 The timeout is in milli seconds
2684 ****************************************************************************/
2685 BOOL receive_message_or_smb(int smbfd, int oplock_fd,
2686 char *buffer, int buffer_len,
2687 int timeout, BOOL *got_smb)
2698 * Check to see if we already have a message on the smb queue.
2699 * If so - copy and return it.
2704 pending_message_list *msg = smb_msg_head;
2705 memcpy(buffer, msg->msg_buf, MIN(buffer_len, msg->msg_len));
2706 smb_msg_head = msg->msg_next;
2708 /* Free the message we just copied. */
2709 free((char *)msg->msg_buf);
2713 DEBUG(5,("receive_message_or_smb: returning queued smb message.\n"));
2719 FD_SET(oplock_fd,&fds);
2721 to.tv_sec = timeout / 1000;
2722 to.tv_usec = (timeout % 1000) * 1000;
2724 selrtn = sys_select(&fds,timeout>0?&to:NULL);
2726 /* Check if error */
2728 /* something is wrong. Maybe the socket is dead? */
2729 smb_read_error = READ_ERROR;
2733 /* Did we timeout ? */
2735 smb_read_error = READ_TIMEOUT;
2739 if (FD_ISSET(smbfd,&fds))
2742 return receive_smb(smbfd, buffer, 0);
2746 return receive_local_message(oplock_fd, buffer, buffer_len, 0);
2750 /****************************************************************************
2752 ****************************************************************************/
2753 BOOL send_smb(int fd,char *buffer)
2757 len = smb_len(buffer) + 4;
2759 while (nwritten < len)
2761 ret = write_socket(fd,buffer+nwritten,len - nwritten);
2764 DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
2776 /****************************************************************************
2777 find a pointer to a netbios name
2778 ****************************************************************************/
2779 char *name_ptr(char *buf,int ofs)
2781 unsigned char c = *(unsigned char *)(buf+ofs);
2783 if ((c & 0xC0) == 0xC0)
2787 memcpy(p,buf+ofs,2);
2790 DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
2797 /****************************************************************************
2798 extract a netbios name from a buf
2799 ****************************************************************************/
2800 int name_extract(char *buf,int ofs,char *name)
2802 char *p = name_ptr(buf,ofs);
2803 int d = PTR_DIFF(p,buf+ofs);
2805 if (d < -50 || d > 50) return(0);
2806 return(name_interpret(p,name));
2809 /****************************************************************************
2810 return the total storage length of a mangled name
2811 ****************************************************************************/
2812 int name_len( char *s )
2816 /* If the two high bits of the byte are set, return 2. */
2817 if( 0xC0 == (*(unsigned char *)s & 0xC0) )
2820 /* Add up the length bytes. */
2821 for( len = 1; (*s); s += (*s) + 1 )
2829 /****************************************************************************
2830 send a single packet to a port on another machine
2831 ****************************************************************************/
2832 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
2836 struct sockaddr_in sock_out;
2841 /* create a socket to write to */
2842 out_fd = socket(AF_INET, type, 0);
2845 DEBUG(0,("socket failed"));
2849 /* set the address and port */
2850 bzero((char *)&sock_out,sizeof(sock_out));
2851 putip((char *)&sock_out.sin_addr,(char *)&ip);
2852 sock_out.sin_port = htons( port );
2853 sock_out.sin_family = AF_INET;
2856 DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
2857 len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
2860 ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
2863 DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
2864 inet_ntoa(ip),port,strerror(errno)));
2870 /*******************************************************************
2871 sleep for a specified number of milliseconds
2872 ********************************************************************/
2876 struct timeval tval,t1,t2;
2883 tval.tv_sec = (t-tdiff)/1000;
2884 tval.tv_usec = 1000*((t-tdiff)%1000);
2888 sys_select(&fds,&tval);
2891 tdiff = TvalDiff(&t1,&t2);
2895 /****************************************************************************
2896 check if a string is part of a list
2897 ****************************************************************************/
2898 BOOL in_list(char *s,char *list,BOOL casesensitive)
2903 if (!list) return(False);
2905 while (next_token(&p,tok,LIST_SEP))
2907 if (casesensitive) {
2908 if (strcmp(tok,s) == 0)
2911 if (StrCaseCmp(tok,s) == 0)
2918 /* this is used to prevent lots of mallocs of size 1 */
2919 static char *null_string = NULL;
2921 /****************************************************************************
2922 set a string value, allocing the space for the string
2923 ****************************************************************************/
2924 BOOL string_init(char **dest,char *src)
2935 null_string = (char *)malloc(1);
2938 *dest = null_string;
2942 (*dest) = (char *)malloc(l+1);
2943 if ((*dest) == NULL) {
2944 DEBUG(0,("Out of memory in string_init\n"));
2953 /****************************************************************************
2955 ****************************************************************************/
2956 void string_free(char **s)
2958 if (!s || !(*s)) return;
2959 if (*s == null_string)
2965 /****************************************************************************
2966 set a string value, allocing the space for the string, and deallocating any
2968 ****************************************************************************/
2969 BOOL string_set(char **dest,char *src)
2973 return(string_init(dest,src));
2976 /****************************************************************************
2977 substitute a string for a pattern in another string. Make sure there is
2980 This routine looks for pattern in s and replaces it with
2981 insert. It may do multiple replacements.
2983 return True if a substitution was done.
2984 ****************************************************************************/
2985 BOOL string_sub(char *s,char *pattern,char *insert)
2991 if (!insert || !pattern || !s) return(False);
2994 lp = strlen(pattern);
2995 li = strlen(insert);
2997 if (!*pattern) return(False);
2999 while (lp <= ls && (p = strstr(s,pattern)))
3002 memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
3003 memcpy(p,insert,li);
3010 /*********************************************************
3011 * Recursive routine that is called by mask_match.
3012 * Does the actual matching. Returns True if matched,
3014 *********************************************************/
3016 BOOL do_match(char *str, char *regexp, int case_sig)
3020 for( p = regexp; *p && *str; ) {
3027 /* Look for a character matching
3028 the one after the '*' */
3031 return True; /* Automatic match */
3033 while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
3035 /* Now eat all characters that match, as
3036 we want the *last* character to match. */
3037 while(*str && (case_sig ? (*p == *str) : (toupper(*p)==toupper(*str))))
3039 str--; /* We've eaten the match char after the '*' */
3040 if(do_match(str,p,case_sig)) {
3057 if(toupper(*str) != toupper(*p)) {
3069 if (!*p && str[0] == '.' && str[1] == 0) {
3073 if (!*str && *p == '?') {
3079 if(!*str && (*p == '*' && p[1] == '\0')) {
3087 /*********************************************************
3088 * Routine to match a given string with a regexp - uses
3089 * simplified regexp that takes * and ? only. Case can be
3090 * significant or not.
3091 * The 8.3 handling was rewritten by Ums Harald <Harald.Ums@pro-sieben.de>
3092 *********************************************************/
3094 BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
3097 pstring t_pattern, t_filename, te_pattern, te_filename;
3098 fstring ebase,eext,sbase,sext;
3100 BOOL matched = False;
3102 /* Make local copies of str and regexp */
3103 pstrcpy(t_pattern,regexp);
3104 pstrcpy(t_filename,str);
3108 * Not sure if this is a good idea. JRA.
3110 if(trans2 && is_8_3(t_pattern,False) && is_8_3(t_filename,False))
3115 if (!strchr(t_filename,'.')) {
3116 pstrcat(t_filename,".");
3120 /* Remove any *? and ** as they are meaningless */
3121 string_sub(t_pattern, "*?", "*");
3122 string_sub(t_pattern, "**", "*");
3124 if (strequal(t_pattern,"*"))
3127 DEBUG(8,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", t_filename, t_pattern, case_sig));
3131 * Match each component of the regexp, split up by '.'
3134 char *fp, *rp, *cp2, *cp1;
3135 BOOL last_wcard_was_star = False;
3136 int num_path_components, num_regexp_components;
3138 pstrcpy(te_pattern,t_pattern);
3139 pstrcpy(te_filename,t_filename);
3141 * Remove multiple "*." patterns.
3143 string_sub(te_pattern, "*.*.", "*.");
3144 num_regexp_components = count_chars(te_pattern, '.');
3145 num_path_components = count_chars(te_filename, '.');
3148 * Check for special 'hack' case of "DIR a*z". - needs to match a.b.c...z
3150 if(num_regexp_components == 0)
3151 matched = do_match( te_filename, te_pattern, case_sig);
3153 for( cp1 = te_pattern, cp2 = te_filename; cp1;) {
3154 fp = strchr(cp2, '.');
3157 rp = strchr(cp1, '.');
3161 if(cp1[strlen(cp1)-1] == '*')
3162 last_wcard_was_star = True;
3164 last_wcard_was_star = False;
3166 if(!do_match(cp2, cp1, case_sig))
3169 cp1 = rp ? rp + 1 : NULL;
3170 cp2 = fp ? fp + 1 : "";
3172 if(last_wcard_was_star || ((cp1 != NULL) && (*cp1 == '*'))) {
3173 /* Eat the extra path components. */
3176 for(i = 0; i < num_path_components - num_regexp_components; i++) {
3177 fp = strchr(cp2, '.');
3181 if((cp1 != NULL) && do_match( cp2, cp1, case_sig)) {
3182 cp2 = fp ? fp + 1 : "";
3185 cp2 = fp ? fp + 1 : "";
3187 num_path_components -= i;
3190 if(cp1 == NULL && ((*cp2 == '\0') || last_wcard_was_star))
3195 /* -------------------------------------------------
3196 * Behaviour of Win95
3197 * for 8.3 filenames and 8.3 Wildcards
3198 * -------------------------------------------------
3200 if (strequal (t_filename, ".")) {
3202 * Patterns: *.* *. ?. ? are valid
3205 if(strequal(t_pattern, "*.*") || strequal(t_pattern, "*.") ||
3206 strequal(t_pattern, "?.") || strequal(t_pattern, "?"))
3208 } else if (strequal (t_filename, "..")) {
3210 * Patterns: *.* *. ?. ? *.? are valid
3213 if(strequal(t_pattern, "*.*") || strequal(t_pattern, "*.") ||
3214 strequal(t_pattern, "?.") || strequal(t_pattern, "?") ||
3215 strequal(t_pattern, "*.?") || strequal(t_pattern, "?.*"))
3219 if ((p = strrchr (t_pattern, '.'))) {
3221 * Wildcard has a suffix.
3224 fstrcpy (ebase, t_pattern);
3226 fstrcpy (eext, p + 1);
3228 /* pattern ends in DOT: treat as if there is no DOT */
3230 if (strequal (ebase, "*"))
3235 * No suffix for wildcard.
3237 fstrcpy (ebase, t_pattern);
3241 p = strrchr (t_filename, '.');
3242 if (p && (p[1] == 0) ) {
3244 * Filename has an extension of '.' only.
3246 *p = 0; /* nuke dot at end of string */
3247 p = 0; /* and treat it as if there is no extension */
3252 * Filename has an extension.
3255 fstrcpy (sbase, t_filename);
3256 fstrcpy (sext, p + 1);
3258 matched = do_match(sbase, ebase, case_sig)
3259 && do_match(sext, eext, case_sig);
3261 /* pattern has no extension */
3262 /* Really: match complete filename with pattern ??? means exactly 3 chars */
3263 matched = do_match(str, ebase, case_sig);
3267 * Filename has no extension.
3269 fstrcpy (sbase, t_filename);
3272 /* pattern has extension */
3273 matched = do_match(sbase, ebase, case_sig)
3274 && do_match(sext, eext, case_sig);
3276 matched = do_match(sbase, ebase, case_sig);
3277 #ifdef EMULATE_WEIRD_W95_MATCHING
3279 * Even Microsoft has some problems
3280 * Behaviour Win95 -> local disk
3281 * is different from Win95 -> smb drive from Nt 4.0
3282 * This branch would reflect the Win95 local disk behaviour
3285 /* a? matches aa and a in w95 */
3286 fstrcat (sbase, ".");
3287 matched = do_match(sbase, ebase, case_sig);
3295 DEBUG(8,("mask_match returning %d\n", matched));
3300 /****************************************************************************
3301 become a daemon, discarding the controlling terminal
3302 ****************************************************************************/
3303 void become_daemon(void)
3309 /* detach from the terminal */
3312 #elif defined(TIOCNOTTY)
3314 int i = open("/dev/tty", O_RDWR);
3316 ioctl(i, (int) TIOCNOTTY, (char *)0);
3320 #endif /* HAVE_SETSID */
3322 /* Close fd's 0,1,2. Needed if started by rsh */
3327 /****************************************************************************
3328 put up a yes/no prompt
3329 ****************************************************************************/
3335 if (!fgets(ans,sizeof(ans)-1,stdin))
3338 if (*ans == 'y' || *ans == 'Y')
3344 /****************************************************************************
3345 read a line from a file with possible \ continuation chars.
3346 Blanks at the start or end of a line are stripped.
3347 The string will be allocated if s2 is NULL
3348 ****************************************************************************/
3349 char *fgets_slash(char *s2,int maxlen,FILE *f)
3354 BOOL start_of_line = True;
3361 maxlen = MIN(maxlen,8);
3362 s = (char *)Realloc(s,maxlen);
3365 if (!s || maxlen < 2) return(NULL);
3369 while (len < maxlen-1)
3377 while (len > 0 && s[len-1] == ' ')
3381 if (len > 0 && s[len-1] == '\\')
3384 start_of_line = True;
3389 if (len <= 0 && !s2)
3391 return(len>0?s:NULL);
3396 start_of_line = False;
3400 if (!s2 && len > maxlen-3)
3403 s = (char *)Realloc(s,maxlen);
3404 if (!s) return(NULL);
3412 /****************************************************************************
3413 set the length of a file from a filedescriptor.
3414 Returns 0 on success, -1 on failure.
3415 ****************************************************************************/
3416 int set_filelen(int fd, long len)
3418 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
3419 extend a file with ftruncate. Provide alternate implementation
3422 #ifdef HAVE_FTRUNCATE_EXTEND
3423 return ftruncate(fd, len);
3427 long currpos = lseek(fd, 0L, SEEK_CUR);
3431 /* Do an fstat to see if the file is longer than
3432 the requested size (call ftruncate),
3433 or shorter, in which case seek to len - 1 and write 1
3435 if(fstat(fd, &st)<0)
3439 if (S_ISFIFO(st.st_mode)) return 0;
3442 if(st.st_size == len)
3444 if(st.st_size > len)
3445 return ftruncate(fd, len);
3447 if(lseek(fd, len-1, SEEK_SET) != len -1)
3449 if(write(fd, &c, 1)!=1)
3451 /* Seek to where we were */
3452 lseek(fd, currpos, SEEK_SET);
3458 /****************************************************************************
3459 return the byte checksum of some data
3460 ****************************************************************************/
3461 int byte_checksum(char *buf,int len)
3463 unsigned char *p = (unsigned char *)buf;
3473 /****************************************************************************
3474 this is a version of setbuffer() for those machines that only have setvbuf
3475 ****************************************************************************/
3476 void setbuffer(FILE *f,char *buf,int bufsize)
3478 setvbuf(f,buf,_IOFBF,bufsize);
3483 /****************************************************************************
3484 parse out a directory name from a path name. Assumes dos style filenames.
3485 ****************************************************************************/
3486 char *dirname_dos(char *path,char *buf)
3488 char *p = strrchr(path,'\\');
3503 /****************************************************************************
3504 parse out a filename from a path name. Assumes dos style filenames.
3505 ****************************************************************************/
3506 static char *filename_dos(char *path,char *buf)
3508 char *p = strrchr(path,'\\');
3520 /****************************************************************************
3521 expand a pointer to be a particular size
3522 ****************************************************************************/
3523 void *Realloc(void *p,int size)
3529 DEBUG(5,("Realloc asked for 0 bytes\n"));
3534 ret = (void *)malloc(size);
3536 ret = (void *)realloc(p,size);
3539 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
3545 /****************************************************************************
3546 Signal handler for SIGPIPE (write on a disconnected socket)
3547 ****************************************************************************/
3550 DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
3554 /****************************************************************************
3555 get my own name and IP
3556 ****************************************************************************/
3557 BOOL get_myname(char *my_name,struct in_addr *ip)
3564 /* get my host name */
3565 if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
3567 DEBUG(0,("gethostname failed\n"));
3572 if ((hp = Get_Hostbyname(hostname)) == 0)
3574 DEBUG(0,( "Get_Hostbyname: Unknown host %s\n",hostname));
3580 /* split off any parts after an initial . */
3581 char *p = strchr(hostname,'.');
3584 fstrcpy(my_name,hostname);
3588 putip((char *)ip,(char *)hp->h_addr);
3594 /****************************************************************************
3595 true if two IP addresses are equal
3596 ****************************************************************************/
3597 BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
3600 a1 = ntohl(ip1.s_addr);
3601 a2 = ntohl(ip2.s_addr);
3606 /****************************************************************************
3607 open a socket of the specified type, port and address for incoming data
3608 ****************************************************************************/
3609 int open_socket_in(int type, int port, int dlevel,uint32 socket_addr)
3612 struct sockaddr_in sock;
3616 /* get my host name */
3617 if (gethostname(host_name, MAXHOSTNAMELEN) == -1)
3618 { DEBUG(0,("gethostname failed\n")); return -1; }
3621 if ((hp = Get_Hostbyname(host_name)) == 0)
3623 DEBUG(0,( "Get_Hostbyname: Unknown host %s\n",host_name));
3627 bzero((char *)&sock,sizeof(sock));
3628 memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
3630 #ifdef HAVE_SOCK_SIN_LEN
3631 sock.sin_len = sizeof(sock);
3633 sock.sin_port = htons( port );
3634 sock.sin_family = hp->h_addrtype;
3635 sock.sin_addr.s_addr = socket_addr;
3636 res = socket(hp->h_addrtype, type, 0);
3638 { DEBUG(0,("socket failed\n")); return -1; }
3642 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
3645 /* now we've got a socket - we need to bind it */
3646 if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0)
3649 if (port == SMB_PORT || port == NMB_PORT)
3650 DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
3651 port,inet_ntoa(sock.sin_addr),strerror(errno)));
3654 if (dlevel > 0 && port < 1000)
3657 if (port >= 1000 && port < 9000)
3658 return(open_socket_in(type,port+1,dlevel,socket_addr));
3663 DEBUG(3,("bind succeeded on port %d\n",port));
3669 /****************************************************************************
3670 create an outgoing socket
3671 **************************************************************************/
3672 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
3674 struct sockaddr_in sock_out;
3676 int connect_loop = 250; /* 250 milliseconds */
3677 int loops = (timeout * 1000) / connect_loop;
3679 /* create a socket to write to */
3680 res = socket(PF_INET, type, 0);
3682 { DEBUG(0,("socket error\n")); return -1; }
3684 if (type != SOCK_STREAM) return(res);
3686 bzero((char *)&sock_out,sizeof(sock_out));
3687 putip((char *)&sock_out.sin_addr,(char *)addr);
3689 sock_out.sin_port = htons( port );
3690 sock_out.sin_family = PF_INET;
3692 /* set it non-blocking */
3693 set_blocking(res,False);
3695 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
3697 /* and connect it to the destination */
3699 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
3701 /* Some systems return EAGAIN when they mean EINPROGRESS */
3702 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3703 errno == EAGAIN) && loops--) {
3704 msleep(connect_loop);
3708 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3710 DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
3716 if (ret < 0 && errno == EISCONN) {
3723 DEBUG(1,("error connecting to %s:%d (%s)\n",
3724 inet_ntoa(*addr),port,strerror(errno)));
3729 /* set it blocking again */
3730 set_blocking(res,True);
3736 /****************************************************************************
3737 interpret a protocol description string, with a default
3738 ****************************************************************************/
3739 int interpret_protocol(char *str,int def)
3741 if (strequal(str,"NT1"))
3742 return(PROTOCOL_NT1);
3743 if (strequal(str,"LANMAN2"))
3744 return(PROTOCOL_LANMAN2);
3745 if (strequal(str,"LANMAN1"))
3746 return(PROTOCOL_LANMAN1);
3747 if (strequal(str,"CORE"))
3748 return(PROTOCOL_CORE);
3749 if (strequal(str,"COREPLUS"))
3750 return(PROTOCOL_COREPLUS);
3751 if (strequal(str,"CORE+"))
3752 return(PROTOCOL_COREPLUS);
3754 DEBUG(0,("Unrecognised protocol level %s\n",str));
3759 /****************************************************************************
3760 interpret a security level
3761 ****************************************************************************/
3762 int interpret_security(char *str,int def)
3764 if (strequal(str,"SERVER"))
3766 if (strequal(str,"USER"))
3768 if (strequal(str,"SHARE"))
3771 DEBUG(0,("Unrecognised security level %s\n",str));
3777 /****************************************************************************
3778 interpret an internet address or name into an IP address in 4 byte form
3779 ****************************************************************************/
3780 uint32 interpret_addr(char *str)
3785 BOOL pure_address = True;
3787 if (strcmp(str,"0.0.0.0") == 0) return(0);
3788 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
3790 for (i=0; pure_address && str[i]; i++)
3791 if (!(isdigit(str[i]) || str[i] == '.'))
3792 pure_address = False;
3794 /* if it's in the form of an IP address then get the lib to interpret it */
3796 res = inet_addr(str);
3798 /* otherwise assume it's a network name of some sort and use
3800 if ((hp = Get_Hostbyname(str)) == 0) {
3801 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
3804 if(hp->h_addr == NULL) {
3805 DEBUG(3,("Get_Hostbyname: host address is invalid for host %s\n",str));
3808 putip((char *)&res,(char *)hp->h_addr);
3811 if (res == (uint32)-1) return(0);
3816 /*******************************************************************
3817 a convenient addition to interpret_addr()
3818 ******************************************************************/
3819 struct in_addr *interpret_addr2(char *str)
3821 static struct in_addr ret;
3822 uint32 a = interpret_addr(str);
3827 /*******************************************************************
3828 check if an IP is the 0.0.0.0
3829 ******************************************************************/
3830 BOOL zero_ip(struct in_addr ip)
3833 putip((char *)&a,(char *)&ip);
3838 /*******************************************************************
3839 matchname - determine if host name matches IP address
3840 ******************************************************************/
3841 static BOOL matchname(char *remotehost,struct in_addr addr)
3846 if ((hp = Get_Hostbyname(remotehost)) == 0) {
3847 DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
3852 * Make sure that gethostbyname() returns the "correct" host name.
3853 * Unfortunately, gethostbyname("localhost") sometimes yields
3854 * "localhost.domain". Since the latter host name comes from the
3855 * local DNS, we just have to trust it (all bets are off if the local
3856 * DNS is perverted). We always check the address list, though.
3859 if (strcasecmp(remotehost, hp->h_name)
3860 && strcasecmp(remotehost, "localhost")) {
3861 DEBUG(0,("host name/name mismatch: %s != %s",
3862 remotehost, hp->h_name));
3866 /* Look up the host address in the address list we just got. */
3867 for (i = 0; hp->h_addr_list[i]; i++) {
3868 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
3873 * The host name does not map to the original host address. Perhaps
3874 * someone has compromised a name server. More likely someone botched
3875 * it, but that could be dangerous, too.
3878 DEBUG(0,("host name/address mismatch: %s != %s",
3879 inet_ntoa(addr), hp->h_name));
3883 /*******************************************************************
3884 Reset the 'done' variables so after a client process is created
3885 from a fork call these calls will be re-done. This should be
3886 expanded if more variables need reseting.
3887 ******************************************************************/
3889 static BOOL global_client_name_done = False;
3890 static BOOL global_client_addr_done = False;
3892 void reset_globals_after_fork(void)
3894 global_client_name_done = False;
3895 global_client_addr_done = False;
3898 * Re-seed the random crypto generator, so all smbd's
3899 * started from the same parent won't generate the same
3903 unsigned char dummy;
3904 generate_random_buffer( &dummy, 1, True);
3908 /*******************************************************************
3909 return the DNS name of the client
3910 ******************************************************************/
3911 char *client_name(int fd)
3914 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3915 int length = sizeof(sa);
3916 static pstring name_buf;
3918 static int last_fd=-1;
3920 if (global_client_name_done && last_fd == fd)
3924 global_client_name_done = False;
3926 pstrcpy(name_buf,"UNKNOWN");
3932 if (getpeername(fd, &sa, &length) < 0) {
3933 DEBUG(0,("getpeername failed\n"));
3937 /* Look up the remote host name. */
3938 if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
3939 sizeof(sockin->sin_addr),
3941 DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr(fd)));
3942 StrnCpy(name_buf,client_addr(fd),sizeof(name_buf) - 1);
3944 StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
3945 if (!matchname(name_buf, sockin->sin_addr)) {
3946 DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr(fd)));
3947 pstrcpy(name_buf,"UNKNOWN");
3950 global_client_name_done = True;
3954 /*******************************************************************
3955 return the IP addr of the client as a string
3956 ******************************************************************/
3957 char *client_addr(int fd)
3960 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3961 int length = sizeof(sa);
3962 static fstring addr_buf;
3963 static int last_fd = -1;
3965 if (global_client_addr_done && fd == last_fd)
3969 global_client_addr_done = False;
3971 fstrcpy(addr_buf,"0.0.0.0");
3977 if (getpeername(fd, &sa, &length) < 0) {
3978 DEBUG(0,("getpeername failed\n"));
3982 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
3984 global_client_addr_done = True;
3988 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
3989 /******************************************************************
3990 Remove any mount options such as -rsize=2048,wsize=2048 etc.
3991 Based on a fix from <Thomas.Hepper@icem.de>.
3992 *******************************************************************/
3994 static void strip_mount_options( pstring *str)
3999 while(*p && !isspace(*p))
4001 while(*p && isspace(*p))
4006 pstrcpy(tmp_str, p);
4007 pstrcpy(*str, tmp_str);
4012 /*******************************************************************
4013 Patch from jkf@soton.ac.uk
4014 Split Luke's automount_server into YP lookup and string splitter
4015 so can easily implement automount_path().
4016 As we may end up doing both, cache the last YP result.
4017 *******************************************************************/
4020 static char *automount_lookup(char *user_name)
4022 static fstring last_key = "";
4023 static pstring last_value = "";
4025 char *nis_map = (char *)lp_nis_home_map_name();
4027 char nis_domain[NIS_MAXNAMELEN + 1];
4028 char buffer[NIS_MAXATTRVAL + 1];
4033 strncpy(nis_domain, (char *)nis_local_directory(), NIS_MAXNAMELEN);
4034 nis_domain[NIS_MAXNAMELEN] = '\0';
4036 DEBUG(5, ("NIS+ Domain: %s\n", nis_domain));
4038 if (strcmp(user_name, last_key))
4040 slprintf(buffer, sizeof(buffer)-1, "[%s=%s]%s.%s", "key", user_name, nis_map, nis_domain);
4041 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
4043 if (result = nis_list(buffer, RETURN_RESULT, NULL, NULL))
4045 if (result->status != NIS_SUCCESS)
4047 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
4048 fstrcpy(last_key, ""); pstrcpy(last_value, "");
4052 object = result->objects.objects_val;
4053 if (object->zo_data.zo_type == ENTRY_OBJ)
4055 entry = &object->zo_data.objdata_u.en_data;
4056 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
4057 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
4059 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
4060 string_sub(last_value, "&", user_name);
4061 fstrcpy(last_key, user_name);
4065 nis_freeresult(result);
4068 strip_mount_options(&last_value);
4070 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
4073 #else /* NISPLUS_HOME */
4074 static char *automount_lookup(char *user_name)
4076 static fstring last_key = "";
4077 static pstring last_value = "";
4079 int nis_error; /* returned by yp all functions */
4080 char *nis_result; /* yp_match inits this */
4081 int nis_result_len; /* and set this */
4082 char *nis_domain; /* yp_get_default_domain inits this */
4083 char *nis_map = (char *)lp_nis_home_map_name();
4085 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0)
4087 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
4091 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
4093 if (!strcmp(user_name, last_key))
4095 nis_result = last_value;
4096 nis_result_len = strlen(last_value);
4101 if ((nis_error = yp_match(nis_domain, nis_map,
4102 user_name, strlen(user_name),
4103 &nis_result, &nis_result_len)) != 0)
4105 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
4106 yperr_string(nis_error), user_name, nis_map));
4108 if (!nis_error && nis_result_len >= sizeof(pstring))
4110 nis_result_len = sizeof(pstring)-1;
4112 fstrcpy(last_key, user_name);
4113 strncpy(last_value, nis_result, nis_result_len);
4114 last_value[nis_result_len] = '\0';
4117 strip_mount_options(&last_value);
4119 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
4122 #endif /* NISPLUS_HOME */
4125 /*******************************************************************
4126 Patch from jkf@soton.ac.uk
4127 This is Luke's original function with the NIS lookup code
4128 moved out to a separate function.
4129 *******************************************************************/
4131 char *automount_server(char *user_name)
4133 static pstring server_name;
4135 /* use the local machine name as the default */
4136 /* this will be the default if WITH_AUTOMOUNT is not used or fails */
4137 pstrcpy(server_name, local_machine);
4139 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
4141 if (lp_nis_home_map())
4143 int home_server_len;
4144 char *automount_value = automount_lookup(user_name);
4145 home_server_len = strcspn(automount_value,":");
4146 DEBUG(5, ("NIS lookup succeeded. Home server length: %d\n",home_server_len));
4147 if (home_server_len > sizeof(pstring))
4149 home_server_len = sizeof(pstring);
4151 strncpy(server_name, automount_value, home_server_len);
4152 server_name[home_server_len] = '\0';
4156 DEBUG(4,("Home server: %s\n", server_name));
4161 /*******************************************************************
4162 Patch from jkf@soton.ac.uk
4163 Added this to implement %p (NIS auto-map version of %H)
4164 *******************************************************************/
4166 char *automount_path(char *user_name)
4168 static pstring server_path;
4170 /* use the passwd entry as the default */
4171 /* this will be the default if WITH_AUTOMOUNT is not used or fails */
4172 /* pstrcpy() copes with get_home_dir() returning NULL */
4173 pstrcpy(server_path, get_home_dir(user_name));
4175 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
4177 if (lp_nis_home_map())
4179 char *home_path_start;
4180 char *automount_value = automount_lookup(user_name);
4181 home_path_start = strchr(automount_value,':');
4182 if (home_path_start != NULL)
4184 DEBUG(5, ("NIS lookup succeeded. Home path is: %s\n",
4185 home_path_start?(home_path_start+1):""));
4186 pstrcpy(server_path, home_path_start+1);
4191 DEBUG(4,("Home server path: %s\n", server_path));
4197 /*******************************************************************
4198 sub strings with useful parameters
4199 Rewritten by Stefaan A Eeckels <Stefaan.Eeckels@ecc.lu> and
4200 Paul Rippin <pr3245@nopc.eurostat.cec.be>
4201 ********************************************************************/
4202 void standard_sub_basic(char *str)
4206 struct passwd *pass;
4207 char *username = sam_logon_in_ssb ? samlogon_user : sesssetup_user;
4209 for (s = str ; s && *s && (p = strchr(s,'%')); s = p )
4215 if ((pass = Get_Pwnam(username,False))!=NULL)
4217 string_sub(p,"%G",gidtoname(pass->pw_gid));
4225 case 'N' : string_sub(p,"%N", automount_server(username)); break;
4226 case 'I' : string_sub(p,"%I", client_addr(Client)); break;
4227 case 'L' : string_sub(p,"%L", local_machine); break;
4228 case 'M' : string_sub(p,"%M", client_name(Client)); break;
4229 case 'R' : string_sub(p,"%R", remote_proto); break;
4230 case 'T' : string_sub(p,"%T", timestring()); break;
4231 case 'U' : string_sub(p,"%U", username); break;
4232 case 'a' : string_sub(p,"%a", remote_arch); break;
4235 slprintf(pidstr,sizeof(pidstr) - 1, "%d",(int)getpid());
4236 string_sub(p,"%d", pidstr);
4239 case 'h' : string_sub(p,"%h", myhostname); break;
4240 case 'm' : string_sub(p,"%m", remote_machine); break;
4241 case 'v' : string_sub(p,"%v", VERSION); break;
4242 case '$' : /* Expand environment variables */
4244 /* Contributed by Branko Cibej <branko.cibej@hermes.si> */
4255 if ((q = strchr(p,')')) == NULL)
4257 DEBUG(0,("standard_sub_basic: Unterminated environment \
4258 variable [%s]\n", p));
4264 copylen = MIN((q-r),(sizeof(envname)-1));
4265 strncpy(envname,r,copylen);
4266 envname[copylen] = '\0';
4268 if ((envval = getenv(envname)) == NULL)
4270 DEBUG(0,("standard_sub_basic: Environment variable [%s] not set\n",
4276 copylen = MIN((q+1-p),(sizeof(envname)-1));
4277 strncpy(envname,p,copylen);
4278 envname[copylen] = '\0';
4279 string_sub(p,envname,envval);
4282 case '\0': p++; break; /* don't run off end if last character is % */
4283 default : p+=2; break;
4289 /*******************************************************************
4290 are two IPs on the same subnet?
4291 ********************************************************************/
4292 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
4294 uint32 net1,net2,nmask;
4296 nmask = ntohl(mask.s_addr);
4297 net1 = ntohl(ip1.s_addr);
4298 net2 = ntohl(ip2.s_addr);
4300 return((net1 & nmask) == (net2 & nmask));
4304 /*******************************************************************
4305 write a string in unicoode format
4306 ********************************************************************/
4307 int PutUniCode(char *dst,char *src)
4311 dst[ret++] = src[0];
4320 /****************************************************************************
4321 a wrapper for gethostbyname() that tries with all lower and all upper case
4322 if the initial name fails
4323 ****************************************************************************/
4324 struct hostent *Get_Hostbyname(char *name)
4326 char *name2 = strdup(name);
4327 struct hostent *ret;
4331 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
4337 * This next test is redundent and causes some systems (with
4338 * broken isalnum() calls) problems.
4343 if (!isalnum(*name2))
4350 ret = sys_gethostbyname(name2);
4357 /* try with all lowercase */
4359 ret = sys_gethostbyname(name2);
4366 /* try with all uppercase */
4368 ret = sys_gethostbyname(name2);
4375 /* nothing works :-( */
4381 /****************************************************************************
4382 check if a process exists. Does this work on all unixes?
4383 ****************************************************************************/
4384 BOOL process_exists(int pid)
4386 return(kill(pid,0) == 0 || errno != ESRCH);
4390 /*******************************************************************
4391 turn a uid into a user name
4392 ********************************************************************/
4393 char *uidtoname(int uid)
4395 static char name[40];
4396 struct passwd *pass = getpwuid(uid);
4397 if (pass) return(pass->pw_name);
4398 slprintf(name, sizeof(name) - 1, "%d",uid);
4402 /*******************************************************************
4403 turn a gid into a group name
4404 ********************************************************************/
4405 char *gidtoname(int gid)
4407 static char name[40];
4408 struct group *grp = getgrgid(gid);
4409 if (grp) return(grp->gr_name);
4410 slprintf(name,sizeof(name) - 1, "%d",gid);
4415 /*******************************************************************
4416 my own panic function - not suitable for general use
4417 ********************************************************************/
4418 void ajt_panic(void)
4420 system("/usr/bin/X11/xedit -display :0 /tmp/ERROR_FAULT");
4425 /*******************************************************************
4426 a readdir wrapper which just returns the file name
4427 also return the inode number if requested
4428 ********************************************************************/
4429 char *readdirname(void *p)
4434 if (!p) return(NULL);
4436 ptr = (struct dirent *)readdir(p);
4437 if (!ptr) return(NULL);
4439 dname = ptr->d_name;
4442 if (telldir(p) < 0) return(NULL);
4445 #ifdef HAVE_BROKEN_READDIR
4446 /* using /usr/ucb/cc is BAD */
4452 memcpy(buf, dname, NAMLEN(ptr)+1);
4453 unix_to_dos(buf, True);
4460 /*******************************************************************
4461 Utility function used to decide if the last component
4462 of a path matches a (possibly wildcarded) entry in a namelist.
4463 ********************************************************************/
4465 BOOL is_in_path(char *name, name_compare_entry *namelist)
4467 pstring last_component;
4470 DEBUG(8, ("is_in_path: %s\n", name));
4472 /* if we have no list it's obviously not in the path */
4473 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
4475 DEBUG(8,("is_in_path: no name list.\n"));
4479 /* Get the last component of the unix name. */
4480 p = strrchr(name, '/');
4481 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
4482 last_component[sizeof(last_component)-1] = '\0';
4484 for(; namelist->name != NULL; namelist++)
4486 if(namelist->is_wild)
4488 /* look for a wildcard match. */
4489 if (mask_match(last_component, namelist->name, case_sensitive, False))
4491 DEBUG(8,("is_in_path: mask match succeeded\n"));
4497 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
4498 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
4500 DEBUG(8,("is_in_path: match succeeded\n"));
4505 DEBUG(8,("is_in_path: match not found\n"));
4510 /*******************************************************************
4511 Strip a '/' separated list into an array of
4512 name_compare_enties structures suitable for
4513 passing to is_in_path(). We do this for
4514 speed so we can pre-parse all the names in the list
4515 and don't do it for each call to is_in_path().
4516 namelist is modified here and is assumed to be
4517 a copy owned by the caller.
4518 We also check if the entry contains a wildcard to
4519 remove a potentially expensive call to mask_match
4521 ********************************************************************/
4523 void set_namearray(name_compare_entry **ppname_array, char *namelist)
4526 char *nameptr = namelist;
4527 int num_entries = 0;
4530 (*ppname_array) = NULL;
4532 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
4535 /* We need to make two passes over the string. The
4536 first to count the number of elements, the second
4541 if ( *nameptr == '/' )
4543 /* cope with multiple (useless) /s) */
4547 /* find the next / */
4548 name_end = strchr(nameptr, '/');
4550 /* oops - the last check for a / didn't find one. */
4551 if (name_end == NULL)
4554 /* next segment please */
4555 nameptr = name_end + 1;
4559 if(num_entries == 0)
4562 if(( (*ppname_array) = (name_compare_entry *)malloc(
4563 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
4565 DEBUG(0,("set_namearray: malloc fail\n"));
4569 /* Now copy out the names */
4574 if ( *nameptr == '/' )
4576 /* cope with multiple (useless) /s) */
4580 /* find the next / */
4581 if ((name_end = strchr(nameptr, '/')) != NULL)
4586 /* oops - the last check for a / didn't find one. */
4587 if(name_end == NULL)
4590 (*ppname_array)[i].is_wild = ((strchr( nameptr, '?')!=NULL) ||
4591 (strchr( nameptr, '*')!=NULL));
4592 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
4594 DEBUG(0,("set_namearray: malloc fail (1)\n"));
4598 /* next segment please */
4599 nameptr = name_end + 1;
4603 (*ppname_array)[i].name = NULL;
4608 /****************************************************************************
4609 routine to free a namearray.
4610 ****************************************************************************/
4612 void free_namearray(name_compare_entry *name_array)
4617 if(name_array->name != NULL)
4618 free(name_array->name);
4620 free((char *)name_array);
4623 /****************************************************************************
4624 routine to do file locking
4625 ****************************************************************************/
4626 BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
4633 uint32 mask = 0xC0000000;
4635 /* make sure the count is reasonable, we might kill the lockd otherwise */
4638 /* the offset is often strange - remove 2 of its bits if either of
4639 the top two bits are set. Shift the top ones by two bits. This
4640 still allows OLE2 apps to operate, but should stop lockd from
4642 if ((offset & mask) != 0)
4643 offset = (offset & ~mask) | ((offset & mask) >> 2);
4645 uint32 mask = ((unsigned)1<<31);
4647 /* interpret negative counts as large numbers */
4651 /* no negative offsets */
4654 /* count + offset must be in range */
4655 while ((offset < 0 || (offset + count < 0)) && mask)
4663 DEBUG(8,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
4666 lock.l_whence = SEEK_SET;
4667 lock.l_start = (int)offset;
4668 lock.l_len = (int)count;
4673 ret = fcntl(fd,op,&lock);
4676 DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
4682 (lock.l_type != F_UNLCK) &&
4683 (lock.l_pid != 0) &&
4684 (lock.l_pid != getpid()))
4686 DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
4690 /* it must be not locked or locked by me */
4694 /* a lock set or unset */
4697 DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
4698 offset,count,op,type,strerror(errno)));
4700 /* perhaps it doesn't support this sort of locking?? */
4701 if (errno == EINVAL)
4703 DEBUG(3,("locking not supported? returning True\n"));
4710 /* everything went OK */
4711 DEBUG(8,("Lock call successful\n"));
4719 /*******************************************************************
4720 lock a file - returning a open file descriptor or -1 on failure
4721 The timeout is in seconds. 0 means no timeout
4722 ********************************************************************/
4723 int file_lock(char *name,int timeout)
4725 int fd = open(name,O_RDWR|O_CREAT,0666);
4727 if (fd < 0) return(-1);
4730 if (timeout) t = time(NULL);
4731 while (!timeout || (time(NULL)-t < timeout)) {
4732 if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);
4733 msleep(LOCK_RETRY_TIMEOUT);
4741 /*******************************************************************
4742 unlock a file locked by file_lock
4743 ********************************************************************/
4744 void file_unlock(int fd)
4748 fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
4753 /*******************************************************************
4754 is the name specified one of my netbios names
4755 returns true is it is equal, false otherwise
4756 ********************************************************************/
4757 BOOL is_myname(char *s)
4762 for (n=0; my_netbios_names[n]; n++) {
4763 if (strequal(my_netbios_names[n], s))
4766 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
4770 /*******************************************************************
4771 set the horrid remote_arch string based on an enum.
4772 ********************************************************************/
4773 void set_remote_arch(enum remote_arch_types type)
4779 fstrcpy(remote_arch, "WfWg");
4782 fstrcpy(remote_arch, "OS2");
4785 fstrcpy(remote_arch, "Win95");
4788 fstrcpy(remote_arch, "WinNT");
4791 fstrcpy(remote_arch,"Samba");
4794 ra_type = RA_UNKNOWN;
4795 fstrcpy(remote_arch, "UNKNOWN");
4800 /*******************************************************************
4801 Get the remote_arch type.
4802 ********************************************************************/
4803 enum remote_arch_types get_remote_arch(void)
4809 /*******************************************************************
4810 skip past some unicode strings in a buffer
4811 ********************************************************************/
4812 char *skip_unicode_string(char *buf,int n)
4823 /*******************************************************************
4824 Return a ascii version of a unicode string
4825 Hack alert: uses fixed buffer(s) and only handles ascii strings
4826 ********************************************************************/
4828 char *unistrn2(uint16 *buf, int len)
4830 static char lbufs[8][MAXUNI];
4832 char *lbuf = lbufs[nexti];
4835 nexti = (nexti+1)%8;
4837 DEBUG(10, ("unistrn2: "));
4839 for (p = lbuf; *buf && p-lbuf < MAXUNI-2 && len > 0; len--, p++, buf++)
4841 DEBUG(10, ("%4x ", *buf));
4851 /*******************************************************************
4852 Return a ascii version of a unicode string
4853 Hack alert: uses fixed buffer(s) and only handles ascii strings
4854 ********************************************************************/
4856 char *unistr2(uint16 *buf)
4858 static char lbufs[8][MAXUNI];
4860 char *lbuf = lbufs[nexti];
4863 nexti = (nexti+1)%8;
4865 DEBUG(10, ("unistr2: "));
4867 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf++)
4869 DEBUG(10, ("%4x ", *buf));
4879 /*******************************************************************
4880 create a null-terminated unicode string from a null-terminated ascii string.
4881 return number of unicode chars copied, excluding the null character.
4883 only handles ascii strings
4884 ********************************************************************/
4886 int struni2(uint16 *p, char *buf)
4890 if (p == NULL) return 0;
4892 DEBUG(10, ("struni2: "));
4896 for (; *buf && len < MAXUNI-2; len++, p++, buf++)
4898 DEBUG(10, ("%2x ", *buf));
4910 /*******************************************************************
4911 Return a ascii version of a unicode string
4912 Hack alert: uses fixed buffer(s) and only handles ascii strings
4913 ********************************************************************/
4915 char *unistr(char *buf)
4917 static char lbufs[8][MAXUNI];
4919 char *lbuf = lbufs[nexti];
4922 nexti = (nexti+1)%8;
4924 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf += 2)
4932 /*******************************************************************
4933 strncpy for unicode strings
4934 ********************************************************************/
4935 int unistrncpy(char *dst, char *src, int len)
4939 while (*src && len > 0)
4953 /*******************************************************************
4954 strcpy for unicode strings. returns length (in num of wide chars)
4955 ********************************************************************/
4956 int unistrcpy(char *dst, char *src)
4972 /*******************************************************************
4973 safe string copy into a known length string. maxlength does not
4974 include the terminating zero.
4975 ********************************************************************/
4976 char *safe_strcpy(char *dest, char *src, int maxlength)
4981 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
4992 if (len > maxlength) {
4993 DEBUG(0,("ERROR: string overflow by %d in safe_strcpy [%.50s]\n",
4994 len-maxlength, src));
4998 memcpy(dest, src, len);
5003 /*******************************************************************
5004 safe string cat into a string. maxlength does not
5005 include the terminating zero.
5006 ********************************************************************/
5007 char *safe_strcat(char *dest, char *src, int maxlength)
5009 int src_len, dest_len;
5012 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
5020 src_len = strlen(src);
5021 dest_len = strlen(dest);
5023 if (src_len + dest_len > maxlength) {
5024 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
5025 src_len + dest_len - maxlength, src));
5026 src_len = maxlength - dest_len;
5029 memcpy(&dest[dest_len], src, src_len);
5030 dest[dest_len + src_len] = 0;
5034 /*******************************************************************
5035 align a pointer to a multiple of 4 bytes
5036 ********************************************************************/
5037 char *align4(char *q, char *base)
5041 q += 4 - ((q - base) & 3);
5046 /*******************************************************************
5047 align a pointer to a multiple of 2 bytes
5048 ********************************************************************/
5049 char *align2(char *q, char *base)
5058 /*******************************************************************
5059 align a pointer to a multiple of align_offset bytes. looks like it
5060 will work for offsets of 0, 2 and 4...
5061 ********************************************************************/
5062 char *align_offset(char *q, char *base, int align_offset_len)
5064 int mod = ((q - base) & (align_offset_len-1));
5065 if (align_offset_len != 0 && mod != 0)
5067 q += align_offset_len - mod;
5072 void print_asc(int level, unsigned char *buf,int len)
5076 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
5079 void dump_data(int level,char *buf1,int len)
5081 unsigned char *buf = (unsigned char *)buf1;
5085 DEBUG(level,("[%03X] ",i));
5087 DEBUG(level,("%02X ",(int)buf[i]));
5089 if (i%8 == 0) DEBUG(level,(" "));
5091 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
5092 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
5093 if (i<len) DEBUG(level,("[%03X] ",i));
5101 if (n>8) DEBUG(level,(" "));
5102 while (n--) DEBUG(level,(" "));
5105 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
5107 if (n>0) print_asc(level,&buf[i-n],n);
5108 DEBUG(level,("\n"));
5112 char *tab_depth(int depth)
5114 static pstring spaces;
5115 memset(spaces, ' ', depth * 4);
5116 spaces[depth * 4] = 0;
5120 /*****************************************************************
5121 Convert a SID to an ascii string.
5122 *****************************************************************/
5124 char *sid_to_string(pstring sidstr_out, DOM_SID *sid)
5128 /* BIG NOTE: this function only does SIDS where the identauth is not >= 2^32 */
5129 uint32 ia = (sid->id_auth[5]) +
5130 (sid->id_auth[4] << 8 ) +
5131 (sid->id_auth[3] << 16) +
5132 (sid->id_auth[2] << 24);
5134 slprintf(sidstr_out, sizeof(pstring) - 1, "S-%d-%d", sid->sid_rev_num, ia);
5136 for (i = 0; i < sid->num_auths; i++)
5138 slprintf(subauth, sizeof(subauth)-1, "-%d", sid->sub_auths[i]);
5139 pstrcat(sidstr_out, subauth);
5142 DEBUG(7,("sid_to_string returning %s\n", sidstr_out));
5146 /*****************************************************************
5147 Convert a string to a SID. Returns True on success, False on fail.
5148 *****************************************************************/
5150 BOOL string_to_sid(DOM_SID *sidout, char *sidstr)
5154 /* BIG NOTE: this function only does SIDS where the identauth is not >= 2^32 */
5157 memset((char *)sidout, '\0', sizeof(DOM_SID));
5159 if(StrnCaseCmp( sidstr, "S-", 2)) {
5160 DEBUG(0,("string_to_sid: Sid %s does not start with 'S-'.\n", sidstr));
5165 if(!next_token(&p, tok, "-")) {
5166 DEBUG(0,("string_to_sid: Sid %s is not in a valid format.\n", sidstr));
5170 /* Get the revision number. */
5171 sidout->sid_rev_num = atoi(tok);
5173 if(!next_token(&p, tok, "-")) {
5174 DEBUG(0,("string_to_sid: Sid %s is not in a valid format.\n", sidstr));
5178 /* identauth in decimal should be < 2^32 */
5181 /* NOTE - the ia value is in big-endian format. */
5182 sidout->id_auth[0] = 0;
5183 sidout->id_auth[1] = 0;
5184 sidout->id_auth[2] = (ia & 0xff000000) >> 24;
5185 sidout->id_auth[3] = (ia & 0x00ff0000) >> 16;
5186 sidout->id_auth[4] = (ia & 0x0000ff00) >> 8;
5187 sidout->id_auth[5] = (ia & 0x000000ff);
5189 sidout->num_auths = 0;
5191 while(next_token(&p, tok, "-") && sidout->num_auths < MAXSUBAUTHS) {
5193 * NOTE - the subauths are in native machine-endian format. They
5194 * are converted to little-endian when linearized onto the wire.
5196 sidout->sub_auths[sidout->num_auths++] = atoi(tok);
5199 DEBUG(7,("string_to_sid: converted SID %s ok\n", sidstr));