Decouple ldap-ssl-ads from ldap-ssl option
[samba.git] / source3 / lib / util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2007
6    Copyright (C) Simo Sorce 2001
7    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
8    Copyright (C) James Peach 2006
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/passwd.h"
26 #include "system/filesys.h"
27 #include "lib/util/server_id.h"
28 #include "util_tdb.h"
29 #include "ctdbd_conn.h"
30 #include "../lib/util/util_pw.h"
31 #include "messages.h"
32 #include "lib/messaging/messages_dgm.h"
33 #include "libcli/security/security.h"
34 #include "serverid.h"
35 #include "lib/util/sys_rw.h"
36 #include "lib/util/sys_rw_data.h"
37 #include "lib/util/util_process.h"
38 #include "lib/dbwrap/dbwrap_ctdb.h"
39 #include "lib/gencache.h"
40
41 #ifdef HAVE_SYS_PRCTL_H
42 #include <sys/prctl.h>
43 #endif
44
45 /* Max allowable allococation - 256mb - 0x10000000 */
46 #define MAX_ALLOC_SIZE (1024*1024*256)
47
48 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
49 /* rpc/xdr.h uses TRUE and FALSE */
50 #ifdef TRUE
51 #undef TRUE
52 #endif
53
54 #ifdef FALSE
55 #undef FALSE
56 #endif
57
58 #include "system/nis.h"
59
60 #ifdef WITH_NISPLUS_HOME
61 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
62 /*
63  * The following lines are needed due to buggy include files
64  * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
65  * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
66  * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
67  * an enum in /usr/include/rpcsvc/nis.h.
68  */
69
70 #if defined(GROUP)
71 #undef GROUP
72 #endif
73
74 #if defined(GROUP_OBJ)
75 #undef GROUP_OBJ
76 #endif
77
78 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
79
80 #include <rpcsvc/nis.h>
81
82 #endif /* WITH_NISPLUS_HOME */
83 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
84
85 static enum protocol_types Protocol = PROTOCOL_COREPLUS;
86
87 enum protocol_types get_Protocol(void)
88 {
89         return Protocol;
90 }
91
92 void set_Protocol(enum protocol_types  p)
93 {
94         Protocol = p;
95 }
96
97 static enum remote_arch_types ra_type = RA_UNKNOWN;
98
99 void gfree_all( void )
100 {
101         gfree_names();
102         gfree_loadparm();
103         gfree_charcnv();
104         gfree_interfaces();
105         gfree_debugsyms();
106 }
107
108 /*******************************************************************
109  Check if a file exists - call vfs_file_exist for samba files.
110 ********************************************************************/
111
112 bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
113                      bool fake_dir_create_times)
114 {
115         SMB_STRUCT_STAT st;
116         if (!sbuf)
117                 sbuf = &st;
118
119         if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
120                 return(False);
121
122         return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
123 }
124
125 /*******************************************************************
126  Check if a unix domain socket exists - call vfs_file_exist for samba files.
127 ********************************************************************/
128
129 bool socket_exist(const char *fname)
130 {
131         SMB_STRUCT_STAT st;
132         if (sys_stat(fname, &st, false) != 0)
133                 return(False);
134
135         return S_ISSOCK(st.st_ex_mode);
136 }
137
138 /*******************************************************************
139  Returns the size in bytes of the named given the stat struct.
140 ********************************************************************/
141
142 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
143 {
144         return sbuf->st_ex_size;
145 }
146
147 /****************************************************************************
148  Check two stats have identical dev and ino fields.
149 ****************************************************************************/
150
151 bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
152                         const SMB_STRUCT_STAT *sbuf2)
153 {
154         if (sbuf1->st_ex_dev != sbuf2->st_ex_dev ||
155                         sbuf1->st_ex_ino != sbuf2->st_ex_ino) {
156                 return false;
157         }
158         return true;
159 }
160
161 /****************************************************************************
162  Check if a stat struct is identical for use.
163 ****************************************************************************/
164
165 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
166                         const SMB_STRUCT_STAT *sbuf2)
167 {
168         if (sbuf1->st_ex_uid != sbuf2->st_ex_uid ||
169                         sbuf1->st_ex_gid != sbuf2->st_ex_gid ||
170                         !check_same_dev_ino(sbuf1, sbuf2)) {
171                 return false;
172         }
173         return true;
174 }
175
176 /*******************************************************************
177  Show a smb message structure.
178 ********************************************************************/
179
180 void show_msg(const char *buf)
181 {
182         int i;
183         int bcc=0;
184
185         if (!DEBUGLVL(5))
186                 return;
187
188         DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
189                         smb_len(buf),
190                         (int)CVAL(buf,smb_com),
191                         (int)CVAL(buf,smb_rcls),
192                         (int)CVAL(buf,smb_reh),
193                         (int)SVAL(buf,smb_err),
194                         (int)CVAL(buf,smb_flg),
195                         (int)SVAL(buf,smb_flg2)));
196         DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
197                         (int)SVAL(buf,smb_tid),
198                         (int)SVAL(buf,smb_pid),
199                         (int)SVAL(buf,smb_uid),
200                         (int)SVAL(buf,smb_mid)));
201         DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
202
203         for (i=0;i<(int)CVAL(buf,smb_wct);i++)
204                 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
205                         SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
206
207         bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
208
209         DEBUGADD(5,("smb_bcc=%d\n",bcc));
210
211         if (DEBUGLEVEL < 10)
212                 return;
213
214         if (DEBUGLEVEL < 50)
215                 bcc = MIN(bcc, 512);
216
217         dump_data(10, (const uint8_t *)smb_buf_const(buf), bcc);
218 }
219
220 /*******************************************************************
221  Setup only the byte count for a smb message.
222 ********************************************************************/
223
224 int set_message_bcc(char *buf,int num_bytes)
225 {
226         int num_words = CVAL(buf,smb_wct);
227         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
228         _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
229         return (smb_size + num_words*2 + num_bytes);
230 }
231
232 /*******************************************************************
233  Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
234  Return the bytes added
235 ********************************************************************/
236
237 ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
238 {
239         size_t newlen = smb_len(*outbuf) + 4 + blob.length;
240         uint8_t *tmp;
241
242         if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
243                 DEBUG(0, ("talloc failed\n"));
244                 return -1;
245         }
246         *outbuf = tmp;
247
248         memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
249         set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
250         return blob.length;
251 }
252
253 /*******************************************************************
254  Reduce a file name, removing .. elements.
255 ********************************************************************/
256
257 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
258 {
259         char *p = NULL;
260         char *str = NULL;
261
262         DEBUG(3,("dos_clean_name [%s]\n",s));
263
264         /* remove any double slashes */
265         str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
266         if (!str) {
267                 return NULL;
268         }
269
270         /* Remove leading .\\ characters */
271         if(strncmp(str, ".\\", 2) == 0) {
272                 trim_string(str, ".\\", NULL);
273                 if(*str == 0) {
274                         str = talloc_strdup(ctx, ".\\");
275                         if (!str) {
276                                 return NULL;
277                         }
278                 }
279         }
280
281         while ((p = strstr_m(str,"\\..\\")) != NULL) {
282                 char *s1;
283
284                 *p = 0;
285                 s1 = p+3;
286
287                 if ((p=strrchr_m(str,'\\')) != NULL) {
288                         *p = 0;
289                 } else {
290                         *str = 0;
291                 }
292                 str = talloc_asprintf(ctx,
293                                 "%s%s",
294                                 str,
295                                 s1);
296                 if (!str) {
297                         return NULL;
298                 }
299         }
300
301         trim_string(str,NULL,"\\..");
302         return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
303 }
304
305 /*******************************************************************
306  Reduce a file name, removing .. elements.
307 ********************************************************************/
308
309 char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
310 {
311         char *p = NULL;
312         char *str = NULL;
313
314         DEBUG(3,("unix_clean_name [%s]\n",s));
315
316         /* remove any double slashes */
317         str = talloc_all_string_sub(ctx, s, "//","/");
318         if (!str) {
319                 return NULL;
320         }
321
322         /* Remove leading ./ characters */
323         if(strncmp(str, "./", 2) == 0) {
324                 trim_string(str, "./", NULL);
325                 if(*str == 0) {
326                         str = talloc_strdup(ctx, "./");
327                         if (!str) {
328                                 return NULL;
329                         }
330                 }
331         }
332
333         while ((p = strstr_m(str,"/../")) != NULL) {
334                 char *s1;
335
336                 *p = 0;
337                 s1 = p+3;
338
339                 if ((p=strrchr_m(str,'/')) != NULL) {
340                         *p = 0;
341                 } else {
342                         *str = 0;
343                 }
344                 str = talloc_asprintf(ctx,
345                                 "%s%s",
346                                 str,
347                                 s1);
348                 if (!str) {
349                         return NULL;
350                 }
351         }
352
353         trim_string(str,NULL,"/..");
354         return talloc_all_string_sub(ctx, str, "/./", "/");
355 }
356
357 char *clean_name(TALLOC_CTX *ctx, const char *s)
358 {
359         char *str = dos_clean_name(ctx, s);
360         if (!str) {
361                 return NULL;
362         }
363         return unix_clean_name(ctx, str);
364 }
365
366 /*******************************************************************
367  Write data into an fd at a given offset. Ignore seek errors.
368 ********************************************************************/
369
370 ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
371 {
372         size_t total=0;
373         ssize_t ret;
374
375         if (pos == (off_t)-1) {
376                 return write_data(fd, buffer, N);
377         }
378 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
379         while (total < N) {
380                 ret = sys_pwrite(fd,buffer + total,N - total, pos);
381                 if (ret == -1 && errno == ESPIPE) {
382                         return write_data(fd, buffer + total,N - total);
383                 }
384                 if (ret == -1) {
385                         DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
386                         return -1;
387                 }
388                 if (ret == 0) {
389                         return total;
390                 }
391                 total += ret;
392                 pos += ret;
393         }
394         return (ssize_t)total;
395 #else
396         /* Use lseek and write_data. */
397         if (lseek(fd, pos, SEEK_SET) == -1) {
398                 if (errno != ESPIPE) {
399                         return -1;
400                 }
401         }
402         return write_data(fd, buffer, N);
403 #endif
404 }
405
406 static int reinit_after_fork_pipe[2] = { -1, -1 };
407
408 NTSTATUS init_before_fork(void)
409 {
410         int ret;
411
412         ret = pipe(reinit_after_fork_pipe);
413         if (ret == -1) {
414                 NTSTATUS status;
415
416                 status = map_nt_error_from_unix_common(errno);
417
418                 DEBUG(0, ("Error creating child_pipe: %s\n",
419                           nt_errstr(status)));
420
421                 return status;
422         }
423
424         return NT_STATUS_OK;
425 }
426
427 /**
428  * Detect died parent by detecting EOF on the pipe
429  */
430 static void reinit_after_fork_pipe_handler(struct tevent_context *ev,
431                                            struct tevent_fd *fde,
432                                            uint16_t flags,
433                                            void *private_data)
434 {
435         char c;
436
437         if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
438                 /*
439                  * we have reached EOF on stdin, which means the
440                  * parent has exited. Shutdown the server
441                  */
442                 TALLOC_FREE(fde);
443                 (void)kill(getpid(), SIGTERM);
444         }
445 }
446
447
448 NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
449                            struct tevent_context *ev_ctx,
450                            bool parent_longlived,
451                            const char *comment)
452 {
453         NTSTATUS status = NT_STATUS_OK;
454         int ret;
455
456         /*
457          * The main process thread should never
458          * allow per_thread_cwd_enable() to be
459          * called.
460          */
461         per_thread_cwd_disable();
462
463         if (reinit_after_fork_pipe[1] != -1) {
464                 close(reinit_after_fork_pipe[1]);
465                 reinit_after_fork_pipe[1] = -1;
466         }
467
468         /* tdb needs special fork handling */
469         if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
470                 DEBUG(0,("tdb_reopen_all failed.\n"));
471                 status = NT_STATUS_OPEN_FAILED;
472                 goto done;
473         }
474
475         if (ev_ctx != NULL) {
476                 tevent_set_trace_callback(ev_ctx, NULL, NULL);
477                 if (tevent_re_initialise(ev_ctx) != 0) {
478                         smb_panic(__location__ ": Failed to re-initialise event context");
479                 }
480         }
481
482         if (reinit_after_fork_pipe[0] != -1) {
483                 struct tevent_fd *fde;
484
485                 fde = tevent_add_fd(ev_ctx, ev_ctx /* TALLOC_CTX */,
486                                     reinit_after_fork_pipe[0], TEVENT_FD_READ,
487                                     reinit_after_fork_pipe_handler, NULL);
488                 if (fde == NULL) {
489                         smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
490                 }
491         }
492
493         if (msg_ctx) {
494                 /*
495                  * For clustering, we need to re-init our ctdbd connection after the
496                  * fork
497                  */
498                 status = messaging_reinit(msg_ctx);
499                 if (!NT_STATUS_IS_OK(status)) {
500                         DEBUG(0,("messaging_reinit() failed: %s\n",
501                                  nt_errstr(status)));
502                 }
503
504                 if (lp_clustering()) {
505                         ret = ctdb_async_ctx_reinit(
506                                 NULL, messaging_tevent_context(msg_ctx));
507                         if (ret != 0) {
508                                 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
509                                         strerror(errno));
510                                 return map_nt_error_from_unix(ret);
511                         }
512                 }
513         }
514
515         if (comment) {
516                 prctl_set_comment("%s", comment);
517         }
518
519  done:
520         return status;
521 }
522
523 /****************************************************************************
524  (Hopefully) efficient array append.
525 ****************************************************************************/
526
527 void add_to_large_array(TALLOC_CTX *mem_ctx, size_t element_size,
528                         void *element, void *_array, uint32_t *num_elements,
529                         ssize_t *array_size)
530 {
531         void **array = (void **)_array;
532
533         if (*array_size < 0) {
534                 return;
535         }
536
537         if (*array == NULL) {
538                 if (*array_size == 0) {
539                         *array_size = 128;
540                 }
541
542                 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
543                         goto error;
544                 }
545
546                 *array = TALLOC(mem_ctx, element_size * (*array_size));
547                 if (*array == NULL) {
548                         goto error;
549                 }
550         }
551
552         if (*num_elements == *array_size) {
553                 *array_size *= 2;
554
555                 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
556                         goto error;
557                 }
558
559                 *array = TALLOC_REALLOC(mem_ctx, *array,
560                                         element_size * (*array_size));
561
562                 if (*array == NULL) {
563                         goto error;
564                 }
565         }
566
567         memcpy((char *)(*array) + element_size*(*num_elements),
568                element, element_size);
569         *num_elements += 1;
570
571         return;
572
573  error:
574         *num_elements = 0;
575         *array_size = -1;
576 }
577
578 /****************************************************************************
579  Get my own domain name, or "" if we have none.
580 ****************************************************************************/
581
582 char *get_mydnsdomname(TALLOC_CTX *ctx)
583 {
584         const char *domname;
585         char *p;
586
587         domname = get_mydnsfullname();
588         if (!domname) {
589                 return NULL;
590         }
591
592         p = strchr_m(domname, '.');
593         if (p) {
594                 p++;
595                 return talloc_strdup(ctx, p);
596         } else {
597                 return talloc_strdup(ctx, "");
598         }
599 }
600
601 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
602 /******************************************************************
603  Remove any mount options such as -rsize=2048,wsize=2048 etc.
604  Based on a fix from <Thomas.Hepper@icem.de>.
605  Returns a malloc'ed string.
606 *******************************************************************/
607
608 static char *strip_mount_options(TALLOC_CTX *ctx, const char *str)
609 {
610         if (*str == '-') {
611                 const char *p = str;
612                 while(*p && !isspace(*p))
613                         p++;
614                 while(*p && isspace(*p))
615                         p++;
616                 if(*p) {
617                         return talloc_strdup(ctx, p);
618                 }
619         }
620         return NULL;
621 }
622
623 /*******************************************************************
624  Patch from jkf@soton.ac.uk
625  Split Luke's automount_server into YP lookup and string splitter
626  so can easily implement automount_path().
627  Returns a malloc'ed string.
628 *******************************************************************/
629
630 #ifdef WITH_NISPLUS_HOME
631 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
632 {
633         const struct loadparm_substitution *lp_sub =
634                 loadparm_s3_global_substitution();
635         char *value = NULL;
636
637         char *nis_map = (char *)lp_homedir_map(talloc_tos(), lp_sub);
638
639         char buffer[NIS_MAXATTRVAL + 1];
640         nis_result *result;
641         nis_object *object;
642         entry_obj  *entry;
643
644         snprintf(buffer, sizeof(buffer), "[key=%s],%s", user_name, nis_map);
645         DEBUG(5, ("NIS+ querystring: %s\n", buffer));
646
647         if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
648                 if (result->status != NIS_SUCCESS) {
649                         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
650                 } else {
651                         object = result->objects.objects_val;
652                         if (object->zo_data.zo_type == ENTRY_OBJ) {
653                                 entry = &object->zo_data.objdata_u.en_data;
654                                 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
655                                 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
656
657                                 value = talloc_strdup(ctx,
658                                                 entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
659                                 if (!value) {
660                                         nis_freeresult(result);
661                                         return NULL;
662                                 }
663                                 value = talloc_string_sub(ctx,
664                                                 value,
665                                                 "&",
666                                                 user_name);
667                         }
668                 }
669         }
670         nis_freeresult(result);
671
672         if (value) {
673                 value = strip_mount_options(ctx, value);
674                 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
675                                         user_name, value));
676         }
677         return value;
678 }
679 #else /* WITH_NISPLUS_HOME */
680
681 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
682 {
683         const struct loadparm_substitution *lp_sub =
684                 loadparm_s3_global_substitution();
685         char *value = NULL;
686
687         int nis_error;        /* returned by yp all functions */
688         char *nis_result;     /* yp_match inits this */
689         int nis_result_len;  /* and set this */
690         char *nis_domain;     /* yp_get_default_domain inits this */
691         char *nis_map = lp_homedir_map(talloc_tos(), lp_sub);
692
693         if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
694                 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
695                 return NULL;
696         }
697
698         DEBUG(5, ("NIS Domain: %s\n", nis_domain));
699
700         if ((nis_error = yp_match(nis_domain, nis_map, user_name,
701                                         strlen(user_name), &nis_result,
702                                         &nis_result_len)) == 0) {
703                 if (nis_result_len > 0 && nis_result[nis_result_len] == '\n') {
704                         nis_result[nis_result_len] = '\0';
705                 }
706                 value = talloc_strdup(ctx, nis_result);
707                 if (!value) {
708                         return NULL;
709                 }
710                 value = strip_mount_options(ctx, value);
711         } else if(nis_error == YPERR_KEY) {
712                 DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
713                                 user_name, nis_map));
714                 DEBUG(3, ("using defaults for server and home directory\n"));
715         } else {
716                 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
717                                 yperr_string(nis_error), user_name, nis_map));
718         }
719
720         if (value) {
721                 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, value));
722         }
723         return value;
724 }
725 #endif /* WITH_NISPLUS_HOME */
726 #endif
727
728 bool process_exists(const struct server_id pid)
729 {
730         return serverid_exists(&pid);
731 }
732
733 /*******************************************************************
734  Convert a uid into a user name.
735 ********************************************************************/
736
737 const char *uidtoname(uid_t uid)
738 {
739         TALLOC_CTX *ctx = talloc_tos();
740         char *name = NULL;
741         struct passwd *pass = NULL;
742
743         pass = getpwuid_alloc(ctx,uid);
744         if (pass) {
745                 name = talloc_strdup(ctx,pass->pw_name);
746                 TALLOC_FREE(pass);
747         } else {
748                 name = talloc_asprintf(ctx,
749                                 "%ld",
750                                 (long int)uid);
751         }
752         return name;
753 }
754
755 /*******************************************************************
756  Convert a gid into a group name.
757 ********************************************************************/
758
759 char *gidtoname(gid_t gid)
760 {
761         struct group *grp;
762
763         grp = getgrgid(gid);
764         if (grp) {
765                 return talloc_strdup(talloc_tos(), grp->gr_name);
766         }
767         else {
768                 return talloc_asprintf(talloc_tos(),
769                                         "%d",
770                                         (int)gid);
771         }
772 }
773
774 /*******************************************************************
775  Convert a user name into a uid.
776 ********************************************************************/
777
778 uid_t nametouid(const char *name)
779 {
780         struct passwd *pass;
781         char *p;
782         uid_t u;
783
784         pass = Get_Pwnam_alloc(talloc_tos(), name);
785         if (pass) {
786                 u = pass->pw_uid;
787                 TALLOC_FREE(pass);
788                 return u;
789         }
790
791         u = (uid_t)strtol(name, &p, 0);
792         if ((p != name) && (*p == '\0'))
793                 return u;
794
795         return (uid_t)-1;
796 }
797
798 /*******************************************************************
799  Convert a name to a gid_t if possible. Return -1 if not a group. 
800 ********************************************************************/
801
802 gid_t nametogid(const char *name)
803 {
804         struct group *grp;
805         char *p;
806         gid_t g;
807
808         g = (gid_t)strtol(name, &p, 0);
809         if ((p != name) && (*p == '\0'))
810                 return g;
811
812         grp = getgrnam(name);
813         if (grp)
814                 return(grp->gr_gid);
815         return (gid_t)-1;
816 }
817
818 /*******************************************************************
819  Something really nasty happened - panic !
820 ********************************************************************/
821
822 void smb_panic_s3(const char *why)
823 {
824         const struct loadparm_substitution *lp_sub =
825                 loadparm_s3_global_substitution();
826         char *cmd;
827         int result;
828
829 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
830         /*
831          * Make sure all children can attach a debugger.
832          */
833         prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
834 #endif
835
836         cmd = lp_panic_action(talloc_tos(), lp_sub);
837         if (cmd && *cmd) {
838                 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
839                 result = system(cmd);
840
841                 if (result == -1)
842                         DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
843                                           strerror(errno)));
844                 else
845                         DEBUG(0, ("smb_panic(): action returned status %d\n",
846                                           WEXITSTATUS(result)));
847         }
848
849         dump_core();
850 }
851
852 /*******************************************************************
853   A readdir wrapper which just returns the file name.
854  ********************************************************************/
855
856 const char *readdirname(DIR *p)
857 {
858         struct dirent *ptr;
859         char *dname;
860
861         if (!p)
862                 return(NULL);
863
864         ptr = (struct dirent *)readdir(p);
865         if (!ptr)
866                 return(NULL);
867
868         dname = ptr->d_name;
869
870 #ifdef NEXT2
871         if (telldir(p) < 0)
872                 return(NULL);
873 #endif
874
875 #ifdef HAVE_BROKEN_READDIR_NAME
876         /* using /usr/ucb/cc is BAD */
877         dname = dname - 2;
878 #endif
879
880         return talloc_strdup(talloc_tos(), dname);
881 }
882
883 /*******************************************************************
884  Utility function used to decide if the last component 
885  of a path matches a (possibly wildcarded) entry in a namelist.
886 ********************************************************************/
887
888 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
889 {
890         const char *last_component;
891
892         /* if we have no list it's obviously not in the path */
893         if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
894                 return False;
895         }
896
897         DEBUG(8, ("is_in_path: %s\n", name));
898
899         /* Get the last component of the unix name. */
900         last_component = strrchr_m(name, '/');
901         if (!last_component) {
902                 last_component = name;
903         } else {
904                 last_component++; /* Go past '/' */
905         }
906
907         for(; namelist->name != NULL; namelist++) {
908                 if(namelist->is_wild) {
909                         if (mask_match(last_component, namelist->name, case_sensitive)) {
910                                 DEBUG(8,("is_in_path: mask match succeeded\n"));
911                                 return True;
912                         }
913                 } else {
914                         if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
915                                                 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
916                                 DEBUG(8,("is_in_path: match succeeded\n"));
917                                 return True;
918                         }
919                 }
920         }
921         DEBUG(8,("is_in_path: match not found\n"));
922         return False;
923 }
924
925 /*******************************************************************
926  Strip a '/' separated list into an array of 
927  name_compare_enties structures suitable for 
928  passing to is_in_path(). We do this for
929  speed so we can pre-parse all the names in the list 
930  and don't do it for each call to is_in_path().
931  We also check if the entry contains a wildcard to
932  remove a potentially expensive call to mask_match
933  if possible.
934 ********************************************************************/
935
936 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
937 {
938         char *name_end;
939         char *namelist;
940         char *namelist_end;
941         char *nameptr;
942         int num_entries = 0;
943         int i;
944
945         (*ppname_array) = NULL;
946
947         if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0'))) 
948                 return;
949
950         namelist = talloc_strdup(talloc_tos(), namelist_in);
951         if (namelist == NULL) {
952                 DEBUG(0,("set_namearray: talloc fail\n"));
953                 return;
954         }
955         nameptr = namelist;
956
957         namelist_end = &namelist[strlen(namelist)];
958
959         /* We need to make two passes over the string. The
960                 first to count the number of elements, the second
961                 to split it.
962         */
963
964         while(nameptr <= namelist_end) {
965                 if ( *nameptr == '/' ) {
966                         /* cope with multiple (useless) /s) */
967                         nameptr++;
968                         continue;
969                 }
970                 /* anything left? */
971                 if ( *nameptr == '\0' )
972                         break;
973
974                 /* find the next '/' or consume remaining */
975                 name_end = strchr_m(nameptr, '/');
976                 if (name_end == NULL) {
977                         /* Point nameptr at the terminating '\0' */
978                         nameptr += strlen(nameptr);
979                 } else {
980                         /* next segment please */
981                         nameptr = name_end + 1;
982                 }
983                 num_entries++;
984         }
985
986         if(num_entries == 0) {
987                 talloc_free(namelist);
988                 return;
989         }
990
991         if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
992                 DEBUG(0,("set_namearray: malloc fail\n"));
993                 talloc_free(namelist);
994                 return;
995         }
996
997         /* Now copy out the names */
998         nameptr = namelist;
999         i = 0;
1000         while(nameptr <= namelist_end) {
1001                 if ( *nameptr == '/' ) {
1002                         /* cope with multiple (useless) /s) */
1003                         nameptr++;
1004                         continue;
1005                 }
1006                 /* anything left? */
1007                 if ( *nameptr == '\0' )
1008                         break;
1009
1010                 /* find the next '/' or consume remaining */
1011                 name_end = strchr_m(nameptr, '/');
1012                 if (name_end != NULL) {
1013                         *name_end = '\0';
1014                 }
1015
1016                 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1017                 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1018                         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1019                         talloc_free(namelist);
1020                         return;
1021                 }
1022
1023                 if (name_end == NULL) {
1024                         /* Point nameptr at the terminating '\0' */
1025                         nameptr += strlen(nameptr);
1026                 } else {
1027                         /* next segment please */
1028                         nameptr = name_end + 1;
1029                 }
1030                 i++;
1031         }
1032
1033         (*ppname_array)[i].name = NULL;
1034
1035         talloc_free(namelist);
1036         return;
1037 }
1038
1039 #undef DBGC_CLASS
1040 #define DBGC_CLASS DBGC_LOCKING
1041
1042 /****************************************************************************
1043  Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1044  is dealt with in posix.c
1045  Returns True if we have information regarding this lock region (and returns
1046  F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1047 ****************************************************************************/
1048
1049 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
1050 {
1051         struct flock lock;
1052         int ret;
1053
1054         DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1055                     fd,op,(double)*poffset,(double)*pcount,*ptype));
1056
1057         lock.l_type = *ptype;
1058         lock.l_whence = SEEK_SET;
1059         lock.l_start = *poffset;
1060         lock.l_len = *pcount;
1061         lock.l_pid = 0;
1062
1063         ret = sys_fcntl_ptr(fd,op,&lock);
1064
1065         if (ret == -1) {
1066                 int sav = errno;
1067                 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1068                         (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
1069                 errno = sav;
1070                 return False;
1071         }
1072
1073         *ptype = lock.l_type;
1074         *poffset = lock.l_start;
1075         *pcount = lock.l_len;
1076         *ppid = lock.l_pid;
1077
1078         DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1079                         fd, (int)lock.l_type, (unsigned int)lock.l_pid));
1080         return True;
1081 }
1082
1083 #if defined(HAVE_OFD_LOCKS)
1084 int map_process_lock_to_ofd_lock(int op)
1085 {
1086         switch (op) {
1087         case F_GETLK:
1088         case F_OFD_GETLK:
1089                 op = F_OFD_GETLK;
1090                 break;
1091         case F_SETLK:
1092         case F_OFD_SETLK:
1093                 op = F_OFD_SETLK;
1094                 break;
1095         case F_SETLKW:
1096         case F_OFD_SETLKW:
1097                 op = F_OFD_SETLKW;
1098                 break;
1099         default:
1100                 return -1;
1101         }
1102         return op;
1103 }
1104 #else /* HAVE_OFD_LOCKS */
1105 int map_process_lock_to_ofd_lock(int op)
1106 {
1107         return op;
1108 }
1109 #endif /* HAVE_OFD_LOCKS */
1110
1111 #undef DBGC_CLASS
1112 #define DBGC_CLASS DBGC_ALL
1113
1114 /*******************************************************************
1115  Is the name specified one of my netbios names.
1116  Returns true if it is equal, false otherwise.
1117 ********************************************************************/
1118
1119 bool is_myname(const char *s)
1120 {
1121         int n;
1122         bool ret = False;
1123
1124         for (n=0; my_netbios_names(n); n++) {
1125                 const char *nbt_name = my_netbios_names(n);
1126
1127                 if (strncasecmp_m(nbt_name, s, MAX_NETBIOSNAME_LEN-1) == 0) {
1128                         ret=True;
1129                         break;
1130                 }
1131         }
1132         DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1133         return(ret);
1134 }
1135
1136 /*******************************************************************
1137  we distinguish between 2K and XP by the "Native Lan Manager" string
1138    WinXP => "Windows 2002 5.1"
1139    WinXP 64bit => "Windows XP 5.2"
1140    Win2k => "Windows 2000 5.0"
1141    NT4   => "Windows NT 4.0"
1142    Win9x => "Windows 4.0"
1143  Windows 2003 doesn't set the native lan manager string but
1144  they do set the domain to "Windows 2003 5.2" (probably a bug).
1145 ********************************************************************/
1146
1147 void ra_lanman_string( const char *native_lanman )
1148 {
1149         if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1150                 set_remote_arch( RA_WINXP );
1151         else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1152                 set_remote_arch( RA_WINXP64 );
1153         else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1154                 set_remote_arch( RA_WIN2K3 );
1155 }
1156
1157 static const char *remote_arch_strings[] = {
1158         [RA_UNKNOWN] =  "UNKNOWN",
1159         [RA_WFWG] =     "WfWg",
1160         [RA_OS2] =      "OS2",
1161         [RA_WIN95] =    "Win95",
1162         [RA_WINNT] =    "WinNT",
1163         [RA_WIN2K] =    "Win2K",
1164         [RA_WINXP] =    "WinXP",
1165         [RA_WIN2K3] =   "Win2K3",
1166         [RA_VISTA] =    "Vista",
1167         [RA_SAMBA] =    "Samba",
1168         [RA_CIFSFS] =   "CIFSFS",
1169         [RA_WINXP64] =  "WinXP64",
1170         [RA_OSX] =      "OSX",
1171 };
1172
1173 const char *get_remote_arch_str(void)
1174 {
1175         if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1176                 /*
1177                  * set_remote_arch() already checks this so ra_type
1178                  * should be in the allowed range, but anyway, let's
1179                  * do another bound check here.
1180                  */
1181                 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1182                 ra_type = RA_UNKNOWN;
1183         }
1184         return remote_arch_strings[ra_type];
1185 }
1186
1187 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1188 {
1189         int i;
1190
1191         for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1192                 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1193                         return i;
1194                 }
1195         }
1196         return RA_UNKNOWN;
1197 }
1198
1199 /*******************************************************************
1200  Set the horrid remote_arch string based on an enum.
1201 ********************************************************************/
1202
1203 void set_remote_arch(enum remote_arch_types type)
1204 {
1205         if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1206                 /*
1207                  * This protects against someone adding values to enum
1208                  * remote_arch_types without updating
1209                  * remote_arch_strings array.
1210                  */
1211                 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1212                 ra_type = RA_UNKNOWN;
1213                 return;
1214         }
1215
1216         ra_type = type;
1217         DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1218                   get_remote_arch_str()));
1219 }
1220
1221 /*******************************************************************
1222  Get the remote_arch type.
1223 ********************************************************************/
1224
1225 enum remote_arch_types get_remote_arch(void)
1226 {
1227         return ra_type;
1228 }
1229
1230 #define RA_CACHE_TTL 7*24*3600
1231
1232 static bool remote_arch_cache_key(const struct GUID *client_guid,
1233                                   fstring key)
1234 {
1235         struct GUID_txt_buf guid_buf;
1236         const char *guid_string = NULL;
1237
1238         guid_string = GUID_buf_string(client_guid, &guid_buf);
1239         if (guid_string == NULL) {
1240                 return false;
1241         }
1242
1243         fstr_sprintf(key, "RA/%s", guid_string);
1244         return true;
1245 }
1246
1247 struct ra_parser_state {
1248         bool found;
1249         enum remote_arch_types ra;
1250 };
1251
1252 static void ra_parser(const struct gencache_timeout *t,
1253                       DATA_BLOB blob,
1254                       void *priv_data)
1255 {
1256         struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1257         const char *ra_str = NULL;
1258
1259         if (gencache_timeout_expired(t)) {
1260                 return;
1261         }
1262
1263         if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1264                 DBG_ERR("Remote arch cache key not a string\n");
1265                 return;
1266         }
1267
1268         ra_str = (const char *)blob.data;
1269         DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1270
1271         state->ra = get_remote_arch_from_str(ra_str);
1272         state->found = true;
1273         return;
1274 }
1275
1276 static bool remote_arch_cache_get(const struct GUID *client_guid)
1277 {
1278         bool ok;
1279         fstring ra_key;
1280         struct ra_parser_state state = (struct ra_parser_state) {
1281                 .found = false,
1282                 .ra = RA_UNKNOWN,
1283         };
1284
1285         ok = remote_arch_cache_key(client_guid, ra_key);
1286         if (!ok) {
1287                 return false;
1288         }
1289
1290         ok = gencache_parse(ra_key, ra_parser, &state);
1291         if (!ok || !state.found) {
1292                 return true;
1293         }
1294
1295         if (state.ra == RA_UNKNOWN) {
1296                 return true;
1297         }
1298
1299         set_remote_arch(state.ra);
1300         return true;
1301 }
1302
1303 static bool remote_arch_cache_set(const struct GUID *client_guid)
1304 {
1305         bool ok;
1306         fstring ra_key;
1307         const char *ra_str = NULL;
1308
1309         if (get_remote_arch() == RA_UNKNOWN) {
1310                 return true;
1311         }
1312
1313         ok = remote_arch_cache_key(client_guid, ra_key);
1314         if (!ok) {
1315                 return false;
1316         }
1317
1318         ra_str = get_remote_arch_str();
1319         if (ra_str == NULL) {
1320                 return false;
1321         }
1322
1323         ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1324         if (!ok) {
1325                 return false;
1326         }
1327
1328         return true;
1329 }
1330
1331 bool remote_arch_cache_update(const struct GUID *client_guid)
1332 {
1333         bool ok;
1334
1335         if (get_remote_arch() == RA_UNKNOWN) {
1336
1337                 become_root();
1338                 ok = remote_arch_cache_get(client_guid);
1339                 unbecome_root();
1340
1341                 return ok;
1342         }
1343
1344         become_root();
1345         ok = remote_arch_cache_set(client_guid);
1346         unbecome_root();
1347
1348         return ok;
1349 }
1350
1351 bool remote_arch_cache_delete(const struct GUID *client_guid)
1352 {
1353         bool ok;
1354         fstring ra_key;
1355
1356         ok = remote_arch_cache_key(client_guid, ra_key);
1357         if (!ok) {
1358                 return false;
1359         }
1360
1361         become_root();
1362         ok = gencache_del(ra_key);
1363         unbecome_root();
1364
1365         if (!ok) {
1366                 return false;
1367         }
1368
1369         return true;
1370 }
1371
1372 const char *tab_depth(int level, int depth)
1373 {
1374         if( CHECK_DEBUGLVL(level) ) {
1375                 dbgtext("%*s", depth*4, "");
1376         }
1377         return "";
1378 }
1379
1380 /*****************************************************************************
1381  Provide a checksum on a string
1382
1383  Input:  s - the null-terminated character string for which the checksum
1384              will be calculated.
1385
1386   Output: The checksum value calculated for s.
1387 *****************************************************************************/
1388
1389 int str_checksum(const char *s)
1390 {
1391         TDB_DATA key;
1392         if (s == NULL)
1393                 return 0;
1394
1395         key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1396                            .dsize = strlen(s) };
1397
1398         return tdb_jenkins_hash(&key);
1399 }
1400
1401 /*****************************************************************
1402  Zero a memory area then free it. Used to catch bugs faster.
1403 *****************************************************************/  
1404
1405 void zero_free(void *p, size_t size)
1406 {
1407         memset(p, 0, size);
1408         SAFE_FREE(p);
1409 }
1410
1411 /*****************************************************************
1412  Set our open file limit to a requested max and return the limit.
1413 *****************************************************************/  
1414
1415 int set_maxfiles(int requested_max)
1416 {
1417 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1418         struct rlimit rlp;
1419         int saved_current_limit;
1420
1421         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1422                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1423                         strerror(errno) ));
1424                 /* just guess... */
1425                 return requested_max;
1426         }
1427
1428         /* 
1429          * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1430          * account for the extra fd we need 
1431          * as well as the log files and standard
1432          * handles etc. Save the limit we want to set in case
1433          * we are running on an OS that doesn't support this limit (AIX)
1434          * which always returns RLIM_INFINITY for rlp.rlim_max.
1435          */
1436
1437         /* Try raising the hard (max) limit to the requested amount. */
1438
1439 #if defined(RLIM_INFINITY)
1440         if (rlp.rlim_max != RLIM_INFINITY) {
1441                 int orig_max = rlp.rlim_max;
1442
1443                 if ( rlp.rlim_max < requested_max )
1444                         rlp.rlim_max = requested_max;
1445
1446                 /* This failing is not an error - many systems (Linux) don't
1447                         support our default request of 10,000 open files. JRA. */
1448
1449                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1450                         DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n", 
1451                                 (int)rlp.rlim_max, strerror(errno) ));
1452
1453                         /* Set failed - restore original value from get. */
1454                         rlp.rlim_max = orig_max;
1455                 }
1456         }
1457 #endif
1458
1459         /* Now try setting the soft (current) limit. */
1460
1461         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1462
1463         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1464                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1465                         (int)rlp.rlim_cur, strerror(errno) ));
1466                 /* just guess... */
1467                 return saved_current_limit;
1468         }
1469
1470         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1471                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1472                         strerror(errno) ));
1473                 /* just guess... */
1474                 return saved_current_limit;
1475     }
1476
1477 #if defined(RLIM_INFINITY)
1478         if(rlp.rlim_cur == RLIM_INFINITY)
1479                 return saved_current_limit;
1480 #endif
1481
1482         if((int)rlp.rlim_cur > saved_current_limit)
1483                 return saved_current_limit;
1484
1485         return rlp.rlim_cur;
1486 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1487         /*
1488          * No way to know - just guess...
1489          */
1490         return requested_max;
1491 #endif
1492 }
1493
1494 /*****************************************************************
1495  malloc that aborts with smb_panic on fail or zero size.
1496  *****************************************************************/  
1497
1498 void *smb_xmalloc_array(size_t size, unsigned int count)
1499 {
1500         void *p;
1501         if (size == 0) {
1502                 smb_panic("smb_xmalloc_array: called with zero size");
1503         }
1504         if (count >= MAX_ALLOC_SIZE/size) {
1505                 smb_panic("smb_xmalloc_array: alloc size too large");
1506         }
1507         if ((p = SMB_MALLOC(size*count)) == NULL) {
1508                 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1509                         (unsigned long)size, (unsigned long)count));
1510                 smb_panic("smb_xmalloc_array: malloc failed");
1511         }
1512         return p;
1513 }
1514
1515 /*****************************************************************
1516  Get local hostname and cache result.
1517 *****************************************************************/
1518
1519 char *myhostname(void)
1520 {
1521         static char *ret;
1522         if (ret == NULL) {
1523                 ret = get_myname(NULL);
1524         }
1525         return ret;
1526 }
1527
1528 /*****************************************************************
1529  Get local hostname and cache result.
1530 *****************************************************************/
1531
1532 char *myhostname_upper(void)
1533 {
1534         static char *ret;
1535         if (ret == NULL) {
1536                 char *name = get_myname(NULL);
1537                 if (name == NULL) {
1538                         return NULL;
1539                 }
1540                 ret = strupper_talloc(NULL, name);
1541                 talloc_free(name);
1542         }
1543         return ret;
1544 }
1545
1546 /*******************************************************************
1547  Given a filename - get its directory name
1548 ********************************************************************/
1549
1550 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1551                     const char **name)
1552 {
1553         char *p;
1554         ptrdiff_t len;
1555
1556         p = strrchr_m(dir, '/'); /* Find final '/', if any */
1557
1558         if (p == NULL) {
1559                 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1560                         return False;
1561                 }
1562                 if (name) {
1563                         *name = dir;
1564                 }
1565                 return True;
1566         }
1567
1568         len = p-dir;
1569
1570         if (!(*parent = (char *)talloc_memdup(mem_ctx, dir, len+1))) {
1571                 return False;
1572         }
1573         (*parent)[len] = '\0';
1574
1575         if (name) {
1576                 *name = p+1;
1577         }
1578         return True;
1579 }
1580
1581 /*******************************************************************
1582  Determine if a pattern contains any Microsoft wildcard characters.
1583 *******************************************************************/
1584
1585 bool ms_has_wild(const char *s)
1586 {
1587         char c;
1588
1589         while ((c = *s++)) {
1590                 switch (c) {
1591                 case '*':
1592                 case '?':
1593                 case '<':
1594                 case '>':
1595                 case '"':
1596                         return True;
1597                 }
1598         }
1599         return False;
1600 }
1601
1602 bool ms_has_wild_w(const smb_ucs2_t *s)
1603 {
1604         smb_ucs2_t c;
1605         if (!s) return False;
1606         while ((c = *s++)) {
1607                 switch (c) {
1608                 case UCS2_CHAR('*'):
1609                 case UCS2_CHAR('?'):
1610                 case UCS2_CHAR('<'):
1611                 case UCS2_CHAR('>'):
1612                 case UCS2_CHAR('"'):
1613                         return True;
1614                 }
1615         }
1616         return False;
1617 }
1618
1619 /*******************************************************************
1620  A wrapper that handles case sensitivity and the special handling
1621  of the ".." name.
1622 *******************************************************************/
1623
1624 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1625 {
1626         if (ISDOTDOT(string))
1627                 string = ".";
1628         if (ISDOT(pattern))
1629                 return False;
1630
1631         return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1632 }
1633
1634 /*******************************************************************
1635  A wrapper that handles case sensitivity and the special handling
1636  of the ".." name. Varient that is only called by old search code which requires
1637  pattern translation.
1638 *******************************************************************/
1639
1640 bool mask_match_search(const char *string, const char *pattern, bool is_case_sensitive)
1641 {
1642         if (ISDOTDOT(string))
1643                 string = ".";
1644         if (ISDOT(pattern))
1645                 return False;
1646
1647         return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
1648 }
1649
1650 /*******************************************************************
1651  A wrapper that handles a list of patters and calls mask_match()
1652  on each.  Returns True if any of the patterns match.
1653 *******************************************************************/
1654
1655 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1656 {
1657        while (listLen-- > 0) {
1658                if (mask_match(string, *list++, is_case_sensitive))
1659                        return True;
1660        }
1661        return False;
1662 }
1663
1664 /**********************************************************************
1665   Converts a name to a fully qualified domain name.
1666   Returns true if lookup succeeded, false if not (then fqdn is set to name)
1667   Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1668   canonical name of the host. getaddrinfo() may use a variety of sources
1669   including /etc/hosts to obtain the domainname. It expects aliases in
1670   /etc/hosts to NOT be the FQDN. The FQDN should come first.
1671 ************************************************************************/
1672
1673 bool name_to_fqdn(fstring fqdn, const char *name)
1674 {
1675         char *full = NULL;
1676         struct addrinfo hints;
1677         struct addrinfo *result;
1678         int s;
1679
1680         /* Configure hints to obtain canonical name */
1681
1682         memset(&hints, 0, sizeof(struct addrinfo));
1683         hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
1684         hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
1685         hints.ai_flags = AI_CANONNAME;  /* Get host's FQDN */
1686         hints.ai_protocol = 0;          /* Any protocol */
1687
1688         s = getaddrinfo(name, NULL, &hints, &result);
1689         if (s != 0) {
1690                 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s)));
1691                 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
1692                 fstrcpy(fqdn, name);
1693                 return false;
1694         }
1695         full = result->ai_canonname;
1696
1697         /* Find out if the FQDN is returned as an alias
1698          * to cope with /etc/hosts files where the first
1699          * name is not the FQDN but the short name.
1700          * getaddrinfo provides no easy way of handling aliases
1701          * in /etc/hosts. Users should make sure the FQDN
1702          * comes first in /etc/hosts. */
1703         if (full && (! strchr_m(full, '.'))) {
1704                 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1705                 DEBUGADD(1, ("    Full qualified domain names (FQDNs) should not be specified\n"));
1706                 DEBUGADD(1, ("    as an alias in /etc/hosts. FQDN should be the first name\n"));
1707                 DEBUGADD(1, ("    prior to any aliases.\n"));
1708         }
1709         if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
1710                 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1711                 DEBUGADD(1, ("    Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1712                 DEBUGADD(1, ("    to Kerberos authentication problems as localhost.localdomain\n"));
1713                 DEBUGADD(1, ("    may end up being used instead of the real machine FQDN.\n"));
1714         }
1715
1716         DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
1717         fstrcpy(fqdn, full);
1718         freeaddrinfo(result);           /* No longer needed */
1719         return true;
1720 }
1721
1722 uint32_t map_share_mode_to_deny_mode(uint32_t share_access, uint32_t private_options)
1723 {
1724         switch (share_access & ~FILE_SHARE_DELETE) {
1725                 case FILE_SHARE_NONE:
1726                         return DENY_ALL;
1727                 case FILE_SHARE_READ:
1728                         return DENY_WRITE;
1729                 case FILE_SHARE_WRITE:
1730                         return DENY_READ;
1731                 case FILE_SHARE_READ|FILE_SHARE_WRITE:
1732                         return DENY_NONE;
1733         }
1734         if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) {
1735                 return DENY_DOS;
1736         } else if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_FCB) {
1737                 return DENY_FCB;
1738         }
1739
1740         return (uint32_t)-1;
1741 }
1742
1743 struct server_id interpret_pid(const char *pid_string)
1744 {
1745         return server_id_from_string(get_my_vnn(), pid_string);
1746 }
1747
1748 /****************************************************************
1749  Check if an offset into a buffer is safe.
1750  If this returns True it's safe to indirect into the byte at
1751  pointer ptr+off.
1752 ****************************************************************/
1753
1754 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1755 {
1756         const char *end_base = buf_base + buf_len;
1757         char *end_ptr = ptr + off;
1758
1759         if (!buf_base || !ptr) {
1760                 return False;
1761         }
1762
1763         if (end_base < buf_base || end_ptr < ptr) {
1764                 return False; /* wrap. */
1765         }
1766
1767         if (end_ptr < end_base) {
1768                 return True;
1769         }
1770         return False;
1771 }
1772
1773 /****************************************************************
1774  Return a safe pointer into a buffer, or NULL.
1775 ****************************************************************/
1776
1777 char *get_safe_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1778 {
1779         return is_offset_safe(buf_base, buf_len, ptr, off) ?
1780                         ptr + off : NULL;
1781 }
1782
1783 /****************************************************************
1784  Return a safe pointer into a string within a buffer, or NULL.
1785 ****************************************************************/
1786
1787 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1788 {
1789         if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1790                 return NULL;
1791         }
1792         /* Check if a valid string exists at this offset. */
1793         if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1794                 return NULL;
1795         }
1796         return ptr + off;
1797 }
1798
1799 /****************************************************************
1800  Return an SVAL at a pointer, or failval if beyond the end.
1801 ****************************************************************/
1802
1803 int get_safe_SVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1804 {
1805         /*
1806          * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1807          * NOT ptr[2].
1808          */
1809         if (!is_offset_safe(buf_base, buf_len, ptr, off+1)) {
1810                 return failval;
1811         }
1812         return SVAL(ptr,off);
1813 }
1814
1815 /****************************************************************
1816  Return an IVAL at a pointer, or failval if beyond the end.
1817 ****************************************************************/
1818
1819 int get_safe_IVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1820 {
1821         /*
1822          * Note we use off+3 here, not off+4 as IVAL accesses 
1823          * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1824          */
1825         if (!is_offset_safe(buf_base, buf_len, ptr, off+3)) {
1826                 return failval;
1827         }
1828         return IVAL(ptr,off);
1829 }
1830
1831 /****************************************************************
1832  Split DOM\user into DOM and user. Do not mix with winbind variants of that
1833  call (they take care of winbind separator and other winbind specific settings).
1834 ****************************************************************/
1835
1836 bool split_domain_user(TALLOC_CTX *mem_ctx,
1837                        const char *full_name,
1838                        char **domain,
1839                        char **user)
1840 {
1841         const char *p = NULL;
1842
1843         p = strchr_m(full_name, '\\');
1844
1845         if (p != NULL) {
1846                 *domain = talloc_strndup(mem_ctx, full_name,
1847                                          PTR_DIFF(p, full_name));
1848                 if (*domain == NULL) {
1849                         return false;
1850                 }
1851                 *user = talloc_strdup(mem_ctx, p+1);
1852                 if (*user == NULL) {
1853                         TALLOC_FREE(*domain);
1854                         return false;
1855                 }
1856         } else {
1857                 *domain = NULL;
1858                 *user = talloc_strdup(mem_ctx, full_name);
1859                 if (*user == NULL) {
1860                         return false;
1861                 }
1862         }
1863
1864         return true;
1865 }
1866
1867 /****************************************************************
1868  strip off leading '\\' from a hostname
1869 ****************************************************************/
1870
1871 const char *strip_hostname(const char *s)
1872 {
1873         if (!s) {
1874                 return NULL;
1875         }
1876
1877         if (strlen_m(s) < 3) {
1878                 return s;
1879         }
1880
1881         if (s[0] == '\\') s++;
1882         if (s[0] == '\\') s++;
1883
1884         return s;
1885 }
1886
1887 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1888 {
1889         if (!NT_STATUS_IS_OK(err1)) {
1890                 *result = err1;
1891                 return true;
1892         }
1893         if (!NT_STATUS_IS_OK(err2)) {
1894                 *result = err2;
1895                 return true;
1896         }
1897         return false;
1898 }
1899
1900 int timeval_to_msec(struct timeval t)
1901 {
1902         return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
1903 }
1904
1905 /*******************************************************************
1906  Check a given DOS pathname is valid for a share.
1907 ********************************************************************/
1908
1909 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
1910 {
1911         char *ptr = NULL;
1912
1913         if (!dos_pathname) {
1914                 return NULL;
1915         }
1916
1917         ptr = talloc_strdup(ctx, dos_pathname);
1918         if (!ptr) {
1919                 return NULL;
1920         }
1921         /* Convert any '\' paths to '/' */
1922         unix_format(ptr);
1923         ptr = unix_clean_name(ctx, ptr);
1924         if (!ptr) {
1925                 return NULL;
1926         }
1927
1928         /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1929         if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1930                 ptr += 2;
1931
1932         /* Only absolute paths allowed. */
1933         if (*ptr != '/')
1934                 return NULL;
1935
1936         return ptr;
1937 }
1938
1939 /*******************************************************************
1940  Return True if the filename is one of the special executable types.
1941 ********************************************************************/
1942
1943 bool is_executable(const char *fname)
1944 {
1945         if ((fname = strrchr_m(fname,'.'))) {
1946                 if (strequal(fname,".com") ||
1947                     strequal(fname,".dll") ||
1948                     strequal(fname,".exe") ||
1949                     strequal(fname,".sym")) {
1950                         return True;
1951                 }
1952         }
1953         return False;
1954 }
1955
1956 /****************************************************************************
1957  Open a file with a share mode - old openX method - map into NTCreate.
1958 ****************************************************************************/
1959
1960 bool map_open_params_to_ntcreate(const char *smb_base_fname,
1961                                  int deny_mode, int open_func,
1962                                  uint32_t *paccess_mask,
1963                                  uint32_t *pshare_mode,
1964                                  uint32_t *pcreate_disposition,
1965                                  uint32_t *pcreate_options,
1966                                  uint32_t *pprivate_flags)
1967 {
1968         uint32_t access_mask;
1969         uint32_t share_mode;
1970         uint32_t create_disposition;
1971         uint32_t create_options = FILE_NON_DIRECTORY_FILE;
1972         uint32_t private_flags = 0;
1973
1974         DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1975                   "open_func = 0x%x\n",
1976                   smb_base_fname, (unsigned int)deny_mode,
1977                   (unsigned int)open_func ));
1978
1979         /* Create the NT compatible access_mask. */
1980         switch (GET_OPENX_MODE(deny_mode)) {
1981                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1982                 case DOS_OPEN_RDONLY:
1983                         access_mask = FILE_GENERIC_READ;
1984                         break;
1985                 case DOS_OPEN_WRONLY:
1986                         access_mask = FILE_GENERIC_WRITE;
1987                         break;
1988                 case DOS_OPEN_RDWR:
1989                 case DOS_OPEN_FCB:
1990                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1991                         break;
1992                 default:
1993                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1994                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
1995                         return False;
1996         }
1997
1998         /* Create the NT compatible create_disposition. */
1999         switch (open_func) {
2000                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
2001                         create_disposition = FILE_CREATE;
2002                         break;
2003
2004                 case OPENX_FILE_EXISTS_OPEN:
2005                         create_disposition = FILE_OPEN;
2006                         break;
2007
2008                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
2009                         create_disposition = FILE_OPEN_IF;
2010                         break;
2011
2012                 case OPENX_FILE_EXISTS_TRUNCATE:
2013                         create_disposition = FILE_OVERWRITE;
2014                         break;
2015
2016                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
2017                         create_disposition = FILE_OVERWRITE_IF;
2018                         break;
2019
2020                 default:
2021                         /* From samba4 - to be confirmed. */
2022                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
2023                                 create_disposition = FILE_CREATE;
2024                                 break;
2025                         }
2026                         DEBUG(10,("map_open_params_to_ntcreate: bad "
2027                                   "open_func 0x%x\n", (unsigned int)open_func));
2028                         return False;
2029         }
2030
2031         /* Create the NT compatible share modes. */
2032         switch (GET_DENY_MODE(deny_mode)) {
2033                 case DENY_ALL:
2034                         share_mode = FILE_SHARE_NONE;
2035                         break;
2036
2037                 case DENY_WRITE:
2038                         share_mode = FILE_SHARE_READ;
2039                         break;
2040
2041                 case DENY_READ:
2042                         share_mode = FILE_SHARE_WRITE;
2043                         break;
2044
2045                 case DENY_NONE:
2046                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2047                         break;
2048
2049                 case DENY_DOS:
2050                         private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
2051                         if (is_executable(smb_base_fname)) {
2052                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2053                         } else {
2054                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
2055                                         share_mode = FILE_SHARE_READ;
2056                                 } else {
2057                                         share_mode = FILE_SHARE_NONE;
2058                                 }
2059                         }
2060                         break;
2061
2062                 case DENY_FCB:
2063                         private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
2064                         share_mode = FILE_SHARE_NONE;
2065                         break;
2066
2067                 default:
2068                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2069                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
2070                         return False;
2071         }
2072
2073         DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2074                   "share_mode = 0x%x, create_disposition = 0x%x, "
2075                   "create_options = 0x%x private_flags = 0x%x\n",
2076                   smb_base_fname,
2077                   (unsigned int)access_mask,
2078                   (unsigned int)share_mode,
2079                   (unsigned int)create_disposition,
2080                   (unsigned int)create_options,
2081                   (unsigned int)private_flags));
2082
2083         if (paccess_mask) {
2084                 *paccess_mask = access_mask;
2085         }
2086         if (pshare_mode) {
2087                 *pshare_mode = share_mode;
2088         }
2089         if (pcreate_disposition) {
2090                 *pcreate_disposition = create_disposition;
2091         }
2092         if (pcreate_options) {
2093                 *pcreate_options = create_options;
2094         }
2095         if (pprivate_flags) {
2096                 *pprivate_flags = private_flags;
2097         }
2098
2099         return True;
2100
2101 }
2102
2103 /*************************************************************************
2104  Return a talloced copy of a struct security_unix_token. NULL on fail.
2105 *************************************************************************/
2106
2107 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
2108 {
2109         struct security_unix_token *cpy;
2110
2111         cpy = talloc(ctx, struct security_unix_token);
2112         if (!cpy) {
2113                 return NULL;
2114         }
2115
2116         cpy->uid = tok->uid;
2117         cpy->gid = tok->gid;
2118         cpy->ngroups = tok->ngroups;
2119         if (tok->ngroups) {
2120                 /* Make this a talloc child of cpy. */
2121                 cpy->groups = (gid_t *)talloc_memdup(
2122                         cpy, tok->groups, tok->ngroups * sizeof(gid_t));
2123                 if (!cpy->groups) {
2124                         TALLOC_FREE(cpy);
2125                         return NULL;
2126                 }
2127         } else {
2128                 cpy->groups = NULL;
2129         }
2130         return cpy;
2131 }
2132
2133 /****************************************************************************
2134  Return a root token
2135 ****************************************************************************/
2136
2137 struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
2138 {
2139         struct security_unix_token *t = NULL;
2140
2141         t = talloc_zero(mem_ctx, struct security_unix_token);
2142         if (t == NULL) {
2143                 return NULL;
2144         }
2145
2146         /*
2147          * This is not needed, but lets make it explicit, not implicit.
2148          */
2149         *t = (struct security_unix_token) {
2150                 .uid = 0,
2151                 .gid = 0,
2152                 .ngroups = 0,
2153                 .groups = NULL
2154         };
2155
2156         return t;
2157 }
2158
2159 char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
2160 {
2161         char *str;
2162         uint32_t i;
2163
2164         str = talloc_asprintf(
2165                 mem_ctx,
2166                 "uid=%ju, gid=%ju, %"PRIu32" groups:",
2167                 (uintmax_t)(tok->uid),
2168                 (uintmax_t)(tok->gid),
2169                 tok->ngroups);
2170         if (str == NULL) {
2171                 return NULL;
2172         }
2173
2174         for (i=0; i<tok->ngroups; i++) {
2175                 char *tmp;
2176                 tmp = talloc_asprintf_append_buffer(
2177                         str, " %ju", (uintmax_t)tok->groups[i]);
2178                 if (tmp == NULL) {
2179                         TALLOC_FREE(str);
2180                         return NULL;
2181                 }
2182                 str = tmp;
2183         }
2184
2185         return str;
2186 }
2187
2188 /****************************************************************************
2189  Check that a file matches a particular file type.
2190 ****************************************************************************/
2191
2192 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
2193 {
2194         uint32_t mask;
2195
2196         /* Check the "may have" search bits. */
2197         if (((mode & ~dirtype) &
2198                         (FILE_ATTRIBUTE_HIDDEN |
2199                          FILE_ATTRIBUTE_SYSTEM |
2200                          FILE_ATTRIBUTE_DIRECTORY)) != 0) {
2201                 return false;
2202         }
2203
2204         /* Check the "must have" bits,
2205            which are the may have bits shifted eight */
2206         /* If must have bit is set, the file/dir can
2207            not be returned in search unless the matching
2208            file attribute is set */
2209         mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
2210                                     FILE_ATTRIBUTE_ARCHIVE|
2211                                    FILE_ATTRIBUTE_READONLY|
2212                                      FILE_ATTRIBUTE_HIDDEN|
2213                                      FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
2214         if(mask) {
2215                 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
2216                                       FILE_ATTRIBUTE_ARCHIVE|
2217                                      FILE_ATTRIBUTE_READONLY|
2218                                        FILE_ATTRIBUTE_HIDDEN|
2219                                         FILE_ATTRIBUTE_SYSTEM))) == mask) {
2220                         /* check if matching attribute present */
2221                         return true;
2222                 } else {
2223                         return false;
2224                 }
2225         }
2226
2227         return true;
2228 }