s3:vfs: Correctly check if OFD locks should be enabled or not
[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 "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(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         char *value = NULL;
634
635         char *nis_map = (char *)lp_homedir_map();
636
637         char buffer[NIS_MAXATTRVAL + 1];
638         nis_result *result;
639         nis_object *object;
640         entry_obj  *entry;
641
642         snprintf(buffer, sizeof(buffer), "[key=%s],%s", user_name, nis_map);
643         DEBUG(5, ("NIS+ querystring: %s\n", buffer));
644
645         if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
646                 if (result->status != NIS_SUCCESS) {
647                         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
648                 } else {
649                         object = result->objects.objects_val;
650                         if (object->zo_data.zo_type == ENTRY_OBJ) {
651                                 entry = &object->zo_data.objdata_u.en_data;
652                                 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
653                                 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
654
655                                 value = talloc_strdup(ctx,
656                                                 entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
657                                 if (!value) {
658                                         nis_freeresult(result);
659                                         return NULL;
660                                 }
661                                 value = talloc_string_sub(ctx,
662                                                 value,
663                                                 "&",
664                                                 user_name);
665                         }
666                 }
667         }
668         nis_freeresult(result);
669
670         if (value) {
671                 value = strip_mount_options(ctx, value);
672                 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
673                                         user_name, value));
674         }
675         return value;
676 }
677 #else /* WITH_NISPLUS_HOME */
678
679 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
680 {
681         char *value = NULL;
682
683         int nis_error;        /* returned by yp all functions */
684         char *nis_result;     /* yp_match inits this */
685         int nis_result_len;  /* and set this */
686         char *nis_domain;     /* yp_get_default_domain inits this */
687         char *nis_map = lp_homedir_map(talloc_tos());
688
689         if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
690                 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
691                 return NULL;
692         }
693
694         DEBUG(5, ("NIS Domain: %s\n", nis_domain));
695
696         if ((nis_error = yp_match(nis_domain, nis_map, user_name,
697                                         strlen(user_name), &nis_result,
698                                         &nis_result_len)) == 0) {
699                 if (nis_result_len > 0 && nis_result[nis_result_len] == '\n') {
700                         nis_result[nis_result_len] = '\0';
701                 }
702                 value = talloc_strdup(ctx, nis_result);
703                 if (!value) {
704                         return NULL;
705                 }
706                 value = strip_mount_options(ctx, value);
707         } else if(nis_error == YPERR_KEY) {
708                 DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
709                                 user_name, nis_map));
710                 DEBUG(3, ("using defaults for server and home directory\n"));
711         } else {
712                 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
713                                 yperr_string(nis_error), user_name, nis_map));
714         }
715
716         if (value) {
717                 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, value));
718         }
719         return value;
720 }
721 #endif /* WITH_NISPLUS_HOME */
722 #endif
723
724 bool process_exists(const struct server_id pid)
725 {
726         return serverid_exists(&pid);
727 }
728
729 /*******************************************************************
730  Convert a uid into a user name.
731 ********************************************************************/
732
733 const char *uidtoname(uid_t uid)
734 {
735         TALLOC_CTX *ctx = talloc_tos();
736         char *name = NULL;
737         struct passwd *pass = NULL;
738
739         pass = getpwuid_alloc(ctx,uid);
740         if (pass) {
741                 name = talloc_strdup(ctx,pass->pw_name);
742                 TALLOC_FREE(pass);
743         } else {
744                 name = talloc_asprintf(ctx,
745                                 "%ld",
746                                 (long int)uid);
747         }
748         return name;
749 }
750
751 /*******************************************************************
752  Convert a gid into a group name.
753 ********************************************************************/
754
755 char *gidtoname(gid_t gid)
756 {
757         struct group *grp;
758
759         grp = getgrgid(gid);
760         if (grp) {
761                 return talloc_strdup(talloc_tos(), grp->gr_name);
762         }
763         else {
764                 return talloc_asprintf(talloc_tos(),
765                                         "%d",
766                                         (int)gid);
767         }
768 }
769
770 /*******************************************************************
771  Convert a user name into a uid.
772 ********************************************************************/
773
774 uid_t nametouid(const char *name)
775 {
776         struct passwd *pass;
777         char *p;
778         uid_t u;
779
780         pass = Get_Pwnam_alloc(talloc_tos(), name);
781         if (pass) {
782                 u = pass->pw_uid;
783                 TALLOC_FREE(pass);
784                 return u;
785         }
786
787         u = (uid_t)strtol(name, &p, 0);
788         if ((p != name) && (*p == '\0'))
789                 return u;
790
791         return (uid_t)-1;
792 }
793
794 /*******************************************************************
795  Convert a name to a gid_t if possible. Return -1 if not a group. 
796 ********************************************************************/
797
798 gid_t nametogid(const char *name)
799 {
800         struct group *grp;
801         char *p;
802         gid_t g;
803
804         g = (gid_t)strtol(name, &p, 0);
805         if ((p != name) && (*p == '\0'))
806                 return g;
807
808         grp = getgrnam(name);
809         if (grp)
810                 return(grp->gr_gid);
811         return (gid_t)-1;
812 }
813
814 /*******************************************************************
815  Something really nasty happened - panic !
816 ********************************************************************/
817
818 void smb_panic_s3(const char *why)
819 {
820         char *cmd;
821         int result;
822
823         DEBUG(0,("PANIC (pid %llu): %s\n",
824                     (unsigned long long)getpid(), why));
825         log_stack_trace();
826
827 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
828         /*
829          * Make sure all children can attach a debugger.
830          */
831         prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
832 #endif
833
834         cmd = lp_panic_action(talloc_tos());
835         if (cmd && *cmd) {
836                 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
837                 result = system(cmd);
838
839                 if (result == -1)
840                         DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
841                                           strerror(errno)));
842                 else
843                         DEBUG(0, ("smb_panic(): action returned status %d\n",
844                                           WEXITSTATUS(result)));
845         }
846
847         dump_core();
848 }
849
850 /*******************************************************************
851   A readdir wrapper which just returns the file name.
852  ********************************************************************/
853
854 const char *readdirname(DIR *p)
855 {
856         struct dirent *ptr;
857         char *dname;
858
859         if (!p)
860                 return(NULL);
861
862         ptr = (struct dirent *)readdir(p);
863         if (!ptr)
864                 return(NULL);
865
866         dname = ptr->d_name;
867
868 #ifdef NEXT2
869         if (telldir(p) < 0)
870                 return(NULL);
871 #endif
872
873 #ifdef HAVE_BROKEN_READDIR_NAME
874         /* using /usr/ucb/cc is BAD */
875         dname = dname - 2;
876 #endif
877
878         return talloc_strdup(talloc_tos(), dname);
879 }
880
881 /*******************************************************************
882  Utility function used to decide if the last component 
883  of a path matches a (possibly wildcarded) entry in a namelist.
884 ********************************************************************/
885
886 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
887 {
888         const char *last_component;
889
890         /* if we have no list it's obviously not in the path */
891         if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
892                 return False;
893         }
894
895         DEBUG(8, ("is_in_path: %s\n", name));
896
897         /* Get the last component of the unix name. */
898         last_component = strrchr_m(name, '/');
899         if (!last_component) {
900                 last_component = name;
901         } else {
902                 last_component++; /* Go past '/' */
903         }
904
905         for(; namelist->name != NULL; namelist++) {
906                 if(namelist->is_wild) {
907                         if (mask_match(last_component, namelist->name, case_sensitive)) {
908                                 DEBUG(8,("is_in_path: mask match succeeded\n"));
909                                 return True;
910                         }
911                 } else {
912                         if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
913                                                 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
914                                 DEBUG(8,("is_in_path: match succeeded\n"));
915                                 return True;
916                         }
917                 }
918         }
919         DEBUG(8,("is_in_path: match not found\n"));
920         return False;
921 }
922
923 /*******************************************************************
924  Strip a '/' separated list into an array of 
925  name_compare_enties structures suitable for 
926  passing to is_in_path(). We do this for
927  speed so we can pre-parse all the names in the list 
928  and don't do it for each call to is_in_path().
929  We also check if the entry contains a wildcard to
930  remove a potentially expensive call to mask_match
931  if possible.
932 ********************************************************************/
933
934 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
935 {
936         char *name_end;
937         char *namelist;
938         char *namelist_end;
939         char *nameptr;
940         int num_entries = 0;
941         int i;
942
943         (*ppname_array) = NULL;
944
945         if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0'))) 
946                 return;
947
948         namelist = talloc_strdup(talloc_tos(), namelist_in);
949         if (namelist == NULL) {
950                 DEBUG(0,("set_namearray: talloc fail\n"));
951                 return;
952         }
953         nameptr = namelist;
954
955         namelist_end = &namelist[strlen(namelist)];
956
957         /* We need to make two passes over the string. The
958                 first to count the number of elements, the second
959                 to split it.
960         */
961
962         while(nameptr <= namelist_end) {
963                 if ( *nameptr == '/' ) {
964                         /* cope with multiple (useless) /s) */
965                         nameptr++;
966                         continue;
967                 }
968                 /* anything left? */
969                 if ( *nameptr == '\0' )
970                         break;
971
972                 /* find the next '/' or consume remaining */
973                 name_end = strchr_m(nameptr, '/');
974                 if (name_end == NULL) {
975                         /* Point nameptr at the terminating '\0' */
976                         nameptr += strlen(nameptr);
977                 } else {
978                         /* next segment please */
979                         nameptr = name_end + 1;
980                 }
981                 num_entries++;
982         }
983
984         if(num_entries == 0) {
985                 talloc_free(namelist);
986                 return;
987         }
988
989         if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
990                 DEBUG(0,("set_namearray: malloc fail\n"));
991                 talloc_free(namelist);
992                 return;
993         }
994
995         /* Now copy out the names */
996         nameptr = namelist;
997         i = 0;
998         while(nameptr <= namelist_end) {
999                 if ( *nameptr == '/' ) {
1000                         /* cope with multiple (useless) /s) */
1001                         nameptr++;
1002                         continue;
1003                 }
1004                 /* anything left? */
1005                 if ( *nameptr == '\0' )
1006                         break;
1007
1008                 /* find the next '/' or consume remaining */
1009                 name_end = strchr_m(nameptr, '/');
1010                 if (name_end != NULL) {
1011                         *name_end = '\0';
1012                 }
1013
1014                 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1015                 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1016                         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1017                         talloc_free(namelist);
1018                         return;
1019                 }
1020
1021                 if (name_end == NULL) {
1022                         /* Point nameptr at the terminating '\0' */
1023                         nameptr += strlen(nameptr);
1024                 } else {
1025                         /* next segment please */
1026                         nameptr = name_end + 1;
1027                 }
1028                 i++;
1029         }
1030
1031         (*ppname_array)[i].name = NULL;
1032
1033         talloc_free(namelist);
1034         return;
1035 }
1036
1037 #undef DBGC_CLASS
1038 #define DBGC_CLASS DBGC_LOCKING
1039
1040 /****************************************************************************
1041  Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1042  is dealt with in posix.c
1043  Returns True if we have information regarding this lock region (and returns
1044  F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1045 ****************************************************************************/
1046
1047 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
1048 {
1049         struct flock lock;
1050         int ret;
1051
1052         DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1053                     fd,op,(double)*poffset,(double)*pcount,*ptype));
1054
1055         lock.l_type = *ptype;
1056         lock.l_whence = SEEK_SET;
1057         lock.l_start = *poffset;
1058         lock.l_len = *pcount;
1059         lock.l_pid = 0;
1060
1061         ret = sys_fcntl_ptr(fd,op,&lock);
1062
1063         if (ret == -1) {
1064                 int sav = errno;
1065                 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1066                         (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
1067                 errno = sav;
1068                 return False;
1069         }
1070
1071         *ptype = lock.l_type;
1072         *poffset = lock.l_start;
1073         *pcount = lock.l_len;
1074         *ppid = lock.l_pid;
1075
1076         DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1077                         fd, (int)lock.l_type, (unsigned int)lock.l_pid));
1078         return True;
1079 }
1080
1081 #if defined(HAVE_OFD_LOCKS)
1082 int map_process_lock_to_ofd_lock(int op)
1083 {
1084         switch (op) {
1085         case F_GETLK:
1086         case F_OFD_GETLK:
1087                 op = F_OFD_GETLK;
1088                 break;
1089         case F_SETLK:
1090         case F_OFD_SETLK:
1091                 op = F_OFD_SETLK;
1092                 break;
1093         case F_SETLKW:
1094         case F_OFD_SETLKW:
1095                 op = F_OFD_SETLKW;
1096                 break;
1097         default:
1098                 return -1;
1099         }
1100         return op;
1101 }
1102 #else /* HAVE_OFD_LOCKS */
1103 int map_process_lock_to_ofd_lock(int op)
1104 {
1105         return op;
1106 }
1107 #endif /* HAVE_OFD_LOCKS */
1108
1109 #undef DBGC_CLASS
1110 #define DBGC_CLASS DBGC_ALL
1111
1112 /*******************************************************************
1113  Is the name specified one of my netbios names.
1114  Returns true if it is equal, false otherwise.
1115 ********************************************************************/
1116
1117 bool is_myname(const char *s)
1118 {
1119         int n;
1120         bool ret = False;
1121
1122         for (n=0; my_netbios_names(n); n++) {
1123                 const char *nbt_name = my_netbios_names(n);
1124
1125                 if (strncasecmp_m(nbt_name, s, MAX_NETBIOSNAME_LEN-1) == 0) {
1126                         ret=True;
1127                         break;
1128                 }
1129         }
1130         DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1131         return(ret);
1132 }
1133
1134 /*******************************************************************
1135  we distinguish between 2K and XP by the "Native Lan Manager" string
1136    WinXP => "Windows 2002 5.1"
1137    WinXP 64bit => "Windows XP 5.2"
1138    Win2k => "Windows 2000 5.0"
1139    NT4   => "Windows NT 4.0"
1140    Win9x => "Windows 4.0"
1141  Windows 2003 doesn't set the native lan manager string but
1142  they do set the domain to "Windows 2003 5.2" (probably a bug).
1143 ********************************************************************/
1144
1145 void ra_lanman_string( const char *native_lanman )
1146 {
1147         if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1148                 set_remote_arch( RA_WINXP );
1149         else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1150                 set_remote_arch( RA_WINXP64 );
1151         else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1152                 set_remote_arch( RA_WIN2K3 );
1153 }
1154
1155 static const char *remote_arch_strings[] = {
1156         [RA_UNKNOWN] =  "UNKNOWN",
1157         [RA_WFWG] =     "WfWg",
1158         [RA_OS2] =      "OS2",
1159         [RA_WIN95] =    "Win95",
1160         [RA_WINNT] =    "WinNT",
1161         [RA_WIN2K] =    "Win2K",
1162         [RA_WINXP] =    "WinXP",
1163         [RA_WIN2K3] =   "Win2K3",
1164         [RA_VISTA] =    "Vista",
1165         [RA_SAMBA] =    "Samba",
1166         [RA_CIFSFS] =   "CIFSFS",
1167         [RA_WINXP64] =  "WinXP64",
1168         [RA_OSX] =      "OSX",
1169 };
1170
1171 const char *get_remote_arch_str(void)
1172 {
1173         if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1174                 /*
1175                  * set_remote_arch() already checks this so ra_type
1176                  * should be in the allowed range, but anyway, let's
1177                  * do another bound check here.
1178                  */
1179                 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1180                 ra_type = RA_UNKNOWN;
1181         }
1182         return remote_arch_strings[ra_type];
1183 }
1184
1185 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1186 {
1187         int i;
1188
1189         for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1190                 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1191                         return i;
1192                 }
1193         }
1194         return RA_UNKNOWN;
1195 }
1196
1197 /*******************************************************************
1198  Set the horrid remote_arch string based on an enum.
1199 ********************************************************************/
1200
1201 void set_remote_arch(enum remote_arch_types type)
1202 {
1203         if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1204                 /*
1205                  * This protects against someone adding values to enum
1206                  * remote_arch_types without updating
1207                  * remote_arch_strings array.
1208                  */
1209                 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1210                 ra_type = RA_UNKNOWN;
1211                 return;
1212         }
1213
1214         ra_type = type;
1215         DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1216                   get_remote_arch_str()));
1217 }
1218
1219 /*******************************************************************
1220  Get the remote_arch type.
1221 ********************************************************************/
1222
1223 enum remote_arch_types get_remote_arch(void)
1224 {
1225         return ra_type;
1226 }
1227
1228 #define RA_CACHE_TTL 7*24*3600
1229
1230 static bool remote_arch_cache_key(const struct GUID *client_guid,
1231                                   fstring key)
1232 {
1233         struct GUID_txt_buf guid_buf;
1234         const char *guid_string = NULL;
1235
1236         guid_string = GUID_buf_string(client_guid, &guid_buf);
1237         if (guid_string == NULL) {
1238                 return false;
1239         }
1240
1241         fstr_sprintf(key, "RA/%s", guid_string);
1242         return true;
1243 }
1244
1245 struct ra_parser_state {
1246         bool found;
1247         enum remote_arch_types ra;
1248 };
1249
1250 static void ra_parser(const struct gencache_timeout *t,
1251                       DATA_BLOB blob,
1252                       void *priv_data)
1253 {
1254         struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1255         const char *ra_str = NULL;
1256
1257         if (gencache_timeout_expired(t)) {
1258                 return;
1259         }
1260
1261         if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1262                 DBG_ERR("Remote arch cache key not a string\n");
1263                 return;
1264         }
1265
1266         ra_str = (const char *)blob.data;
1267         DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1268
1269         state->ra = get_remote_arch_from_str(ra_str);
1270         state->found = true;
1271         return;
1272 }
1273
1274 static bool remote_arch_cache_get(const struct GUID *client_guid)
1275 {
1276         bool ok;
1277         fstring ra_key;
1278         struct ra_parser_state state = (struct ra_parser_state) {
1279                 .found = false,
1280                 .ra = RA_UNKNOWN,
1281         };
1282
1283         ok = remote_arch_cache_key(client_guid, ra_key);
1284         if (!ok) {
1285                 return false;
1286         }
1287
1288         ok = gencache_parse(ra_key, ra_parser, &state);
1289         if (!ok || !state.found) {
1290                 return true;
1291         }
1292
1293         if (state.ra == RA_UNKNOWN) {
1294                 return true;
1295         }
1296
1297         set_remote_arch(state.ra);
1298         return true;
1299 }
1300
1301 static bool remote_arch_cache_set(const struct GUID *client_guid)
1302 {
1303         bool ok;
1304         fstring ra_key;
1305         const char *ra_str = NULL;
1306
1307         if (get_remote_arch() == RA_UNKNOWN) {
1308                 return true;
1309         }
1310
1311         ok = remote_arch_cache_key(client_guid, ra_key);
1312         if (!ok) {
1313                 return false;
1314         }
1315
1316         ra_str = get_remote_arch_str();
1317         if (ra_str == NULL) {
1318                 return false;
1319         }
1320
1321         ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1322         if (!ok) {
1323                 return false;
1324         }
1325
1326         return true;
1327 }
1328
1329 bool remote_arch_cache_update(const struct GUID *client_guid)
1330 {
1331         bool ok;
1332
1333         if (get_remote_arch() == RA_UNKNOWN) {
1334
1335                 become_root();
1336                 ok = remote_arch_cache_get(client_guid);
1337                 unbecome_root();
1338
1339                 return ok;
1340         }
1341
1342         become_root();
1343         ok = remote_arch_cache_set(client_guid);
1344         unbecome_root();
1345
1346         return ok;
1347 }
1348
1349 bool remote_arch_cache_delete(const struct GUID *client_guid)
1350 {
1351         bool ok;
1352         fstring ra_key;
1353
1354         ok = remote_arch_cache_key(client_guid, ra_key);
1355         if (!ok) {
1356                 return false;
1357         }
1358
1359         become_root();
1360         ok = gencache_del(ra_key);
1361         unbecome_root();
1362
1363         if (!ok) {
1364                 return false;
1365         }
1366
1367         return true;
1368 }
1369
1370 const char *tab_depth(int level, int depth)
1371 {
1372         if( CHECK_DEBUGLVL(level) ) {
1373                 dbgtext("%*s", depth*4, "");
1374         }
1375         return "";
1376 }
1377
1378 /*****************************************************************************
1379  Provide a checksum on a string
1380
1381  Input:  s - the null-terminated character string for which the checksum
1382              will be calculated.
1383
1384   Output: The checksum value calculated for s.
1385 *****************************************************************************/
1386
1387 int str_checksum(const char *s)
1388 {
1389         TDB_DATA key;
1390         if (s == NULL)
1391                 return 0;
1392
1393         key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1394                            .dsize = strlen(s) };
1395
1396         return tdb_jenkins_hash(&key);
1397 }
1398
1399 /*****************************************************************
1400  Zero a memory area then free it. Used to catch bugs faster.
1401 *****************************************************************/  
1402
1403 void zero_free(void *p, size_t size)
1404 {
1405         memset(p, 0, size);
1406         SAFE_FREE(p);
1407 }
1408
1409 /*****************************************************************
1410  Set our open file limit to a requested max and return the limit.
1411 *****************************************************************/  
1412
1413 int set_maxfiles(int requested_max)
1414 {
1415 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1416         struct rlimit rlp;
1417         int saved_current_limit;
1418
1419         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1420                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1421                         strerror(errno) ));
1422                 /* just guess... */
1423                 return requested_max;
1424         }
1425
1426         /* 
1427          * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1428          * account for the extra fd we need 
1429          * as well as the log files and standard
1430          * handles etc. Save the limit we want to set in case
1431          * we are running on an OS that doesn't support this limit (AIX)
1432          * which always returns RLIM_INFINITY for rlp.rlim_max.
1433          */
1434
1435         /* Try raising the hard (max) limit to the requested amount. */
1436
1437 #if defined(RLIM_INFINITY)
1438         if (rlp.rlim_max != RLIM_INFINITY) {
1439                 int orig_max = rlp.rlim_max;
1440
1441                 if ( rlp.rlim_max < requested_max )
1442                         rlp.rlim_max = requested_max;
1443
1444                 /* This failing is not an error - many systems (Linux) don't
1445                         support our default request of 10,000 open files. JRA. */
1446
1447                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1448                         DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n", 
1449                                 (int)rlp.rlim_max, strerror(errno) ));
1450
1451                         /* Set failed - restore original value from get. */
1452                         rlp.rlim_max = orig_max;
1453                 }
1454         }
1455 #endif
1456
1457         /* Now try setting the soft (current) limit. */
1458
1459         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1460
1461         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1462                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1463                         (int)rlp.rlim_cur, strerror(errno) ));
1464                 /* just guess... */
1465                 return saved_current_limit;
1466         }
1467
1468         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1469                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1470                         strerror(errno) ));
1471                 /* just guess... */
1472                 return saved_current_limit;
1473     }
1474
1475 #if defined(RLIM_INFINITY)
1476         if(rlp.rlim_cur == RLIM_INFINITY)
1477                 return saved_current_limit;
1478 #endif
1479
1480         if((int)rlp.rlim_cur > saved_current_limit)
1481                 return saved_current_limit;
1482
1483         return rlp.rlim_cur;
1484 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1485         /*
1486          * No way to know - just guess...
1487          */
1488         return requested_max;
1489 #endif
1490 }
1491
1492 /*****************************************************************
1493  malloc that aborts with smb_panic on fail or zero size.
1494  *****************************************************************/  
1495
1496 void *smb_xmalloc_array(size_t size, unsigned int count)
1497 {
1498         void *p;
1499         if (size == 0) {
1500                 smb_panic("smb_xmalloc_array: called with zero size");
1501         }
1502         if (count >= MAX_ALLOC_SIZE/size) {
1503                 smb_panic("smb_xmalloc_array: alloc size too large");
1504         }
1505         if ((p = SMB_MALLOC(size*count)) == NULL) {
1506                 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1507                         (unsigned long)size, (unsigned long)count));
1508                 smb_panic("smb_xmalloc_array: malloc failed");
1509         }
1510         return p;
1511 }
1512
1513 /*
1514   vasprintf that aborts on malloc fail
1515 */
1516
1517  int smb_xvasprintf(char **ptr, const char *format, va_list ap)
1518 {
1519         int n;
1520         va_list ap2;
1521
1522         va_copy(ap2, ap);
1523
1524         n = vasprintf(ptr, format, ap2);
1525         va_end(ap2);
1526         if (n == -1 || ! *ptr) {
1527                 smb_panic("smb_xvasprintf: out of memory");
1528         }
1529         return n;
1530 }
1531
1532 /*****************************************************************
1533  Get local hostname and cache result.
1534 *****************************************************************/
1535
1536 char *myhostname(void)
1537 {
1538         static char *ret;
1539         if (ret == NULL) {
1540                 ret = get_myname(NULL);
1541         }
1542         return ret;
1543 }
1544
1545 /*****************************************************************
1546  Get local hostname and cache result.
1547 *****************************************************************/
1548
1549 char *myhostname_upper(void)
1550 {
1551         static char *ret;
1552         if (ret == NULL) {
1553                 char *name = get_myname(NULL);
1554                 if (name == NULL) {
1555                         return NULL;
1556                 }
1557                 ret = strupper_talloc(NULL, name);
1558                 talloc_free(name);
1559         }
1560         return ret;
1561 }
1562
1563 /*******************************************************************
1564  Given a filename - get its directory name
1565 ********************************************************************/
1566
1567 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1568                     const char **name)
1569 {
1570         char *p;
1571         ptrdiff_t len;
1572
1573         p = strrchr_m(dir, '/'); /* Find final '/', if any */
1574
1575         if (p == NULL) {
1576                 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1577                         return False;
1578                 }
1579                 if (name) {
1580                         *name = dir;
1581                 }
1582                 return True;
1583         }
1584
1585         len = p-dir;
1586
1587         if (!(*parent = (char *)talloc_memdup(mem_ctx, dir, len+1))) {
1588                 return False;
1589         }
1590         (*parent)[len] = '\0';
1591
1592         if (name) {
1593                 *name = p+1;
1594         }
1595         return True;
1596 }
1597
1598 /*******************************************************************
1599  Determine if a pattern contains any Microsoft wildcard characters.
1600 *******************************************************************/
1601
1602 bool ms_has_wild(const char *s)
1603 {
1604         char c;
1605
1606         while ((c = *s++)) {
1607                 switch (c) {
1608                 case '*':
1609                 case '?':
1610                 case '<':
1611                 case '>':
1612                 case '"':
1613                         return True;
1614                 }
1615         }
1616         return False;
1617 }
1618
1619 bool ms_has_wild_w(const smb_ucs2_t *s)
1620 {
1621         smb_ucs2_t c;
1622         if (!s) return False;
1623         while ((c = *s++)) {
1624                 switch (c) {
1625                 case UCS2_CHAR('*'):
1626                 case UCS2_CHAR('?'):
1627                 case UCS2_CHAR('<'):
1628                 case UCS2_CHAR('>'):
1629                 case UCS2_CHAR('"'):
1630                         return True;
1631                 }
1632         }
1633         return False;
1634 }
1635
1636 /*******************************************************************
1637  A wrapper that handles case sensitivity and the special handling
1638  of the ".." name.
1639 *******************************************************************/
1640
1641 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1642 {
1643         if (ISDOTDOT(string))
1644                 string = ".";
1645         if (ISDOT(pattern))
1646                 return False;
1647
1648         return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1649 }
1650
1651 /*******************************************************************
1652  A wrapper that handles case sensitivity and the special handling
1653  of the ".." name. Varient that is only called by old search code which requires
1654  pattern translation.
1655 *******************************************************************/
1656
1657 bool mask_match_search(const char *string, const char *pattern, bool is_case_sensitive)
1658 {
1659         if (ISDOTDOT(string))
1660                 string = ".";
1661         if (ISDOT(pattern))
1662                 return False;
1663
1664         return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
1665 }
1666
1667 /*******************************************************************
1668  A wrapper that handles a list of patters and calls mask_match()
1669  on each.  Returns True if any of the patterns match.
1670 *******************************************************************/
1671
1672 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1673 {
1674        while (listLen-- > 0) {
1675                if (mask_match(string, *list++, is_case_sensitive))
1676                        return True;
1677        }
1678        return False;
1679 }
1680
1681 /**********************************************************************
1682   Converts a name to a fully qualified domain name.
1683   Returns true if lookup succeeded, false if not (then fqdn is set to name)
1684   Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1685   canonical name of the host. getaddrinfo() may use a variety of sources
1686   including /etc/hosts to obtain the domainname. It expects aliases in
1687   /etc/hosts to NOT be the FQDN. The FQDN should come first.
1688 ************************************************************************/
1689
1690 bool name_to_fqdn(fstring fqdn, const char *name)
1691 {
1692         char *full = NULL;
1693         struct addrinfo hints;
1694         struct addrinfo *result;
1695         int s;
1696
1697         /* Configure hints to obtain canonical name */
1698
1699         memset(&hints, 0, sizeof(struct addrinfo));
1700         hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
1701         hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
1702         hints.ai_flags = AI_CANONNAME;  /* Get host's FQDN */
1703         hints.ai_protocol = 0;          /* Any protocol */
1704
1705         s = getaddrinfo(name, NULL, &hints, &result);
1706         if (s != 0) {
1707                 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s)));
1708                 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
1709                 fstrcpy(fqdn, name);
1710                 return false;
1711         }
1712         full = result->ai_canonname;
1713
1714         /* Find out if the FQDN is returned as an alias
1715          * to cope with /etc/hosts files where the first
1716          * name is not the FQDN but the short name.
1717          * getaddrinfo provides no easy way of handling aliases
1718          * in /etc/hosts. Users should make sure the FQDN
1719          * comes first in /etc/hosts. */
1720         if (full && (! strchr_m(full, '.'))) {
1721                 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1722                 DEBUGADD(1, ("    Full qualified domain names (FQDNs) should not be specified\n"));
1723                 DEBUGADD(1, ("    as an alias in /etc/hosts. FQDN should be the first name\n"));
1724                 DEBUGADD(1, ("    prior to any aliases.\n"));
1725         }
1726         if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
1727                 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1728                 DEBUGADD(1, ("    Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1729                 DEBUGADD(1, ("    to Kerberos authentication problems as localhost.localdomain\n"));
1730                 DEBUGADD(1, ("    may end up being used instead of the real machine FQDN.\n"));
1731         }
1732
1733         DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
1734         fstrcpy(fqdn, full);
1735         freeaddrinfo(result);           /* No longer needed */
1736         return true;
1737 }
1738
1739 uint32_t map_share_mode_to_deny_mode(uint32_t share_access, uint32_t private_options)
1740 {
1741         switch (share_access & ~FILE_SHARE_DELETE) {
1742                 case FILE_SHARE_NONE:
1743                         return DENY_ALL;
1744                 case FILE_SHARE_READ:
1745                         return DENY_WRITE;
1746                 case FILE_SHARE_WRITE:
1747                         return DENY_READ;
1748                 case FILE_SHARE_READ|FILE_SHARE_WRITE:
1749                         return DENY_NONE;
1750         }
1751         if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) {
1752                 return DENY_DOS;
1753         } else if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_FCB) {
1754                 return DENY_FCB;
1755         }
1756
1757         return (uint32_t)-1;
1758 }
1759
1760 struct server_id interpret_pid(const char *pid_string)
1761 {
1762         return server_id_from_string(get_my_vnn(), pid_string);
1763 }
1764
1765 /****************************************************************
1766  Check if an offset into a buffer is safe.
1767  If this returns True it's safe to indirect into the byte at
1768  pointer ptr+off.
1769 ****************************************************************/
1770
1771 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1772 {
1773         const char *end_base = buf_base + buf_len;
1774         char *end_ptr = ptr + off;
1775
1776         if (!buf_base || !ptr) {
1777                 return False;
1778         }
1779
1780         if (end_base < buf_base || end_ptr < ptr) {
1781                 return False; /* wrap. */
1782         }
1783
1784         if (end_ptr < end_base) {
1785                 return True;
1786         }
1787         return False;
1788 }
1789
1790 /****************************************************************
1791  Return a safe pointer into a buffer, or NULL.
1792 ****************************************************************/
1793
1794 char *get_safe_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1795 {
1796         return is_offset_safe(buf_base, buf_len, ptr, off) ?
1797                         ptr + off : NULL;
1798 }
1799
1800 /****************************************************************
1801  Return a safe pointer into a string within a buffer, or NULL.
1802 ****************************************************************/
1803
1804 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1805 {
1806         if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1807                 return NULL;
1808         }
1809         /* Check if a valid string exists at this offset. */
1810         if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1811                 return NULL;
1812         }
1813         return ptr + off;
1814 }
1815
1816 /****************************************************************
1817  Return an SVAL at a pointer, or failval if beyond the end.
1818 ****************************************************************/
1819
1820 int get_safe_SVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1821 {
1822         /*
1823          * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1824          * NOT ptr[2].
1825          */
1826         if (!is_offset_safe(buf_base, buf_len, ptr, off+1)) {
1827                 return failval;
1828         }
1829         return SVAL(ptr,off);
1830 }
1831
1832 /****************************************************************
1833  Return an IVAL at a pointer, or failval if beyond the end.
1834 ****************************************************************/
1835
1836 int get_safe_IVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1837 {
1838         /*
1839          * Note we use off+3 here, not off+4 as IVAL accesses 
1840          * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1841          */
1842         if (!is_offset_safe(buf_base, buf_len, ptr, off+3)) {
1843                 return failval;
1844         }
1845         return IVAL(ptr,off);
1846 }
1847
1848 /****************************************************************
1849  Split DOM\user into DOM and user. Do not mix with winbind variants of that
1850  call (they take care of winbind separator and other winbind specific settings).
1851 ****************************************************************/
1852
1853 bool split_domain_user(TALLOC_CTX *mem_ctx,
1854                        const char *full_name,
1855                        char **domain,
1856                        char **user)
1857 {
1858         const char *p = NULL;
1859
1860         p = strchr_m(full_name, '\\');
1861
1862         if (p != NULL) {
1863                 *domain = talloc_strndup(mem_ctx, full_name,
1864                                          PTR_DIFF(p, full_name));
1865                 if (*domain == NULL) {
1866                         return false;
1867                 }
1868                 *user = talloc_strdup(mem_ctx, p+1);
1869                 if (*user == NULL) {
1870                         TALLOC_FREE(*domain);
1871                         return false;
1872                 }
1873         } else {
1874                 *domain = NULL;
1875                 *user = talloc_strdup(mem_ctx, full_name);
1876                 if (*user == NULL) {
1877                         return false;
1878                 }
1879         }
1880
1881         return true;
1882 }
1883
1884 /****************************************************************
1885  strip off leading '\\' from a hostname
1886 ****************************************************************/
1887
1888 const char *strip_hostname(const char *s)
1889 {
1890         if (!s) {
1891                 return NULL;
1892         }
1893
1894         if (strlen_m(s) < 3) {
1895                 return s;
1896         }
1897
1898         if (s[0] == '\\') s++;
1899         if (s[0] == '\\') s++;
1900
1901         return s;
1902 }
1903
1904 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1905 {
1906         if (!NT_STATUS_IS_OK(err1)) {
1907                 *result = err1;
1908                 return true;
1909         }
1910         if (!NT_STATUS_IS_OK(err2)) {
1911                 *result = err2;
1912                 return true;
1913         }
1914         return false;
1915 }
1916
1917 int timeval_to_msec(struct timeval t)
1918 {
1919         return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
1920 }
1921
1922 /*******************************************************************
1923  Check a given DOS pathname is valid for a share.
1924 ********************************************************************/
1925
1926 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
1927 {
1928         char *ptr = NULL;
1929
1930         if (!dos_pathname) {
1931                 return NULL;
1932         }
1933
1934         ptr = talloc_strdup(ctx, dos_pathname);
1935         if (!ptr) {
1936                 return NULL;
1937         }
1938         /* Convert any '\' paths to '/' */
1939         unix_format(ptr);
1940         ptr = unix_clean_name(ctx, ptr);
1941         if (!ptr) {
1942                 return NULL;
1943         }
1944
1945         /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1946         if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1947                 ptr += 2;
1948
1949         /* Only absolute paths allowed. */
1950         if (*ptr != '/')
1951                 return NULL;
1952
1953         return ptr;
1954 }
1955
1956 /*******************************************************************
1957  Return True if the filename is one of the special executable types.
1958 ********************************************************************/
1959
1960 bool is_executable(const char *fname)
1961 {
1962         if ((fname = strrchr_m(fname,'.'))) {
1963                 if (strequal(fname,".com") ||
1964                     strequal(fname,".dll") ||
1965                     strequal(fname,".exe") ||
1966                     strequal(fname,".sym")) {
1967                         return True;
1968                 }
1969         }
1970         return False;
1971 }
1972
1973 /****************************************************************************
1974  Open a file with a share mode - old openX method - map into NTCreate.
1975 ****************************************************************************/
1976
1977 bool map_open_params_to_ntcreate(const char *smb_base_fname,
1978                                  int deny_mode, int open_func,
1979                                  uint32_t *paccess_mask,
1980                                  uint32_t *pshare_mode,
1981                                  uint32_t *pcreate_disposition,
1982                                  uint32_t *pcreate_options,
1983                                  uint32_t *pprivate_flags)
1984 {
1985         uint32_t access_mask;
1986         uint32_t share_mode;
1987         uint32_t create_disposition;
1988         uint32_t create_options = FILE_NON_DIRECTORY_FILE;
1989         uint32_t private_flags = 0;
1990
1991         DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1992                   "open_func = 0x%x\n",
1993                   smb_base_fname, (unsigned int)deny_mode,
1994                   (unsigned int)open_func ));
1995
1996         /* Create the NT compatible access_mask. */
1997         switch (GET_OPENX_MODE(deny_mode)) {
1998                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1999                 case DOS_OPEN_RDONLY:
2000                         access_mask = FILE_GENERIC_READ;
2001                         break;
2002                 case DOS_OPEN_WRONLY:
2003                         access_mask = FILE_GENERIC_WRITE;
2004                         break;
2005                 case DOS_OPEN_RDWR:
2006                 case DOS_OPEN_FCB:
2007                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
2008                         break;
2009                 default:
2010                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
2011                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
2012                         return False;
2013         }
2014
2015         /* Create the NT compatible create_disposition. */
2016         switch (open_func) {
2017                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
2018                         create_disposition = FILE_CREATE;
2019                         break;
2020
2021                 case OPENX_FILE_EXISTS_OPEN:
2022                         create_disposition = FILE_OPEN;
2023                         break;
2024
2025                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
2026                         create_disposition = FILE_OPEN_IF;
2027                         break;
2028
2029                 case OPENX_FILE_EXISTS_TRUNCATE:
2030                         create_disposition = FILE_OVERWRITE;
2031                         break;
2032
2033                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
2034                         create_disposition = FILE_OVERWRITE_IF;
2035                         break;
2036
2037                 default:
2038                         /* From samba4 - to be confirmed. */
2039                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
2040                                 create_disposition = FILE_CREATE;
2041                                 break;
2042                         }
2043                         DEBUG(10,("map_open_params_to_ntcreate: bad "
2044                                   "open_func 0x%x\n", (unsigned int)open_func));
2045                         return False;
2046         }
2047
2048         /* Create the NT compatible share modes. */
2049         switch (GET_DENY_MODE(deny_mode)) {
2050                 case DENY_ALL:
2051                         share_mode = FILE_SHARE_NONE;
2052                         break;
2053
2054                 case DENY_WRITE:
2055                         share_mode = FILE_SHARE_READ;
2056                         break;
2057
2058                 case DENY_READ:
2059                         share_mode = FILE_SHARE_WRITE;
2060                         break;
2061
2062                 case DENY_NONE:
2063                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2064                         break;
2065
2066                 case DENY_DOS:
2067                         private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
2068                         if (is_executable(smb_base_fname)) {
2069                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2070                         } else {
2071                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
2072                                         share_mode = FILE_SHARE_READ;
2073                                 } else {
2074                                         share_mode = FILE_SHARE_NONE;
2075                                 }
2076                         }
2077                         break;
2078
2079                 case DENY_FCB:
2080                         private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
2081                         share_mode = FILE_SHARE_NONE;
2082                         break;
2083
2084                 default:
2085                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2086                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
2087                         return False;
2088         }
2089
2090         DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2091                   "share_mode = 0x%x, create_disposition = 0x%x, "
2092                   "create_options = 0x%x private_flags = 0x%x\n",
2093                   smb_base_fname,
2094                   (unsigned int)access_mask,
2095                   (unsigned int)share_mode,
2096                   (unsigned int)create_disposition,
2097                   (unsigned int)create_options,
2098                   (unsigned int)private_flags));
2099
2100         if (paccess_mask) {
2101                 *paccess_mask = access_mask;
2102         }
2103         if (pshare_mode) {
2104                 *pshare_mode = share_mode;
2105         }
2106         if (pcreate_disposition) {
2107                 *pcreate_disposition = create_disposition;
2108         }
2109         if (pcreate_options) {
2110                 *pcreate_options = create_options;
2111         }
2112         if (pprivate_flags) {
2113                 *pprivate_flags = private_flags;
2114         }
2115
2116         return True;
2117
2118 }
2119
2120 /*************************************************************************
2121  Return a talloced copy of a struct security_unix_token. NULL on fail.
2122 *************************************************************************/
2123
2124 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
2125 {
2126         struct security_unix_token *cpy;
2127
2128         cpy = talloc(ctx, struct security_unix_token);
2129         if (!cpy) {
2130                 return NULL;
2131         }
2132
2133         cpy->uid = tok->uid;
2134         cpy->gid = tok->gid;
2135         cpy->ngroups = tok->ngroups;
2136         if (tok->ngroups) {
2137                 /* Make this a talloc child of cpy. */
2138                 cpy->groups = (gid_t *)talloc_memdup(
2139                         cpy, tok->groups, tok->ngroups * sizeof(gid_t));
2140                 if (!cpy->groups) {
2141                         TALLOC_FREE(cpy);
2142                         return NULL;
2143                 }
2144         } else {
2145                 cpy->groups = NULL;
2146         }
2147         return cpy;
2148 }
2149
2150 /****************************************************************************
2151  Return a root token
2152 ****************************************************************************/
2153
2154 struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
2155 {
2156         struct security_unix_token *t = NULL;
2157
2158         t = talloc_zero(mem_ctx, struct security_unix_token);
2159         if (t == NULL) {
2160                 return NULL;
2161         }
2162
2163         /*
2164          * This is not needed, but lets make it explicit, not implicit.
2165          */
2166         *t = (struct security_unix_token) {
2167                 .uid = 0,
2168                 .gid = 0,
2169                 .ngroups = 0,
2170                 .groups = NULL
2171         };
2172
2173         return t;
2174 }
2175
2176 /****************************************************************************
2177  Check that a file matches a particular file type.
2178 ****************************************************************************/
2179
2180 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
2181 {
2182         uint32_t mask;
2183
2184         /* Check the "may have" search bits. */
2185         if (((mode & ~dirtype) &
2186                         (FILE_ATTRIBUTE_HIDDEN |
2187                          FILE_ATTRIBUTE_SYSTEM |
2188                          FILE_ATTRIBUTE_DIRECTORY)) != 0) {
2189                 return false;
2190         }
2191
2192         /* Check the "must have" bits,
2193            which are the may have bits shifted eight */
2194         /* If must have bit is set, the file/dir can
2195            not be returned in search unless the matching
2196            file attribute is set */
2197         mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
2198                                     FILE_ATTRIBUTE_ARCHIVE|
2199                                    FILE_ATTRIBUTE_READONLY|
2200                                      FILE_ATTRIBUTE_HIDDEN|
2201                                      FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
2202         if(mask) {
2203                 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
2204                                       FILE_ATTRIBUTE_ARCHIVE|
2205                                      FILE_ATTRIBUTE_READONLY|
2206                                        FILE_ATTRIBUTE_HIDDEN|
2207                                         FILE_ATTRIBUTE_SYSTEM))) == mask) {
2208                         /* check if matching attribute present */
2209                         return true;
2210                 } else {
2211                         return false;
2212                 }
2213         }
2214
2215         return true;
2216 }