LCOV - code coverage report
Current view: top level - source3/lib - util.c (source / functions) Hit Total Coverage
Test: coverage report for master 2f515e9b Lines: 611 869 70.3 %
Date: 2024-04-21 15:09:00 Functions: 62 72 86.1 %

          Line data    Source code
       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       30863 : void set_Protocol(enum protocol_types  p)
      58             : {
      59       30863 :         Protocol = p;
      60       30863 : }
      61             : 
      62             : static enum remote_arch_types ra_type = RA_UNKNOWN;
      63             : 
      64       14425 : void gfree_all( void )
      65             : {
      66       14425 :         gfree_loadparm();
      67       14425 :         gfree_charcnv();
      68       14425 :         gfree_interfaces();
      69       14425 :         gfree_debugsyms();
      70       14425 :         gfree_memcache();
      71             : 
      72       14425 : }
      73             : 
      74             : /*******************************************************************
      75             :  Check if a file exists - call vfs_file_exist for samba files.
      76             : ********************************************************************/
      77             : 
      78        1024 : bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
      79             :                      bool fake_dir_create_times)
      80             : {
      81           0 :         SMB_STRUCT_STAT st;
      82        1024 :         if (!sbuf)
      83           0 :                 sbuf = &st;
      84             : 
      85        1024 :         if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
      86           0 :                 return(False);
      87             : 
      88        1024 :         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           0 : bool socket_exist(const char *fname)
      96             : {
      97           0 :         SMB_STRUCT_STAT st;
      98           0 :         if (sys_stat(fname, &st, false) != 0)
      99           0 :                 return(False);
     100             : 
     101           0 :         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     2340793 : uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
     109             : {
     110     2340793 :         return sbuf->st_ex_size;
     111             : }
     112             : 
     113             : /****************************************************************************
     114             :  Check two stats have identical dev and ino fields.
     115             : ****************************************************************************/
     116             : 
     117      292441 : bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
     118             :                         const SMB_STRUCT_STAT *sbuf2)
     119             : {
     120      584169 :         return ((sbuf1->st_ex_dev == sbuf2->st_ex_dev) &&
     121      292441 :                 (sbuf1->st_ex_ino == sbuf2->st_ex_ino));
     122             : }
     123             : 
     124             : /****************************************************************************
     125             :  Check if a stat struct is identical for use.
     126             : ****************************************************************************/
     127             : 
     128           2 : bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
     129             :                      const SMB_STRUCT_STAT *sbuf2)
     130             : {
     131           4 :         return ((sbuf1->st_ex_uid == sbuf2->st_ex_uid) &&
     132           4 :                 (sbuf1->st_ex_gid == sbuf2->st_ex_gid) &&
     133           2 :                 check_same_dev_ino(sbuf1, sbuf2));
     134             : }
     135             : 
     136             : /*******************************************************************
     137             :  Show a smb message structure.
     138             : ********************************************************************/
     139             : 
     140     1312238 : void show_msg(const char *buf)
     141             : {
     142       15942 :         int i;
     143     1312238 :         int bcc=0;
     144             : 
     145     1312238 :         if (!DEBUGLVL(5))
     146     1312238 :                 return;
     147             : 
     148           0 :         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           0 :         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           0 :         DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
     162             : 
     163           0 :         for (i=0;i<(int)CVAL(buf,smb_wct);i++)
     164           0 :                 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           0 :         bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
     168             : 
     169           0 :         DEBUGADD(5,("smb_bcc=%d\n",bcc));
     170             : 
     171           0 :         if (DEBUGLEVEL < 10)
     172           0 :                 return;
     173             : 
     174           0 :         if (DEBUGLEVEL < 50)
     175           0 :                 bcc = MIN(bcc, 512);
     176             : 
     177           0 :         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       93010 : int set_message_bcc(char *buf,int num_bytes)
     185             : {
     186       93010 :         int num_words = CVAL(buf,smb_wct);
     187       93010 :         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
     188       93010 :         _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
     189       93010 :         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       38400 : ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
     198             : {
     199       38400 :         size_t newlen = smb_len(*outbuf) + 4 + blob.length;
     200         266 :         uint8_t *tmp;
     201             : 
     202       38400 :         if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
     203           0 :                 DEBUG(0, ("talloc failed\n"));
     204           0 :                 return -1;
     205             :         }
     206       38400 :         *outbuf = tmp;
     207             : 
     208       38400 :         memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
     209       38400 :         set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
     210       38400 :         return blob.length;
     211             : }
     212             : 
     213             : /*******************************************************************
     214             :  Reduce a file name, removing .. elements.
     215             : ********************************************************************/
     216             : 
     217       15618 : static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
     218             : {
     219       15618 :         char *p = NULL;
     220       15618 :         char *str = NULL;
     221             : 
     222       15618 :         DEBUG(3,("dos_clean_name [%s]\n",s));
     223             : 
     224             :         /* remove any double slashes */
     225       15618 :         str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
     226       15618 :         if (!str) {
     227           0 :                 return NULL;
     228             :         }
     229             : 
     230             :         /* Remove leading .\\ characters */
     231       15618 :         if(strncmp(str, ".\\", 2) == 0) {
     232           0 :                 trim_string(str, ".\\", NULL);
     233           0 :                 if(*str == 0) {
     234           0 :                         str = talloc_strdup(ctx, ".\\");
     235           0 :                         if (!str) {
     236           0 :                                 return NULL;
     237             :                         }
     238             :                 }
     239             :         }
     240             : 
     241       15680 :         while ((p = strstr_m(str,"\\..\\")) != NULL) {
     242           0 :                 char *s1;
     243             : 
     244          62 :                 *p = 0;
     245          62 :                 s1 = p+3;
     246             : 
     247          62 :                 if ((p=strrchr_m(str,'\\')) != NULL) {
     248          60 :                         *p = 0;
     249             :                 } else {
     250           2 :                         *str = 0;
     251             :                 }
     252          62 :                 str = talloc_asprintf(ctx,
     253             :                                 "%s%s",
     254             :                                 str,
     255             :                                 s1);
     256          62 :                 if (!str) {
     257           0 :                         return NULL;
     258             :                 }
     259             :         }
     260             : 
     261       15618 :         trim_string(str,NULL,"\\..");
     262       15618 :         return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
     263             : }
     264             : 
     265             : /*******************************************************************
     266             :  Reduce a file name, removing .. elements.
     267             : ********************************************************************/
     268             : 
     269       16056 : char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
     270             : {
     271       16056 :         char *p = NULL;
     272       16056 :         char *str = NULL;
     273             : 
     274       16056 :         DEBUG(3,("unix_clean_name [%s]\n",s));
     275             : 
     276             :         /* remove any double slashes */
     277       16056 :         str = talloc_all_string_sub(ctx, s, "//","/");
     278       16056 :         if (!str) {
     279           0 :                 return NULL;
     280             :         }
     281             : 
     282             :         /* Remove leading ./ characters */
     283       16056 :         if(strncmp(str, "./", 2) == 0) {
     284           0 :                 trim_string(str, "./", NULL);
     285           0 :                 if(*str == 0) {
     286           0 :                         str = talloc_strdup(ctx, "./");
     287           0 :                         if (!str) {
     288           0 :                                 return NULL;
     289             :                         }
     290             :                 }
     291             :         }
     292             : 
     293       16056 :         while ((p = strstr_m(str,"/../")) != NULL) {
     294           0 :                 char *s1;
     295             : 
     296           0 :                 *p = 0;
     297           0 :                 s1 = p+3;
     298             : 
     299           0 :                 if ((p=strrchr_m(str,'/')) != NULL) {
     300           0 :                         *p = 0;
     301             :                 } else {
     302           0 :                         *str = 0;
     303             :                 }
     304           0 :                 str = talloc_asprintf(ctx,
     305             :                                 "%s%s",
     306             :                                 str,
     307             :                                 s1);
     308           0 :                 if (!str) {
     309           0 :                         return NULL;
     310             :                 }
     311             :         }
     312             : 
     313       16056 :         trim_string(str,NULL,"/..");
     314       16056 :         return talloc_all_string_sub(ctx, str, "/./", "/");
     315             : }
     316             : 
     317       15618 : char *clean_name(TALLOC_CTX *ctx, const char *s)
     318             : {
     319       15618 :         char *str = dos_clean_name(ctx, s);
     320       15618 :         if (!str) {
     321           0 :                 return NULL;
     322             :         }
     323       15618 :         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           0 : ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
     331             : {
     332           0 :         size_t total=0;
     333           0 :         ssize_t ret;
     334             : 
     335           0 :         if (pos == (off_t)-1) {
     336           0 :                 return write_data(fd, buffer, N);
     337             :         }
     338             : #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
     339           0 :         while (total < N) {
     340           0 :                 ret = sys_pwrite(fd,buffer + total,N - total, pos);
     341           0 :                 if (ret == -1 && errno == ESPIPE) {
     342           0 :                         return write_data(fd, buffer + total,N - total);
     343             :                 }
     344           0 :                 if (ret == -1) {
     345           0 :                         DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
     346           0 :                         return -1;
     347             :                 }
     348           0 :                 if (ret == 0) {
     349           0 :                         return total;
     350             :                 }
     351           0 :                 total += ret;
     352           0 :                 pos += ret;
     353             :         }
     354           0 :         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          88 : NTSTATUS init_before_fork(void)
     369             : {
     370           0 :         int ret;
     371             : 
     372          88 :         ret = pipe(reinit_after_fork_pipe);
     373          88 :         if (ret == -1) {
     374           0 :                 NTSTATUS status;
     375             : 
     376           0 :                 status = map_nt_error_from_unix_common(errno);
     377             : 
     378           0 :                 DEBUG(0, ("Error creating child_pipe: %s\n",
     379             :                           nt_errstr(status)));
     380             : 
     381           0 :                 return status;
     382             :         }
     383             : 
     384          88 :         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           0 : int parent_watch_fd(void)
     397             : {
     398           0 :         return reinit_after_fork_pipe[0];
     399             : }
     400             : 
     401             : /**
     402             :  * Detect died parent by detecting EOF on the pipe
     403             :  */
     404          11 : 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           0 :         char c;
     410             : 
     411          11 :         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          11 :                 TALLOC_FREE(fde);
     417          11 :                 (void)kill(getpid(), SIGTERM);
     418             :         }
     419          11 : }
     420             : 
     421             : 
     422       31808 : NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
     423             :                            struct tevent_context *ev_ctx,
     424             :                            bool parent_longlived)
     425             : {
     426       31808 :         NTSTATUS status = NT_STATUS_OK;
     427         850 :         int ret;
     428             : 
     429             :         /*
     430             :          * The main process thread should never
     431             :          * allow per_thread_cwd_enable() to be
     432             :          * called.
     433             :          */
     434       31808 :         per_thread_cwd_disable();
     435             : 
     436       31808 :         if (reinit_after_fork_pipe[1] != -1) {
     437       31565 :                 close(reinit_after_fork_pipe[1]);
     438       31565 :                 reinit_after_fork_pipe[1] = -1;
     439             :         }
     440             : 
     441             :         /* tdb needs special fork handling */
     442       31808 :         if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
     443           0 :                 DEBUG(0,("tdb_reopen_all failed.\n"));
     444           0 :                 status = NT_STATUS_OPEN_FAILED;
     445           0 :                 goto done;
     446             :         }
     447             : 
     448       31808 :         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       31808 :                 tevent_set_trace_callback(ev_ctx, NULL, NULL);
     454       31808 :                 tevent_set_trace_fd_callback(ev_ctx, NULL, NULL);
     455       31808 :                 tevent_set_trace_signal_callback(ev_ctx, NULL, NULL);
     456       31808 :                 tevent_set_trace_timer_callback(ev_ctx, NULL, NULL);
     457       31808 :                 tevent_set_trace_immediate_callback(ev_ctx, NULL, NULL);
     458       31808 :                 tevent_set_trace_queue_callback(ev_ctx, NULL, NULL);
     459       31808 :                 if (tevent_re_initialise(ev_ctx) != 0) {
     460           0 :                         smb_panic(__location__ ": Failed to re-initialise event context");
     461             :                 }
     462             :         }
     463             : 
     464       31808 :         if (reinit_after_fork_pipe[0] != -1) {
     465         842 :                 struct tevent_fd *fde;
     466             : 
     467       31565 :                 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       31565 :                 if (fde == NULL) {
     471           0 :                         smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
     472             :                 }
     473             :         }
     474             : 
     475       31808 :         if (msg_ctx) {
     476             :                 /*
     477             :                  * For clustering, we need to re-init our ctdbd connection after the
     478             :                  * fork
     479             :                  */
     480       31808 :                 status = messaging_reinit(msg_ctx);
     481       31808 :                 if (!NT_STATUS_IS_OK(status)) {
     482           0 :                         DEBUG(0,("messaging_reinit() failed: %s\n",
     483             :                                  nt_errstr(status)));
     484             :                 }
     485             : 
     486       31808 :                 if (lp_clustering()) {
     487           0 :                         ret = ctdb_async_ctx_reinit(
     488             :                                 NULL, messaging_tevent_context(msg_ctx));
     489           0 :                         if (ret != 0) {
     490           0 :                                 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
     491             :                                         strerror(errno));
     492           0 :                                 return map_nt_error_from_unix(ret);
     493             :                         }
     494             :                 }
     495             :         }
     496             : 
     497       31808 :  done:
     498       31808 :         return status;
     499             : }
     500             : 
     501             : /****************************************************************************
     502             :  (Hopefully) efficient array append.
     503             : ****************************************************************************/
     504             : 
     505        2631 : 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        2631 :         void **array = (void **)_array;
     510             : 
     511        2631 :         if (*array_size < 0) {
     512           0 :                 return;
     513             :         }
     514             : 
     515        2631 :         if (*array == NULL) {
     516          43 :                 if (*array_size == 0) {
     517          43 :                         *array_size = 128;
     518             :                 }
     519             : 
     520          43 :                 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
     521           0 :                         goto error;
     522             :                 }
     523             : 
     524          43 :                 *array = TALLOC(mem_ctx, element_size * (*array_size));
     525          43 :                 if (*array == NULL) {
     526           0 :                         goto error;
     527             :                 }
     528             :         }
     529             : 
     530        2631 :         if (*num_elements == *array_size) {
     531          16 :                 *array_size *= 2;
     532             : 
     533          16 :                 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
     534           0 :                         goto error;
     535             :                 }
     536             : 
     537          16 :                 *array = TALLOC_REALLOC(mem_ctx, *array,
     538             :                                         element_size * (*array_size));
     539             : 
     540          16 :                 if (*array == NULL) {
     541           0 :                         goto error;
     542             :                 }
     543             :         }
     544             : 
     545        2631 :         memcpy((char *)(*array) + element_size*(*num_elements),
     546             :                element, element_size);
     547        2631 :         *num_elements += 1;
     548             : 
     549        2631 :         return;
     550             : 
     551           0 :  error:
     552           0 :         *num_elements = 0;
     553           0 :         *array_size = -1;
     554             : }
     555             : 
     556             : /****************************************************************************
     557             :  Get my own domain name, or "" if we have none.
     558             : ****************************************************************************/
     559             : 
     560       58547 : char *get_mydnsdomname(TALLOC_CTX *ctx)
     561             : {
     562           0 :         const char *domname;
     563           0 :         char *p;
     564             : 
     565       58547 :         domname = get_mydnsfullname();
     566       58547 :         if (!domname) {
     567           0 :                 return NULL;
     568             :         }
     569             : 
     570       58547 :         p = strchr_m(domname, '.');
     571       58547 :         if (p) {
     572       58547 :                 p++;
     573       58547 :                 return talloc_strdup(ctx, p);
     574             :         } else {
     575           0 :                 return talloc_strdup(ctx, "");
     576             :         }
     577             : }
     578             : 
     579          62 : bool process_exists(const struct server_id pid)
     580             : {
     581          62 :         return serverid_exists(&pid);
     582             : }
     583             : 
     584             : /*******************************************************************
     585             :  Convert a uid into a user name.
     586             : ********************************************************************/
     587             : 
     588         176 : const char *uidtoname(uid_t uid)
     589             : {
     590         176 :         TALLOC_CTX *ctx = talloc_tos();
     591         176 :         char *name = NULL;
     592         176 :         struct passwd *pass = NULL;
     593             : 
     594         176 :         pass = getpwuid_alloc(ctx,uid);
     595         176 :         if (pass) {
     596          46 :                 name = talloc_strdup(ctx,pass->pw_name);
     597          46 :                 TALLOC_FREE(pass);
     598             :         } else {
     599         130 :                 name = talloc_asprintf(ctx,
     600             :                                 "%ld",
     601             :                                 (long int)uid);
     602             :         }
     603         176 :         return name;
     604             : }
     605             : 
     606             : /*******************************************************************
     607             :  Convert a gid into a group name.
     608             : ********************************************************************/
     609             : 
     610          60 : char *gidtoname(gid_t gid)
     611             : {
     612           4 :         struct group *grp;
     613             : 
     614          60 :         grp = getgrgid(gid);
     615          60 :         if (grp) {
     616          60 :                 return talloc_strdup(talloc_tos(), grp->gr_name);
     617             :         }
     618             :         else {
     619           0 :                 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         368 : uid_t nametouid(const char *name)
     630             : {
     631           0 :         struct passwd *pass;
     632           0 :         char *p;
     633           0 :         uid_t u;
     634             : 
     635         368 :         pass = Get_Pwnam_alloc(talloc_tos(), name);
     636         368 :         if (pass) {
     637         368 :                 u = pass->pw_uid;
     638         368 :                 TALLOC_FREE(pass);
     639         368 :                 return u;
     640             :         }
     641             : 
     642           0 :         u = (uid_t)strtol(name, &p, 0);
     643           0 :         if ((p != name) && (*p == '\0'))
     644           0 :                 return u;
     645             : 
     646           0 :         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         197 : gid_t nametogid(const char *name)
     654             : {
     655           0 :         struct group *grp;
     656           0 :         char *p;
     657           0 :         gid_t g;
     658             : 
     659         197 :         g = (gid_t)strtol(name, &p, 0);
     660         197 :         if ((p != name) && (*p == '\0'))
     661           0 :                 return g;
     662             : 
     663         197 :         grp = getgrnam(name);
     664         197 :         if (grp)
     665         197 :                 return(grp->gr_gid);
     666           0 :         return (gid_t)-1;
     667             : }
     668             : 
     669             : /*******************************************************************
     670             :  Something really nasty happened - panic !
     671             : ********************************************************************/
     672             : 
     673           0 : static void call_panic_action(const char *why, bool as_root)
     674             : {
     675           0 :         const struct loadparm_substitution *lp_sub =
     676           0 :                 loadparm_s3_global_substitution();
     677           0 :         char *cmd;
     678           0 :         int result;
     679             : 
     680           0 :         cmd = lp_panic_action(talloc_tos(), lp_sub);
     681           0 :         if (cmd == NULL || cmd[0] == '\0') {
     682           0 :                 return;
     683             :         }
     684             : 
     685           0 :         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           0 :         prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
     692             : #endif
     693             : 
     694           0 :         if (as_root) {
     695           0 :                 become_root();
     696             :         }
     697             : 
     698           0 :         result = system(cmd);
     699             : 
     700           0 :         if (as_root) {
     701           0 :                 unbecome_root();
     702             :         }
     703             : 
     704           0 :         if (result == -1)
     705           0 :                 DBG_ERR("fork failed in panic action: %s\n",
     706             :                         strerror(errno));
     707             :         else
     708           0 :                 DBG_ERR("action returned status %d\n",
     709             :                         WEXITSTATUS(result));
     710             : }
     711             : 
     712           0 : void smb_panic_s3(const char *why)
     713             : {
     714           0 :         call_panic_action(why, false);
     715           0 :         dump_core();
     716             : }
     717             : 
     718           0 : void log_panic_action(const char *msg)
     719             : {
     720           0 :         DBG_ERR("%s", msg);
     721           0 :         call_panic_action(msg, true);
     722           0 : }
     723             : 
     724             : /*******************************************************************
     725             :   A readdir wrapper which just returns the file name.
     726             :  ********************************************************************/
     727             : 
     728           0 : const char *readdirname(DIR *p)
     729             : {
     730           0 :         struct dirent *ptr;
     731           0 :         char *dname;
     732             : 
     733           0 :         if (!p)
     734           0 :                 return(NULL);
     735             : 
     736           0 :         ptr = (struct dirent *)readdir(p);
     737           0 :         if (!ptr)
     738           0 :                 return(NULL);
     739             : 
     740           0 :         dname = ptr->d_name;
     741             : 
     742           0 :         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     6209561 : bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
     751             : {
     752       23300 :         const char *last_component;
     753             : 
     754             :         /* if we have no list it's obviously not in the path */
     755     6209561 :         if ((namelist == NULL) || (namelist[0].name == NULL)) {
     756     6185771 :                 return False;
     757             :         }
     758             : 
     759             :         /* Do not reject path components if namelist is set to '.*' */
     760         504 :         if (ISDOT(name) || ISDOTDOT(name)) {
     761          70 :                 return false;
     762             :         }
     763             : 
     764         434 :         DEBUG(8, ("is_in_path: %s\n", name));
     765             : 
     766             :         /* Get the last component of the unix name. */
     767         434 :         last_component = strrchr_m(name, '/');
     768         434 :         if (!last_component) {
     769         419 :                 last_component = name;
     770             :         } else {
     771          29 :                 last_component++; /* Go past '/' */
     772             :         }
     773             : 
     774         800 :         for(; namelist->name != NULL; namelist++) {
     775         453 :                 if(namelist->is_wild) {
     776         427 :                         if (mask_match(last_component, namelist->name, case_sensitive)) {
     777          76 :                                 DEBUG(8,("is_in_path: mask match succeeded\n"));
     778          76 :                                 return True;
     779             :                         }
     780             :                 } else {
     781          26 :                         if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
     782          21 :                                                 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
     783          11 :                                 DEBUG(8,("is_in_path: match succeeded\n"));
     784          11 :                                 return True;
     785             :                         }
     786             :                 }
     787             :         }
     788         347 :         DEBUG(8,("is_in_path: match not found\n"));
     789         342 :         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       88637 : void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
     804             : {
     805        1437 :         char *name_end;
     806        1437 :         char *namelist;
     807        1437 :         char *namelist_end;
     808        1437 :         char *nameptr;
     809       88637 :         int num_entries = 0;
     810        1437 :         int i;
     811             : 
     812       88637 :         (*ppname_array) = NULL;
     813             : 
     814       88637 :         if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0')))
     815       87100 :                 return;
     816             : 
     817         101 :         namelist = talloc_strdup(talloc_tos(), namelist_in);
     818         101 :         if (namelist == NULL) {
     819           0 :                 DEBUG(0,("set_namearray: talloc fail\n"));
     820           0 :                 return;
     821             :         }
     822         101 :         nameptr = namelist;
     823             : 
     824         101 :         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         301 :         while(nameptr <= namelist_end) {
     832         301 :                 if ( *nameptr == '/' ) {
     833             :                         /* cope with multiple (useless) /s) */
     834          97 :                         nameptr++;
     835          97 :                         continue;
     836             :                 }
     837             :                 /* anything left? */
     838         204 :                 if ( *nameptr == '\0' )
     839         100 :                         break;
     840             : 
     841             :                 /* find the next '/' or consume remaining */
     842         103 :                 name_end = strchr_m(nameptr, '/');
     843         103 :                 if (name_end == NULL) {
     844             :                         /* Point nameptr at the terminating '\0' */
     845           4 :                         nameptr += strlen(nameptr);
     846             :                 } else {
     847             :                         /* next segment please */
     848          99 :                         nameptr = name_end + 1;
     849             :                 }
     850         103 :                 num_entries++;
     851             :         }
     852             : 
     853         101 :         if(num_entries == 0) {
     854           0 :                 talloc_free(namelist);
     855           0 :                 return;
     856             :         }
     857             : 
     858         101 :         if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
     859           0 :                 DEBUG(0,("set_namearray: malloc fail\n"));
     860           0 :                 talloc_free(namelist);
     861           0 :                 return;
     862             :         }
     863             : 
     864             :         /* Now copy out the names */
     865         100 :         nameptr = namelist;
     866         100 :         i = 0;
     867         301 :         while(nameptr <= namelist_end) {
     868         301 :                 if ( *nameptr == '/' ) {
     869             :                         /* cope with multiple (useless) /s) */
     870          97 :                         nameptr++;
     871          97 :                         continue;
     872             :                 }
     873             :                 /* anything left? */
     874         204 :                 if ( *nameptr == '\0' )
     875         100 :                         break;
     876             : 
     877             :                 /* find the next '/' or consume remaining */
     878         103 :                 name_end = strchr_m(nameptr, '/');
     879         103 :                 if (name_end != NULL) {
     880          99 :                         *name_end = '\0';
     881             :                 }
     882             : 
     883         103 :                 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
     884         103 :                 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
     885           0 :                         DEBUG(0,("set_namearray: malloc fail (1)\n"));
     886           0 :                         talloc_free(namelist);
     887           0 :                         return;
     888             :                 }
     889             : 
     890         103 :                 if (name_end == NULL) {
     891             :                         /* Point nameptr at the terminating '\0' */
     892           4 :                         nameptr += strlen(nameptr);
     893             :                 } else {
     894             :                         /* next segment please */
     895          99 :                         nameptr = name_end + 1;
     896             :                 }
     897         103 :                 i++;
     898             :         }
     899             : 
     900         101 :         (*ppname_array)[i].name = NULL;
     901             : 
     902         101 :         talloc_free(namelist);
     903         101 :         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      205832 : bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
     917             : {
     918         113 :         struct flock lock;
     919         113 :         int ret;
     920             : 
     921      205832 :         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      205832 :         lock.l_type = *ptype;
     925      205832 :         lock.l_whence = SEEK_SET;
     926      205832 :         lock.l_start = *poffset;
     927      205832 :         lock.l_len = *pcount;
     928      205832 :         lock.l_pid = 0;
     929             : 
     930      205832 :         ret = sys_fcntl_ptr(fd,op,&lock);
     931             : 
     932      205832 :         if (ret == -1) {
     933           0 :                 int saved_errno = errno;
     934           0 :                 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           0 :                 errno = saved_errno;
     937           0 :                 return False;
     938             :         }
     939             : 
     940      205832 :         *ptype = lock.l_type;
     941      205832 :         *poffset = lock.l_start;
     942      205832 :         *pcount = lock.l_len;
     943      205832 :         *ppid = lock.l_pid;
     944             : 
     945      205832 :         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      205719 :         return True;
     948             : }
     949             : 
     950             : #if defined(HAVE_OFD_LOCKS)
     951      211512 : int map_process_lock_to_ofd_lock(int op)
     952             : {
     953      211512 :         switch (op) {
     954      205719 :         case F_GETLK:
     955             :         case F_OFD_GETLK:
     956      205719 :                 op = F_OFD_GETLK;
     957      205719 :                 break;
     958        5680 :         case F_SETLK:
     959             :         case F_OFD_SETLK:
     960        5680 :                 op = F_OFD_SETLK;
     961        5680 :                 break;
     962           0 :         case F_SETLKW:
     963             :         case F_OFD_SETLKW:
     964           0 :                 op = F_OFD_SETLKW;
     965           0 :                 break;
     966           0 :         default:
     967           0 :                 return -1;
     968             :         }
     969      211365 :         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       20577 : static bool nb_name_equal(const char *s1, const char *s2)
     987             : {
     988       20577 :         int cmp = strncasecmp_m(s1, s2, MAX_NETBIOSNAME_LEN-1);
     989       20577 :         return (cmp == 0);
     990             : }
     991             : 
     992       17646 : bool is_myname(const char *s)
     993             : {
     994       17646 :         const char **aliases = NULL;
     995       17646 :         bool ok = false;
     996             : 
     997       17646 :         ok = nb_name_equal(lp_netbios_name(), s);
     998       17646 :         if (ok) {
     999        2316 :                 goto done;
    1000             :         }
    1001             : 
    1002       15330 :         aliases = lp_netbios_aliases();
    1003       15330 :         if (aliases == NULL) {
    1004       13843 :                 goto done;
    1005             :         }
    1006             : 
    1007        4332 :         while (*aliases != NULL) {
    1008        2931 :                 ok = nb_name_equal(*aliases, s);
    1009        2931 :                 if (ok) {
    1010          86 :                         goto done;
    1011             :                 }
    1012        2845 :                 aliases += 1;
    1013             :         }
    1014             : 
    1015        1401 : done:
    1016       17646 :         DBG_DEBUG("is_myname(\"%s\") returns %d\n", s, (int)ok);
    1017       17646 :         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           0 : void ra_lanman_string( const char *native_lanman )
    1032             : {
    1033           0 :         if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
    1034           0 :                 set_remote_arch( RA_WINXP );
    1035           0 :         else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
    1036           0 :                 set_remote_arch( RA_WINXP64 );
    1037           0 :         else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
    1038           0 :                 set_remote_arch( RA_WIN2K3 );
    1039           0 : }
    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       17678 : const char *get_remote_arch_str(void)
    1058             : {
    1059       17678 :         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           0 :                 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
    1066           0 :                 ra_type = RA_UNKNOWN;
    1067             :         }
    1068       17678 :         return remote_arch_strings[ra_type];
    1069             : }
    1070             : 
    1071         697 : enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
    1072             : {
    1073           2 :         int i;
    1074             : 
    1075        6273 :         for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
    1076        6273 :                 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
    1077         697 :                         return i;
    1078             :                 }
    1079             :         }
    1080           0 :         return RA_UNKNOWN;
    1081             : }
    1082             : 
    1083             : /*******************************************************************
    1084             :  Set the horrid remote_arch string based on an enum.
    1085             : ********************************************************************/
    1086             : 
    1087       30867 : void set_remote_arch(enum remote_arch_types type)
    1088             : {
    1089       30867 :         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           0 :                 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
    1096           0 :                 ra_type = RA_UNKNOWN;
    1097           0 :                 return;
    1098             :         }
    1099             : 
    1100       30867 :         ra_type = type;
    1101       30867 :         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     2204259 : enum remote_arch_types get_remote_arch(void)
    1110             : {
    1111     2204259 :         return ra_type;
    1112             : }
    1113             : 
    1114             : #define RA_CACHE_TTL 7*24*3600
    1115             : 
    1116       26253 : static bool remote_arch_cache_key(const struct GUID *client_guid,
    1117             :                                   fstring key)
    1118             : {
    1119         755 :         struct GUID_txt_buf guid_buf;
    1120       26253 :         const char *guid_string = NULL;
    1121             : 
    1122       26253 :         guid_string = GUID_buf_string(client_guid, &guid_buf);
    1123       26253 :         if (guid_string == NULL) {
    1124           0 :                 return false;
    1125             :         }
    1126             : 
    1127       26253 :         fstr_sprintf(key, "RA/%s", guid_string);
    1128       26253 :         return true;
    1129             : }
    1130             : 
    1131             : struct ra_parser_state {
    1132             :         bool found;
    1133             :         enum remote_arch_types ra;
    1134             : };
    1135             : 
    1136         697 : static void ra_parser(const struct gencache_timeout *t,
    1137             :                       DATA_BLOB blob,
    1138             :                       void *priv_data)
    1139             : {
    1140         697 :         struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
    1141         697 :         const char *ra_str = NULL;
    1142             : 
    1143         697 :         if (gencache_timeout_expired(t)) {
    1144           0 :                 return;
    1145             :         }
    1146             : 
    1147         697 :         if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
    1148           0 :                 DBG_ERR("Remote arch cache key not a string\n");
    1149           0 :                 return;
    1150             :         }
    1151             : 
    1152         697 :         ra_str = (const char *)blob.data;
    1153         697 :         DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
    1154             : 
    1155         697 :         state->ra = get_remote_arch_from_str(ra_str);
    1156         697 :         state->found = true;
    1157         697 :         return;
    1158             : }
    1159             : 
    1160        8430 : static bool remote_arch_cache_get(const struct GUID *client_guid)
    1161             : {
    1162         307 :         bool ok;
    1163         307 :         fstring ra_key;
    1164        8430 :         struct ra_parser_state state = (struct ra_parser_state) {
    1165             :                 .found = false,
    1166             :                 .ra = RA_UNKNOWN,
    1167             :         };
    1168             : 
    1169        8430 :         ok = remote_arch_cache_key(client_guid, ra_key);
    1170        8430 :         if (!ok) {
    1171           0 :                 return false;
    1172             :         }
    1173             : 
    1174        8430 :         ok = gencache_parse(ra_key, ra_parser, &state);
    1175        8430 :         if (!ok || !state.found) {
    1176        7428 :                 return true;
    1177             :         }
    1178             : 
    1179         697 :         if (state.ra == RA_UNKNOWN) {
    1180           0 :                 return true;
    1181             :         }
    1182             : 
    1183         697 :         set_remote_arch(state.ra);
    1184         697 :         return true;
    1185             : }
    1186             : 
    1187       17676 : static bool remote_arch_cache_set(const struct GUID *client_guid)
    1188             : {
    1189         442 :         bool ok;
    1190         442 :         fstring ra_key;
    1191       17676 :         const char *ra_str = NULL;
    1192             : 
    1193       17676 :         if (get_remote_arch() == RA_UNKNOWN) {
    1194           0 :                 return true;
    1195             :         }
    1196             : 
    1197       17676 :         ok = remote_arch_cache_key(client_guid, ra_key);
    1198       17676 :         if (!ok) {
    1199           0 :                 return false;
    1200             :         }
    1201             : 
    1202       17676 :         ra_str = get_remote_arch_str();
    1203       17676 :         if (ra_str == NULL) {
    1204           0 :                 return false;
    1205             :         }
    1206             : 
    1207       17676 :         ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
    1208       17676 :         if (!ok) {
    1209           0 :                 return false;
    1210             :         }
    1211             : 
    1212       17234 :         return true;
    1213             : }
    1214             : 
    1215       26106 : bool remote_arch_cache_update(const struct GUID *client_guid)
    1216             : {
    1217         749 :         bool ok;
    1218             : 
    1219       26106 :         if (get_remote_arch() == RA_UNKNOWN) {
    1220             : 
    1221        8430 :                 become_root();
    1222        8430 :                 ok = remote_arch_cache_get(client_guid);
    1223        8430 :                 unbecome_root();
    1224             : 
    1225        8430 :                 return ok;
    1226             :         }
    1227             : 
    1228       17676 :         become_root();
    1229       17676 :         ok = remote_arch_cache_set(client_guid);
    1230       17676 :         unbecome_root();
    1231             : 
    1232       17676 :         return ok;
    1233             : }
    1234             : 
    1235         147 : bool remote_arch_cache_delete(const struct GUID *client_guid)
    1236             : {
    1237           6 :         bool ok;
    1238           6 :         fstring ra_key;
    1239             : 
    1240         147 :         ok = remote_arch_cache_key(client_guid, ra_key);
    1241         147 :         if (!ok) {
    1242           0 :                 return false;
    1243             :         }
    1244             : 
    1245         147 :         become_root();
    1246         147 :         ok = gencache_del(ra_key);
    1247         147 :         unbecome_root();
    1248             : 
    1249         147 :         if (!ok) {
    1250         135 :                 return false;
    1251             :         }
    1252             : 
    1253          10 :         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         510 : int str_checksum(const char *s)
    1267             : {
    1268           0 :         TDB_DATA key;
    1269         510 :         if (s == NULL)
    1270           0 :                 return 0;
    1271             : 
    1272         510 :         key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
    1273         510 :                            .dsize = strlen(s) };
    1274             : 
    1275         510 :         return tdb_jenkins_hash(&key);
    1276             : }
    1277             : 
    1278             : /*****************************************************************
    1279             :  Zero a memory area then free it. Used to catch bugs faster.
    1280             : *****************************************************************/
    1281             : 
    1282          32 : void zero_free(void *p, size_t size)
    1283             : {
    1284          32 :         memset(p, 0, size);
    1285          32 :         SAFE_FREE(p);
    1286          32 : }
    1287             : 
    1288             : /*****************************************************************
    1289             :  Set our open file limit to a requested max and return the limit.
    1290             : *****************************************************************/
    1291             : 
    1292         149 : int set_maxfiles(int requested_max)
    1293             : {
    1294             : #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
    1295           0 :         struct rlimit rlp;
    1296           0 :         int saved_current_limit;
    1297             : 
    1298         149 :         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
    1299           0 :                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
    1300             :                         strerror(errno) ));
    1301             :                 /* just guess... */
    1302           0 :                 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         149 :         if (rlp.rlim_max != RLIM_INFINITY) {
    1318         149 :                 int orig_max = rlp.rlim_max;
    1319             : 
    1320         149 :                 if ( rlp.rlim_max < requested_max )
    1321           0 :                         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         149 :                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
    1327           0 :                         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           0 :                         rlp.rlim_max = orig_max;
    1332             :                 }
    1333             :         }
    1334             : #endif
    1335             : 
    1336             :         /* Now try setting the soft (current) limit. */
    1337             : 
    1338         149 :         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
    1339             : 
    1340         149 :         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
    1341           0 :                 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           0 :                 return saved_current_limit;
    1345             :         }
    1346             : 
    1347         149 :         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
    1348           0 :                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
    1349             :                         strerror(errno) ));
    1350             :                 /* just guess... */
    1351           0 :                 return saved_current_limit;
    1352             :     }
    1353             : 
    1354             : #if defined(RLIM_INFINITY)
    1355         149 :         if(rlp.rlim_cur == RLIM_INFINITY)
    1356           0 :                 return saved_current_limit;
    1357             : #endif
    1358             : 
    1359         149 :         if((int)rlp.rlim_cur > saved_current_limit)
    1360           0 :                 return saved_current_limit;
    1361             : 
    1362         149 :         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      497804 : void *smb_xmalloc_array(size_t size, unsigned int count)
    1376             : {
    1377       12740 :         void *p;
    1378      497804 :         if (size == 0) {
    1379           0 :                 smb_panic("smb_xmalloc_array: called with zero size");
    1380             :         }
    1381      497804 :         if (count >= MAX_ALLOC_SIZE/size) {
    1382           0 :                 smb_panic("smb_xmalloc_array: alloc size too large");
    1383             :         }
    1384      497804 :         if ((p = SMB_MALLOC(size*count)) == NULL) {
    1385           0 :                 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
    1386             :                         (unsigned long)size, (unsigned long)count));
    1387           0 :                 smb_panic("smb_xmalloc_array: malloc failed");
    1388             :         }
    1389      497804 :         return p;
    1390             : }
    1391             : 
    1392             : /*****************************************************************
    1393             :  Get local hostname and cache result.
    1394             : *****************************************************************/
    1395             : 
    1396           2 : char *myhostname(void)
    1397             : {
    1398           0 :         static char *ret;
    1399           2 :         if (ret == NULL) {
    1400           2 :                 ret = get_myname(NULL);
    1401             :         }
    1402           2 :         return ret;
    1403             : }
    1404             : 
    1405             : /*****************************************************************
    1406             :  Get local hostname and cache result.
    1407             : *****************************************************************/
    1408             : 
    1409       87202 : char *myhostname_upper(void)
    1410             : {
    1411         212 :         static char *ret;
    1412       87202 :         if (ret == NULL) {
    1413       39609 :                 char *name = get_myname(NULL);
    1414       39609 :                 if (name == NULL) {
    1415           0 :                         return NULL;
    1416             :                 }
    1417       39609 :                 ret = strupper_talloc(NULL, name);
    1418       39609 :                 talloc_free(name);
    1419             :         }
    1420       87202 :         return ret;
    1421             : }
    1422             : 
    1423             : /*******************************************************************
    1424             :  Given a filename - get its directory name
    1425             : ********************************************************************/
    1426             : 
    1427       11782 : bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
    1428             :                     const char **name)
    1429             : {
    1430          36 :         char *p;
    1431          36 :         ptrdiff_t len;
    1432             : 
    1433       11782 :         p = strrchr_m(dir, '/'); /* Find final '/', if any */
    1434             : 
    1435       11782 :         if (p == NULL) {
    1436        5658 :                 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
    1437           0 :                         return False;
    1438             :                 }
    1439        5658 :                 if (name) {
    1440        5254 :                         *name = dir;
    1441             :                 }
    1442        5658 :                 return True;
    1443             :         }
    1444             : 
    1445        6124 :         len = p-dir;
    1446             : 
    1447        6124 :         *parent = talloc_strndup(mem_ctx, dir, len);
    1448        6124 :         if (*parent == NULL) {
    1449           0 :                 return False;
    1450             :         }
    1451             : 
    1452        6124 :         if (name) {
    1453        4608 :                 *name = p+1;
    1454             :         }
    1455        6092 :         return True;
    1456             : }
    1457             : 
    1458             : /*******************************************************************
    1459             :  Determine if a pattern contains any Microsoft wildcard characters.
    1460             : *******************************************************************/
    1461             : 
    1462     1644744 : bool ms_has_wild(const char *s)
    1463             : {
    1464     1644744 :         const char *found = strpbrk(s, "*?<>\"");
    1465     1644744 :         return (found != NULL);
    1466             : }
    1467             : 
    1468           0 : bool ms_has_wild_w(const smb_ucs2_t *s)
    1469             : {
    1470           0 :         smb_ucs2_t c;
    1471           0 :         if (!s) return False;
    1472           0 :         while ((c = *s++)) {
    1473           0 :                 switch (c) {
    1474           0 :                 case UCS2_CHAR('*'):
    1475             :                 case UCS2_CHAR('?'):
    1476             :                 case UCS2_CHAR('<'):
    1477             :                 case UCS2_CHAR('>'):
    1478             :                 case UCS2_CHAR('"'):
    1479           0 :                         return True;
    1480             :                 }
    1481             :         }
    1482           0 :         return False;
    1483             : }
    1484             : 
    1485             : /*******************************************************************
    1486             :  A wrapper that handles case sensitivity and the special handling
    1487             :  of the ".." name.
    1488             : *******************************************************************/
    1489             : 
    1490      914985 : bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
    1491             : {
    1492      914985 :         if (ISDOTDOT(string))
    1493       18143 :                 string = ".";
    1494      914985 :         if (ISDOT(pattern))
    1495          72 :                 return False;
    1496             : 
    1497      914913 :         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         296 : bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
    1506             : {
    1507         752 :        while (listLen-- > 0) {
    1508         516 :                if (mask_match(string, *list++, is_case_sensitive))
    1509          60 :                        return True;
    1510             :        }
    1511         236 :        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          48 : bool name_to_fqdn(fstring fqdn, const char *name)
    1524             : {
    1525          48 :         char *full = NULL;
    1526           0 :         struct addrinfo hints;
    1527           0 :         struct addrinfo *result;
    1528           0 :         int s;
    1529             : 
    1530             :         /* Configure hints to obtain canonical name */
    1531             : 
    1532          48 :         memset(&hints, 0, sizeof(struct addrinfo));
    1533          48 :         hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
    1534          48 :         hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
    1535          48 :         hints.ai_flags = AI_CANONNAME;  /* Get host's FQDN */
    1536          48 :         hints.ai_protocol = 0;          /* Any protocol */
    1537             : 
    1538          48 :         s = getaddrinfo(name, NULL, &hints, &result);
    1539          48 :         if (s != 0) {
    1540          26 :                 DBG_WARNING("getaddrinfo lookup for %s failed: %s\n",
    1541             :                         name,
    1542             :                         gai_strerror(s));
    1543          26 :                 fstrcpy(fqdn, name);
    1544          26 :                 return false;
    1545             :         }
    1546          22 :         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          22 :         if (full && (! strchr_m(full, '.'))) {
    1555           0 :                 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
    1556           0 :                 DEBUGADD(1, ("    Full qualified domain names (FQDNs) should not be specified\n"));
    1557           0 :                 DEBUGADD(1, ("    as an alias in /etc/hosts. FQDN should be the first name\n"));
    1558           0 :                 DEBUGADD(1, ("    prior to any aliases.\n"));
    1559             :         }
    1560          22 :         if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
    1561           0 :                 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
    1562           0 :                 DEBUGADD(1, ("    Specifying the machine hostname for address 127.0.0.1 may lead\n"));
    1563           0 :                 DEBUGADD(1, ("    to Kerberos authentication problems as localhost.localdomain\n"));
    1564           0 :                 DEBUGADD(1, ("    may end up being used instead of the real machine FQDN.\n"));
    1565             :         }
    1566             : 
    1567          22 :         DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
    1568          22 :         fstrcpy(fqdn, full);
    1569          22 :         freeaddrinfo(result);           /* No longer needed */
    1570          22 :         return true;
    1571             : }
    1572             : 
    1573         208 : struct server_id interpret_pid(const char *pid_string)
    1574             : {
    1575         208 :         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         364 : bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
    1585             : {
    1586         364 :         const char *end_base = buf_base + buf_len;
    1587         364 :         char *end_ptr = ptr + off;
    1588             : 
    1589         364 :         if (!buf_base || !ptr) {
    1590           0 :                 return False;
    1591             :         }
    1592             : 
    1593         364 :         if (end_base < buf_base || end_ptr < ptr) {
    1594           0 :                 return False; /* wrap. */
    1595             :         }
    1596             : 
    1597         364 :         if (end_ptr < end_base) {
    1598         364 :                 return True;
    1599             :         }
    1600           0 :         return False;
    1601             : }
    1602             : 
    1603             : /****************************************************************
    1604             :  Return a safe pointer into a string within a buffer, or NULL.
    1605             : ****************************************************************/
    1606             : 
    1607         115 : char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
    1608             : {
    1609         115 :         if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
    1610           0 :                 return NULL;
    1611             :         }
    1612             :         /* Check if a valid string exists at this offset. */
    1613         115 :         if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
    1614           0 :                 return NULL;
    1615             :         }
    1616         115 :         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         114 : bool split_domain_user(TALLOC_CTX *mem_ctx,
    1626             :                        const char *full_name,
    1627             :                        char **domain,
    1628             :                        char **user)
    1629             : {
    1630         114 :         const char *p = NULL;
    1631             : 
    1632         114 :         p = strchr_m(full_name, '\\');
    1633             : 
    1634         114 :         if (p != NULL) {
    1635           0 :                 *domain = talloc_strndup(mem_ctx, full_name,
    1636           0 :                                          PTR_DIFF(p, full_name));
    1637           0 :                 if (*domain == NULL) {
    1638           0 :                         return false;
    1639             :                 }
    1640           0 :                 *user = talloc_strdup(mem_ctx, p+1);
    1641           0 :                 if (*user == NULL) {
    1642           0 :                         TALLOC_FREE(*domain);
    1643           0 :                         return false;
    1644             :                 }
    1645             :         } else {
    1646         114 :                 *domain = NULL;
    1647         114 :                 *user = talloc_strdup(mem_ctx, full_name);
    1648         114 :                 if (*user == NULL) {
    1649           0 :                         return false;
    1650             :                 }
    1651             :         }
    1652             : 
    1653         114 :         return true;
    1654             : }
    1655             : 
    1656             : /****************************************************************
    1657             :  strip off leading '\\' from a hostname
    1658             : ****************************************************************/
    1659             : 
    1660         160 : const char *strip_hostname(const char *s)
    1661             : {
    1662         160 :         if (!s) {
    1663           0 :                 return NULL;
    1664             :         }
    1665             : 
    1666         160 :         if (strlen_m(s) < 3) {
    1667           0 :                 return s;
    1668             :         }
    1669             : 
    1670         160 :         if (s[0] == '\\') s++;
    1671         160 :         if (s[0] == '\\') s++;
    1672             : 
    1673         160 :         return s;
    1674             : }
    1675             : 
    1676      137690 : bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
    1677             : {
    1678      137690 :         if (!NT_STATUS_IS_OK(err1)) {
    1679         128 :                 *result = err1;
    1680         128 :                 return true;
    1681             :         }
    1682      137562 :         if (!NT_STATUS_IS_OK(err2)) {
    1683        1685 :                 *result = err2;
    1684        1685 :                 return true;
    1685             :         }
    1686      135877 :         return false;
    1687             : }
    1688             : 
    1689           0 : int timeval_to_msec(struct timeval t)
    1690             : {
    1691           0 :         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          30 : char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
    1699             : {
    1700          30 :         char *ptr = NULL;
    1701             : 
    1702          30 :         if (!dos_pathname) {
    1703           0 :                 return NULL;
    1704             :         }
    1705             : 
    1706          30 :         ptr = talloc_strdup(ctx, dos_pathname);
    1707          30 :         if (!ptr) {
    1708           0 :                 return NULL;
    1709             :         }
    1710             :         /* Convert any '\' paths to '/' */
    1711          30 :         unix_format(ptr);
    1712          30 :         ptr = unix_clean_name(ctx, ptr);
    1713          30 :         if (!ptr) {
    1714           0 :                 return NULL;
    1715             :         }
    1716             : 
    1717             :         /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
    1718          30 :         if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
    1719           3 :                 ptr += 2;
    1720             : 
    1721             :         /* Only absolute paths allowed. */
    1722          30 :         if (*ptr != '/')
    1723           0 :                 return NULL;
    1724             : 
    1725          30 :         return ptr;
    1726             : }
    1727             : 
    1728             : /*******************************************************************
    1729             :  Return True if the filename is one of the special executable types.
    1730             : ********************************************************************/
    1731             : 
    1732        1767 : bool is_executable(const char *fname)
    1733             : {
    1734        1767 :         if ((fname = strrchr_m(fname,'.'))) {
    1735        2852 :                 if (strequal(fname,".com") ||
    1736        2852 :                     strequal(fname,".dll") ||
    1737        2258 :                     strequal(fname,".exe") ||
    1738         832 :                     strequal(fname,".sym")) {
    1739         594 :                         return True;
    1740             :                 }
    1741             :         }
    1742        1150 :         return False;
    1743             : }
    1744             : 
    1745             : /****************************************************************************
    1746             :  Open a file with a share mode - old openX method - map into NTCreate.
    1747             : ****************************************************************************/
    1748             : 
    1749       27239 : 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         122 :         uint32_t access_mask;
    1758         122 :         uint32_t share_mode;
    1759         122 :         uint32_t create_disposition;
    1760       27239 :         uint32_t create_options = FILE_NON_DIRECTORY_FILE;
    1761       27239 :         uint32_t private_flags = 0;
    1762             : 
    1763       27239 :         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       27239 :         switch (GET_OPENX_MODE(deny_mode)) {
    1770        4729 :                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
    1771             :                 case DOS_OPEN_RDONLY:
    1772        4729 :                         access_mask = FILE_GENERIC_READ;
    1773        4729 :                         break;
    1774        2459 :                 case DOS_OPEN_WRONLY:
    1775        2459 :                         access_mask = FILE_GENERIC_WRITE;
    1776        2459 :                         break;
    1777       20035 :                 case DOS_OPEN_RDWR:
    1778             :                 case DOS_OPEN_FCB:
    1779       20035 :                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
    1780       20035 :                         break;
    1781           0 :                 default:
    1782           0 :                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
    1783             :                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
    1784           0 :                         return False;
    1785             :         }
    1786             : 
    1787             :         /* Create the NT compatible create_disposition. */
    1788       27239 :         switch (open_func) {
    1789         328 :                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
    1790         328 :                         create_disposition = FILE_CREATE;
    1791         328 :                         break;
    1792             : 
    1793       10075 :                 case OPENX_FILE_EXISTS_OPEN:
    1794       10075 :                         create_disposition = FILE_OPEN;
    1795       10075 :                         break;
    1796             : 
    1797       14552 :                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
    1798       14552 :                         create_disposition = FILE_OPEN_IF;
    1799       14552 :                         break;
    1800             : 
    1801          36 :                 case OPENX_FILE_EXISTS_TRUNCATE:
    1802          36 :                         create_disposition = FILE_OVERWRITE;
    1803          36 :                         break;
    1804             : 
    1805        2222 :                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
    1806        2222 :                         create_disposition = FILE_OVERWRITE_IF;
    1807        2222 :                         break;
    1808             : 
    1809          15 :                 default:
    1810             :                         /* From samba4 - to be confirmed. */
    1811          15 :                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
    1812           4 :                                 create_disposition = FILE_CREATE;
    1813           4 :                                 break;
    1814             :                         }
    1815          10 :                         DEBUG(10,("map_open_params_to_ntcreate: bad "
    1816             :                                   "open_func 0x%x\n", (unsigned int)open_func));
    1817           8 :                         return False;
    1818             :         }
    1819             : 
    1820             :         /* Create the NT compatible share modes. */
    1821       27229 :         switch (GET_DENY_MODE(deny_mode)) {
    1822        1740 :                 case DENY_ALL:
    1823        1740 :                         share_mode = FILE_SHARE_NONE;
    1824        1740 :                         break;
    1825             : 
    1826        1263 :                 case DENY_WRITE:
    1827        1263 :                         share_mode = FILE_SHARE_READ;
    1828        1263 :                         break;
    1829             : 
    1830        1244 :                 case DENY_READ:
    1831        1244 :                         share_mode = FILE_SHARE_WRITE;
    1832        1244 :                         break;
    1833             : 
    1834       20075 :                 case DENY_NONE:
    1835       20075 :                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
    1836       20075 :                         break;
    1837             : 
    1838        1630 :                 case DENY_DOS:
    1839        1630 :                         private_flags |= NTCREATEX_FLAG_DENY_DOS;
    1840        1630 :                         if (is_executable(smb_base_fname)) {
    1841         534 :                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
    1842             :                         } else {
    1843        1096 :                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
    1844         530 :                                         share_mode = FILE_SHARE_READ;
    1845             :                                 } else {
    1846         564 :                                         share_mode = FILE_SHARE_NONE;
    1847             :                                 }
    1848             :                         }
    1849        1608 :                         break;
    1850             : 
    1851        1263 :                 case DENY_FCB:
    1852        1263 :                         private_flags |= NTCREATEX_FLAG_DENY_FCB;
    1853        1263 :                         share_mode = FILE_SHARE_NONE;
    1854        1263 :                         break;
    1855             : 
    1856           8 :                 default:
    1857           8 :                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
    1858             :                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
    1859           8 :                         return False;
    1860             :         }
    1861             : 
    1862       27221 :         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       27221 :         if (paccess_mask) {
    1873       27221 :                 *paccess_mask = access_mask;
    1874             :         }
    1875       27221 :         if (pshare_mode) {
    1876       27221 :                 *pshare_mode = share_mode;
    1877             :         }
    1878       27221 :         if (pcreate_disposition) {
    1879       27221 :                 *pcreate_disposition = create_disposition;
    1880             :         }
    1881       27221 :         if (pcreate_options) {
    1882       27221 :                 *pcreate_options = create_options;
    1883             :         }
    1884       27221 :         if (pprivate_flags) {
    1885       23386 :                 *pprivate_flags = private_flags;
    1886             :         }
    1887             : 
    1888       27101 :         return True;
    1889             : 
    1890             : }
    1891             : 
    1892             : /*************************************************************************
    1893             :  Return a talloced copy of a struct security_unix_token. NULL on fail.
    1894             : *************************************************************************/
    1895             : 
    1896      170365 : struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
    1897             : {
    1898         340 :         struct security_unix_token *cpy;
    1899             : 
    1900      170365 :         cpy = talloc(ctx, struct security_unix_token);
    1901      170365 :         if (!cpy) {
    1902           0 :                 return NULL;
    1903             :         }
    1904             : 
    1905      170365 :         *cpy = (struct security_unix_token){
    1906      170365 :                 .uid = tok->uid,
    1907      170365 :                 .gid = tok->gid,
    1908      170365 :                 .ngroups = tok->ngroups,
    1909             :         };
    1910             : 
    1911      170365 :         if (tok->ngroups) {
    1912             :                 /* Make this a talloc child of cpy. */
    1913      170365 :                 cpy->groups = (gid_t *)talloc_memdup(
    1914             :                         cpy, tok->groups, tok->ngroups * sizeof(gid_t));
    1915      170365 :                 if (!cpy->groups) {
    1916           0 :                         TALLOC_FREE(cpy);
    1917           0 :                         return NULL;
    1918             :                 }
    1919             :         }
    1920      170025 :         return cpy;
    1921             : }
    1922             : 
    1923             : /****************************************************************************
    1924             :  Return a root token
    1925             : ****************************************************************************/
    1926             : 
    1927       10075 : struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
    1928             : {
    1929       10075 :         struct security_unix_token *t = NULL;
    1930             : 
    1931       10075 :         t = talloc_zero(mem_ctx, struct security_unix_token);
    1932       10075 :         if (t == NULL) {
    1933           0 :                 return NULL;
    1934             :         }
    1935             : 
    1936             :         /*
    1937             :          * This is not needed, but lets make it explicit, not implicit.
    1938             :          */
    1939       10075 :         *t = (struct security_unix_token) {
    1940             :                 .uid = 0,
    1941             :                 .gid = 0,
    1942             :                 .ngroups = 0,
    1943             :                 .groups = NULL
    1944             :         };
    1945             : 
    1946       10075 :         return t;
    1947             : }
    1948             : 
    1949         152 : char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
    1950             : {
    1951           0 :         char *str;
    1952           0 :         uint32_t i;
    1953             : 
    1954         304 :         str = talloc_asprintf(
    1955             :                 mem_ctx,
    1956             :                 "uid=%ju, gid=%ju, %"PRIu32" groups:",
    1957         152 :                 (uintmax_t)(tok->uid),
    1958         152 :                 (uintmax_t)(tok->gid),
    1959         152 :                 tok->ngroups);
    1960             : 
    1961        1059 :         for (i=0; i<tok->ngroups; i++) {
    1962         907 :                 talloc_asprintf_addbuf(
    1963         907 :                         &str, " %ju", (uintmax_t)tok->groups[i]);
    1964             :         }
    1965             : 
    1966         152 :         return str;
    1967             : }
    1968             : 
    1969             : /****************************************************************************
    1970             :  Check that a file matches a particular file type.
    1971             : ****************************************************************************/
    1972             : 
    1973     1009028 : bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
    1974             : {
    1975         502 :         uint32_t mask;
    1976             : 
    1977             :         /* Check the "may have" search bits. */
    1978     1009028 :         if (((mode & ~dirtype) &
    1979             :                         (FILE_ATTRIBUTE_HIDDEN |
    1980             :                          FILE_ATTRIBUTE_SYSTEM |
    1981             :                          FILE_ATTRIBUTE_DIRECTORY)) != 0) {
    1982        8468 :                 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     1000472 :         mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
    1991             :                                     FILE_ATTRIBUTE_ARCHIVE|
    1992             :                                    FILE_ATTRIBUTE_READONLY|
    1993             :                                      FILE_ATTRIBUTE_HIDDEN|
    1994             :                                      FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
    1995     1000472 :         if(mask) {
    1996       16016 :                 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
    1997             :                                       FILE_ATTRIBUTE_ARCHIVE|
    1998             :                                      FILE_ATTRIBUTE_READONLY|
    1999             :                                        FILE_ATTRIBUTE_HIDDEN|
    2000       16016 :                                         FILE_ATTRIBUTE_SYSTEM))) == mask) {
    2001             :                         /* check if matching attribute present */
    2002        8008 :                         return true;
    2003             :                 } else {
    2004        8008 :                         return false;
    2005             :                 }
    2006             :         }
    2007             : 
    2008      984042 :         return true;
    2009             : }

Generated by: LCOV version 1.14