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