s3-librpc: add ads.idl and convert ads_struct to talloc.
[samba.git] / source3 / param / loadparm.c
1 /*
2    Unix SMB/CIFS implementation.
3    Parameter loading functions
4    Copyright (C) Karl Auer 1993-1998
5
6    Largely re-written by Andrew Tridgell, September 1994
7
8    Copyright (C) Simo Sorce 2001
9    Copyright (C) Alexander Bokovoy 2002
10    Copyright (C) Stefan (metze) Metzmacher 2002
11    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
12    Copyright (C) Michael Adam 2008
13    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
14    Copyright (C) Andrew Bartlett 2011
15
16    This program is free software; you can redistribute it and/or modify
17    it under the terms of the GNU General Public License as published by
18    the Free Software Foundation; either version 3 of the License, or
19    (at your option) any later version.
20
21    This program is distributed in the hope that it will be useful,
22    but WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24    GNU General Public License for more details.
25
26    You should have received a copy of the GNU General Public License
27    along with this program.  If not, see <http://www.gnu.org/licenses/>.
28 */
29
30 /*
31  *  Load parameters.
32  *
33  *  This module provides suitable callback functions for the params
34  *  module. It builds the internal table of service details which is
35  *  then used by the rest of the server.
36  *
37  * To add a parameter:
38  *
39  * 1) add it to the global or service structure definition
40  * 2) add it to the parm_table
41  * 3) add it to the list of available functions (eg: using FN_GLOBAL_STRING())
42  * 4) If it's a global then initialise it in init_globals. If a local
43  *    (ie. service) parameter then initialise it in the sDefault structure
44  *
45  *
46  * Notes:
47  *   The configuration file is processed sequentially for speed. It is NOT
48  *   accessed randomly as happens in 'real' Windows. For this reason, there
49  *   is a fair bit of sequence-dependent code here - ie., code which assumes
50  *   that certain things happen before others. In particular, the code which
51  *   happens at the boundary between sections is delicately poised, so be
52  *   careful!
53  *
54  */
55
56 #define LOADPARM_SUBSTITUTION_INTERNALS 1
57 #include "includes.h"
58 #include "system/filesys.h"
59 #include "util_tdb.h"
60 #include "lib/param/loadparm.h"
61 #include "lib/param/param.h"
62 #include "printing.h"
63 #include "lib/smbconf/smbconf.h"
64 #include "lib/smbconf/smbconf_init.h"
65
66 #include "include/smb_ldap.h"
67 #include "../librpc/gen_ndr/svcctl.h"
68 #include "intl.h"
69 #include "../libcli/smb/smb_signing.h"
70 #include "dbwrap/dbwrap.h"
71 #include "dbwrap/dbwrap_rbt.h"
72 #include "../lib/util/bitmap.h"
73 #include "librpc/gen_ndr/nbt.h"
74 #include "librpc/gen_ndr/dns.h"
75 #include "source4/lib/tls/tls.h"
76 #include "libcli/auth/ntlm_check.h"
77 #include "lib/crypto/gnutls_helpers.h"
78 #include "lib/util/string_wrappers.h"
79 #include "auth/credentials/credentials.h"
80 #include "source3/lib/substitute.h"
81 #include "source3/librpc/gen_ndr/ads.h"
82
83 #ifdef HAVE_SYS_SYSCTL_H
84 #include <sys/sysctl.h>
85 #endif
86
87 bool bLoaded = false;
88
89 /* the special value for the include parameter
90  * to be interpreted not as a file name but to
91  * trigger loading of the global smb.conf options
92  * from registry. */
93 #ifndef INCLUDE_REGISTRY_NAME
94 #define INCLUDE_REGISTRY_NAME "registry"
95 #endif
96
97 static bool in_client = false;          /* Not in the client by default */
98 static struct smbconf_csn conf_last_csn;
99
100 static int config_backend = CONFIG_BACKEND_FILE;
101
102 /* some helpful bits */
103 #define LP_SNUM_OK(i) (((i) >= 0) && ((i) < iNumServices) && \
104                        (ServicePtrs != NULL) && \
105                        (ServicePtrs[(i)] != NULL) && ServicePtrs[(i)]->valid)
106 #define VALID(i) ((ServicePtrs != NULL) && (ServicePtrs[i]!= NULL) && \
107                   ServicePtrs[i]->valid)
108
109 #define USERSHARE_VALID 1
110 #define USERSHARE_PENDING_DELETE 2
111
112 static bool defaults_saved = false;
113
114 #include "lib/param/param_global.h"
115
116 static struct loadparm_global Globals;
117
118 /* This is a default service used to prime a services structure */
119 static const struct loadparm_service _sDefault =
120 {
121         .valid = true,
122         .autoloaded = false,
123         .usershare = 0,
124         .usershare_last_mod = {0, 0},
125         .szService = NULL,
126         .path = NULL,
127         .invalid_users = NULL,
128         .valid_users = NULL,
129         .admin_users = NULL,
130         .copy = NULL,
131         .include = NULL,
132         .preexec = NULL,
133         .postexec = NULL,
134         .root_preexec = NULL,
135         .root_postexec = NULL,
136         .cups_options = NULL,
137         .print_command = NULL,
138         .lpq_command = NULL,
139         .lprm_command = NULL,
140         .lppause_command = NULL,
141         .lpresume_command = NULL,
142         .queuepause_command = NULL,
143         .queueresume_command = NULL,
144         ._printername = NULL,
145         .printjob_username = NULL,
146         .dont_descend = NULL,
147         .hosts_allow = NULL,
148         .hosts_deny = NULL,
149         .magic_script = NULL,
150         .magic_output = NULL,
151         .veto_files = NULL,
152         .hide_files = NULL,
153         .veto_oplock_files = NULL,
154         .comment = NULL,
155         .force_user = NULL,
156         .force_group = NULL,
157         .read_list = NULL,
158         .write_list = NULL,
159         .volume = NULL,
160         .fstype = NULL,
161         .vfs_objects = NULL,
162         .msdfs_proxy = NULL,
163         .aio_write_behind = NULL,
164         .dfree_command = NULL,
165         .min_print_space = 0,
166         .max_print_jobs = 1000,
167         .max_reported_print_jobs = 0,
168         .create_mask = 0744,
169         .force_create_mode = 0,
170         .directory_mask = 0755,
171         .force_directory_mode = 0,
172         .max_connections = 0,
173         .default_case = CASE_LOWER,
174         .printing = DEFAULT_PRINTING,
175         .csc_policy = 0,
176         .block_size = 1024,
177         .dfree_cache_time = 0,
178         .preexec_close = false,
179         .root_preexec_close = false,
180         .case_sensitive = Auto,
181         .preserve_case = true,
182         .short_preserve_case = true,
183         .hide_dot_files = true,
184         .hide_special_files = false,
185         .hide_unreadable = false,
186         .hide_unwriteable_files = false,
187         .browseable = true,
188         .access_based_share_enum = false,
189         .available = true,
190         .read_only = true,
191         .spotlight = false,
192         .guest_only = false,
193         .administrative_share = false,
194         .guest_ok = false,
195         .printable = false,
196         .print_notify_backchannel = false,
197         .map_system = false,
198         .map_hidden = false,
199         .map_archive = true,
200         .store_dos_attributes = true,
201         .smbd_max_xattr_size = 65536,
202         .dmapi_support = false,
203         .locking = true,
204         .strict_locking = Auto,
205         .posix_locking = true,
206         .oplocks = true,
207         .kernel_oplocks = false,
208         .level2_oplocks = true,
209         .mangled_names = MANGLED_NAMES_ILLEGAL,
210         .wide_links = false,
211         .follow_symlinks = true,
212         .sync_always = false,
213         .strict_allocate = false,
214         .strict_rename = false,
215         .strict_sync = true,
216         .mangling_char = '~',
217         .copymap = NULL,
218         .delete_readonly = false,
219         .fake_oplocks = false,
220         .delete_veto_files = false,
221         .dos_filemode = false,
222         .dos_filetimes = true,
223         .dos_filetime_resolution = false,
224         .fake_directory_create_times = false,
225         .blocking_locks = true,
226         .inherit_permissions = false,
227         .inherit_acls = false,
228         .inherit_owner = false,
229         .msdfs_root = false,
230         .msdfs_shuffle_referrals = false,
231         .use_client_driver = false,
232         .default_devmode = true,
233         .force_printername = false,
234         .nt_acl_support = true,
235         .force_unknown_acl_user = false,
236         ._use_sendfile = false,
237         .map_acl_inherit = false,
238         .afs_share = false,
239         .ea_support = true,
240         .acl_check_permissions = true,
241         .acl_map_full_control = true,
242         .acl_group_control = false,
243         .acl_allow_execute_always = false,
244         .acl_flag_inherited_canonicalization = true,
245         .aio_read_size = 1,
246         .aio_write_size = 1,
247         .map_readonly = MAP_READONLY_NO,
248         .directory_name_cache_size = 100,
249         .server_smb_encrypt = SMB_ENCRYPTION_DEFAULT,
250         .kernel_share_modes = false,
251         .durable_handles = true,
252         .check_parent_directory_delete_on_close = false,
253         .param_opt = NULL,
254         .smbd_search_ask_sharemode = true,
255         .smbd_getinfo_ask_sharemode = true,
256         .spotlight_backend = SPOTLIGHT_BACKEND_NOINDEX,
257         .honor_change_notify_privilege = false,
258         .volume_serial_number = -1,
259         .dummy = ""
260 };
261
262 /*
263  * This is a copy of the default service structure. Service options in the
264  * global section would otherwise overwrite the initial default values.
265  */
266 static struct loadparm_service sDefault;
267
268 /* local variables */
269 static struct loadparm_service **ServicePtrs = NULL;
270 static int iNumServices = 0;
271 static int iServiceIndex = 0;
272 static struct db_context *ServiceHash;
273 static bool bInGlobalSection = true;
274 static bool bGlobalOnly = false;
275 static struct file_lists *file_lists = NULL;
276 static unsigned int *flags_list = NULL;
277
278 static void set_allowed_client_auth(void);
279
280 static bool lp_set_cmdline_helper(const char *pszParmName, const char *pszParmValue);
281 static void free_param_opts(struct parmlist_entry **popts);
282
283 /**
284  *  Function to return the default value for the maximum number of open
285  *  file descriptors permitted.  This function tries to consult the
286  *  kernel-level (sysctl) and ulimit (getrlimit()) values and goes
287  *  the smaller of those.
288  */
289 static int max_open_files(void)
290 {
291         int sysctl_max = MAX_OPEN_FILES;
292         int rlimit_max = MAX_OPEN_FILES;
293
294 #ifdef HAVE_SYSCTLBYNAME
295         {
296                 size_t size = sizeof(sysctl_max);
297                 sysctlbyname("kern.maxfilesperproc", &sysctl_max, &size, NULL,
298                              0);
299         }
300 #endif
301
302 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
303         {
304                 struct rlimit rl;
305
306                 ZERO_STRUCT(rl);
307
308                 if (getrlimit(RLIMIT_NOFILE, &rl) == 0)
309                         rlimit_max = rl.rlim_cur;
310
311 #if defined(RLIM_INFINITY)
312                 if(rl.rlim_cur == RLIM_INFINITY)
313                         rlimit_max = MAX_OPEN_FILES;
314 #endif
315         }
316 #endif
317
318         if (sysctl_max < MIN_OPEN_FILES_WINDOWS) {
319                 DEBUG(2,("max_open_files: increasing sysctl_max (%d) to "
320                         "minimum Windows limit (%d)\n",
321                         sysctl_max,
322                         MIN_OPEN_FILES_WINDOWS));
323                 sysctl_max = MIN_OPEN_FILES_WINDOWS;
324         }
325
326         if (rlimit_max < MIN_OPEN_FILES_WINDOWS) {
327                 DEBUG(2,("rlimit_max: increasing rlimit_max (%d) to "
328                         "minimum Windows limit (%d)\n",
329                         rlimit_max,
330                         MIN_OPEN_FILES_WINDOWS));
331                 rlimit_max = MIN_OPEN_FILES_WINDOWS;
332         }
333
334         return MIN(sysctl_max, rlimit_max);
335 }
336
337 /**
338  * Common part of freeing allocated data for one parameter.
339  */
340 static void free_one_parameter_common(void *parm_ptr,
341                                       struct parm_struct parm)
342 {
343         if ((parm.type == P_STRING) ||
344             (parm.type == P_USTRING))
345         {
346                 lpcfg_string_free((char**)parm_ptr);
347         } else if (parm.type == P_LIST || parm.type == P_CMDLIST) {
348                 TALLOC_FREE(*((char***)parm_ptr));
349         }
350 }
351
352 /**
353  * Free the allocated data for one parameter for a share
354  * given as a service struct.
355  */
356 static void free_one_parameter(struct loadparm_service *service,
357                                struct parm_struct parm)
358 {
359         void *parm_ptr;
360
361         if (parm.p_class != P_LOCAL) {
362                 return;
363         }
364
365         parm_ptr = lp_parm_ptr(service, &parm);
366
367         free_one_parameter_common(parm_ptr, parm);
368 }
369
370 /**
371  * Free the allocated parameter data of a share given
372  * as a service struct.
373  */
374 static void free_parameters(struct loadparm_service *service)
375 {
376         uint32_t i;
377
378         for (i=0; parm_table[i].label; i++) {
379                 free_one_parameter(service, parm_table[i]);
380         }
381 }
382
383 /**
384  * Free the allocated data for one parameter for a given share
385  * specified by an snum.
386  */
387 static void free_one_parameter_by_snum(int snum, struct parm_struct parm)
388 {
389         void *parm_ptr;
390
391         if (snum < 0) {
392                 parm_ptr = lp_parm_ptr(NULL, &parm);
393         } else if (parm.p_class != P_LOCAL) {
394                 return;
395         } else {
396                 parm_ptr = lp_parm_ptr(ServicePtrs[snum], &parm);
397         }
398
399         free_one_parameter_common(parm_ptr, parm);
400 }
401
402 /**
403  * Free the allocated parameter data for a share specified
404  * by an snum.
405  */
406 static void free_parameters_by_snum(int snum)
407 {
408         uint32_t i;
409
410         for (i=0; parm_table[i].label; i++) {
411                 free_one_parameter_by_snum(snum, parm_table[i]);
412         }
413 }
414
415 /**
416  * Free the allocated global parameters.
417  */
418 static void free_global_parameters(void)
419 {
420         uint32_t i;
421         struct parm_struct *parm;
422
423         free_param_opts(&Globals.param_opt);
424         free_parameters_by_snum(GLOBAL_SECTION_SNUM);
425
426         /* Reset references in the defaults because the context is going to be freed */
427         for (i=0; parm_table[i].label; i++) {
428                 parm = &parm_table[i];
429                 if ((parm->type == P_STRING) ||
430                     (parm->type == P_USTRING)) {
431                         if ((parm->def.svalue != NULL) &&
432                             (*(parm->def.svalue) != '\0')) {
433                                 if (talloc_parent(parm->def.svalue) == Globals.ctx) {
434                                         parm->def.svalue = NULL;
435                                 }
436                         }
437                 }
438         }
439         TALLOC_FREE(Globals.ctx);
440 }
441
442 struct lp_stored_option {
443         struct lp_stored_option *prev, *next;
444         const char *label;
445         const char *value;
446 };
447
448 static struct lp_stored_option *stored_options;
449
450 /*
451   save options set by lp_set_cmdline() into a list. This list is
452   re-applied when we do a globals reset, so that cmdline set options
453   are sticky across reloads of smb.conf
454  */
455 bool store_lp_set_cmdline(const char *pszParmName, const char *pszParmValue)
456 {
457         struct lp_stored_option *entry, *entry_next;
458         for (entry = stored_options; entry != NULL; entry = entry_next) {
459                 entry_next = entry->next;
460                 if (strcmp(pszParmName, entry->label) == 0) {
461                         DLIST_REMOVE(stored_options, entry);
462                         talloc_free(entry);
463                         break;
464                 }
465         }
466
467         entry = talloc(NULL, struct lp_stored_option);
468         if (!entry) {
469                 return false;
470         }
471
472         entry->label = talloc_strdup(entry, pszParmName);
473         if (!entry->label) {
474                 talloc_free(entry);
475                 return false;
476         }
477
478         entry->value = talloc_strdup(entry, pszParmValue);
479         if (!entry->value) {
480                 talloc_free(entry);
481                 return false;
482         }
483
484         DLIST_ADD_END(stored_options, entry);
485
486         return true;
487 }
488
489 static bool apply_lp_set_cmdline(void)
490 {
491         struct lp_stored_option *entry = NULL;
492         for (entry = stored_options; entry != NULL; entry = entry->next) {
493                 if (!lp_set_cmdline_helper(entry->label, entry->value)) {
494                         DEBUG(0, ("Failed to re-apply cmdline parameter %s = %s\n",
495                                   entry->label, entry->value));
496                         return false;
497                 }
498         }
499         return true;
500 }
501
502 /***************************************************************************
503  Initialise the global parameter structure.
504 ***************************************************************************/
505
506 static void init_globals(struct loadparm_context *lp_ctx, bool reinit_globals)
507 {
508         static bool done_init = false;
509         char *s = NULL;
510         int i;
511
512         /* If requested to initialize only once and we've already done it... */
513         if (!reinit_globals && done_init) {
514                 /* ... then we have nothing more to do */
515                 return;
516         }
517
518         if (!done_init) {
519                 /* The logfile can be set before this is invoked. Free it if so. */
520                 lpcfg_string_free(&Globals.logfile);
521                 done_init = true;
522         } else {
523                 free_global_parameters();
524         }
525
526         /* This memset and the free_global_parameters() above will
527          * wipe out smb.conf options set with lp_set_cmdline().  The
528          * apply_lp_set_cmdline() call puts these values back in the
529          * table once the defaults are set */
530         ZERO_STRUCT(Globals);
531
532         Globals.ctx = talloc_pooled_object(NULL, char, 272, 2048);
533
534         /* Initialize the flags list if necessary */
535         if (flags_list == NULL) {
536                 get_flags();
537         }
538
539         for (i = 0; parm_table[i].label; i++) {
540                 if ((parm_table[i].type == P_STRING ||
541                      parm_table[i].type == P_USTRING))
542                 {
543                         lpcfg_string_set(
544                                 Globals.ctx,
545                                 (char **)lp_parm_ptr(NULL, &parm_table[i]),
546                                 "");
547                 }
548         }
549
550
551         lpcfg_string_set(Globals.ctx, &sDefault.fstype, FSTYPE_STRING);
552         lpcfg_string_set(Globals.ctx, &sDefault.printjob_username, "%U");
553
554         init_printer_values(lp_ctx, Globals.ctx, &sDefault);
555
556         sDefault.ntvfs_handler = str_list_make_v3_const(Globals.ctx, "unixuid default", NULL);
557
558         DEBUG(3, ("Initialising global parameters\n"));
559
560         /* Must manually force to upper case here, as this does not go via the handler */
561         lpcfg_string_set(Globals.ctx, &Globals.netbios_name,
562                          myhostname_upper());
563
564         lpcfg_string_set(Globals.ctx, &Globals.smb_passwd_file,
565                          get_dyn_SMB_PASSWD_FILE());
566         lpcfg_string_set(Globals.ctx, &Globals.private_dir,
567                          get_dyn_PRIVATE_DIR());
568         lpcfg_string_set(Globals.ctx, &Globals.binddns_dir,
569                          get_dyn_BINDDNS_DIR());
570
571         /* use the new 'hash2' method by default, with a prefix of 1 */
572         lpcfg_string_set(Globals.ctx, &Globals.mangling_method, "hash2");
573         Globals.mangle_prefix = 1;
574
575         lpcfg_string_set(Globals.ctx, &Globals.guest_account, GUEST_ACCOUNT);
576
577         /* using UTF8 by default allows us to support all chars */
578         lpcfg_string_set(Globals.ctx, &Globals.unix_charset,
579                          DEFAULT_UNIX_CHARSET);
580
581         /* Use codepage 850 as a default for the dos character set */
582         lpcfg_string_set(Globals.ctx, &Globals.dos_charset,
583                          DEFAULT_DOS_CHARSET);
584
585         /*
586          * Allow the default PASSWD_CHAT to be overridden in local.h.
587          */
588         lpcfg_string_set(Globals.ctx, &Globals.passwd_chat,
589                          DEFAULT_PASSWD_CHAT);
590
591         lpcfg_string_set(Globals.ctx, &Globals.workgroup, DEFAULT_WORKGROUP);
592
593         lpcfg_string_set(Globals.ctx, &Globals.passwd_program, "");
594         lpcfg_string_set(Globals.ctx, &Globals.lock_directory,
595                          get_dyn_LOCKDIR());
596         lpcfg_string_set(Globals.ctx, &Globals.state_directory,
597                          get_dyn_STATEDIR());
598         lpcfg_string_set(Globals.ctx, &Globals.cache_directory,
599                          get_dyn_CACHEDIR());
600         lpcfg_string_set(Globals.ctx, &Globals.pid_directory,
601                          get_dyn_PIDDIR());
602         lpcfg_string_set(Globals.ctx, &Globals.nbt_client_socket_address,
603                          "0.0.0.0");
604         /*
605          * By default support explicit binding to broadcast
606          * addresses.
607          */
608         Globals.nmbd_bind_explicit_broadcast = true;
609
610         s = talloc_asprintf(talloc_tos(), "Samba %s", samba_version_string());
611         if (s == NULL) {
612                 smb_panic("init_globals: ENOMEM");
613         }
614         lpcfg_string_set(Globals.ctx, &Globals.server_string, s);
615         TALLOC_FREE(s);
616 #ifdef DEVELOPER
617         lpcfg_string_set(Globals.ctx, &Globals.panic_action,
618                          "/bin/sleep 999999999");
619 #endif
620
621         lpcfg_string_set(Globals.ctx, &Globals.socket_options,
622                          DEFAULT_SOCKET_OPTIONS);
623
624         lpcfg_string_set(Globals.ctx, &Globals.logon_drive, "");
625         /* %N is the NIS auto.home server if -DAUTOHOME is used, else same as %L */
626         lpcfg_string_set(Globals.ctx, &Globals.logon_home, "\\\\%N\\%U");
627         lpcfg_string_set(Globals.ctx, &Globals.logon_path,
628                          "\\\\%N\\%U\\profile");
629
630         Globals.name_resolve_order =
631                         str_list_make_v3_const(Globals.ctx,
632                                                DEFAULT_NAME_RESOLVE_ORDER,
633                                                NULL);
634         lpcfg_string_set(Globals.ctx, &Globals.password_server, "*");
635
636         Globals.algorithmic_rid_base = BASE_RID;
637
638         Globals.load_printers = true;
639         Globals.printcap_cache_time = 750;      /* 12.5 minutes */
640
641         Globals.config_backend = config_backend;
642         Globals._server_role = ROLE_AUTO;
643
644         /* Was 65535 (0xFFFF). 0x4101 matches W2K and causes major speed improvements... */
645         /* Discovered by 2 days of pain by Don McCall @ HP :-). */
646         Globals.max_xmit = 0x4104;
647         Globals.max_mux = 50;   /* This is *needed* for profile support. */
648         Globals.lpq_cache_time = 30;    /* changed to handle large print servers better -- jerry */
649         Globals._disable_spoolss = false;
650         Globals.max_smbd_processes = 0;/* no limit specified */
651         Globals.username_level = 0;
652         Globals.deadtime = 10080;
653         Globals.getwd_cache = true;
654         Globals.large_readwrite = true;
655         Globals.max_log_size = 5000;
656         Globals.max_open_files = max_open_files();
657         Globals.server_max_protocol = PROTOCOL_SMB3_11;
658         Globals.server_min_protocol = PROTOCOL_SMB2_02;
659         Globals._client_max_protocol = PROTOCOL_DEFAULT;
660         Globals.client_min_protocol = PROTOCOL_SMB2_02;
661         Globals._client_ipc_max_protocol = PROTOCOL_DEFAULT;
662         Globals._client_ipc_min_protocol = PROTOCOL_DEFAULT;
663         Globals._security = SEC_AUTO;
664         Globals.encrypt_passwords = true;
665         Globals.client_schannel = true;
666         Globals.winbind_sealed_pipes = true;
667         Globals.require_strong_key = true;
668         Globals.reject_md5_servers = true;
669         Globals.server_schannel = true;
670         Globals.server_schannel_require_seal = true;
671         Globals.reject_md5_clients = true;
672         Globals.read_raw = true;
673         Globals.write_raw = true;
674         Globals.null_passwords = false;
675         Globals.old_password_allowed_period = 60;
676         Globals.obey_pam_restrictions = false;
677         Globals.syslog = 1;
678         Globals.syslog_only = false;
679         Globals.timestamp_logs = true;
680         lpcfg_string_set(Globals.ctx, &Globals.log_level, "0");
681         Globals.debug_prefix_timestamp = false;
682         Globals.debug_hires_timestamp = true;
683         Globals.debug_syslog_format = false;
684         Globals.debug_pid = false;
685         Globals.debug_uid = false;
686         Globals.debug_class = false;
687         Globals.enable_core_files = true;
688         Globals.max_ttl = 60 * 60 * 24 * 3;     /* 3 days default. */
689         Globals.max_wins_ttl = 60 * 60 * 24 * 6;        /* 6 days default. */
690         Globals.min_wins_ttl = 60 * 60 * 6;     /* 6 hours default. */
691         Globals.machine_password_timeout = 60 * 60 * 24 * 7;    /* 7 days default. */
692         Globals.lm_announce = Auto;     /* = Auto: send only if LM clients found */
693         Globals.lm_interval = 60;
694         Globals.time_server = false;
695         Globals.bind_interfaces_only = false;
696         Globals.unix_password_sync = false;
697         Globals.pam_password_change = false;
698         Globals.passwd_chat_debug = false;
699         Globals.passwd_chat_timeout = 2; /* 2 second default. */
700         Globals.nt_pipe_support = true; /* Do NT pipes by default. */
701         Globals.nt_status_support = true; /* Use NT status by default. */
702         Globals.smbd_profiling_level = 0;
703         Globals.stat_cache = true;      /* use stat cache by default */
704         Globals.max_stat_cache_size = 512; /* 512k by default */
705         Globals.restrict_anonymous = 0;
706         Globals.client_lanman_auth = false;     /* Do NOT use the LanMan hash if it is available */
707         Globals.client_plaintext_auth = false;  /* Do NOT use a plaintext password even if is requested by the server */
708         Globals._lanman_auth = false;   /* Do NOT use the LanMan hash, even if it is supplied */
709         Globals.ntlm_auth = NTLM_AUTH_NTLMV2_ONLY;      /* Do NOT use NTLMv1 if it is supplied by the client (otherwise NTLMv2) */
710         Globals.nt_hash_store = NT_HASH_STORE_ALWAYS;   /* Fill in NT hash when setting password */
711         Globals.raw_ntlmv2_auth = false; /* Reject NTLMv2 without NTLMSSP */
712         Globals.client_ntlmv2_auth = true; /* Client should always use use NTLMv2, as we can't tell that the server supports it, but most modern servers do */
713         /* Note, that we will also use NTLM2 session security (which is different), if it is available */
714
715         Globals.allow_dcerpc_auth_level_connect = false; /* we don't allow this by default */
716
717         Globals.map_to_guest = 0;       /* By Default, "Never" */
718         Globals.oplock_break_wait_time = 0;     /* By Default, 0 msecs. */
719         Globals.enhanced_browsing = true;
720         Globals.lock_spin_time = WINDOWS_MINIMUM_LOCK_TIMEOUT_MS; /* msec. */
721         Globals.use_mmap = true;
722         Globals.unicode = true;
723         Globals.smb1_unix_extensions = true;
724         Globals.reset_on_zero_vc = false;
725         Globals.log_writeable_files_on_exit = false;
726         Globals.create_krb5_conf = true;
727         Globals.include_system_krb5_conf = true;
728         Globals._winbind_max_domain_connections = 1;
729
730         /* hostname lookups can be very expensive and are broken on
731            a large number of sites (tridge) */
732         Globals.hostname_lookups = false;
733
734         Globals.change_notify = true,
735         Globals.kernel_change_notify = true,
736
737         lpcfg_string_set(Globals.ctx, &Globals.passdb_backend, "tdbsam");
738         lpcfg_string_set(Globals.ctx, &Globals.ldap_suffix, "");
739         lpcfg_string_set(Globals.ctx, &Globals._ldap_machine_suffix, "");
740         lpcfg_string_set(Globals.ctx, &Globals._ldap_user_suffix, "");
741         lpcfg_string_set(Globals.ctx, &Globals._ldap_group_suffix, "");
742         lpcfg_string_set(Globals.ctx, &Globals._ldap_idmap_suffix, "");
743
744         lpcfg_string_set(Globals.ctx, &Globals.ldap_admin_dn, "");
745         Globals.ldap_ssl = LDAP_SSL_START_TLS;
746         Globals.ldap_deref = -1;
747         Globals.ldap_passwd_sync = LDAP_PASSWD_SYNC_OFF;
748         Globals.ldap_delete_dn = false;
749         Globals.ldap_replication_sleep = 1000; /* wait 1 sec for replication */
750         Globals.ldap_follow_referral = Auto;
751         Globals.ldap_timeout = LDAP_DEFAULT_TIMEOUT;
752         Globals.ldap_connection_timeout = LDAP_CONNECTION_DEFAULT_TIMEOUT;
753         Globals.ldap_page_size = LDAP_PAGE_SIZE;
754
755         Globals.ldap_debug_level = 0;
756         Globals.ldap_debug_threshold = 10;
757
758         Globals.client_ldap_sasl_wrapping = ADS_AUTH_SASL_SIGN;
759
760         Globals.ldap_server_require_strong_auth =
761                 LDAP_SERVER_REQUIRE_STRONG_AUTH_YES;
762
763         /* This is what we tell the afs client. in reality we set the token
764          * to never expire, though, when this runs out the afs client will
765          * forget the token. Set to 0 to get NEVERDATE.*/
766         Globals.afs_token_lifetime = 604800;
767         Globals.cups_connection_timeout = CUPS_DEFAULT_CONNECTION_TIMEOUT;
768
769 /* these parameters are set to defaults that are more appropriate
770    for the increasing samba install base:
771
772    as a member of the workgroup, that will possibly become a
773    _local_ master browser (lm = true).  this is opposed to a forced
774    local master browser startup (pm = true).
775
776    doesn't provide WINS server service by default (wsupp = false),
777    and doesn't provide domain master browser services by default, either.
778
779 */
780
781         Globals.show_add_printer_wizard = true;
782         Globals.os_level = 20;
783         Globals.local_master = true;
784         Globals._domain_master = Auto;  /* depending on _domain_logons */
785         Globals._domain_logons = false;
786         Globals.browse_list = true;
787         Globals.we_are_a_wins_server = false;
788         Globals.wins_proxy = false;
789
790         TALLOC_FREE(Globals.init_logon_delayed_hosts);
791         Globals.init_logon_delay = 100; /* 100 ms default delay */
792
793         Globals.wins_dns_proxy = true;
794         Globals.dns_port = DNS_SERVICE_PORT;
795
796         Globals.allow_trusted_domains = true;
797         lpcfg_string_set(Globals.ctx, &Globals.idmap_backend, "tdb");
798
799         lpcfg_string_set(Globals.ctx, &Globals.template_shell, "/bin/false");
800         lpcfg_string_set(Globals.ctx, &Globals.template_homedir,
801                          "/home/%D/%U");
802         lpcfg_string_set(Globals.ctx, &Globals.winbind_separator, "\\");
803         lpcfg_string_set(Globals.ctx, &Globals.winbindd_socket_directory,
804                          dyn_WINBINDD_SOCKET_DIR);
805
806         lpcfg_string_set(Globals.ctx, &Globals.cups_server, "");
807         lpcfg_string_set(Globals.ctx, &Globals.iprint_server, "");
808
809         lpcfg_string_set(Globals.ctx, &Globals._ctdbd_socket, "");
810
811         Globals.cluster_addresses = NULL;
812         Globals.clustering = false;
813         Globals.ctdb_timeout = 0;
814         Globals.ctdb_locktime_warn_threshold = 0;
815
816         Globals.winbind_cache_time = 300;       /* 5 minutes */
817         Globals.winbind_reconnect_delay = 30;   /* 30 seconds */
818         Globals.winbind_request_timeout = 60;   /* 60 seconds */
819         Globals.winbind_max_clients = 200;
820         Globals.winbind_enum_users = false;
821         Globals.winbind_enum_groups = false;
822         Globals.winbind_use_default_domain = false;
823         Globals.winbind_nested_groups = true;
824         Globals.winbind_expand_groups = 0;
825         Globals.winbind_nss_info = str_list_make_v3_const(NULL, "template", NULL);
826         Globals.winbind_refresh_tickets = false;
827         Globals.winbind_offline_logon = false;
828         Globals.winbind_scan_trusted_domains = false;
829
830         Globals.idmap_cache_time = 86400 * 7; /* a week by default */
831         Globals.idmap_negative_cache_time = 120; /* 2 minutes by default */
832
833         Globals.passdb_expand_explicit = false;
834
835         Globals.name_cache_timeout = 660; /* In seconds */
836
837         Globals.client_use_spnego = true;
838
839         Globals.client_signing = SMB_SIGNING_DEFAULT;
840         Globals._client_ipc_signing = SMB_SIGNING_DEFAULT;
841         Globals.server_signing = SMB_SIGNING_DEFAULT;
842
843         Globals.defer_sharing_violations = true;
844         Globals.smb_ports = str_list_make_v3_const(NULL, SMB_PORTS, NULL);
845
846         Globals.enable_privileges = true;
847         Globals.host_msdfs        = true;
848         Globals.enable_asu_support       = false;
849
850         /* User defined shares. */
851         s = talloc_asprintf(talloc_tos(), "%s/usershares", get_dyn_STATEDIR());
852         if (s == NULL) {
853                 smb_panic("init_globals: ENOMEM");
854         }
855         lpcfg_string_set(Globals.ctx, &Globals.usershare_path, s);
856         TALLOC_FREE(s);
857         lpcfg_string_set(Globals.ctx, &Globals.usershare_template_share, "");
858         Globals.usershare_max_shares = 0;
859         /* By default disallow sharing of directories not owned by the sharer. */
860         Globals.usershare_owner_only = true;
861         /* By default disallow guest access to usershares. */
862         Globals.usershare_allow_guests = false;
863
864         Globals.keepalive = DEFAULT_KEEPALIVE;
865
866         /* By default no shares out of the registry */
867         Globals.registry_shares = false;
868
869         Globals.min_receivefile_size = 0;
870
871         Globals.multicast_dns_register = true;
872
873         Globals.smb2_max_read = DEFAULT_SMB2_MAX_READ;
874         Globals.smb2_max_write = DEFAULT_SMB2_MAX_WRITE;
875         Globals.smb2_max_trans = DEFAULT_SMB2_MAX_TRANSACT;
876         Globals.smb2_max_credits = DEFAULT_SMB2_MAX_CREDITS;
877         Globals.smb2_leases = true;
878         Globals.server_multi_channel_support = true;
879
880         lpcfg_string_set(Globals.ctx, &Globals.ncalrpc_dir,
881                          get_dyn_NCALRPCDIR());
882
883         Globals.server_services = str_list_make_v3_const(NULL, "s3fs rpc nbt wrepl ldap cldap kdc drepl winbindd ntp_signd kcc dnsupdate dns", NULL);
884
885         Globals.dcerpc_endpoint_servers = str_list_make_v3_const(NULL, "epmapper wkssvc rpcecho samr netlogon lsarpc drsuapi dssetup unixinfo browser eventlog6 backupkey dnsserver", NULL);
886
887         Globals.tls_enabled = true;
888         Globals.tls_verify_peer = TLS_VERIFY_PEER_AS_STRICT_AS_POSSIBLE;
889
890         lpcfg_string_set(Globals.ctx, &Globals._tls_keyfile, "tls/key.pem");
891         lpcfg_string_set(Globals.ctx, &Globals._tls_certfile, "tls/cert.pem");
892         lpcfg_string_set(Globals.ctx, &Globals._tls_cafile, "tls/ca.pem");
893         lpcfg_string_set(Globals.ctx,
894                          &Globals.tls_priority,
895                          "NORMAL:-VERS-SSL3.0");
896
897         Globals._preferred_master = Auto;
898
899         Globals.allow_dns_updates = DNS_UPDATE_SIGNED;
900         Globals.dns_zone_scavenging = false;
901
902         lpcfg_string_set(Globals.ctx, &Globals.ntp_signd_socket_directory,
903                          get_dyn_NTP_SIGND_SOCKET_DIR());
904
905         s = talloc_asprintf(talloc_tos(), "%s/samba_kcc", get_dyn_SCRIPTSBINDIR());
906         if (s == NULL) {
907                 smb_panic("init_globals: ENOMEM");
908         }
909         Globals.samba_kcc_command = str_list_make_v3_const(NULL, s, NULL);
910         TALLOC_FREE(s);
911
912 #ifdef MIT_KDC_PATH
913         Globals.mit_kdc_command = str_list_make_v3_const(NULL, MIT_KDC_PATH, NULL);
914 #endif
915
916         s = talloc_asprintf(talloc_tos(), "%s/samba_dnsupdate", get_dyn_SCRIPTSBINDIR());
917         if (s == NULL) {
918                 smb_panic("init_globals: ENOMEM");
919         }
920         Globals.dns_update_command = str_list_make_v3_const(NULL, s, NULL);
921         TALLOC_FREE(s);
922
923         s = talloc_asprintf(talloc_tos(), "%s/samba-gpupdate", get_dyn_SCRIPTSBINDIR());
924         if (s == NULL) {
925                 smb_panic("init_globals: ENOMEM");
926         }
927         Globals.gpo_update_command = str_list_make_v3_const(NULL, s, NULL);
928         TALLOC_FREE(s);
929
930         Globals.apply_group_policies = false;
931
932         s = talloc_asprintf(talloc_tos(), "%s/samba_spnupdate", get_dyn_SCRIPTSBINDIR());
933         if (s == NULL) {
934                 smb_panic("init_globals: ENOMEM");
935         }
936         Globals.spn_update_command = str_list_make_v3_const(NULL, s, NULL);
937         TALLOC_FREE(s);
938
939         Globals.nsupdate_command = str_list_make_v3_const(NULL, "/usr/bin/nsupdate -g", NULL);
940
941         Globals.cldap_port = 389;
942
943         Globals.dgram_port = NBT_DGRAM_SERVICE_PORT;
944
945         Globals.nbt_port = NBT_NAME_SERVICE_PORT;
946
947         Globals.krb5_port = 88;
948
949         Globals.kpasswd_port = 464;
950
951         Globals.kdc_enable_fast = true;
952
953         Globals.aio_max_threads = 100;
954
955         lpcfg_string_set(Globals.ctx,
956                          &Globals.rpc_server_dynamic_port_range,
957                          "49152-65535");
958         Globals.rpc_low_port = SERVER_TCP_LOW_PORT;
959         Globals.rpc_high_port = SERVER_TCP_HIGH_PORT;
960         Globals.prefork_children = 4;
961         Globals.prefork_backoff_increment = 10;
962         Globals.prefork_maximum_backoff = 120;
963
964         Globals.ldap_max_anonymous_request_size = 256000;
965         Globals.ldap_max_authenticated_request_size = 16777216;
966         Globals.ldap_max_search_request_size = 256000;
967
968         /* Async DNS query timeout (in seconds). */
969         Globals.async_dns_timeout = 10;
970
971         Globals.client_smb_encrypt = SMB_ENCRYPTION_DEFAULT;
972
973         Globals._client_use_kerberos = CRED_USE_KERBEROS_DESIRED;
974
975         Globals.client_protection = CRED_CLIENT_PROTECTION_DEFAULT;
976
977         Globals.winbind_use_krb5_enterprise_principals = true;
978
979         Globals.client_smb3_signing_algorithms =
980                 str_list_make_v3_const(NULL, DEFAULT_SMB3_SIGNING_ALGORITHMS, NULL);
981         Globals.server_smb3_signing_algorithms =
982                 str_list_make_v3_const(NULL, DEFAULT_SMB3_SIGNING_ALGORITHMS, NULL);
983
984         Globals.client_smb3_encryption_algorithms =
985                 str_list_make_v3_const(NULL, DEFAULT_SMB3_ENCRYPTION_ALGORITHMS, NULL);
986         Globals.server_smb3_encryption_algorithms =
987                 str_list_make_v3_const(NULL, DEFAULT_SMB3_ENCRYPTION_ALGORITHMS, NULL);
988
989         Globals.min_domain_uid = 1000;
990
991         /*
992          * By default allow smbd and winbindd to start samba-dcerpcd as
993          * a named-pipe helper.
994          */
995         Globals.rpc_start_on_demand_helpers = true;
996
997         /* Now put back the settings that were set with lp_set_cmdline() */
998         apply_lp_set_cmdline();
999 }
1000
1001 /* Convenience routine to setup an lp_context with additional s3 variables */
1002 static struct loadparm_context *setup_lp_context(TALLOC_CTX *mem_ctx)
1003 {
1004         struct loadparm_context *lp_ctx;
1005
1006         lp_ctx = loadparm_init_s3(mem_ctx,
1007                                   loadparm_s3_helpers());
1008         if (lp_ctx == NULL) {
1009                 DEBUG(0, ("loadparm_init_s3 failed\n"));
1010                 return NULL;
1011         }
1012
1013         lp_ctx->sDefault = talloc_zero(lp_ctx, struct loadparm_service);
1014         if (lp_ctx->sDefault == NULL) {
1015                 DBG_ERR("talloc_zero failed\n");
1016                 TALLOC_FREE(lp_ctx);
1017                 return NULL;
1018         }
1019
1020         *lp_ctx->sDefault = _sDefault;
1021         lp_ctx->services = NULL; /* We do not want to access this directly */
1022         lp_ctx->bInGlobalSection = bInGlobalSection;
1023         lp_ctx->flags = flags_list;
1024
1025         return lp_ctx;
1026 }
1027
1028 /*******************************************************************
1029  Convenience routine to grab string parameters into talloced memory
1030  and run standard_sub_basic on them. The buffers can be written to by
1031  callers without affecting the source string.
1032 ********************************************************************/
1033
1034 static char *loadparm_s3_global_substitution_fn(
1035                         TALLOC_CTX *mem_ctx,
1036                         const struct loadparm_substitution *lp_sub,
1037                         const char *s,
1038                         void *private_data)
1039 {
1040         char *ret;
1041
1042         /* The follow debug is useful for tracking down memory problems
1043            especially if you have an inner loop that is calling a lp_*()
1044            function that returns a string.  Perhaps this debug should be
1045            present all the time? */
1046
1047 #if 0
1048         DEBUG(10, ("lp_string(%s)\n", s));
1049 #endif
1050         if (!s) {
1051                 return NULL;
1052         }
1053
1054         ret = talloc_sub_basic(mem_ctx,
1055                         get_current_username(),
1056                         get_current_user_info_domain(),
1057                         s);
1058         if (trim_char(ret, '\"', '\"')) {
1059                 if (strchr(ret,'\"') != NULL) {
1060                         TALLOC_FREE(ret);
1061                         ret = talloc_sub_basic(mem_ctx,
1062                                         get_current_username(),
1063                                         get_current_user_info_domain(),
1064                                         s);
1065                 }
1066         }
1067         return ret;
1068 }
1069
1070 static const struct loadparm_substitution s3_global_substitution = {
1071         .substituted_string_fn = loadparm_s3_global_substitution_fn,
1072 };
1073
1074 const struct loadparm_substitution *loadparm_s3_global_substitution(void)
1075 {
1076         return &s3_global_substitution;
1077 }
1078
1079 /*
1080    In this section all the functions that are used to access the
1081    parameters from the rest of the program are defined
1082 */
1083
1084 #define FN_GLOBAL_SUBSTITUTED_STRING(fn_name,ptr) \
1085 char *lp_ ## fn_name(TALLOC_CTX *ctx, const struct loadparm_substitution *lp_sub) \
1086  {return lpcfg_substituted_string(ctx, lp_sub, *(char **)(&Globals.ptr) ? *(char **)(&Globals.ptr) : "");}
1087 #define FN_GLOBAL_CONST_STRING(fn_name,ptr) \
1088  const char *lp_ ## fn_name(void) {return(*(const char * const *)(&Globals.ptr) ? *(const char * const *)(&Globals.ptr) : "");}
1089 #define FN_GLOBAL_LIST(fn_name,ptr) \
1090  const char **lp_ ## fn_name(void) {return(*(const char ***)(&Globals.ptr));}
1091 #define FN_GLOBAL_BOOL(fn_name,ptr) \
1092  bool lp_ ## fn_name(void) {return(*(bool *)(&Globals.ptr));}
1093 #define FN_GLOBAL_CHAR(fn_name,ptr) \
1094  char lp_ ## fn_name(void) {return(*(char *)(&Globals.ptr));}
1095 #define FN_GLOBAL_INTEGER(fn_name,ptr) \
1096  int lp_ ## fn_name(void) {return(*(int *)(&Globals.ptr));}
1097
1098 #define FN_LOCAL_SUBSTITUTED_STRING(fn_name,val) \
1099 char *lp_ ## fn_name(TALLOC_CTX *ctx, const struct loadparm_substitution *lp_sub, int i) \
1100  {return lpcfg_substituted_string((ctx), lp_sub, (LP_SNUM_OK(i) && ServicePtrs[(i)]->val) ? ServicePtrs[(i)]->val : sDefault.val);}
1101 #define FN_LOCAL_CONST_STRING(fn_name,val) \
1102  const char *lp_ ## fn_name(int i) {return (const char *)((LP_SNUM_OK(i) && ServicePtrs[(i)]->val) ? ServicePtrs[(i)]->val : sDefault.val);}
1103 #define FN_LOCAL_LIST(fn_name,val) \
1104  const char **lp_ ## fn_name(int i) {return(const char **)(LP_SNUM_OK(i)? ServicePtrs[(i)]->val : sDefault.val);}
1105 #define FN_LOCAL_BOOL(fn_name,val) \
1106  bool lp_ ## fn_name(int i) {return(bool)(LP_SNUM_OK(i)? ServicePtrs[(i)]->val : sDefault.val);}
1107 #define FN_LOCAL_INTEGER(fn_name,val) \
1108  int lp_ ## fn_name(int i) {return(LP_SNUM_OK(i)? ServicePtrs[(i)]->val : sDefault.val);}
1109
1110 #define FN_LOCAL_PARM_BOOL(fn_name,val) \
1111  bool lp_ ## fn_name(const struct share_params *p) {return(bool)(LP_SNUM_OK(p->service)? ServicePtrs[(p->service)]->val : sDefault.val);}
1112 #define FN_LOCAL_PARM_INTEGER(fn_name,val) \
1113  int lp_ ## fn_name(const struct share_params *p) {return(LP_SNUM_OK(p->service)? ServicePtrs[(p->service)]->val : sDefault.val);}
1114 #define FN_LOCAL_PARM_CHAR(fn_name,val) \
1115  char lp_ ## fn_name(const struct share_params *p) {return(LP_SNUM_OK(p->service)? ServicePtrs[(p->service)]->val : sDefault.val);}
1116
1117 int lp_winbind_max_domain_connections(void)
1118 {
1119         if (lp_winbind_offline_logon() &&
1120             lp__winbind_max_domain_connections() > 1) {
1121                 DEBUG(1, ("offline logons active, restricting max domain "
1122                           "connections to 1\n"));
1123                 return 1;
1124         }
1125         return MAX(1, lp__winbind_max_domain_connections());
1126 }
1127
1128 /* These functions remain in source3/param for now */
1129
1130 #include "lib/param/param_functions.c"
1131
1132 FN_LOCAL_SUBSTITUTED_STRING(servicename, szService)
1133 FN_LOCAL_CONST_STRING(const_servicename, szService)
1134
1135 /* These functions cannot be auto-generated */
1136 FN_LOCAL_BOOL(autoloaded, autoloaded)
1137 FN_GLOBAL_CONST_STRING(dnsdomain, dnsdomain)
1138
1139 /* local prototypes */
1140
1141 static int map_parameter_canonical(const char *pszParmName, bool *inverse);
1142 static const char *get_boolean(bool bool_value);
1143 static bool do_parameter(const char *pszParmName, const char *pszParmValue,
1144                          void *userdata);
1145 static bool hash_a_service(const char *name, int number);
1146 static void free_service_byindex(int iService);
1147 static void show_parameter(int parmIndex);
1148 static bool is_synonym_of(int parm1, int parm2, bool *inverse);
1149 static bool lp_parameter_value_is_valid(const char *parm_name, const char *val);
1150
1151 /*
1152  * This is a helper function for parametrical options support.  It returns a
1153  * pointer to parametrical option value if it exists or NULL otherwise. Actual
1154  * parametrical functions are quite simple
1155  */
1156 static struct parmlist_entry *get_parametrics(int snum, const char *type,
1157                                                 const char *option)
1158 {
1159         if (snum >= iNumServices) return NULL;
1160
1161         if (snum < 0) {
1162                 return get_parametric_helper(NULL, type, option, Globals.param_opt);
1163         } else {
1164                 return get_parametric_helper(ServicePtrs[snum],
1165                                              type, option, Globals.param_opt);
1166         }
1167 }
1168
1169 static void discard_whitespace(char *str)
1170 {
1171         size_t len = strlen(str);
1172         size_t i = 0;
1173
1174         while (i < len) {
1175                 if (isspace(str[i])) {
1176                         memmove(&str[i], &str[i+1], len-i);
1177                         len -= 1;
1178                         continue;
1179                 }
1180                 i += 1;
1181         }
1182 }
1183
1184 /**
1185  * @brief Go through all global parametric parameters
1186  *
1187  * @param regex_str     A regular expression to scan param for
1188  * @param max_matches   Max number of submatches the regexp expects
1189  * @param cb            Function to call on match. Should return true
1190  *                      when it wants wi_scan_global_parametrics to stop
1191  *                      scanning
1192  * @param private_data  Anonymous pointer passed to cb
1193  *
1194  * @return              0: success, regcomp/regexec return value on error.
1195  *                      See "man regexec" for possible errors
1196  */
1197
1198 int lp_wi_scan_global_parametrics(
1199         const char *regex_str, size_t max_matches,
1200         bool (*cb)(const char *string, regmatch_t matches[],
1201                    void *private_data),
1202         void *private_data)
1203 {
1204         struct parmlist_entry *data;
1205         regex_t regex;
1206         int ret;
1207
1208         ret = regcomp(&regex, regex_str, REG_ICASE);
1209         if (ret != 0) {
1210                 return ret;
1211         }
1212
1213         for (data = Globals.param_opt; data != NULL; data = data->next) {
1214                 size_t keylen = strlen(data->key);
1215                 char key[keylen+1];
1216                 regmatch_t matches[max_matches];
1217                 bool stop;
1218
1219                 memcpy(key, data->key, sizeof(key));
1220                 discard_whitespace(key);
1221
1222                 ret = regexec(&regex, key, max_matches, matches, 0);
1223                 if (ret == REG_NOMATCH) {
1224                         continue;
1225                 }
1226                 if (ret != 0) {
1227                         goto fail;
1228                 }
1229
1230                 stop = cb(key, matches, private_data);
1231                 if (stop) {
1232                         break;
1233                 }
1234         }
1235
1236         ret = 0;
1237 fail:
1238         regfree(&regex);
1239         return ret;
1240 }
1241
1242
1243 #define MISSING_PARAMETER(name) \
1244     DEBUG(0, ("%s(): value is NULL or empty!\n", #name))
1245
1246 /*******************************************************************
1247 convenience routine to return enum parameters.
1248 ********************************************************************/
1249 static int lp_enum(const char *s,const struct enum_list *_enum)
1250 {
1251         int i;
1252
1253         if (!s || !*s || !_enum) {
1254                 MISSING_PARAMETER(lp_enum);
1255                 return (-1);
1256         }
1257
1258         for (i=0; _enum[i].name; i++) {
1259                 if (strequal(_enum[i].name,s))
1260                         return _enum[i].value;
1261         }
1262
1263         DEBUG(0,("lp_enum(%s,enum): value is not in enum_list!\n",s));
1264         return (-1);
1265 }
1266
1267 #undef MISSING_PARAMETER
1268
1269 /* Return parametric option from a given service. Type is a part of option before ':' */
1270 /* Parametric option has following syntax: 'Type: option = value' */
1271 char *lp_parm_substituted_string(TALLOC_CTX *mem_ctx,
1272                                  const struct loadparm_substitution *lp_sub,
1273                                  int snum,
1274                                  const char *type,
1275                                  const char *option,
1276                                  const char *def)
1277 {
1278         struct parmlist_entry *data = get_parametrics(snum, type, option);
1279
1280         SMB_ASSERT(lp_sub != NULL);
1281
1282         if (data == NULL||data->value==NULL) {
1283                 if (def) {
1284                         return lpcfg_substituted_string(mem_ctx, lp_sub, def);
1285                 } else {
1286                         return NULL;
1287                 }
1288         }
1289
1290         return lpcfg_substituted_string(mem_ctx, lp_sub, data->value);
1291 }
1292
1293 /* Return parametric option from a given service. Type is a part of option before ':' */
1294 /* Parametric option has following syntax: 'Type: option = value' */
1295 const char *lp_parm_const_string(int snum, const char *type, const char *option, const char *def)
1296 {
1297         struct parmlist_entry *data = get_parametrics(snum, type, option);
1298
1299         if (data == NULL||data->value==NULL)
1300                 return def;
1301
1302         return data->value;
1303 }
1304
1305
1306 /* Return parametric option from a given service. Type is a part of option before ':' */
1307 /* Parametric option has following syntax: 'Type: option = value' */
1308
1309 const char **lp_parm_string_list(int snum, const char *type, const char *option, const char **def)
1310 {
1311         struct parmlist_entry *data = get_parametrics(snum, type, option);
1312
1313         if (data == NULL||data->value==NULL)
1314                 return (const char **)def;
1315
1316         if (data->list==NULL) {
1317                 data->list = str_list_make_v3(NULL, data->value, NULL);
1318         }
1319
1320         return discard_const_p(const char *, data->list);
1321 }
1322
1323 /* Return parametric option from a given service. Type is a part of option before ':' */
1324 /* Parametric option has following syntax: 'Type: option = value' */
1325
1326 int lp_parm_int(int snum, const char *type, const char *option, int def)
1327 {
1328         struct parmlist_entry *data = get_parametrics(snum, type, option);
1329
1330         if (data && data->value && *data->value)
1331                 return lp_int(data->value);
1332
1333         return def;
1334 }
1335
1336 /* Return parametric option from a given service. Type is a part of option before ':' */
1337 /* Parametric option has following syntax: 'Type: option = value' */
1338
1339 unsigned long lp_parm_ulong(int snum, const char *type, const char *option, unsigned long def)
1340 {
1341         struct parmlist_entry *data = get_parametrics(snum, type, option);
1342
1343         if (data && data->value && *data->value)
1344                 return lp_ulong(data->value);
1345
1346         return def;
1347 }
1348
1349 /* Return parametric option from a given service. Type is a part of option before ':' */
1350 /* Parametric option has following syntax: 'Type: option = value' */
1351
1352 unsigned long long lp_parm_ulonglong(int snum, const char *type,
1353                                      const char *option, unsigned long long def)
1354 {
1355         struct parmlist_entry *data = get_parametrics(snum, type, option);
1356
1357         if (data && data->value && *data->value) {
1358                 return lp_ulonglong(data->value);
1359         }
1360
1361         return def;
1362 }
1363
1364 /* Return parametric option from a given service. Type is a part of option
1365  * before ':' */
1366 /* Parametric option has following syntax: 'Type: option = value' */
1367
1368 bool lp_parm_bool(int snum, const char *type, const char *option, bool def)
1369 {
1370         struct parmlist_entry *data = get_parametrics(snum, type, option);
1371
1372         if (data && data->value && *data->value)
1373                 return lp_bool(data->value);
1374
1375         return def;
1376 }
1377
1378 /* Return parametric option from a given service. Type is a part of option before ':' */
1379 /* Parametric option has following syntax: 'Type: option = value' */
1380
1381 int lp_parm_enum(int snum, const char *type, const char *option,
1382                  const struct enum_list *_enum, int def)
1383 {
1384         struct parmlist_entry *data = get_parametrics(snum, type, option);
1385
1386         if (data && data->value && *data->value && _enum)
1387                 return lp_enum(data->value, _enum);
1388
1389         return def;
1390 }
1391
1392 /**
1393  * free a param_opts structure.
1394  * param_opts handling should be moved to talloc;
1395  * then this whole functions reduces to a TALLOC_FREE().
1396  */
1397
1398 static void free_param_opts(struct parmlist_entry **popts)
1399 {
1400         struct parmlist_entry *opt, *next_opt;
1401
1402         if (*popts != NULL) {
1403                 DEBUG(5, ("Freeing parametrics:\n"));
1404         }
1405         opt = *popts;
1406         while (opt != NULL) {
1407                 lpcfg_string_free(&opt->key);
1408                 lpcfg_string_free(&opt->value);
1409                 TALLOC_FREE(opt->list);
1410                 next_opt = opt->next;
1411                 TALLOC_FREE(opt);
1412                 opt = next_opt;
1413         }
1414         *popts = NULL;
1415 }
1416
1417 /***************************************************************************
1418  Free the dynamically allocated parts of a service struct.
1419 ***************************************************************************/
1420
1421 static void free_service(struct loadparm_service *pservice)
1422 {
1423         if (!pservice)
1424                 return;
1425
1426         if (pservice->szService)
1427                 DEBUG(5, ("free_service: Freeing service %s\n",
1428                        pservice->szService));
1429
1430         free_parameters(pservice);
1431
1432         lpcfg_string_free(&pservice->szService);
1433         TALLOC_FREE(pservice->copymap);
1434
1435         free_param_opts(&pservice->param_opt);
1436
1437         ZERO_STRUCTP(pservice);
1438 }
1439
1440
1441 /***************************************************************************
1442  remove a service indexed in the ServicePtrs array from the ServiceHash
1443  and free the dynamically allocated parts
1444 ***************************************************************************/
1445
1446 static void free_service_byindex(int idx)
1447 {
1448         if ( !LP_SNUM_OK(idx) )
1449                 return;
1450
1451         ServicePtrs[idx]->valid = false;
1452
1453         /* we have to cleanup the hash record */
1454
1455         if (ServicePtrs[idx]->szService) {
1456                 char *canon_name = canonicalize_servicename(
1457                         talloc_tos(),
1458                         ServicePtrs[idx]->szService );
1459
1460                 dbwrap_delete_bystring(ServiceHash, canon_name );
1461                 TALLOC_FREE(canon_name);
1462         }
1463
1464         free_service(ServicePtrs[idx]);
1465         TALLOC_FREE(ServicePtrs[idx]);
1466 }
1467
1468 /***************************************************************************
1469  Add a new service to the services array initialising it with the given
1470  service.
1471 ***************************************************************************/
1472
1473 static int add_a_service(const struct loadparm_service *pservice, const char *name)
1474 {
1475         int i;
1476         struct loadparm_service **tsp = NULL;
1477
1478         /* it might already exist */
1479         if (name) {
1480                 i = getservicebyname(name, NULL);
1481                 if (i >= 0) {
1482                         return (i);
1483                 }
1484         }
1485
1486         /* Re use empty slots if any before allocating new one.*/
1487         for (i=0; i < iNumServices; i++) {
1488                 if (ServicePtrs[i] == NULL) {
1489                         break;
1490                 }
1491         }
1492         if (i == iNumServices) {
1493                 /* if not, then create one */
1494                 tsp = talloc_realloc(NULL, ServicePtrs,
1495                                      struct loadparm_service *,
1496                                      iNumServices + 1);
1497                 if (tsp == NULL) {
1498                         DEBUG(0, ("add_a_service: failed to enlarge "
1499                                   "ServicePtrs!\n"));
1500                         return (-1);
1501                 }
1502                 ServicePtrs = tsp;
1503                 iNumServices++;
1504         }
1505         ServicePtrs[i] = talloc_zero(ServicePtrs, struct loadparm_service);
1506         if (!ServicePtrs[i]) {
1507                 DEBUG(0,("add_a_service: out of memory!\n"));
1508                 return (-1);
1509         }
1510
1511         ServicePtrs[i]->valid = true;
1512
1513         copy_service(ServicePtrs[i], pservice, NULL);
1514         if (name)
1515                 lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->szService,
1516                                  name);
1517
1518         DEBUG(8,("add_a_service: Creating snum = %d for %s\n",
1519                 i, ServicePtrs[i]->szService));
1520
1521         if (!hash_a_service(ServicePtrs[i]->szService, i)) {
1522                 return (-1);
1523         }
1524
1525         return (i);
1526 }
1527
1528 /***************************************************************************
1529   Convert a string to uppercase and remove whitespaces.
1530 ***************************************************************************/
1531
1532 char *canonicalize_servicename(TALLOC_CTX *ctx, const char *src)
1533 {
1534         char *result;
1535
1536         if ( !src ) {
1537                 DEBUG(0,("canonicalize_servicename: NULL source name!\n"));
1538                 return NULL;
1539         }
1540
1541         result = talloc_strdup(ctx, src);
1542         SMB_ASSERT(result != NULL);
1543
1544         if (!strlower_m(result)) {
1545                 TALLOC_FREE(result);
1546                 return NULL;
1547         }
1548         return result;
1549 }
1550
1551 /***************************************************************************
1552   Add a name/index pair for the services array to the hash table.
1553 ***************************************************************************/
1554
1555 static bool hash_a_service(const char *name, int idx)
1556 {
1557         char *canon_name;
1558
1559         if ( !ServiceHash ) {
1560                 DEBUG(10,("hash_a_service: creating servicehash\n"));
1561                 ServiceHash = db_open_rbt(NULL);
1562                 if ( !ServiceHash ) {
1563                         DEBUG(0,("hash_a_service: open tdb servicehash failed!\n"));
1564                         return false;
1565                 }
1566         }
1567
1568         DEBUG(10,("hash_a_service: hashing index %d for service name %s\n",
1569                 idx, name));
1570
1571         canon_name = canonicalize_servicename(talloc_tos(), name );
1572
1573         dbwrap_store_bystring(ServiceHash, canon_name,
1574                               make_tdb_data((uint8_t *)&idx, sizeof(idx)),
1575                               TDB_REPLACE);
1576
1577         TALLOC_FREE(canon_name);
1578
1579         return true;
1580 }
1581
1582 /***************************************************************************
1583  Add a new home service, with the specified home directory, defaults coming
1584  from service ifrom.
1585 ***************************************************************************/
1586
1587 bool lp_add_home(const char *pszHomename, int iDefaultService,
1588                  const char *user, const char *pszHomedir)
1589 {
1590         const struct loadparm_substitution *lp_sub =
1591                 loadparm_s3_global_substitution();
1592         int i;
1593         char *global_path;
1594
1595         if (pszHomename == NULL || user == NULL || pszHomedir == NULL ||
1596                         pszHomedir[0] == '\0') {
1597                 return false;
1598         }
1599
1600         i = add_a_service(ServicePtrs[iDefaultService], pszHomename);
1601
1602         if (i < 0)
1603                 return false;
1604
1605         global_path = lp_path(talloc_tos(), lp_sub, GLOBAL_SECTION_SNUM);
1606         if (!(*(ServicePtrs[iDefaultService]->path))
1607             || strequal(ServicePtrs[iDefaultService]->path, global_path)) {
1608                 lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->path,
1609                                  pszHomedir);
1610         }
1611         TALLOC_FREE(global_path);
1612
1613         if (!(*(ServicePtrs[i]->comment))) {
1614                 char *comment = talloc_asprintf(talloc_tos(), "Home directory of %s", user);
1615                 if (comment == NULL) {
1616                         return false;
1617                 }
1618                 lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->comment,
1619                                  comment);
1620                 TALLOC_FREE(comment);
1621         }
1622
1623         /* set the browseable flag from the global default */
1624
1625         ServicePtrs[i]->browseable = sDefault.browseable;
1626         ServicePtrs[i]->access_based_share_enum = sDefault.access_based_share_enum;
1627
1628         ServicePtrs[i]->autoloaded = true;
1629
1630         DEBUG(3, ("adding home's share [%s] for user '%s' at '%s'\n", pszHomename,
1631                user, ServicePtrs[i]->path ));
1632
1633         return true;
1634 }
1635
1636 /***************************************************************************
1637  Add a new service, based on an old one.
1638 ***************************************************************************/
1639
1640 int lp_add_service(const char *pszService, int iDefaultService)
1641 {
1642         if (iDefaultService < 0) {
1643                 return add_a_service(&sDefault, pszService);
1644         }
1645
1646         return (add_a_service(ServicePtrs[iDefaultService], pszService));
1647 }
1648
1649 /***************************************************************************
1650  Add the IPC service.
1651 ***************************************************************************/
1652
1653 static bool lp_add_ipc(const char *ipc_name, bool guest_ok)
1654 {
1655         char *comment = NULL;
1656         int i = add_a_service(&sDefault, ipc_name);
1657
1658         if (i < 0)
1659                 return false;
1660
1661         comment = talloc_asprintf(talloc_tos(), "IPC Service (%s)",
1662                                   Globals.server_string);
1663         if (comment == NULL) {
1664                 return false;
1665         }
1666
1667         lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->path, tmpdir());
1668         lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->comment, comment);
1669         lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->fstype, "IPC");
1670         ServicePtrs[i]->max_connections = 0;
1671         ServicePtrs[i]->available = true;
1672         ServicePtrs[i]->read_only = true;
1673         ServicePtrs[i]->guest_only = false;
1674         ServicePtrs[i]->administrative_share = true;
1675         ServicePtrs[i]->guest_ok = guest_ok;
1676         ServicePtrs[i]->printable = false;
1677         ServicePtrs[i]->browseable = sDefault.browseable;
1678         ServicePtrs[i]->autoloaded = false;
1679
1680         DEBUG(3, ("adding IPC service\n"));
1681
1682         TALLOC_FREE(comment);
1683         return true;
1684 }
1685
1686 /***************************************************************************
1687  Add a new printer service, with defaults coming from service iFrom.
1688 ***************************************************************************/
1689
1690 bool lp_add_printer(const char *pszPrintername, int iDefaultService)
1691 {
1692         const char *comment = "From Printcap";
1693         int i = add_a_service(ServicePtrs[iDefaultService], pszPrintername);
1694
1695         if (i < 0)
1696                 return false;
1697
1698         /* note that we do NOT default the availability flag to true - */
1699         /* we take it from the default service passed. This allows all */
1700         /* dynamic printers to be disabled by disabling the [printers] */
1701         /* entry (if/when the 'available' keyword is implemented!).    */
1702
1703         /* the printer name is set to the service name. */
1704         lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->_printername,
1705                          pszPrintername);
1706         lpcfg_string_set(ServicePtrs[i], &ServicePtrs[i]->comment, comment);
1707
1708         /* set the browseable flag from the gloabl default */
1709         ServicePtrs[i]->browseable = sDefault.browseable;
1710
1711         /* Printers cannot be read_only. */
1712         ServicePtrs[i]->read_only = false;
1713         /* No oplocks on printer services. */
1714         ServicePtrs[i]->oplocks = false;
1715         /* Printer services must be printable. */
1716         ServicePtrs[i]->printable = true;
1717
1718         DEBUG(3, ("adding printer service %s\n", pszPrintername));
1719
1720         return true;
1721 }
1722
1723
1724 /***************************************************************************
1725  Check whether the given parameter name is valid.
1726  Parametric options (names containing a colon) are considered valid.
1727 ***************************************************************************/
1728
1729 bool lp_parameter_is_valid(const char *pszParmName)
1730 {
1731         return ((lpcfg_map_parameter(pszParmName) != -1) ||
1732                 (strchr(pszParmName, ':') != NULL));
1733 }
1734
1735 /***************************************************************************
1736  Check whether the given name is the name of a global parameter.
1737  Returns true for strings belonging to parameters of class
1738  P_GLOBAL, false for all other strings, also for parametric options
1739  and strings not belonging to any option.
1740 ***************************************************************************/
1741
1742 bool lp_parameter_is_global(const char *pszParmName)
1743 {
1744         int num = lpcfg_map_parameter(pszParmName);
1745
1746         if (num >= 0) {
1747                 return (parm_table[num].p_class == P_GLOBAL);
1748         }
1749
1750         return false;
1751 }
1752
1753 /**************************************************************************
1754  Determine the canonical name for a parameter.
1755  Indicate when it is an inverse (boolean) synonym instead of a
1756  "usual" synonym.
1757 **************************************************************************/
1758
1759 bool lp_canonicalize_parameter(const char *parm_name, const char **canon_parm,
1760                                bool *inverse)
1761 {
1762         int num;
1763
1764         if (!lp_parameter_is_valid(parm_name)) {
1765                 *canon_parm = NULL;
1766                 return false;
1767         }
1768
1769         num = map_parameter_canonical(parm_name, inverse);
1770         if (num < 0) {
1771                 /* parametric option */
1772                 *canon_parm = parm_name;
1773         } else {
1774                 *canon_parm = parm_table[num].label;
1775         }
1776
1777         return true;
1778
1779 }
1780
1781 /**************************************************************************
1782  Determine the canonical name for a parameter.
1783  Turn the value given into the inverse boolean expression when
1784  the synonym is an invers boolean synonym.
1785
1786  Return true if
1787  - parm_name is a valid parameter name and
1788  - val is a valid value for this parameter and
1789  - in case the parameter is an inverse boolean synonym, if the val
1790    string could successfully be converted to the reverse bool.
1791  Return false in all other cases.
1792 **************************************************************************/
1793
1794 bool lp_canonicalize_parameter_with_value(const char *parm_name,
1795                                           const char *val,
1796                                           const char **canon_parm,
1797                                           const char **canon_val)
1798 {
1799         int num;
1800         bool inverse;
1801         bool ret;
1802
1803         if (!lp_parameter_is_valid(parm_name)) {
1804                 *canon_parm = NULL;
1805                 *canon_val = NULL;
1806                 return false;
1807         }
1808
1809         num = map_parameter_canonical(parm_name, &inverse);
1810         if (num < 0) {
1811                 /* parametric option */
1812                 *canon_parm = parm_name;
1813                 *canon_val = val;
1814                 return true;
1815         }
1816
1817         *canon_parm = parm_table[num].label;
1818         if (inverse) {
1819                 if (!lp_invert_boolean(val, canon_val)) {
1820                         *canon_val = NULL;
1821                         return false;
1822                 }
1823         } else {
1824                 *canon_val = val;
1825         }
1826
1827         ret = lp_parameter_value_is_valid(*canon_parm, *canon_val);
1828
1829         return ret;
1830 }
1831
1832 /***************************************************************************
1833  Map a parameter's string representation to the index of the canonical
1834  form of the parameter (it might be a synonym).
1835  Returns -1 if the parameter string is not recognised.
1836 ***************************************************************************/
1837
1838 static int map_parameter_canonical(const char *pszParmName, bool *inverse)
1839 {
1840         int parm_num, canon_num;
1841         bool loc_inverse = false;
1842
1843         parm_num = lpcfg_map_parameter(pszParmName);
1844         if ((parm_num < 0) || !(parm_table[parm_num].flags & FLAG_SYNONYM)) {
1845                 /* invalid, parametric or no canidate for synonyms ... */
1846                 goto done;
1847         }
1848
1849         for (canon_num = 0; parm_table[canon_num].label; canon_num++) {
1850                 if (is_synonym_of(parm_num, canon_num, &loc_inverse)) {
1851                         parm_num = canon_num;
1852                         goto done;
1853                 }
1854         }
1855
1856 done:
1857         if (inverse != NULL) {
1858                 *inverse = loc_inverse;
1859         }
1860         return parm_num;
1861 }
1862
1863 /***************************************************************************
1864  return true if parameter number parm1 is a synonym of parameter
1865  number parm2 (parm2 being the principal name).
1866  set inverse to true if parm1 is P_BOOLREV and parm2 is P_BOOL,
1867  false otherwise.
1868 ***************************************************************************/
1869
1870 static bool is_synonym_of(int parm1, int parm2, bool *inverse)
1871 {
1872         if ((parm_table[parm1].offset == parm_table[parm2].offset) &&
1873             (parm_table[parm1].p_class == parm_table[parm2].p_class) &&
1874             (parm_table[parm1].flags & FLAG_SYNONYM) &&
1875             !(parm_table[parm2].flags & FLAG_SYNONYM))
1876         {
1877                 if (inverse != NULL) {
1878                         if ((parm_table[parm1].type == P_BOOLREV) &&
1879                             (parm_table[parm2].type == P_BOOL))
1880                         {
1881                                 *inverse = true;
1882                         } else {
1883                                 *inverse = false;
1884                         }
1885                 }
1886                 return true;
1887         }
1888         return false;
1889 }
1890
1891 /***************************************************************************
1892  Show one parameter's name, type, [values,] and flags.
1893  (helper functions for show_parameter_list)
1894 ***************************************************************************/
1895
1896 static void show_parameter(int parmIndex)
1897 {
1898         size_t enumIndex, flagIndex;
1899         size_t parmIndex2;
1900         bool hadFlag;
1901         bool hadSyn;
1902         bool inverse;
1903         const char *type[] = { "P_BOOL", "P_BOOLREV", "P_CHAR", "P_INTEGER",
1904                 "P_OCTAL", "P_LIST", "P_STRING", "P_USTRING",
1905                 "P_ENUM", "P_BYTES", "P_CMDLIST" };
1906         unsigned flags[] = { FLAG_DEPRECATED, FLAG_SYNONYM };
1907         const char *flag_names[] = { "FLAG_DEPRECATED", "FLAG_SYNONYM", NULL};
1908
1909         printf("%s=%s", parm_table[parmIndex].label,
1910                type[parm_table[parmIndex].type]);
1911         if (parm_table[parmIndex].type == P_ENUM) {
1912                 printf(",");
1913                 for (enumIndex=0;
1914                      parm_table[parmIndex].enum_list[enumIndex].name;
1915                      enumIndex++)
1916                 {
1917                         printf("%s%s",
1918                                enumIndex ? "|" : "",
1919                                parm_table[parmIndex].enum_list[enumIndex].name);
1920                 }
1921         }
1922         printf(",");
1923         hadFlag = false;
1924         for (flagIndex=0; flag_names[flagIndex]; flagIndex++) {
1925                 if (parm_table[parmIndex].flags & flags[flagIndex]) {
1926                         printf("%s%s",
1927                                 hadFlag ? "|" : "",
1928                                 flag_names[flagIndex]);
1929                         hadFlag = true;
1930                 }
1931         }
1932
1933         /* output synonyms */
1934         hadSyn = false;
1935         for (parmIndex2=0; parm_table[parmIndex2].label; parmIndex2++) {
1936                 if (is_synonym_of(parmIndex, parmIndex2, &inverse)) {
1937                         printf(" (%ssynonym of %s)", inverse ? "inverse " : "",
1938                                parm_table[parmIndex2].label);
1939                 } else if (is_synonym_of(parmIndex2, parmIndex, &inverse)) {
1940                         if (!hadSyn) {
1941                                 printf(" (synonyms: ");
1942                                 hadSyn = true;
1943                         } else {
1944                                 printf(", ");
1945                         }
1946                         printf("%s%s", parm_table[parmIndex2].label,
1947                                inverse ? "[i]" : "");
1948                 }
1949         }
1950         if (hadSyn) {
1951                 printf(")");
1952         }
1953
1954         printf("\n");
1955 }
1956
1957 /*
1958  * Check the value for a P_ENUM
1959  */
1960 static bool check_enum_parameter(struct parm_struct *parm, const char *value)
1961 {
1962         int i;
1963
1964         for (i = 0; parm->enum_list[i].name; i++) {
1965                 if (strwicmp(value, parm->enum_list[i].name) == 0) {
1966                         return true;
1967                 }
1968         }
1969         return false;
1970 }
1971
1972 /**************************************************************************
1973  Check whether the given value is valid for the given parameter name.
1974 **************************************************************************/
1975
1976 static bool lp_parameter_value_is_valid(const char *parm_name, const char *val)
1977 {
1978         bool ret = false, tmp_bool;
1979         int num = lpcfg_map_parameter(parm_name), tmp_int;
1980         uint64_t tmp_int64 = 0;
1981         struct parm_struct *parm;
1982
1983         /* parametric options (parameter names containing a colon) cannot
1984            be checked and are therefore considered valid. */
1985         if (strchr(parm_name, ':') != NULL) {
1986                 return true;
1987         }
1988
1989         if (num >= 0) {
1990                 parm = &parm_table[num];
1991                 switch (parm->type) {
1992                         case P_BOOL:
1993                         case P_BOOLREV:
1994                                 ret = set_boolean(val, &tmp_bool);
1995                                 break;
1996
1997                         case P_INTEGER:
1998                                 ret = (sscanf(val, "%d", &tmp_int) == 1);
1999                                 break;
2000
2001                         case P_OCTAL:
2002                                 ret = (sscanf(val, "%o", &tmp_int) == 1);
2003                                 break;
2004
2005                         case P_ENUM:
2006                                 ret = check_enum_parameter(parm, val);
2007                                 break;
2008
2009                         case P_BYTES:
2010                                 if (conv_str_size_error(val, &tmp_int64) &&
2011                                     tmp_int64 <= INT_MAX) {
2012                                         ret = true;
2013                                 }
2014                                 break;
2015
2016                         case P_CHAR:
2017                         case P_LIST:
2018                         case P_STRING:
2019                         case P_USTRING:
2020                         case P_CMDLIST:
2021                                 ret = true;
2022                                 break;
2023                 }
2024         }
2025         return ret;
2026 }
2027
2028 /***************************************************************************
2029  Show all parameter's name, type, [values,] and flags.
2030 ***************************************************************************/
2031
2032 void show_parameter_list(void)
2033 {
2034         int classIndex, parmIndex;
2035         const char *section_names[] = { "local", "global", NULL};
2036
2037         for (classIndex=0; section_names[classIndex]; classIndex++) {
2038                 printf("[%s]\n", section_names[classIndex]);
2039                 for (parmIndex = 0; parm_table[parmIndex].label; parmIndex++) {
2040                         if (parm_table[parmIndex].p_class == classIndex) {
2041                                 show_parameter(parmIndex);
2042                         }
2043                 }
2044         }
2045 }
2046
2047 /***************************************************************************
2048  Get the standard string representation of a boolean value ("yes" or "no")
2049 ***************************************************************************/
2050
2051 static const char *get_boolean(bool bool_value)
2052 {
2053         static const char *yes_str = "yes";
2054         static const char *no_str = "no";
2055
2056         return (bool_value ? yes_str : no_str);
2057 }
2058
2059 /***************************************************************************
2060  Provide the string of the negated boolean value associated to the boolean
2061  given as a string. Returns false if the passed string does not correctly
2062  represent a boolean.
2063 ***************************************************************************/
2064
2065 bool lp_invert_boolean(const char *str, const char **inverse_str)
2066 {
2067         bool val;
2068
2069         if (!set_boolean(str, &val)) {
2070                 return false;
2071         }
2072
2073         *inverse_str = get_boolean(!val);
2074         return true;
2075 }
2076
2077 /***************************************************************************
2078  Provide the canonical string representation of a boolean value given
2079  as a string. Return true on success, false if the string given does
2080  not correctly represent a boolean.
2081 ***************************************************************************/
2082
2083 bool lp_canonicalize_boolean(const char *str, const char**canon_str)
2084 {
2085         bool val;
2086
2087         if (!set_boolean(str, &val)) {
2088                 return false;
2089         }
2090
2091         *canon_str = get_boolean(val);
2092         return true;
2093 }
2094
2095 /***************************************************************************
2096 Find a service by name. Otherwise works like get_service.
2097 ***************************************************************************/
2098
2099 int getservicebyname(const char *pszServiceName, struct loadparm_service *pserviceDest)
2100 {
2101         int iService = -1;
2102         char *canon_name;
2103         TDB_DATA data;
2104         NTSTATUS status;
2105
2106         if (ServiceHash == NULL) {
2107                 return -1;
2108         }
2109
2110         canon_name = canonicalize_servicename(talloc_tos(), pszServiceName);
2111
2112         status = dbwrap_fetch_bystring(ServiceHash, canon_name, canon_name,
2113                                        &data);
2114
2115         if (NT_STATUS_IS_OK(status) &&
2116             (data.dptr != NULL) &&
2117             (data.dsize == sizeof(iService)))
2118         {
2119                 memcpy(&iService, data.dptr, sizeof(iService));
2120         }
2121
2122         TALLOC_FREE(canon_name);
2123
2124         if ((iService != -1) && (LP_SNUM_OK(iService))
2125             && (pserviceDest != NULL)) {
2126                 copy_service(pserviceDest, ServicePtrs[iService], NULL);
2127         }
2128
2129         return (iService);
2130 }
2131
2132 /* Return a pointer to a service by name.  Unlike getservicebyname, it does not copy the service */
2133 struct loadparm_service *lp_service(const char *pszServiceName)
2134 {
2135         int iService = getservicebyname(pszServiceName, NULL);
2136         if (iService == -1 || !LP_SNUM_OK(iService)) {
2137                 return NULL;
2138         }
2139         return ServicePtrs[iService];
2140 }
2141
2142 struct loadparm_service *lp_servicebynum(int snum)
2143 {
2144         if ((snum == -1) || !LP_SNUM_OK(snum)) {
2145                 return NULL;
2146         }
2147         return ServicePtrs[snum];
2148 }
2149
2150 struct loadparm_service *lp_default_loadparm_service(void)
2151 {
2152         return &sDefault;
2153 }
2154
2155 static struct smbconf_ctx *lp_smbconf_ctx(void)
2156 {
2157         sbcErr err;
2158         static struct smbconf_ctx *conf_ctx = NULL;
2159
2160         if (conf_ctx == NULL) {
2161                 err = smbconf_init(NULL, &conf_ctx, "registry:");
2162                 if (!SBC_ERROR_IS_OK(err)) {
2163                         DEBUG(1, ("error initializing registry configuration: "
2164                                   "%s\n", sbcErrorString(err)));
2165                         conf_ctx = NULL;
2166                 }
2167         }
2168
2169         return conf_ctx;
2170 }
2171
2172 static bool process_smbconf_service(struct smbconf_service *service)
2173 {
2174         uint32_t count;
2175         bool ret;
2176
2177         if (service == NULL) {
2178                 return false;
2179         }
2180
2181         ret = lp_do_section(service->name, NULL);
2182         if (ret != true) {
2183                 return false;
2184         }
2185         for (count = 0; count < service->num_params; count++) {
2186
2187                 if (!bInGlobalSection && bGlobalOnly) {
2188                         ret = true;
2189                 } else {
2190                         const char *pszParmName = service->param_names[count];
2191                         const char *pszParmValue = service->param_values[count];
2192
2193                         DEBUGADD(4, ("doing parameter %s = %s\n", pszParmName, pszParmValue));
2194
2195                         ret = lp_do_parameter(bInGlobalSection ? -2 : iServiceIndex,
2196                                               pszParmName, pszParmValue);
2197                 }
2198
2199                 if (ret != true) {
2200                         return false;
2201                 }
2202         }
2203         if (iServiceIndex >= 0) {
2204                 return lpcfg_service_ok(ServicePtrs[iServiceIndex]);
2205         }
2206         return true;
2207 }
2208
2209 /**
2210  * load a service from registry and activate it
2211  */
2212 bool process_registry_service(const char *service_name)
2213 {
2214         sbcErr err;
2215         struct smbconf_service *service = NULL;
2216         TALLOC_CTX *mem_ctx = talloc_stackframe();
2217         struct smbconf_ctx *conf_ctx = lp_smbconf_ctx();
2218         bool ret = false;
2219
2220         if (conf_ctx == NULL) {
2221                 goto done;
2222         }
2223
2224         DEBUG(5, ("process_registry_service: service name %s\n", service_name));
2225
2226         if (!smbconf_share_exists(conf_ctx, service_name)) {
2227                 /*
2228                  * Registry does not contain data for this service (yet),
2229                  * but make sure lp_load doesn't return false.
2230                  */
2231                 ret = true;
2232                 goto done;
2233         }
2234
2235         err = smbconf_get_share(conf_ctx, mem_ctx, service_name, &service);
2236         if (!SBC_ERROR_IS_OK(err)) {
2237                 goto done;
2238         }
2239
2240         ret = process_smbconf_service(service);
2241         if (!ret) {
2242                 goto done;
2243         }
2244
2245         /* store the csn */
2246         smbconf_changed(conf_ctx, &conf_last_csn, NULL, NULL);
2247
2248 done:
2249         TALLOC_FREE(mem_ctx);
2250         return ret;
2251 }
2252
2253 /*
2254  * process_registry_globals
2255  */
2256 static bool process_registry_globals(void)
2257 {
2258         bool ret;
2259
2260         add_to_file_list(NULL, &file_lists, INCLUDE_REGISTRY_NAME, INCLUDE_REGISTRY_NAME);
2261
2262         if (!bInGlobalSection && bGlobalOnly) {
2263                 ret = true;
2264         } else {
2265                 const char *pszParmName = "registry shares";
2266                 const char *pszParmValue = "yes";
2267
2268                 DEBUGADD(4, ("doing parameter %s = %s\n", pszParmName, pszParmValue));
2269
2270                 ret = lp_do_parameter(bInGlobalSection ? -2 : iServiceIndex,
2271                                       pszParmName, pszParmValue);
2272         }
2273
2274         if (!ret) {
2275                 return ret;
2276         }
2277
2278         return process_registry_service(GLOBAL_NAME);
2279 }
2280
2281 bool process_registry_shares(void)
2282 {
2283         sbcErr err;
2284         uint32_t count;
2285         struct smbconf_service **service = NULL;
2286         uint32_t num_shares = 0;
2287         TALLOC_CTX *mem_ctx = talloc_stackframe();
2288         struct smbconf_ctx *conf_ctx = lp_smbconf_ctx();
2289         bool ret = false;
2290
2291         if (conf_ctx == NULL) {
2292                 goto done;
2293         }
2294
2295         err = smbconf_get_config(conf_ctx, mem_ctx, &num_shares, &service);
2296         if (!SBC_ERROR_IS_OK(err)) {
2297                 goto done;
2298         }
2299
2300         ret = true;
2301
2302         for (count = 0; count < num_shares; count++) {
2303                 if (strequal(service[count]->name, GLOBAL_NAME)) {
2304                         continue;
2305                 }
2306                 ret = process_smbconf_service(service[count]);
2307                 if (!ret) {
2308                         goto done;
2309                 }
2310         }
2311
2312         /* store the csn */
2313         smbconf_changed(conf_ctx, &conf_last_csn, NULL, NULL);
2314
2315 done:
2316         TALLOC_FREE(mem_ctx);
2317         return ret;
2318 }
2319
2320 /**
2321  * reload those shares from registry that are already
2322  * activated in the services array.
2323  */
2324 static bool reload_registry_shares(void)
2325 {
2326         int i;
2327         bool ret = true;
2328
2329         for (i = 0; i < iNumServices; i++) {
2330                 if (!VALID(i)) {
2331                         continue;
2332                 }
2333
2334                 if (ServicePtrs[i]->usershare == USERSHARE_VALID) {
2335                         continue;
2336                 }
2337
2338                 ret = process_registry_service(ServicePtrs[i]->szService);
2339                 if (!ret) {
2340                         goto done;
2341                 }
2342         }
2343
2344 done:
2345         return ret;
2346 }
2347
2348
2349 #define MAX_INCLUDE_DEPTH 100
2350
2351 static uint8_t include_depth;
2352
2353 /**
2354  * Free the file lists
2355  */
2356 static void free_file_list(void)
2357 {
2358         struct file_lists *f;
2359         struct file_lists *next;
2360
2361         f = file_lists;
2362         while( f ) {
2363                 next = f->next;
2364                 TALLOC_FREE( f );
2365                 f = next;
2366         }
2367         file_lists = NULL;
2368 }
2369
2370
2371 /**
2372  * Utility function for outsiders to check if we're running on registry.
2373  */
2374 bool lp_config_backend_is_registry(void)
2375 {
2376         return (lp_config_backend() == CONFIG_BACKEND_REGISTRY);
2377 }
2378
2379 /**
2380  * Utility function to check if the config backend is FILE.
2381  */
2382 bool lp_config_backend_is_file(void)
2383 {
2384         return (lp_config_backend() == CONFIG_BACKEND_FILE);
2385 }
2386
2387 /*******************************************************************
2388  Check if a config file has changed date.
2389 ********************************************************************/
2390
2391 bool lp_file_list_changed(void)
2392 {
2393         struct file_lists *f = file_lists;
2394
2395         DEBUG(6, ("lp_file_list_changed()\n"));
2396
2397         while (f) {
2398                 if (strequal(f->name, INCLUDE_REGISTRY_NAME)) {
2399                         struct smbconf_ctx *conf_ctx = lp_smbconf_ctx();
2400
2401                         if (conf_ctx == NULL) {
2402                                 return false;
2403                         }
2404                         if (smbconf_changed(conf_ctx, &conf_last_csn, NULL,
2405                                             NULL))
2406                         {
2407                                 DEBUGADD(6, ("registry config changed\n"));
2408                                 return true;
2409                         }
2410                 } else {
2411                         time_t mod_time;
2412                         char *n2 = NULL;
2413
2414                         n2 = talloc_sub_basic(talloc_tos(),
2415                                               get_current_username(),
2416                                               get_current_user_info_domain(),
2417                                               f->name);
2418                         if (!n2) {
2419                                 return false;
2420                         }
2421                         DEBUGADD(6, ("file %s -> %s  last mod_time: %s\n",
2422                                      f->name, n2, ctime(&f->modtime)));
2423
2424                         mod_time = file_modtime(n2);
2425
2426                         if (mod_time &&
2427                             ((f->modtime != mod_time) ||
2428                              (f->subfname == NULL) ||
2429                              (strcmp(n2, f->subfname) != 0)))
2430                         {
2431                                 DEBUGADD(6,
2432                                          ("file %s modified: %s\n", n2,
2433                                           ctime(&mod_time)));
2434                                 f->modtime = mod_time;
2435                                 TALLOC_FREE(f->subfname);
2436                                 f->subfname = talloc_strdup(f, n2);
2437                                 if (f->subfname == NULL) {
2438                                         smb_panic("talloc_strdup failed");
2439                                 }
2440                                 TALLOC_FREE(n2);
2441                                 return true;
2442                         }
2443                         TALLOC_FREE(n2);
2444                 }
2445                 f = f->next;
2446         }
2447         return false;
2448 }
2449
2450
2451 /**
2452  * Initialize iconv conversion descriptors.
2453  *
2454  * This is called the first time it is needed, and also called again
2455  * every time the configuration is reloaded, because the charset or
2456  * codepage might have changed.
2457  **/
2458 static void init_iconv(void)
2459 {
2460         struct smb_iconv_handle *ret = NULL;
2461
2462         ret = reinit_iconv_handle(NULL,
2463                                   lp_dos_charset(),
2464                                   lp_unix_charset());
2465         if (ret == NULL) {
2466                 smb_panic("reinit_iconv_handle failed");
2467         }
2468 }
2469
2470 /***************************************************************************
2471  Handle the include operation.
2472 ***************************************************************************/
2473 static bool bAllowIncludeRegistry = true;
2474
2475 bool lp_include(struct loadparm_context *lp_ctx, struct loadparm_service *service,
2476                 const char *pszParmValue, char **ptr)
2477 {
2478         char *fname;
2479
2480         if (include_depth >= MAX_INCLUDE_DEPTH) {
2481                 DEBUG(0, ("Error: Maximum include depth (%u) exceeded!\n",
2482                           include_depth));
2483                 return false;
2484         }
2485
2486         if (strequal(pszParmValue, INCLUDE_REGISTRY_NAME)) {
2487                 if (!bAllowIncludeRegistry) {
2488                         return true;
2489                 }
2490                 if (lp_ctx->bInGlobalSection) {
2491                         bool ret;
2492                         include_depth++;
2493                         ret = process_registry_globals();
2494                         include_depth--;
2495                         return ret;
2496                 } else {
2497                         DEBUG(1, ("\"include = registry\" only effective "
2498                                   "in %s section\n", GLOBAL_NAME));
2499                         return false;
2500                 }
2501         }
2502
2503         fname = talloc_sub_basic(talloc_tos(), get_current_username(),
2504                                  get_current_user_info_domain(),
2505                                  pszParmValue);
2506
2507         add_to_file_list(NULL, &file_lists, pszParmValue, fname);
2508
2509         if (service == NULL) {
2510                 lpcfg_string_set(Globals.ctx, ptr, fname);
2511         } else {
2512                 lpcfg_string_set(service, ptr, fname);
2513         }
2514
2515         if (file_exist(fname)) {
2516                 bool ret;
2517                 include_depth++;
2518                 ret = pm_process(fname, lp_do_section, do_parameter, lp_ctx);
2519                 include_depth--;
2520                 TALLOC_FREE(fname);
2521                 return ret;
2522         }
2523
2524         DEBUG(2, ("Can't find include file %s\n", fname));
2525         TALLOC_FREE(fname);
2526         return true;
2527 }
2528
2529 bool lp_idmap_range(const char *domain_name, uint32_t *low, uint32_t *high)
2530 {
2531         char *config_option = NULL;
2532         const char *range = NULL;
2533         bool ret = false;
2534
2535         SMB_ASSERT(low != NULL);
2536         SMB_ASSERT(high != NULL);
2537
2538         if ((domain_name == NULL) || (domain_name[0] == '\0')) {
2539                 domain_name = "*";
2540         }
2541
2542         config_option = talloc_asprintf(talloc_tos(), "idmap config %s",
2543                                         domain_name);
2544         if (config_option == NULL) {
2545                 DEBUG(0, ("out of memory\n"));
2546                 return false;
2547         }
2548
2549         range = lp_parm_const_string(-1, config_option, "range", NULL);
2550         if (range == NULL) {
2551                 DEBUG(1, ("idmap range not specified for domain '%s'\n", domain_name));
2552                 goto done;
2553         }
2554
2555         if (sscanf(range, "%u - %u", low, high) != 2) {
2556                 DEBUG(1, ("error parsing idmap range '%s' for domain '%s'\n",
2557                           range, domain_name));
2558                 goto done;
2559         }
2560
2561         ret = true;
2562
2563 done:
2564         talloc_free(config_option);
2565         return ret;
2566
2567 }
2568
2569 bool lp_idmap_default_range(uint32_t *low, uint32_t *high)
2570 {
2571         return lp_idmap_range("*", low, high);
2572 }
2573
2574 const char *lp_idmap_backend(const char *domain_name)
2575 {
2576         char *config_option = NULL;
2577         const char *backend = NULL;
2578
2579         if ((domain_name == NULL) || (domain_name[0] == '\0')) {
2580                 domain_name = "*";
2581         }
2582
2583         config_option = talloc_asprintf(talloc_tos(), "idmap config %s",
2584                                         domain_name);
2585         if (config_option == NULL) {
2586                 DEBUG(0, ("out of memory\n"));
2587                 return false;
2588         }
2589
2590         backend = lp_parm_const_string(-1, config_option, "backend", NULL);
2591         if (backend == NULL) {
2592                 DEBUG(1, ("idmap backend not specified for domain '%s'\n", domain_name));
2593                 goto done;
2594         }
2595
2596 done:
2597         talloc_free(config_option);
2598         return backend;
2599 }
2600
2601 const char *lp_idmap_default_backend(void)
2602 {
2603         return lp_idmap_backend("*");
2604 }
2605
2606 /***************************************************************************
2607  Handle ldap suffixes - default to ldapsuffix if sub-suffixes are not defined.
2608 ***************************************************************************/
2609
2610 static const char *append_ldap_suffix(TALLOC_CTX *ctx, const char *str )
2611 {
2612         const char *suffix_string;
2613
2614         suffix_string = talloc_asprintf(ctx, "%s,%s", str,
2615                                         Globals.ldap_suffix );
2616         if ( !suffix_string ) {
2617                 DEBUG(0,("append_ldap_suffix: talloc_asprintf() failed!\n"));
2618                 return "";
2619         }
2620
2621         return suffix_string;
2622 }
2623
2624 const char *lp_ldap_machine_suffix(TALLOC_CTX *ctx)
2625 {
2626         if (Globals._ldap_machine_suffix[0])
2627                 return append_ldap_suffix(ctx, Globals._ldap_machine_suffix);
2628
2629         return talloc_strdup(ctx, Globals.ldap_suffix);
2630 }
2631
2632 const char *lp_ldap_user_suffix(TALLOC_CTX *ctx)
2633 {
2634         if (Globals._ldap_user_suffix[0])
2635                 return append_ldap_suffix(ctx, Globals._ldap_user_suffix);
2636
2637         return talloc_strdup(ctx, Globals.ldap_suffix);
2638 }
2639
2640 const char *lp_ldap_group_suffix(TALLOC_CTX *ctx)
2641 {
2642         if (Globals._ldap_group_suffix[0])
2643                 return append_ldap_suffix(ctx, Globals._ldap_group_suffix);
2644
2645         return talloc_strdup(ctx, Globals.ldap_suffix);
2646 }
2647
2648 const char *lp_ldap_idmap_suffix(TALLOC_CTX *ctx)
2649 {
2650         if (Globals._ldap_idmap_suffix[0])
2651                 return append_ldap_suffix(ctx, Globals._ldap_idmap_suffix);
2652
2653         return talloc_strdup(ctx, Globals.ldap_suffix);
2654 }
2655
2656 /**
2657   return the parameter pointer for a parameter
2658 */
2659 void *lp_parm_ptr(struct loadparm_service *service, struct parm_struct *parm)
2660 {
2661         if (service == NULL) {
2662                 if (parm->p_class == P_LOCAL)
2663                         return (void *)(((char *)&sDefault)+parm->offset);
2664                 else if (parm->p_class == P_GLOBAL)
2665                         return (void *)(((char *)&Globals)+parm->offset);
2666                 else return NULL;
2667         } else {
2668                 return (void *)(((char *)service) + parm->offset);
2669         }
2670 }
2671
2672 /***************************************************************************
2673  Process a parameter for a particular service number. If snum < 0
2674  then assume we are in the globals.
2675 ***************************************************************************/
2676
2677 bool lp_do_parameter(int snum, const char *pszParmName, const char *pszParmValue)
2678 {
2679         TALLOC_CTX *frame = talloc_stackframe();
2680         struct loadparm_context *lp_ctx;
2681         bool ok;
2682
2683         lp_ctx = setup_lp_context(frame);
2684         if (lp_ctx == NULL) {
2685                 TALLOC_FREE(frame);
2686                 return false;
2687         }
2688
2689         if (snum < 0) {
2690                 ok = lpcfg_do_global_parameter(lp_ctx, pszParmName, pszParmValue);
2691         } else {
2692                 ok = lpcfg_do_service_parameter(lp_ctx, ServicePtrs[snum],
2693                                                 pszParmName, pszParmValue);
2694         }
2695
2696         TALLOC_FREE(frame);
2697
2698         return ok;
2699 }
2700
2701 /***************************************************************************
2702 set a parameter, marking it with FLAG_CMDLINE. Parameters marked as
2703 FLAG_CMDLINE won't be overridden by loads from smb.conf.
2704 ***************************************************************************/
2705
2706 static bool lp_set_cmdline_helper(const char *pszParmName, const char *pszParmValue)
2707 {
2708         int parmnum, i;
2709         parmnum = lpcfg_map_parameter(pszParmName);
2710         if (parmnum >= 0) {
2711                 flags_list[parmnum] &= ~FLAG_CMDLINE;
2712                 if (!lp_do_parameter(-1, pszParmName, pszParmValue)) {
2713                         return false;
2714                 }
2715                 flags_list[parmnum] |= FLAG_CMDLINE;
2716
2717                 /* we have to also set FLAG_CMDLINE on aliases.  Aliases must
2718                  * be grouped in the table, so we don't have to search the
2719                  * whole table */
2720                 for (i=parmnum-1;
2721                      i>=0 && parm_table[i].offset == parm_table[parmnum].offset
2722                              && parm_table[i].p_class == parm_table[parmnum].p_class;
2723                      i--) {
2724                         flags_list[i] |= FLAG_CMDLINE;
2725                 }
2726                 for (i=parmnum+1;i<num_parameters() && parm_table[i].offset == parm_table[parmnum].offset
2727                              && parm_table[i].p_class == parm_table[parmnum].p_class;i++) {
2728                         flags_list[i] |= FLAG_CMDLINE;
2729                 }
2730
2731                 return true;
2732         }
2733
2734         /* it might be parametric */
2735         if (strchr(pszParmName, ':') != NULL) {
2736                 set_param_opt(NULL, &Globals.param_opt, pszParmName, pszParmValue, FLAG_CMDLINE);
2737                 return true;
2738         }
2739
2740         DEBUG(0, ("Ignoring unknown parameter \"%s\"\n",  pszParmName));
2741         return false;
2742 }
2743
2744 bool lp_set_cmdline(const char *pszParmName, const char *pszParmValue)
2745 {
2746         bool ret;
2747         TALLOC_CTX *frame = talloc_stackframe();
2748         struct loadparm_context *lp_ctx;
2749
2750         lp_ctx = setup_lp_context(frame);
2751         if (lp_ctx == NULL) {
2752                 TALLOC_FREE(frame);
2753                 return false;
2754         }
2755
2756         ret = lpcfg_set_cmdline(lp_ctx, pszParmName, pszParmValue);
2757
2758         TALLOC_FREE(frame);
2759         return ret;
2760 }
2761
2762 /***************************************************************************
2763  Process a parameter.
2764 ***************************************************************************/
2765
2766 static bool do_parameter(const char *pszParmName, const char *pszParmValue,
2767                          void *userdata)
2768 {
2769         if (!bInGlobalSection && bGlobalOnly)
2770                 return true;
2771
2772         DEBUGADD(4, ("doing parameter %s = %s\n", pszParmName, pszParmValue));
2773
2774         if (bInGlobalSection) {
2775                 return lpcfg_do_global_parameter(userdata, pszParmName, pszParmValue);
2776         } else {
2777                 return lpcfg_do_service_parameter(userdata, ServicePtrs[iServiceIndex],
2778                                                   pszParmName, pszParmValue);
2779         }
2780 }
2781
2782
2783 static const char *ad_dc_req_vfs_mods[] = {"dfs_samba4", "acl_xattr", NULL};
2784
2785 /*
2786  * check that @vfs_objects includes all vfs modules required by an AD DC.
2787  */
2788 static bool check_ad_dc_required_mods(const char **vfs_objects)
2789 {
2790         int i;
2791         int j;
2792         int got_req;
2793
2794         for (i = 0; ad_dc_req_vfs_mods[i] != NULL; i++) {
2795                 got_req = false;
2796                 for (j = 0; vfs_objects[j] != NULL; j++) {
2797                         if (!strwicmp(ad_dc_req_vfs_mods[i], vfs_objects[j])) {
2798                                 got_req = true;
2799                                 break;
2800                         }
2801                 }
2802                 if (!got_req) {
2803                         DEBUG(0, ("vfs objects specified without required AD "
2804                                   "DC module: %s\n", ad_dc_req_vfs_mods[i]));
2805                         return false;
2806                 }
2807         }
2808
2809         DEBUG(6, ("vfs objects specified with all required AD DC modules\n"));
2810         return true;
2811 }
2812
2813
2814 /***************************************************************************
2815  Initialize any local variables in the sDefault table, after parsing a
2816  [globals] section.
2817 ***************************************************************************/
2818
2819 static void init_locals(void)
2820 {
2821         /*
2822          * We run this check once the [globals] is parsed, to force
2823          * the VFS objects and other per-share settings we need for
2824          * the standard way a AD DC is operated.  We may change these
2825          * as our code evolves, which is why we force these settings.
2826          *
2827          * We can't do this at the end of lp_load_ex(), as by that
2828          * point the services have been loaded and they will already
2829          * have "" as their vfs objects.
2830          */
2831         if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
2832                 const char **vfs_objects = lp_vfs_objects(-1);
2833                 if (vfs_objects != NULL) {
2834                         /* ignore return, only warn if modules are missing */
2835                         check_ad_dc_required_mods(vfs_objects);
2836                 } else {
2837                         if (lp_parm_const_string(-1, "xattr_tdb", "file", NULL)) {
2838                                 lp_do_parameter(-1, "vfs objects", "dfs_samba4 acl_xattr xattr_tdb");
2839                         } else if (lp_parm_const_string(-1, "posix", "eadb", NULL)) {
2840                                 lp_do_parameter(-1, "vfs objects", "dfs_samba4 acl_xattr posix_eadb");
2841                         } else {
2842                                 lp_do_parameter(-1, "vfs objects", "dfs_samba4 acl_xattr");
2843                         }
2844                 }
2845
2846                 lp_do_parameter(-1, "map hidden", "no");
2847                 lp_do_parameter(-1, "map system", "no");
2848                 lp_do_parameter(-1, "map readonly", "no");
2849                 lp_do_parameter(-1, "map archive", "no");
2850                 lp_do_parameter(-1, "store dos attributes", "yes");
2851         }
2852 }
2853
2854 /***************************************************************************
2855  Process a new section (service). At this stage all sections are services.
2856  Later we'll have special sections that permit server parameters to be set.
2857  Returns true on success, false on failure.
2858 ***************************************************************************/
2859
2860 bool lp_do_section(const char *pszSectionName, void *userdata)
2861 {
2862         struct loadparm_context *lp_ctx = (struct loadparm_context *)userdata;
2863         bool bRetval;
2864         bool isglobal = ((strwicmp(pszSectionName, GLOBAL_NAME) == 0) ||
2865                          (strwicmp(pszSectionName, GLOBAL_NAME2) == 0));
2866
2867         /* if we were in a global section then do the local inits */
2868         if (bInGlobalSection && !isglobal)
2869                 init_locals();
2870
2871         /* if we've just struck a global section, note the fact. */
2872         bInGlobalSection = isglobal;
2873         if (lp_ctx != NULL) {
2874                 lp_ctx->bInGlobalSection = isglobal;
2875         }
2876
2877         /* check for multiple global sections */
2878         if (bInGlobalSection) {
2879                 DEBUG(3, ("Processing section \"[%s]\"\n", pszSectionName));
2880                 return true;
2881         }
2882
2883         if (!bInGlobalSection && bGlobalOnly)
2884                 return true;
2885
2886         /* if we have a current service, tidy it up before moving on */
2887         bRetval = true;
2888
2889         if (iServiceIndex >= 0)
2890                 bRetval = lpcfg_service_ok(ServicePtrs[iServiceIndex]);
2891
2892         /* if all is still well, move to the next record in the services array */
2893         if (bRetval) {
2894                 /* We put this here to avoid an odd message order if messages are */
2895                 /* issued by the post-processing of a previous section. */
2896                 DEBUG(2, ("Processing section \"[%s]\"\n", pszSectionName));
2897
2898                 iServiceIndex = add_a_service(&sDefault, pszSectionName);
2899                 if (iServiceIndex < 0) {
2900                         DEBUG(0, ("Failed to add a new service\n"));
2901                         return false;
2902                 }
2903                 /* Clean all parametric options for service */
2904                 /* They will be added during parsing again */
2905                 free_param_opts(&ServicePtrs[iServiceIndex]->param_opt);
2906         }
2907
2908         return bRetval;
2909 }
2910
2911 /***************************************************************************
2912  Display the contents of a parameter of a single services record.
2913 ***************************************************************************/
2914
2915 bool dump_a_parameter(int snum, char *parm_name, FILE * f, bool isGlobal)
2916 {
2917         bool result = false;
2918         struct loadparm_context *lp_ctx;
2919
2920         lp_ctx = setup_lp_context(talloc_tos());
2921         if (lp_ctx == NULL) {
2922                 return false;
2923         }
2924
2925         if (isGlobal) {
2926                 result = lpcfg_dump_a_parameter(lp_ctx, NULL, parm_name, f);
2927         } else {
2928                 result = lpcfg_dump_a_parameter(lp_ctx, ServicePtrs[snum], parm_name, f);
2929         }
2930         TALLOC_FREE(lp_ctx);
2931         return result;
2932 }
2933
2934 #if 0
2935 /***************************************************************************
2936  Display the contents of a single copy structure.
2937 ***************************************************************************/
2938 static void dump_copy_map(bool *pcopymap)
2939 {
2940         int i;
2941         if (!pcopymap)
2942                 return;
2943
2944         printf("\n\tNon-Copied parameters:\n");
2945
2946         for (i = 0; parm_table[i].label; i++)
2947                 if (parm_table[i].p_class == P_LOCAL &&
2948                     parm_table[i].ptr && !pcopymap[i] &&
2949                     (i == 0 || (parm_table[i].ptr != parm_table[i - 1].ptr)))
2950                 {
2951                         printf("\t\t%s\n", parm_table[i].label);
2952                 }
2953 }
2954 #endif
2955
2956 /***************************************************************************
2957  Return TRUE if the passed service number is within range.
2958 ***************************************************************************/
2959
2960 bool lp_snum_ok(int iService)
2961 {
2962         return (LP_SNUM_OK(iService) && ServicePtrs[iService]->available);
2963 }
2964
2965 /***************************************************************************
2966  Auto-load some home services.
2967 ***************************************************************************/
2968
2969 static void lp_add_auto_services(const char *str)
2970 {
2971         char *s;
2972         char *p;
2973         int homes;
2974         char *saveptr;
2975
2976         if (!str)
2977                 return;
2978
2979         s = talloc_strdup(talloc_tos(), str);
2980         if (!s) {
2981                 smb_panic("talloc_strdup failed");
2982                 return;
2983         }
2984
2985         homes = lp_servicenumber(HOMES_NAME);
2986
2987         for (p = strtok_r(s, LIST_SEP, &saveptr); p;
2988              p = strtok_r(NULL, LIST_SEP, &saveptr)) {
2989                 char *home;
2990
2991                 if (lp_servicenumber(p) >= 0)
2992                         continue;
2993
2994                 home = get_user_home_dir(talloc_tos(), p);
2995
2996                 if (home && home[0] && homes >= 0)
2997                         lp_add_home(p, homes, p, home);
2998
2999                 TALLOC_FREE(home);
3000         }
3001         TALLOC_FREE(s);
3002 }
3003
3004 /***************************************************************************
3005  Auto-load one printer.
3006 ***************************************************************************/
3007
3008 void lp_add_one_printer(const char *name, const char *comment,
3009                         const char *location, void *pdata)
3010 {
3011         int printers = lp_servicenumber(PRINTERS_NAME);
3012         int i;
3013
3014         if (lp_servicenumber(name) < 0) {
3015                 lp_add_printer(name, printers);
3016                 if ((i = lp_servicenumber(name)) >= 0) {
3017                         lpcfg_string_set(ServicePtrs[i],
3018                                          &ServicePtrs[i]->comment, comment);
3019                         ServicePtrs[i]->autoloaded = true;
3020                 }
3021         }
3022 }
3023
3024 /***************************************************************************
3025  Have we loaded a services file yet?
3026 ***************************************************************************/
3027
3028 bool lp_loaded(void)
3029 {
3030         return (bLoaded);
3031 }
3032
3033 /***************************************************************************
3034  Unload unused services.
3035 ***************************************************************************/
3036
3037 void lp_killunused(struct smbd_server_connection *sconn,
3038                    bool (*snumused) (struct smbd_server_connection *, int))
3039 {
3040         int i;
3041         for (i = 0; i < iNumServices; i++) {
3042                 if (!VALID(i))
3043                         continue;
3044
3045                 /* don't kill autoloaded or usershare services */
3046                 if ( ServicePtrs[i]->autoloaded ||
3047                                 ServicePtrs[i]->usershare == USERSHARE_VALID) {
3048                         continue;
3049                 }
3050
3051                 if (!snumused || !snumused(sconn, i)) {
3052                         free_service_byindex(i);
3053                 }
3054         }
3055 }
3056
3057 /**
3058  * Kill all except autoloaded and usershare services - convenience wrapper
3059  */
3060 void lp_kill_all_services(void)
3061 {
3062         lp_killunused(NULL, NULL);
3063 }
3064
3065 /***************************************************************************
3066  Unload a service.
3067 ***************************************************************************/
3068
3069 void lp_killservice(int iServiceIn)
3070 {
3071         if (VALID(iServiceIn)) {
3072                 free_service_byindex(iServiceIn);
3073         }
3074 }
3075
3076 /***************************************************************************
3077  Save the curent values of all global and sDefault parameters into the
3078  defaults union. This allows testparm to show only the
3079  changed (ie. non-default) parameters.
3080 ***************************************************************************/
3081
3082 static void lp_save_defaults(void)
3083 {
3084         int i;
3085         struct parmlist_entry * parm;
3086         for (i = 0; parm_table[i].label; i++) {
3087                 if (!(flags_list[i] & FLAG_CMDLINE)) {
3088                         flags_list[i] |= FLAG_DEFAULT;
3089                 }
3090
3091                 if (i > 0 && parm_table[i].offset == parm_table[i - 1].offset
3092                     && parm_table[i].p_class == parm_table[i - 1].p_class)
3093                         continue;
3094                 switch (parm_table[i].type) {
3095                         case P_LIST:
3096                         case P_CMDLIST:
3097                                 parm_table[i].def.lvalue = str_list_copy(
3098                                         NULL, *(const char ***)lp_parm_ptr(NULL, &parm_table[i]));
3099                                 break;
3100                         case P_STRING:
3101                         case P_USTRING:
3102                                 lpcfg_string_set(
3103                                         Globals.ctx,
3104                                         &parm_table[i].def.svalue,
3105                                         *(char **)lp_parm_ptr(
3106                                                 NULL, &parm_table[i]));
3107                                 if (parm_table[i].def.svalue == NULL) {
3108                                         smb_panic("lpcfg_string_set() failed");
3109                                 }
3110                                 break;
3111                         case P_BOOL:
3112                         case P_BOOLREV:
3113                                 parm_table[i].def.bvalue =
3114                                         *(bool *)lp_parm_ptr(NULL, &parm_table[i]);
3115                                 break;
3116                         case P_CHAR:
3117                                 parm_table[i].def.cvalue =
3118                                         *(char *)lp_parm_ptr(NULL, &parm_table[i]);
3119                                 break;
3120                         case P_INTEGER:
3121                         case P_OCTAL:
3122                         case P_ENUM:
3123                         case P_BYTES:
3124                                 parm_table[i].def.ivalue =
3125                                         *(int *)lp_parm_ptr(NULL, &parm_table[i]);
3126                                 break;
3127                 }
3128         }
3129
3130         for (parm=Globals.param_opt; parm; parm=parm->next) {
3131                 if (!(parm->priority & FLAG_CMDLINE)) {
3132                         parm->priority |= FLAG_DEFAULT;
3133                 }
3134         }
3135
3136         for (parm=sDefault.param_opt; parm; parm=parm->next) {
3137                 if (!(parm->priority & FLAG_CMDLINE)) {
3138                         parm->priority |= FLAG_DEFAULT;
3139                 }
3140         }
3141
3142         defaults_saved = true;
3143 }
3144
3145 /***********************************************************
3146  If we should send plaintext/LANMAN passwords in the clinet
3147 ************************************************************/
3148
3149 static void set_allowed_client_auth(void)
3150 {
3151         if (Globals.client_ntlmv2_auth) {
3152                 Globals.client_lanman_auth = false;
3153         }
3154         if (!Globals.client_lanman_auth) {
3155                 Globals.client_plaintext_auth = false;
3156         }
3157 }
3158
3159 /***************************************************************************
3160  JRA.
3161  The following code allows smbd to read a user defined share file.
3162  Yes, this is my intent. Yes, I'm comfortable with that...
3163
3164  THE FOLLOWING IS SECURITY CRITICAL CODE.
3165
3166  It washes your clothes, it cleans your house, it guards you while you sleep...
3167  Do not f%^k with it....
3168 ***************************************************************************/
3169
3170 #define MAX_USERSHARE_FILE_SIZE (10*1024)
3171
3172 /***************************************************************************
3173  Check allowed stat state of a usershare file.
3174  Ensure we print out who is dicking with us so the admin can
3175  get their sorry ass fired.
3176 ***************************************************************************/
3177
3178 static bool check_usershare_stat(const char *fname,
3179                                  const SMB_STRUCT_STAT *psbuf)
3180 {
3181         if (!S_ISREG(psbuf->st_ex_mode)) {
3182                 DEBUG(0,("check_usershare_stat: file %s owned by uid %u is "
3183                         "not a regular file\n",
3184                         fname, (unsigned int)psbuf->st_ex_uid ));
3185                 return false;
3186         }
3187
3188         /* Ensure this doesn't have the other write bit set. */
3189         if (psbuf->st_ex_mode & S_IWOTH) {
3190                 DEBUG(0,("check_usershare_stat: file %s owned by uid %u allows "
3191                         "public write. Refusing to allow as a usershare file.\n",
3192                         fname, (unsigned int)psbuf->st_ex_uid ));
3193                 return false;
3194         }
3195
3196         /* Should be 10k or less. */
3197         if (psbuf->st_ex_size > MAX_USERSHARE_FILE_SIZE) {
3198                 DEBUG(0,("check_usershare_stat: file %s owned by uid %u is "
3199                         "too large (%u) to be a user share file.\n",
3200                         fname, (unsigned int)psbuf->st_ex_uid,
3201                         (unsigned int)psbuf->st_ex_size ));
3202                 return false;
3203         }
3204
3205         return true;
3206 }
3207
3208 /***************************************************************************
3209  Parse the contents of a usershare file.
3210 ***************************************************************************/
3211
3212 enum usershare_err parse_usershare_file(TALLOC_CTX *ctx,
3213                         SMB_STRUCT_STAT *psbuf,
3214                         const char *servicename,
3215                         int snum,
3216                         char **lines,
3217                         int numlines,
3218                         char **pp_sharepath,
3219                         char **pp_comment,
3220                         char **pp_cp_servicename,
3221                         struct security_descriptor **ppsd,
3222                         bool *pallow_guest)
3223 {
3224         const char **prefixallowlist = lp_usershare_prefix_allow_list();
3225         const char **prefixdenylist = lp_usershare_prefix_deny_list();
3226         int us_vers;
3227         DIR *dp;
3228         SMB_STRUCT_STAT sbuf;
3229         char *sharepath = NULL;
3230         char *comment = NULL;
3231
3232         *pp_sharepath = NULL;
3233         *pp_comment = NULL;
3234
3235         *pallow_guest = false;
3236
3237         if (numlines < 4) {
3238                 return USERSHARE_MALFORMED_FILE;
3239         }
3240
3241         if (strcmp(lines[0], "#VERSION 1") == 0) {
3242                 us_vers = 1;
3243         } else if (strcmp(lines[0], "#VERSION 2") == 0) {
3244                 us_vers = 2;
3245                 if (numlines < 5) {
3246                         return USERSHARE_MALFORMED_FILE;
3247                 }
3248         } else {
3249                 return USERSHARE_BAD_VERSION;
3250         }
3251
3252         if (strncmp(lines[1], "path=", 5) != 0) {
3253                 return USERSHARE_MALFORMED_PATH;
3254         }
3255
3256         sharepath = talloc_strdup(ctx, &lines[1][5]);
3257         if (!sharepath) {
3258                 return USERSHARE_POSIX_ERR;
3259         }
3260         trim_string(sharepath, " ", " ");
3261
3262         if (strncmp(lines[2], "comment=", 8) != 0) {
3263                 return USERSHARE_MALFORMED_COMMENT_DEF;
3264         }
3265
3266         comment = talloc_strdup(ctx, &lines[2][8]);
3267         if (!comment) {
3268                 return USERSHARE_POSIX_ERR;
3269         }
3270         trim_string(comment, " ", " ");
3271         trim_char(comment, '"', '"');
3272
3273         if (strncmp(lines[3], "usershare_acl=", 14) != 0) {
3274                 return USERSHARE_MALFORMED_ACL_DEF;
3275         }
3276
3277         if (!parse_usershare_acl(ctx, &lines[3][14], ppsd)) {
3278                 return USERSHARE_ACL_ERR;
3279         }
3280
3281         if (us_vers == 2) {
3282                 if (strncmp(lines[4], "guest_ok=", 9) != 0) {
3283                         return USERSHARE_MALFORMED_ACL_DEF;
3284                 }
3285                 if (lines[4][9] == 'y') {
3286                         *pallow_guest = true;
3287                 }
3288
3289                 /* Backwards compatible extension to file version #2. */
3290                 if (numlines > 5) {
3291                         if (strncmp(lines[5], "sharename=", 10) != 0) {
3292                                 return USERSHARE_MALFORMED_SHARENAME_DEF;
3293                         }
3294                         if (!strequal(&lines[5][10], servicename)) {
3295                                 return USERSHARE_BAD_SHARENAME;
3296                         }
3297                         *pp_cp_servicename = talloc_strdup(ctx, &lines[5][10]);
3298                         if (!*pp_cp_servicename) {
3299                                 return USERSHARE_POSIX_ERR;
3300                         }
3301                 }
3302         }
3303
3304         if (*pp_cp_servicename == NULL) {
3305                 *pp_cp_servicename = talloc_strdup(ctx, servicename);
3306                 if (!*pp_cp_servicename) {
3307                         return USERSHARE_POSIX_ERR;
3308                 }
3309         }
3310
3311         if (snum != -1 && (strcmp(sharepath, ServicePtrs[snum]->path) == 0)) {
3312                 /* Path didn't change, no checks needed. */
3313                 *pp_sharepath = sharepath;
3314                 *pp_comment = comment;
3315                 return USERSHARE_OK;
3316         }
3317
3318         /* The path *must* be absolute. */
3319         if (sharepath[0] != '/') {
3320                 DEBUG(2,("parse_usershare_file: share %s: path %s is not an absolute path.\n",
3321                         servicename, sharepath));
3322                 return USERSHARE_PATH_NOT_ABSOLUTE;
3323         }
3324
3325         /* If there is a usershare prefix deny list ensure one of these paths
3326            doesn't match the start of the user given path. */
3327         if (prefixdenylist) {
3328                 int i;
3329                 for ( i=0; prefixdenylist[i]; i++ ) {
3330                         DEBUG(10,("parse_usershare_file: share %s : checking prefixdenylist[%d]='%s' against %s\n",
3331                                 servicename, i, prefixdenylist[i], sharepath ));
3332                         if (memcmp( sharepath, prefixdenylist[i], strlen(prefixdenylist[i])) == 0) {
3333                                 DEBUG(2,("parse_usershare_file: share %s path %s starts with one of the "
3334                                         "usershare prefix deny list entries.\n",
3335                                         servicename, sharepath));
3336                                 return USERSHARE_PATH_IS_DENIED;
3337                         }
3338                 }
3339         }
3340
3341         /* If there is a usershare prefix allow list ensure one of these paths
3342            does match the start of the user given path. */
3343
3344         if (prefixallowlist) {
3345                 int i;
3346                 for ( i=0; prefixallowlist[i]; i++ ) {
3347                         DEBUG(10,("parse_usershare_file: share %s checking prefixallowlist[%d]='%s' against %s\n",
3348                                 servicename, i, prefixallowlist[i], sharepath ));
3349                         if (memcmp( sharepath, prefixallowlist[i], strlen(prefixallowlist[i])) == 0) {
3350                                 break;
3351                         }
3352                 }
3353                 if (prefixallowlist[i] == NULL) {
3354                         DEBUG(2,("parse_usershare_file: share %s path %s doesn't start with one of the "
3355                                 "usershare prefix allow list entries.\n",
3356                                 servicename, sharepath));
3357                         return USERSHARE_PATH_NOT_ALLOWED;
3358                 }
3359         }
3360
3361         /* Ensure this is pointing to a directory. */
3362         dp = opendir(sharepath);
3363
3364         if (!dp) {
3365                 DEBUG(2,("parse_usershare_file: share %s path %s is not a directory.\n",
3366                         servicename, sharepath));
3367                 return USERSHARE_PATH_NOT_DIRECTORY;
3368         }
3369
3370         /* Ensure the owner of the usershare file has permission to share
3371            this directory. */
3372
3373         if (sys_stat(sharepath, &sbuf, false) == -1) {
3374                 DEBUG(2,("parse_usershare_file: share %s : stat failed on path %s. %s\n",
3375                         servicename, sharepath, strerror(errno) ));
3376                 closedir(dp);
3377                 return USERSHARE_POSIX_ERR;
3378         }
3379
3380         closedir(dp);
3381
3382         if (!S_ISDIR(sbuf.st_ex_mode)) {
3383                 DEBUG(2,("parse_usershare_file: share %s path %s is not a directory.\n",
3384                         servicename, sharepath ));
3385                 return USERSHARE_PATH_NOT_DIRECTORY;
3386         }
3387
3388         /* Check if sharing is restricted to owner-only. */
3389         /* psbuf is the stat of the usershare definition file,
3390            sbuf is the stat of the target directory to be shared. */
3391
3392         if (lp_usershare_owner_only()) {
3393                 /* root can share anything. */
3394                 if ((psbuf->st_ex_uid != 0) && (sbuf.st_ex_uid != psbuf->st_ex_uid)) {
3395                         return USERSHARE_PATH_NOT_ALLOWED;
3396                 }
3397         }
3398
3399         *pp_sharepath = sharepath;
3400         *pp_comment = comment;
3401         return USERSHARE_OK;
3402 }
3403
3404 /***************************************************************************
3405  Deal with a usershare file.
3406  Returns:
3407         >= 0 - snum
3408         -1 - Bad name, invalid contents.
3409            - service name already existed and not a usershare, problem
3410             with permissions to share directory etc.
3411 ***************************************************************************/
3412
3413 static int process_usershare_file(const char *dir_name, const char *file_name, int snum_template)
3414 {
3415         SMB_STRUCT_STAT sbuf;
3416         SMB_STRUCT_STAT lsbuf;
3417         char *fname = NULL;
3418         char *sharepath = NULL;
3419         char *comment = NULL;
3420         char *cp_service_name = NULL;
3421         char **lines = NULL;
3422         int numlines = 0;
3423         int fd = -1;
3424         int iService = -1;
3425         TALLOC_CTX *ctx = talloc_stackframe();
3426         struct security_descriptor *psd = NULL;
3427         bool guest_ok = false;
3428         char *canon_name = NULL;
3429         bool added_service = false;
3430         int ret = -1;
3431         NTSTATUS status;
3432
3433         /* Ensure share name doesn't contain invalid characters. */
3434         if (!validate_net_name(file_name, INVALID_SHARENAME_CHARS, strlen(file_name))) {
3435                 DEBUG(0,("process_usershare_file: share name %s contains "
3436                         "invalid characters (any of %s)\n",
3437                         file_name, INVALID_SHARENAME_CHARS ));
3438                 goto out;
3439         }
3440
3441         canon_name = canonicalize_servicename(ctx, file_name);
3442         if (!canon_name) {
3443                 goto out;
3444         }
3445
3446         fname = talloc_asprintf(ctx, "%s/%s", dir_name, file_name);
3447         if (!fname) {
3448                 goto out;
3449         }
3450
3451         /* Minimize the race condition by doing an lstat before we
3452            open and fstat. Ensure this isn't a symlink link. */
3453
3454         if (sys_lstat(fname, &lsbuf, false) != 0) {
3455                 if (errno == ENOENT) {
3456                         /* Unknown share requested. Just ignore. */
3457                         goto out;
3458                 }
3459                 /* Only log messages for meaningful problems. */
3460                 DEBUG(0,("process_usershare_file: stat of %s failed. %s\n",
3461                         fname, strerror(errno) ));
3462                 goto out;
3463         }
3464
3465         /* This must be a regular file, not a symlink, directory or
3466            other strange filetype. */
3467         if (!check_usershare_stat(fname, &lsbuf)) {
3468                 goto out;
3469         }
3470
3471         {
3472                 TDB_DATA data;
3473
3474                 status = dbwrap_fetch_bystring(ServiceHash, canon_name,
3475                                                canon_name, &data);
3476
3477                 iService = -1;
3478
3479                 if (NT_STATUS_IS_OK(status) &&
3480                     (data.dptr != NULL) &&
3481                     (data.dsize == sizeof(iService))) {
3482                         memcpy(&iService, data.dptr, sizeof(iService));
3483                 }
3484         }
3485
3486         if (iService != -1 &&
3487             timespec_compare(&ServicePtrs[iService]->usershare_last_mod,
3488                              &lsbuf.st_ex_mtime) == 0) {
3489                 /* Nothing changed - Mark valid and return. */
3490                 DEBUG(10,("process_usershare_file: service %s not changed.\n",
3491                         canon_name ));
3492                 ServicePtrs[iService]->usershare = USERSHARE_VALID;
3493                 ret = iService;
3494                 goto out;
3495         }
3496
3497         /* Try and open the file read only - no symlinks allowed. */
3498 #ifdef O_NOFOLLOW
3499         fd = open(fname, O_RDONLY|O_NOFOLLOW, 0);
3500 #else
3501         fd = open(fname, O_RDONLY, 0);
3502 #endif
3503
3504         if (fd == -1) {
3505                 DEBUG(0,("process_usershare_file: unable to open %s. %s\n",
3506                         fname, strerror(errno) ));
3507                 goto out;
3508         }
3509
3510         /* Now fstat to be *SURE* it's a regular file. */
3511         if (sys_fstat(fd, &sbuf, false) != 0) {
3512                 close(fd);
3513                 DEBUG(0,("process_usershare_file: fstat of %s failed. %s\n",
3514                         fname, strerror(errno) ));
3515                 goto out;
3516         }
3517
3518         /* Is it the same dev/inode as was lstated ? */
3519         if (!check_same_stat(&lsbuf, &sbuf)) {
3520                 close(fd);
3521                 DEBUG(0,("process_usershare_file: fstat of %s is a different file from lstat. "
3522                         "Symlink spoofing going on ?\n", fname ));
3523                 goto out;
3524         }
3525
3526         /* This must be a regular file, not a symlink, directory or
3527            other strange filetype. */
3528         if (!check_usershare_stat(fname, &sbuf)) {
3529                 close(fd);
3530                 goto out;
3531         }
3532
3533         lines = fd_lines_load(fd, &numlines, MAX_USERSHARE_FILE_SIZE, NULL);
3534
3535         close(fd);
3536         if (lines == NULL) {
3537                 DEBUG(0,("process_usershare_file: loading file %s owned by %u failed.\n",
3538                         fname, (unsigned int)sbuf.st_ex_uid ));
3539                 goto out;
3540         }
3541
3542         if (parse_usershare_file(ctx, &sbuf, file_name,
3543                         iService, lines, numlines, &sharepath,
3544                         &comment, &cp_service_name,
3545                         &psd, &guest_ok) != USERSHARE_OK) {
3546                 goto out;
3547         }
3548
3549         /* Everything ok - add the service possibly using a template. */
3550         if (iService < 0) {
3551                 const struct loadparm_service *sp = &sDefault;
3552                 if (snum_template != -1) {
3553                         sp = ServicePtrs[snum_template];
3554                 }
3555
3556                 if ((iService = add_a_service(sp, cp_service_name)) < 0) {
3557                         DEBUG(0, ("process_usershare_file: Failed to add "
3558                                 "new service %s\n", cp_service_name));
3559                         goto out;
3560                 }
3561
3562                 added_service = true;
3563
3564                 /* Read only is controlled by usershare ACL below. */
3565                 ServicePtrs[iService]->read_only = false;
3566         }
3567
3568         /* Write the ACL of the new/modified share. */
3569         status = set_share_security(canon_name, psd);
3570         if (!NT_STATUS_IS_OK(status)) {
3571                  DEBUG(0, ("process_usershare_file: Failed to set share "
3572                         "security for user share %s\n",
3573                         canon_name ));
3574                 goto out;
3575         }
3576
3577         /* If from a template it may be marked invalid. */
3578         ServicePtrs[iService]->valid = true;
3579
3580         /* Set the service as a valid usershare. */
3581         ServicePtrs[iService]->usershare = USERSHARE_VALID;
3582
3583         /* Set guest access. */
3584         if (lp_usershare_allow_guests()) {
3585                 ServicePtrs[iService]->guest_ok = guest_ok;
3586         }
3587
3588         /* And note when it was loaded. */
3589         ServicePtrs[iService]->usershare_last_mod = sbuf.st_ex_mtime;
3590         lpcfg_string_set(ServicePtrs[iService], &ServicePtrs[iService]->path,
3591                          sharepath);
3592         lpcfg_string_set(ServicePtrs[iService],
3593                          &ServicePtrs[iService]->comment, comment);
3594
3595         ret = iService;
3596
3597   out:
3598
3599         if (ret == -1 && iService != -1 && added_service) {
3600                 lp_remove_service(iService);
3601         }
3602
3603         TALLOC_FREE(lines);
3604         TALLOC_FREE(ctx);
3605         return ret;
3606 }
3607
3608 /***************************************************************************
3609  Checks if a usershare entry has been modified since last load.
3610 ***************************************************************************/
3611
3612 static bool usershare_exists(int iService, struct timespec *last_mod)
3613 {
3614         SMB_STRUCT_STAT lsbuf;
3615         const char *usersharepath = Globals.usershare_path;
3616         char *fname;
3617
3618         fname = talloc_asprintf(talloc_tos(),
3619                                 "%s/%s",
3620                                 usersharepath,
3621                                 ServicePtrs[iService]->szService);
3622         if (fname == NULL) {
3623                 return false;
3624         }
3625
3626         if (sys_lstat(fname, &lsbuf, false) != 0) {
3627                 TALLOC_FREE(fname);
3628                 return false;
3629         }
3630
3631         if (!S_ISREG(lsbuf.st_ex_mode)) {
3632                 TALLOC_FREE(fname);
3633                 return false;
3634         }
3635
3636         TALLOC_FREE(fname);
3637         *last_mod = lsbuf.st_ex_mtime;
3638         return true;
3639 }
3640
3641 static bool usershare_directory_is_root(uid_t uid)
3642 {
3643         if (uid == 0) {
3644                 return true;
3645         }
3646
3647         if (uid_wrapper_enabled()) {
3648                 return true;
3649         }
3650
3651         return false;
3652 }
3653
3654 /***************************************************************************
3655  Load a usershare service by name. Returns a valid servicenumber or -1.
3656 ***************************************************************************/
3657
3658 int load_usershare_service(const char *servicename)
3659 {
3660         SMB_STRUCT_STAT sbuf;
3661         const char *usersharepath = Globals.usershare_path;
3662         int max_user_shares = Globals.usershare_max_shares;
3663         int snum_template = -1;
3664
3665         if (servicename[0] == '\0') {
3666                 /* Invalid service name. */
3667                 return -1;
3668         }
3669
3670         if (*usersharepath == 0 ||  max_user_shares == 0) {
3671                 return -1;
3672         }
3673
3674         if (sys_stat(usersharepath, &sbuf, false) != 0) {
3675                 DEBUG(0,("load_usershare_service: stat of %s failed. %s\n",
3676                         usersharepath, strerror(errno) ));
3677                 return -1;
3678         }
3679
3680         if (!S_ISDIR(sbuf.st_ex_mode)) {
3681                 DEBUG(0,("load_usershare_service: %s is not a directory.\n",
3682                         usersharepath ));
3683                 return -1;
3684         }
3685
3686         /*
3687          * This directory must be owned by root, and have the 't' bit set.
3688          * It also must not be writable by "other".
3689          */
3690
3691 #ifdef S_ISVTX
3692         if (!usershare_directory_is_root(sbuf.st_ex_uid) ||
3693             !(sbuf.st_ex_mode & S_ISVTX) || (sbuf.st_ex_mode & S_IWOTH)) {
3694 #else
3695         if (!usershare_directory_is_root(sbuf.st_ex_uid) ||
3696             (sbuf.st_ex_mode & S_IWOTH)) {
3697 #endif
3698                 DEBUG(0,("load_usershare_service: directory %s is not owned by root "
3699                         "or does not have the sticky bit 't' set or is writable by anyone.\n",
3700                         usersharepath ));
3701                 return -1;
3702         }
3703
3704         /* Ensure the template share exists if it's set. */
3705         if (Globals.usershare_template_share[0]) {
3706                 /* We can't use lp_servicenumber here as we are recommending that
3707                    template shares have -valid=false set. */
3708                 for (snum_template = iNumServices - 1; snum_template >= 0; snum_template--) {
3709                         if (ServicePtrs[snum_template]->szService &&
3710                                         strequal(ServicePtrs[snum_template]->szService,
3711                                                 Globals.usershare_template_share)) {
3712                                 break;
3713                         }
3714                 }
3715
3716                 if (snum_template == -1) {
3717                         DEBUG(0,("load_usershare_service: usershare template share %s "
3718                                 "does not exist.\n",
3719                                 Globals.usershare_template_share ));
3720                         return -1;
3721                 }
3722         }
3723
3724         return process_usershare_file(usersharepath, servicename, snum_template);
3725 }
3726
3727 /***************************************************************************
3728  Load all user defined shares from the user share directory.
3729  We only do this if we're enumerating the share list.
3730  This is the function that can delete usershares that have
3731  been removed.
3732 ***************************************************************************/
3733
3734 int load_usershare_shares(struct smbd_server_connection *sconn,
3735                           bool (*snumused) (struct smbd_server_connection *, int))
3736 {
3737         DIR *dp;
3738         SMB_STRUCT_STAT sbuf;
3739         struct dirent *de;
3740         int num_usershares = 0;
3741         int max_user_shares = Globals.usershare_max_shares;
3742         unsigned int num_dir_entries, num_bad_dir_entries, num_tmp_dir_entries;
3743         unsigned int allowed_bad_entries = ((2*max_user_shares)/10);
3744         unsigned int allowed_tmp_entries = ((2*max_user_shares)/10);
3745         int iService;
3746         int snum_template = -1;
3747         const char *usersharepath = Globals.usershare_path;
3748         int ret = lp_numservices();
3749         TALLOC_CTX *tmp_ctx;
3750
3751         if (max_user_shares == 0 || *usersharepath == '\0') {
3752                 return lp_numservices();
3753         }
3754
3755         if (sys_stat(usersharepath, &sbuf, false) != 0) {
3756                 DEBUG(0,("load_usershare_shares: stat of %s failed. %s\n",
3757                         usersharepath, strerror(errno) ));
3758                 return ret;
3759         }
3760
3761         /*
3762          * This directory must be owned by root, and have the 't' bit set.
3763          * It also must not be writable by "other".
3764          */
3765
3766 #ifdef S_ISVTX
3767         if (sbuf.st_ex_uid != 0 || !(sbuf.st_ex_mode & S_ISVTX) || (sbuf.st_ex_mode & S_IWOTH)) {
3768 #else
3769         if (sbuf.st_ex_uid != 0 || (sbuf.st_ex_mode & S_IWOTH)) {
3770 #endif
3771                 DEBUG(0,("load_usershare_shares: directory %s is not owned by root "
3772                         "or does not have the sticky bit 't' set or is writable by anyone.\n",
3773                         usersharepath ));
3774                 return ret;
3775         }
3776
3777         /* Ensure the template share exists if it's set. */
3778         if (Globals.usershare_template_share[0]) {
3779                 /* We can't use lp_servicenumber here as we are recommending that
3780                    template shares have -valid=false set. */
3781                 for (snum_template = iNumServices - 1; snum_template >= 0; snum_template--) {
3782                         if (ServicePtrs[snum_template]->szService &&
3783                                         strequal(ServicePtrs[snum_template]->szService,
3784                                                 Globals.usershare_template_share)) {
3785                                 break;
3786                         }
3787                 }
3788
3789                 if (snum_template == -1) {
3790                         DEBUG(0,("load_usershare_shares: usershare template share %s "
3791                                 "does not exist.\n",
3792                                 Globals.usershare_template_share ));
3793                         return ret;
3794                 }
3795         }
3796
3797         /* Mark all existing usershares as pending delete. */
3798         for (iService = iNumServices - 1; iService >= 0; iService--) {
3799                 if (VALID(iService) && ServicePtrs[iService]->usershare) {
3800                         ServicePtrs[iService]->usershare = USERSHARE_PENDING_DELETE;
3801                 }
3802         }
3803
3804         dp = opendir(usersharepath);
3805         if (!dp) {
3806                 DEBUG(0,("load_usershare_shares:: failed to open directory %s. %s\n",
3807                         usersharepath, strerror(errno) ));
3808                 return ret;
3809         }
3810
3811         for (num_dir_entries = 0, num_bad_dir_entries = 0, num_tmp_dir_entries = 0;
3812                         (de = readdir(dp));
3813                         num_dir_entries++ ) {
3814                 int r;
3815                 const char *n = de->d_name;
3816
3817                 /* Ignore . and .. */
3818                 if (*n == '.') {
3819                         if ((n[1] == '\0') || (n[1] == '.' && n[2] == '\0')) {
3820                                 continue;
3821                         }
3822                 }
3823
3824                 if (n[0] == ':') {
3825                         /* Temporary file used when creating a share. */
3826                         num_tmp_dir_entries++;
3827                 }
3828
3829                 /* Allow 20% tmp entries. */
3830                 if (num_tmp_dir_entries > allowed_tmp_entries) {
3831                         DEBUG(0,("load_usershare_shares: too many temp entries (%u) "
3832                                 "in directory %s\n",
3833                                 num_tmp_dir_entries, usersharepath));
3834                         break;
3835                 }
3836
3837                 r = process_usershare_file(usersharepath, n, snum_template);
3838                 if (r == 0) {
3839                         /* Update the services count. */
3840                         num_usershares++;
3841                         if (num_usershares >= max_user_shares) {
3842                                 DEBUG(0,("load_usershare_shares: max user shares reached "
3843                                         "on file %s in directory %s\n",
3844                                         n, usersharepath ));
3845                                 break;
3846                         }
3847                 } else if (r == -1) {
3848                         num_bad_dir_entries++;
3849                 }
3850
3851                 /* Allow 20% bad entries. */
3852                 if (num_bad_dir_entries > allowed_bad_entries) {
3853                         DEBUG(0,("load_usershare_shares: too many bad entries (%u) "
3854                                 "in directory %s\n",
3855                                 num_bad_dir_entries, usersharepath));
3856                         break;
3857                 }
3858
3859                 /* Allow 20% bad entries. */
3860                 if (num_dir_entries > max_user_shares + allowed_bad_entries) {
3861                         DEBUG(0,("load_usershare_shares: too many total entries (%u) "
3862                         "in directory %s\n",
3863                         num_dir_entries, usersharepath));
3864                         break;
3865                 }
3866         }
3867
3868         closedir(dp);
3869
3870         /* Sweep through and delete any non-refreshed usershares that are
3871            not currently in use. */
3872         tmp_ctx = talloc_stackframe();
3873         for (iService = iNumServices - 1; iService >= 0; iService--) {
3874                 if (VALID(iService) && (ServicePtrs[iService]->usershare == USERSHARE_PENDING_DELETE)) {
3875                         const struct loadparm_substitution *lp_sub =
3876                                 loadparm_s3_global_substitution();
3877                         char *servname;
3878
3879                         if (snumused && snumused(sconn, iService)) {
3880                                 continue;
3881                         }
3882
3883                         servname = lp_servicename(tmp_ctx, lp_sub, iService);
3884
3885                         /* Remove from the share ACL db. */
3886                         DEBUG(10,("load_usershare_shares: Removing deleted usershare %s\n",
3887                                   servname ));
3888                         delete_share_security(servname);
3889                         free_service_byindex(iService);
3890                 }
3891         }
3892         talloc_free(tmp_ctx);
3893
3894         return lp_numservices();
3895 }
3896
3897 /********************************************************
3898  Destroy global resources allocated in this file
3899 ********************************************************/
3900
3901 void gfree_loadparm(void)
3902 {
3903         int i;
3904
3905         free_file_list();
3906
3907         /* Free resources allocated to services */
3908
3909         for ( i = 0; i < iNumServices; i++ ) {
3910                 if ( VALID(i) ) {
3911                         free_service_byindex(i);
3912                 }
3913         }
3914
3915         TALLOC_FREE( ServicePtrs );
3916         iNumServices = 0;
3917
3918         /* Now release all resources allocated to global
3919            parameters and the default service */
3920
3921         free_global_parameters();
3922 }
3923
3924
3925 /***************************************************************************
3926  Allow client apps to specify that they are a client
3927 ***************************************************************************/
3928 static void lp_set_in_client(bool b)
3929 {
3930     in_client = b;
3931 }
3932
3933
3934 /***************************************************************************
3935  Determine if we're running in a client app
3936 ***************************************************************************/
3937 static bool lp_is_in_client(void)
3938 {
3939     return in_client;
3940 }
3941
3942 static void lp_enforce_ad_dc_settings(void)
3943 {
3944         lp_do_parameter(GLOBAL_SECTION_SNUM, "passdb backend", "samba_dsdb");
3945         lp_do_parameter(GLOBAL_SECTION_SNUM,
3946                         "winbindd:use external pipes", "true");
3947         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:default", "external");
3948         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:svcctl", "embedded");
3949         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:srvsvc", "embedded");
3950         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:eventlog", "embedded");
3951         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:ntsvcs", "embedded");
3952         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:winreg", "embedded");
3953         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:spoolss", "embedded");
3954         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_daemon:spoolssd", "embedded");
3955         lp_do_parameter(GLOBAL_SECTION_SNUM, "rpc_server:tcpip", "no");
3956 }
3957
3958 /***************************************************************************
3959  Load the services array from the services file. Return true on success,
3960  false on failure.
3961 ***************************************************************************/
3962
3963 static bool lp_load_ex(const char *pszFname,
3964                        bool global_only,
3965                        bool save_defaults,
3966                        bool add_ipc,
3967                        bool reinit_globals,
3968                        bool allow_include_registry,
3969                        bool load_all_shares)
3970 {
3971         char *n2 = NULL;
3972         bool bRetval;
3973         TALLOC_CTX *frame = talloc_stackframe();
3974         struct loadparm_context *lp_ctx;
3975         int max_protocol, min_protocol;
3976
3977         DEBUG(3, ("lp_load_ex: refreshing parameters\n"));
3978
3979         bInGlobalSection = true;
3980         bGlobalOnly = global_only;
3981         bAllowIncludeRegistry = allow_include_registry;
3982         sDefault = _sDefault;
3983
3984         lp_ctx = setup_lp_context(talloc_tos());
3985
3986         init_globals(lp_ctx, reinit_globals);
3987
3988         free_file_list();
3989
3990         if (save_defaults) {
3991                 init_locals();
3992                 lp_save_defaults();
3993         }
3994
3995         if (!reinit_globals) {
3996                 free_param_opts(&Globals.param_opt);
3997                 apply_lp_set_cmdline();
3998         }
3999
4000         lp_do_parameter(-1, "idmap config * : backend", Globals.idmap_backend);
4001
4002         /* We get sections first, so have to start 'behind' to make up */
4003         iServiceIndex = -1;
4004
4005         if (lp_config_backend_is_file()) {
4006                 n2 = talloc_sub_basic(talloc_tos(), get_current_username(),
4007                                         get_current_user_info_domain(),
4008                                         pszFname);
4009                 if (!n2) {
4010                         smb_panic("lp_load_ex: out of memory");
4011                 }
4012
4013                 add_to_file_list(NULL, &file_lists, pszFname, n2);
4014
4015                 bRetval = pm_process(n2, lp_do_section, do_parameter, lp_ctx);
4016                 TALLOC_FREE(n2);
4017
4018                 /* finish up the last section */
4019                 DEBUG(4, ("pm_process() returned %s\n", BOOLSTR(bRetval)));
4020                 if (bRetval) {
4021                         if (iServiceIndex >= 0) {
4022                                 bRetval = lpcfg_service_ok(ServicePtrs[iServiceIndex]);
4023                         }
4024                 }
4025
4026                 if (lp_config_backend_is_registry()) {
4027                         bool ok;
4028                         /* config backend changed to registry in config file */
4029                         /*
4030                          * We need to use this extra global variable here to
4031                          * survive restart: init_globals uses this as a default
4032                          * for config_backend. Otherwise, init_globals would
4033                          *  send us into an endless loop here.
4034                          */
4035
4036                         config_backend = CONFIG_BACKEND_REGISTRY;
4037                         /* start over */
4038                         DEBUG(1, ("lp_load_ex: changing to config backend "
4039                                   "registry\n"));
4040                         init_globals(lp_ctx, true);
4041
4042                         TALLOC_FREE(lp_ctx);
4043
4044                         lp_kill_all_services();
4045                         ok = lp_load_ex(pszFname, global_only, save_defaults,
4046                                         add_ipc, reinit_globals,
4047                                         allow_include_registry,
4048                                         load_all_shares);
4049                         TALLOC_FREE(frame);
4050                         return ok;
4051                 }
4052         } else if (lp_config_backend_is_registry()) {
4053                 bRetval = process_registry_globals();
4054         } else {
4055                 DEBUG(0, ("Illegal config  backend given: %d\n",
4056                           lp_config_backend()));
4057                 bRetval = false;
4058         }
4059
4060         if (bRetval && lp_registry_shares()) {
4061                 if (load_all_shares) {
4062                         bRetval = process_registry_shares();
4063                 } else {
4064                         bRetval = reload_registry_shares();
4065                 }
4066         }
4067
4068         {
4069                 const struct loadparm_substitution *lp_sub =
4070                         loadparm_s3_global_substitution();
4071                 char *serv = lp_auto_services(talloc_tos(), lp_sub);
4072                 lp_add_auto_services(serv);
4073                 TALLOC_FREE(serv);
4074         }
4075
4076         if (add_ipc) {
4077                 /* When 'restrict anonymous = 2' guest connections to ipc$
4078                    are denied */
4079                 lp_add_ipc("IPC$", (lp_restrict_anonymous() < 2));
4080                 if ( lp_enable_asu_support() ) {
4081                         lp_add_ipc("ADMIN$", false);
4082                 }
4083         }
4084
4085         set_allowed_client_auth();
4086
4087         if (lp_security() == SEC_ADS && strchr(lp_password_server(), ':')) {
4088                 DEBUG(1, ("WARNING: The optional ':port' in password server = %s is deprecated\n",
4089                           lp_password_server()));
4090         }
4091
4092         bLoaded = true;
4093
4094         /* Now we check we_are_a_wins_server and set szWINSserver to 127.0.0.1 */
4095         /* if we_are_a_wins_server is true and we are in the client            */
4096         if (lp_is_in_client() && Globals.we_are_a_wins_server) {
4097                 lp_do_parameter(GLOBAL_SECTION_SNUM, "wins server", "127.0.0.1");
4098         }
4099
4100         init_iconv();
4101
4102         fault_configure(smb_panic_s3);
4103
4104         /*
4105          * We run this check once the whole smb.conf is parsed, to
4106          * force some settings for the standard way a AD DC is
4107          * operated.  We may change these as our code evolves, which
4108          * is why we force these settings.
4109          */
4110         if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
4111                 lp_enforce_ad_dc_settings();
4112         }
4113
4114         bAllowIncludeRegistry = true;
4115
4116         /* Check if command line max protocol < min protocol, if so
4117          * report a warning to the user.
4118          */
4119         max_protocol = lp_client_max_protocol();
4120         min_protocol = lp_client_min_protocol();
4121         if (max_protocol < min_protocol) {
4122                 const char *max_protocolp, *min_protocolp;
4123                 max_protocolp = lpcfg_get_smb_protocol(max_protocol);
4124                 min_protocolp = lpcfg_get_smb_protocol(min_protocol);
4125                 DBG_ERR("Max protocol %s is less than min protocol %s.\n",
4126                         max_protocolp, min_protocolp);
4127         }
4128
4129         TALLOC_FREE(frame);
4130         return (bRetval);
4131 }
4132
4133 static bool lp_load(const char *pszFname,
4134                     bool global_only,
4135                     bool save_defaults,
4136                     bool add_ipc,
4137                     bool reinit_globals)
4138 {
4139         return lp_load_ex(pszFname,
4140                           global_only,
4141                           save_defaults,
4142                           add_ipc,
4143                           reinit_globals,
4144                           true,   /* allow_include_registry */
4145                           false); /* load_all_shares*/
4146 }
4147
4148 bool lp_load_initial_only(const char *pszFname)
4149 {
4150         return lp_load_ex(pszFname,
4151                           true,   /* global only */
4152                           true,   /* save_defaults */
4153                           false,  /* add_ipc */
4154                           true,   /* reinit_globals */
4155                           false,  /* allow_include_registry */
4156                           false); /* load_all_shares*/
4157 }
4158
4159 /**
4160  * most common lp_load wrapper, loading only the globals
4161  *
4162  * If this is used in a daemon or client utility it should be called
4163  * after processing popt.
4164  */
4165 bool lp_load_global(const char *file_name)
4166 {
4167         return lp_load(file_name,
4168                        true,   /* global_only */
4169                        false,  /* save_defaults */
4170                        false,  /* add_ipc */
4171                        true);  /* reinit_globals */
4172 }
4173
4174 /**
4175  * The typical lp_load wrapper with shares, loads global and
4176  * shares, including IPC, but does not force immediate
4177  * loading of all shares from registry.
4178  */
4179 bool lp_load_with_shares(const char *file_name)
4180 {
4181         return lp_load(file_name,
4182                        false,  /* global_only */
4183                        false,  /* save_defaults */
4184                        true,   /* add_ipc */
4185                        true);  /* reinit_globals */
4186 }
4187
4188 /**
4189  * lp_load wrapper, especially for clients
4190  */
4191 bool lp_load_client(const char *file_name)
4192 {
4193         lp_set_in_client(true);
4194
4195         return lp_load_global(file_name);
4196 }
4197
4198 /**
4199  * lp_load wrapper, loading only globals, but intended
4200  * for subsequent calls, not reinitializing the globals
4201  * to default values
4202  */
4203 bool lp_load_global_no_reinit(const char *file_name)
4204 {
4205         return lp_load(file_name,
4206                        true,   /* global_only */
4207                        false,  /* save_defaults */
4208                        false,  /* add_ipc */
4209                        false); /* reinit_globals */
4210 }
4211
4212 /**
4213  * lp_load wrapper, loading globals and shares,
4214  * intended for subsequent calls, i.e. not reinitializing
4215  * the globals to default values.
4216  */
4217 bool lp_load_no_reinit(const char *file_name)
4218 {
4219         return lp_load(file_name,
4220                        false,  /* global_only */
4221                        false,  /* save_defaults */
4222                        false,  /* add_ipc */
4223                        false); /* reinit_globals */
4224 }
4225
4226
4227 /**
4228  * lp_load wrapper, especially for clients, no reinitialization
4229  */
4230 bool lp_load_client_no_reinit(const char *file_name)
4231 {
4232         lp_set_in_client(true);
4233
4234         return lp_load_global_no_reinit(file_name);
4235 }
4236
4237 bool lp_load_with_registry_shares(const char *pszFname)
4238 {
4239         return lp_load_ex(pszFname,
4240                           false, /* global_only */
4241                           true,  /* save_defaults */
4242                           false, /* add_ipc */
4243                           true, /* reinit_globals */
4244                           true,  /* allow_include_registry */
4245                           true); /* load_all_shares*/
4246 }
4247
4248 /***************************************************************************
4249  Return the max number of services.
4250 ***************************************************************************/
4251
4252 int lp_numservices(void)
4253 {
4254         return (iNumServices);
4255 }
4256
4257 /***************************************************************************
4258 Display the contents of the services array in human-readable form.
4259 ***************************************************************************/
4260
4261 void lp_dump(FILE *f, bool show_defaults, int maxtoprint)
4262 {
4263         int iService;
4264         struct loadparm_context *lp_ctx;
4265
4266         if (show_defaults)
4267                 defaults_saved = false;
4268
4269         lp_ctx = setup_lp_context(talloc_tos());
4270         if (lp_ctx == NULL) {
4271                 return;
4272         }
4273
4274         lpcfg_dump_globals(lp_ctx, f, !defaults_saved);
4275
4276         lpcfg_dump_a_service(&sDefault, &sDefault, f, flags_list, show_defaults);
4277
4278         for (iService = 0; iService < maxtoprint; iService++) {
4279                 fprintf(f,"\n");
4280                 lp_dump_one(f, show_defaults, iService);
4281         }
4282         TALLOC_FREE(lp_ctx);
4283 }
4284
4285 /***************************************************************************
4286 Display the contents of one service in human-readable form.
4287 ***************************************************************************/
4288
4289 void lp_dump_one(FILE * f, bool show_defaults, int snum)
4290 {
4291         if (VALID(snum)) {
4292                 if (ServicePtrs[snum]->szService[0] == '\0')
4293                         return;
4294                 lpcfg_dump_a_service(ServicePtrs[snum], &sDefault, f,
4295                                      flags_list, show_defaults);
4296         }
4297 }
4298
4299 /***************************************************************************
4300 Return the number of the service with the given name, or -1 if it doesn't
4301 exist. Note that this is a DIFFERENT ANIMAL from the internal function
4302 getservicebyname()! This works ONLY if all services have been loaded, and
4303 does not copy the found service.
4304 ***************************************************************************/
4305
4306 int lp_servicenumber(const char *pszServiceName)
4307 {
4308         int iService;
4309         fstring serviceName;
4310
4311         if (!pszServiceName) {
4312                 return GLOBAL_SECTION_SNUM;
4313         }
4314
4315         for (iService = iNumServices - 1; iService >= 0; iService--) {
4316                 if (VALID(iService) && ServicePtrs[iService]->szService) {
4317                         /*
4318                          * The substitution here is used to support %U in
4319                          * service names
4320                          */
4321                         fstrcpy(serviceName, ServicePtrs[iService]->szService);
4322                         standard_sub_basic(get_current_username(),
4323                                            get_current_user_info_domain(),
4324                                            serviceName,sizeof(serviceName));
4325                         if (strequal(serviceName, pszServiceName)) {
4326                                 break;
4327                         }
4328                 }
4329         }
4330
4331         if (iService >= 0 && ServicePtrs[iService]->usershare == USERSHARE_VALID) {
4332                 struct timespec last_mod;
4333
4334                 if (!usershare_exists(iService, &last_mod)) {
4335                         /* Remove the share security tdb entry for it. */
4336                         delete_share_security(lp_const_servicename(iService));
4337                         /* Remove it from the array. */
4338                         free_service_byindex(iService);
4339                         /* Doesn't exist anymore. */
4340                         return GLOBAL_SECTION_SNUM;
4341                 }
4342
4343                 /* Has it been modified ? If so delete and reload. */
4344                 if (timespec_compare(&ServicePtrs[iService]->usershare_last_mod,
4345                                      &last_mod) < 0) {
4346                         /* Remove it from the array. */
4347                         free_service_byindex(iService);
4348                         /* and now reload it. */
4349                         iService = load_usershare_service(pszServiceName);
4350                 }
4351         }
4352
4353         if (iService < 0) {
4354                 DEBUG(7,("lp_servicenumber: couldn't find %s\n", pszServiceName));
4355                 return GLOBAL_SECTION_SNUM;
4356         }
4357
4358         return (iService);
4359 }
4360
4361 /*******************************************************************
4362  A useful volume label function.
4363 ********************************************************************/
4364
4365 const char *volume_label(TALLOC_CTX *ctx, int snum)
4366 {
4367         const struct loadparm_substitution *lp_sub =
4368                 loadparm_s3_global_substitution();
4369         char *ret;
4370         const char *label = lp_volume(ctx, lp_sub, snum);
4371         size_t end = 32;
4372
4373         if (!*label) {
4374                 label = lp_servicename(ctx, lp_sub, snum);
4375         }
4376
4377         /*
4378          * Volume label can be a max of 32 bytes. Make sure to truncate
4379          * it at a codepoint boundary if it's longer than 32 and contains
4380          * multibyte characters. Windows insists on a volume label being
4381          * a valid mb sequence, and errors out if not.
4382          */
4383         if (strlen(label) > 32) {
4384                 /*
4385                  * A MB char can be a max of 5 bytes, thus
4386                  * we should have a valid mb character at a
4387                  * minimum position of (32-5) = 27.
4388                  */
4389                 while (end >= 27) {
4390                         /*
4391                          * Check if a codepoint starting from next byte
4392                          * is valid. If yes, then the current byte is the
4393                          * end of a MB or ascii sequence and the label can
4394                          * be safely truncated here. If not, keep going
4395                          * backwards till a valid codepoint is found.
4396                          */
4397                         size_t len = 0;
4398                         const char *s = &label[end];
4399                         codepoint_t c = next_codepoint(s, &len);
4400                         if (c != INVALID_CODEPOINT) {
4401                                 break;
4402                         }
4403                         end--;
4404                 }
4405         }
4406
4407         /* This returns a max of 33 byte guarenteed null terminated string. */
4408         ret = talloc_strndup(ctx, label, end);
4409         if (!ret) {
4410                 return "";
4411         }
4412         return ret;
4413 }
4414
4415 /*******************************************************************
4416  Get the default server type we will announce as via nmbd.
4417 ********************************************************************/
4418
4419 int lp_default_server_announce(void)
4420 {
4421         int default_server_announce = 0;
4422         default_server_announce |= SV_TYPE_WORKSTATION;
4423         default_server_announce |= SV_TYPE_SERVER;
4424         default_server_announce |= SV_TYPE_SERVER_UNIX;
4425
4426         /* note that the flag should be set only if we have a
4427            printer service but nmbd doesn't actually load the
4428            services so we can't tell   --jerry */
4429
4430         default_server_announce |= SV_TYPE_PRINTQ_SERVER;
4431
4432         default_server_announce |= SV_TYPE_SERVER_NT;
4433         default_server_announce |= SV_TYPE_NT;
4434
4435         switch (lp_server_role()) {
4436                 case ROLE_DOMAIN_MEMBER:
4437                         default_server_announce |= SV_TYPE_DOMAIN_MEMBER;
4438                         break;
4439                 case ROLE_DOMAIN_PDC:
4440                 case ROLE_IPA_DC:
4441                         default_server_announce |= SV_TYPE_DOMAIN_CTRL;
4442                         break;
4443                 case ROLE_DOMAIN_BDC:
4444                         default_server_announce |= SV_TYPE_DOMAIN_BAKCTRL;
4445                         break;
4446                 case ROLE_STANDALONE:
4447                 default:
4448                         break;
4449         }
4450         if (lp_time_server())
4451                 default_server_announce |= SV_TYPE_TIME_SOURCE;
4452
4453         if (lp_host_msdfs())
4454                 default_server_announce |= SV_TYPE_DFS_SERVER;
4455
4456         return default_server_announce;
4457 }
4458
4459 /***********************************************************
4460  If we are PDC then prefer us as DMB
4461 ************************************************************/
4462
4463 bool lp_domain_master(void)
4464 {
4465         if (Globals._domain_master == Auto)
4466                 return (lp_server_role() == ROLE_DOMAIN_PDC ||
4467                         lp_server_role() == ROLE_IPA_DC);
4468
4469         return (bool)Globals._domain_master;
4470 }
4471
4472 /***********************************************************
4473  If we are PDC then prefer us as DMB
4474 ************************************************************/
4475
4476 static bool lp_domain_master_true_or_auto(void)
4477 {
4478         if (Globals._domain_master) /* auto or yes */
4479                 return true;
4480
4481         return false;
4482 }
4483
4484 /***********************************************************
4485  If we are DMB then prefer us as LMB
4486 ************************************************************/
4487
4488 bool lp_preferred_master(void)
4489 {
4490         int preferred_master = lp__preferred_master();
4491
4492         if (preferred_master == Auto)
4493                 return (lp_local_master() && lp_domain_master());
4494
4495         return (bool)preferred_master;
4496 }
4497
4498 /*******************************************************************
4499  Remove a service.
4500 ********************************************************************/
4501
4502 void lp_remove_service(int snum)
4503 {
4504         ServicePtrs[snum]->valid = false;
4505 }
4506
4507 const char *lp_printername(TALLOC_CTX *ctx,
4508                            const struct loadparm_substitution *lp_sub,
4509                            int snum)
4510 {
4511         const char *ret = lp__printername(ctx, lp_sub, snum);
4512
4513         if (ret == NULL || *ret == '\0') {
4514                 ret = lp_const_servicename(snum);
4515         }
4516
4517         return ret;
4518 }
4519
4520
4521 /***********************************************************
4522  Allow daemons such as winbindd to fix their logfile name.
4523 ************************************************************/
4524
4525 void lp_set_logfile(const char *name)
4526 {
4527         lpcfg_string_set(Globals.ctx, &Globals.logfile, name);
4528         debug_set_logfile(name);
4529 }
4530
4531 /*******************************************************************
4532  Return the max print jobs per queue.
4533 ********************************************************************/
4534
4535 int lp_maxprintjobs(int snum)
4536 {
4537         int maxjobs = lp_max_print_jobs(snum);
4538
4539         if (maxjobs <= 0 || maxjobs >= PRINT_MAX_JOBID)
4540                 maxjobs = PRINT_MAX_JOBID - 1;
4541
4542         return maxjobs;
4543 }
4544
4545 const char *lp_printcapname(void)
4546 {
4547         const char *printcap_name = lp_printcap_name();
4548
4549         if ((printcap_name != NULL) &&
4550             (printcap_name[0] != '\0'))
4551                 return printcap_name;
4552
4553         if (sDefault.printing == PRINT_CUPS) {
4554                 return "cups";
4555         }
4556
4557         if (sDefault.printing == PRINT_BSD)
4558                 return "/etc/printcap";
4559
4560         return PRINTCAP_NAME;
4561 }
4562
4563 static uint32_t spoolss_state;
4564
4565 bool lp_disable_spoolss( void )
4566 {
4567         if ( spoolss_state == SVCCTL_STATE_UNKNOWN )
4568                 spoolss_state = lp__disable_spoolss() ? SVCCTL_STOPPED : SVCCTL_RUNNING;
4569
4570         return spoolss_state == SVCCTL_STOPPED ? true : false;
4571 }
4572
4573 void lp_set_spoolss_state( uint32_t state )
4574 {
4575         SMB_ASSERT( (state == SVCCTL_STOPPED) || (state == SVCCTL_RUNNING) );
4576
4577         spoolss_state = state;
4578 }
4579
4580 uint32_t lp_get_spoolss_state( void )
4581 {
4582         return lp_disable_spoolss() ? SVCCTL_STOPPED : SVCCTL_RUNNING;
4583 }
4584
4585 /*******************************************************************
4586  Turn off sendfile if we find the underlying OS doesn't support it.
4587 ********************************************************************/
4588
4589 void set_use_sendfile(int snum, bool val)
4590 {
4591         if (LP_SNUM_OK(snum))
4592                 ServicePtrs[snum]->_use_sendfile = val;
4593         else
4594                 sDefault._use_sendfile = val;
4595 }
4596
4597 void lp_set_mangling_method(const char *new_method)
4598 {
4599         lpcfg_string_set(Globals.ctx, &Globals.mangling_method, new_method);
4600 }
4601
4602 /*******************************************************************
4603  Global state for POSIX pathname processing.
4604 ********************************************************************/
4605
4606 static bool posix_pathnames;
4607
4608 bool lp_posix_pathnames(void)
4609 {
4610         return posix_pathnames;
4611 }
4612
4613 /*******************************************************************
4614  Change everything needed to ensure POSIX pathname processing (currently
4615  not much).
4616 ********************************************************************/
4617
4618 void lp_set_posix_pathnames(void)
4619 {
4620         posix_pathnames = true;
4621 }
4622
4623 /*******************************************************************
4624  Global state for POSIX lock processing - CIFS unix extensions.
4625 ********************************************************************/
4626
4627 bool posix_default_lock_was_set;
4628 static enum brl_flavour posix_cifsx_locktype; /* By default 0 == WINDOWS_LOCK */
4629
4630 enum brl_flavour lp_posix_cifsu_locktype(files_struct *fsp)
4631 {
4632         if (posix_default_lock_was_set) {
4633                 return posix_cifsx_locktype;
4634         } else {
4635                 return (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
4636                         POSIX_LOCK : WINDOWS_LOCK;
4637         }
4638 }
4639
4640 /*******************************************************************
4641 ********************************************************************/
4642
4643 void lp_set_posix_default_cifsx_readwrite_locktype(enum brl_flavour val)
4644 {
4645         posix_default_lock_was_set = true;
4646         posix_cifsx_locktype = val;
4647 }
4648
4649 int lp_min_receive_file_size(void)
4650 {
4651         int min_receivefile_size = lp_min_receivefile_size();
4652
4653         if (min_receivefile_size < 0) {
4654                 return 0;
4655         }
4656         return min_receivefile_size;
4657 }
4658
4659 /*******************************************************************
4660  Safe wide links checks.
4661  This helper function always verify the validity of wide links,
4662  even after a configuration file reload.
4663 ********************************************************************/
4664
4665 void widelinks_warning(int snum)
4666 {
4667         if (lp_allow_insecure_wide_links()) {
4668                 return;
4669         }
4670
4671         if (lp_wide_links(snum)) {
4672                 if (lp_smb1_unix_extensions()) {
4673                         DBG_ERR("Share '%s' has wide links and SMB1 unix "
4674                         "extensions enabled. "
4675                         "These parameters are incompatible. "
4676                         "Wide links will be disabled for this share.\n",
4677                          lp_const_servicename(snum));
4678                 } else if (lp_smb3_unix_extensions()) {
4679                         DBG_ERR("Share '%s' has wide links and SMB3 unix "
4680                         "extensions enabled. "
4681                         "These parameters are incompatible. "
4682                         "Wide links will be disabled for this share.\n",
4683                          lp_const_servicename(snum));
4684                 }
4685         }
4686 }
4687
4688 bool lp_widelinks(int snum)
4689 {
4690         /* wide links is always incompatible with unix extensions */
4691         if (lp_smb1_unix_extensions() || lp_smb3_unix_extensions()) {
4692                 /*
4693                  * Unless we have "allow insecure widelinks"
4694                  * turned on.
4695                  */
4696                 if (!lp_allow_insecure_wide_links()) {
4697                         return false;
4698                 }
4699         }
4700
4701         return lp_wide_links(snum);
4702 }
4703
4704 int lp_server_role(void)
4705 {
4706         return lp_find_server_role(lp__server_role(),
4707                                    lp__security(),
4708                                    lp__domain_logons(),
4709                                    lp_domain_master_true_or_auto());
4710 }
4711
4712 int lp_security(void)
4713 {
4714         return lp_find_security(lp__server_role(),
4715                                 lp__security());
4716 }
4717
4718 int lp_client_max_protocol(void)
4719 {
4720         int client_max_protocol = lp__client_max_protocol();
4721         if (client_max_protocol == PROTOCOL_DEFAULT) {
4722                 return PROTOCOL_LATEST;
4723         }
4724         return client_max_protocol;
4725 }
4726
4727 int lp_client_ipc_min_protocol(void)
4728 {
4729         int client_ipc_min_protocol = lp__client_ipc_min_protocol();
4730         if (client_ipc_min_protocol == PROTOCOL_DEFAULT) {
4731                 client_ipc_min_protocol = lp_client_min_protocol();
4732         }
4733         if (client_ipc_min_protocol < PROTOCOL_NT1) {
4734                 return PROTOCOL_NT1;
4735         }
4736         return client_ipc_min_protocol;
4737 }
4738
4739 int lp_client_ipc_max_protocol(void)
4740 {
4741         int client_ipc_max_protocol = lp__client_ipc_max_protocol();
4742         if (client_ipc_max_protocol == PROTOCOL_DEFAULT) {
4743                 return PROTOCOL_LATEST;
4744         }
4745         if (client_ipc_max_protocol < PROTOCOL_NT1) {
4746                 return PROTOCOL_NT1;
4747         }
4748         return client_ipc_max_protocol;
4749 }
4750
4751 int lp_client_ipc_signing(void)
4752 {
4753         int client_ipc_signing = lp__client_ipc_signing();
4754         if (client_ipc_signing == SMB_SIGNING_DEFAULT) {
4755                 return SMB_SIGNING_REQUIRED;
4756         }
4757         return client_ipc_signing;
4758 }
4759
4760 enum credentials_use_kerberos lp_client_use_kerberos(void)
4761 {
4762         if (lp_weak_crypto() == SAMBA_WEAK_CRYPTO_DISALLOWED) {
4763                 return CRED_USE_KERBEROS_REQUIRED;
4764         }
4765
4766         return lp__client_use_kerberos();
4767 }
4768
4769
4770 int lp_rpc_low_port(void)
4771 {
4772         return Globals.rpc_low_port;
4773 }
4774
4775 int lp_rpc_high_port(void)
4776 {
4777         return Globals.rpc_high_port;
4778 }
4779
4780 /*
4781  * Do not allow LanMan auth if unless NTLMv1 is also allowed
4782  *
4783  * This also ensures it is disabled if NTLM is totally disabled
4784  */
4785 bool lp_lanman_auth(void)
4786 {
4787         enum ntlm_auth_level ntlm_auth_level = lp_ntlm_auth();
4788
4789         if (ntlm_auth_level == NTLM_AUTH_ON) {
4790                 return lp__lanman_auth();
4791         } else {
4792                 return false;
4793         }
4794 }
4795
4796 struct loadparm_global * get_globals(void)
4797 {
4798         return &Globals;
4799 }
4800
4801 unsigned int * get_flags(void)
4802 {
4803         if (flags_list == NULL) {
4804                 flags_list = talloc_zero_array(NULL, unsigned int, num_parameters());
4805         }
4806
4807         return flags_list;
4808 }
4809
4810 enum samba_weak_crypto lp_weak_crypto(void)
4811 {
4812         if (Globals.weak_crypto == SAMBA_WEAK_CRYPTO_UNKNOWN) {
4813                 Globals.weak_crypto = SAMBA_WEAK_CRYPTO_DISALLOWED;
4814
4815                 if (samba_gnutls_weak_crypto_allowed()) {
4816                         Globals.weak_crypto = SAMBA_WEAK_CRYPTO_ALLOWED;
4817                 }
4818         }
4819
4820         return Globals.weak_crypto;
4821 }
4822
4823 uint32_t lp_get_async_dns_timeout(void)
4824 {
4825         /*
4826          * Clamp minimum async dns timeout to 1 second
4827          * as per the man page.
4828          */
4829         return MAX(Globals.async_dns_timeout, 1);
4830 }
4831
4832 bool lp_smb3_unix_extensions(void)
4833 {
4834 #if defined(DEVELOPER)
4835         return lp__smb3_unix_extensions();
4836 #else
4837         return false;
4838 #endif
4839 }