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