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