Fix accessors F_LENGTH() and F_MOD_NSEC().
[rsync.git] / loadparm.c
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License along
13  * with this program; if not, visit the http://fsf.org website.
14  */
15
16 /* This is based on loadparm.c from Samba, written by Andrew Tridgell
17  * and Karl Auer.  Some of the changes are:
18  *
19  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
20  * Copyright (C) 2003-2009 Wayne Davison <wayned@samba.org>
21  */
22
23 /* Load parameters.
24  *
25  *  This module provides suitable callback functions for the params
26  *  module. It builds the internal table of section details which is
27  *  then used by the rest of the server.
28  *
29  * To add a parameter:
30  *
31  * 1) add it to the global_vars or local_vars structure definition
32  * 2) add it to the parm_table
33  * 3) add it to the list of available functions (eg: using FN_GLOBAL_STRING())
34  * 4) initialise it in the Defaults static stucture
35  *
36  * Notes:
37  *   The configuration file is processed sequentially for speed. For this
38  *   reason, there is a fair bit of sequence-dependent code here - ie., code
39  *   which assumes that certain things happen before others. In particular, the
40  *   code which happens at the boundary between sections is delicately poised,
41  *   so be careful!
42  */
43
44 #include "rsync.h"
45 #include "itypes.h"
46
47 extern item_list dparam_list;
48
49 #define strequal(a, b) (strcasecmp(a, b)==0)
50 #define BOOLSTR(b) ((b) ? "Yes" : "No")
51
52 #ifndef LOG_DAEMON
53 #define LOG_DAEMON 0
54 #endif
55
56 #define DEFAULT_DONT_COMPRESS "*.gz *.zip *.z *.rpm *.deb *.iso *.bz2" \
57         " *.t[gb]z *.7z *.mp[34] *.mov *.avi *.ogg *.jpg *.jpeg" \
58         " *.lzo *.rzip *.lzma *.rar *.ace *.gpg"
59
60 /* the following are used by loadparm for option lists */
61 typedef enum {
62         P_BOOL, P_BOOLREV, P_CHAR, P_INTEGER,
63         P_OCTAL, P_PATH, P_STRING, P_ENUM
64 } parm_type;
65
66 typedef enum {
67         P_LOCAL, P_GLOBAL, P_NONE
68 } parm_class;
69
70 struct enum_list {
71         int value;
72         char *name;
73 };
74
75 struct parm_struct {
76         char *label;
77         parm_type type;
78         parm_class class;
79         void *ptr;
80         struct enum_list *enum_list;
81         unsigned flags;
82 };
83
84 #ifndef GLOBAL_NAME
85 #define GLOBAL_NAME "global"
86 #endif
87
88 /* some helpful bits */
89 #define iSECTION(i) ((local_vars*)section_list.items)[i]
90 #define LP_SNUM_OK(i) ((i) >= 0 && (i) < (int)section_list.count)
91 #define SECTION_PTR(s, p) (((char*)(s)) + (ptrdiff_t)(((char*)(p))-(char*)&Vars.l))
92
93 /* This structure describes global (ie., server-wide) parameters. */
94 typedef struct {
95         char *bind_address;
96         char *motd_file;
97         char *pid_file;
98         char *socket_options;
99
100         int rsync_port;
101 } global_vars;
102
103 /* This structure describes a single section.  Their order must match the
104  * initializers below, which you can accomplish by keeping each sub-section
105  * sorted.  (e.g. in vim, just visually select each subsection and use !sort.)
106  * NOTE: the char* variables MUST all remain at the start of the stuct! */
107 typedef struct {
108         char *auth_users;
109         char *charset;
110         char *comment;
111         char *dont_compress;
112         char *exclude;
113         char *exclude_from;
114         char *filter;
115         char *gid;
116         char *hosts_allow;
117         char *hosts_deny;
118         char *include;
119         char *include_from;
120         char *incoming_chmod;
121         char *lock_file;
122         char *log_file;
123         char *log_format;
124         char *name;
125         char *outgoing_chmod;
126         char *path;
127         char *postxfer_exec;
128         char *prexfer_exec;
129         char *refuse_options;
130         char *secrets_file;
131         char *temp_dir;
132         char *uid;
133 /* NOTE: update this macro if the last char* variable changes! */
134 #define LOCAL_STRING_COUNT() (offsetof(local_vars, uid) / sizeof (char*) + 1)
135
136         int max_connections;
137         int max_verbosity;
138         int syslog_facility;
139         int timeout;
140
141         BOOL fake_super;
142         BOOL ignore_errors;
143         BOOL ignore_nonreadable;
144         BOOL list;
145         BOOL munge_symlinks;
146         BOOL numeric_ids;
147         BOOL read_only;
148         BOOL reverse_lookup;
149         BOOL strict_modes;
150         BOOL transfer_logging;
151         BOOL use_chroot;
152         BOOL write_only;
153 } local_vars;
154
155 /* This structure describes the global variables (g) as well as the globally
156  * specified values of the local variables (l), which are used when modules
157  * don't specify their own values. */
158 typedef struct {
159         global_vars g;
160         local_vars l;
161 } all_vars;
162
163 /* The application defaults for all the variables.  "Defaults" is
164  * used to re-initialize "Vars" before each config-file read.
165  *
166  * In order to keep these sorted in the same way as the structure
167  * above, use the variable name in the leading comment, including a
168  * trailing ';' (to avoid a sorting problem with trailing digits). */
169 static const all_vars Defaults = {
170  /* ==== global_vars ==== */
171  {
172  /* bind_address; */            NULL,
173  /* motd_file; */               NULL,
174  /* pid_file; */                NULL,
175  /* socket_options; */          NULL,
176
177  /* rsync_port; */              0,
178  },
179
180  /* ==== local_vars ==== */
181  {
182  /* auth_users; */              NULL,
183  /* charset; */                 NULL,
184  /* comment; */                 NULL,
185  /* dont_compress; */           DEFAULT_DONT_COMPRESS,
186  /* exclude; */                 NULL,
187  /* exclude_from; */            NULL,
188  /* filter; */                  NULL,
189  /* gid; */                     NULL,
190  /* hosts_allow; */             NULL,
191  /* hosts_deny; */              NULL,
192  /* include; */                 NULL,
193  /* include_from; */            NULL,
194  /* incoming_chmod; */          NULL,
195  /* lock_file; */               DEFAULT_LOCK_FILE,
196  /* log_file; */                NULL,
197  /* log_format; */              "%o %h [%a] %m (%u) %f %l",
198  /* name; */                    NULL,
199  /* outgoing_chmod; */          NULL,
200  /* path; */                    NULL,
201  /* postxfer_exec; */           NULL,
202  /* prexfer_exec; */            NULL,
203  /* refuse_options; */          NULL,
204  /* secrets_file; */            NULL,
205  /* temp_dir; */                NULL,
206  /* uid; */                     NULL,
207
208  /* max_connections; */         0,
209  /* max_verbosity; */           1,
210  /* syslog_facility; */         LOG_DAEMON,
211  /* timeout; */                 0,
212
213  /* fake_super; */              False,
214  /* ignore_errors; */           False,
215  /* ignore_nonreadable; */      False,
216  /* list; */                    True,
217  /* munge_symlinks; */          (BOOL)-1,
218  /* numeric_ids; */             (BOOL)-1,
219  /* read_only; */               True,
220  /* reverse_lookup; */          True,
221  /* strict_modes; */            True,
222  /* transfer_logging; */        False,
223  /* use_chroot; */              True,
224  /* write_only; */              False,
225  }
226 };
227
228 /* The currently configured values for all the variables. */
229 static all_vars Vars;
230
231 /* Stack of "Vars" values used by the &include directive. */
232 static item_list Vars_stack = EMPTY_ITEM_LIST;
233
234 /* The array of section values that holds all the defined modules. */
235 static item_list section_list = EMPTY_ITEM_LIST;
236
237 static int iSectionIndex = -1;
238 static BOOL bInGlobalSection = True;
239
240 #define NUMPARAMETERS (sizeof (parm_table) / sizeof (struct parm_struct))
241
242 static struct enum_list enum_facilities[] = {
243 #ifdef LOG_AUTH
244         { LOG_AUTH, "auth" },
245 #endif
246 #ifdef LOG_AUTHPRIV
247         { LOG_AUTHPRIV, "authpriv" },
248 #endif
249 #ifdef LOG_CRON
250         { LOG_CRON, "cron" },
251 #endif
252 #ifdef LOG_DAEMON
253         { LOG_DAEMON, "daemon" },
254 #endif
255 #ifdef LOG_FTP
256         { LOG_FTP, "ftp" },
257 #endif
258 #ifdef LOG_KERN
259         { LOG_KERN, "kern" },
260 #endif
261 #ifdef LOG_LPR
262         { LOG_LPR, "lpr" },
263 #endif
264 #ifdef LOG_MAIL
265         { LOG_MAIL, "mail" },
266 #endif
267 #ifdef LOG_NEWS
268         { LOG_NEWS, "news" },
269 #endif
270 #ifdef LOG_AUTH
271         { LOG_AUTH, "security" },
272 #endif
273 #ifdef LOG_SYSLOG
274         { LOG_SYSLOG, "syslog" },
275 #endif
276 #ifdef LOG_USER
277         { LOG_USER, "user" },
278 #endif
279 #ifdef LOG_UUCP
280         { LOG_UUCP, "uucp" },
281 #endif
282 #ifdef LOG_LOCAL0
283         { LOG_LOCAL0, "local0" },
284 #endif
285 #ifdef LOG_LOCAL1
286         { LOG_LOCAL1, "local1" },
287 #endif
288 #ifdef LOG_LOCAL2
289         { LOG_LOCAL2, "local2" },
290 #endif
291 #ifdef LOG_LOCAL3
292         { LOG_LOCAL3, "local3" },
293 #endif
294 #ifdef LOG_LOCAL4
295         { LOG_LOCAL4, "local4" },
296 #endif
297 #ifdef LOG_LOCAL5
298         { LOG_LOCAL5, "local5" },
299 #endif
300 #ifdef LOG_LOCAL6
301         { LOG_LOCAL6, "local6" },
302 #endif
303 #ifdef LOG_LOCAL7
304         { LOG_LOCAL7, "local7" },
305 #endif
306         { -1, NULL }
307 };
308
309 static struct parm_struct parm_table[] =
310 {
311  {"address",           P_STRING, P_GLOBAL,&Vars.g.bind_address,        NULL,0},
312  {"motd file",         P_STRING, P_GLOBAL,&Vars.g.motd_file,           NULL,0},
313  {"pid file",          P_STRING, P_GLOBAL,&Vars.g.pid_file,            NULL,0},
314  {"port",              P_INTEGER,P_GLOBAL,&Vars.g.rsync_port,          NULL,0},
315  {"socket options",    P_STRING, P_GLOBAL,&Vars.g.socket_options,      NULL,0},
316
317  {"auth users",        P_STRING, P_LOCAL, &Vars.l.auth_users,          NULL,0},
318  {"charset",           P_STRING, P_LOCAL, &Vars.l.charset,             NULL,0},
319  {"comment",           P_STRING, P_LOCAL, &Vars.l.comment,             NULL,0},
320  {"dont compress",     P_STRING, P_LOCAL, &Vars.l.dont_compress,       NULL,0},
321  {"exclude from",      P_STRING, P_LOCAL, &Vars.l.exclude_from,        NULL,0},
322  {"exclude",           P_STRING, P_LOCAL, &Vars.l.exclude,             NULL,0},
323  {"fake super",        P_BOOL,   P_LOCAL, &Vars.l.fake_super,          NULL,0},
324  {"filter",            P_STRING, P_LOCAL, &Vars.l.filter,              NULL,0},
325  {"gid",               P_STRING, P_LOCAL, &Vars.l.gid,                 NULL,0},
326  {"hosts allow",       P_STRING, P_LOCAL, &Vars.l.hosts_allow,         NULL,0},
327  {"hosts deny",        P_STRING, P_LOCAL, &Vars.l.hosts_deny,          NULL,0},
328  {"ignore errors",     P_BOOL,   P_LOCAL, &Vars.l.ignore_errors,       NULL,0},
329  {"ignore nonreadable",P_BOOL,   P_LOCAL, &Vars.l.ignore_nonreadable,  NULL,0},
330  {"include from",      P_STRING, P_LOCAL, &Vars.l.include_from,        NULL,0},
331  {"include",           P_STRING, P_LOCAL, &Vars.l.include,             NULL,0},
332  {"incoming chmod",    P_STRING, P_LOCAL, &Vars.l.incoming_chmod,      NULL,0},
333  {"list",              P_BOOL,   P_LOCAL, &Vars.l.list,                NULL,0},
334  {"lock file",         P_STRING, P_LOCAL, &Vars.l.lock_file,           NULL,0},
335  {"log file",          P_STRING, P_LOCAL, &Vars.l.log_file,            NULL,0},
336  {"log format",        P_STRING, P_LOCAL, &Vars.l.log_format,          NULL,0},
337  {"max connections",   P_INTEGER,P_LOCAL, &Vars.l.max_connections,     NULL,0},
338  {"max verbosity",     P_INTEGER,P_LOCAL, &Vars.l.max_verbosity,       NULL,0},
339  {"munge symlinks",    P_BOOL,   P_LOCAL, &Vars.l.munge_symlinks,      NULL,0},
340  {"name",              P_STRING, P_LOCAL, &Vars.l.name,                NULL,0},
341  {"numeric ids",       P_BOOL,   P_LOCAL, &Vars.l.numeric_ids,         NULL,0},
342  {"outgoing chmod",    P_STRING, P_LOCAL, &Vars.l.outgoing_chmod,      NULL,0},
343  {"path",              P_PATH,   P_LOCAL, &Vars.l.path,                NULL,0},
344 #ifdef HAVE_PUTENV
345  {"post-xfer exec",    P_STRING, P_LOCAL, &Vars.l.postxfer_exec,       NULL,0},
346  {"pre-xfer exec",     P_STRING, P_LOCAL, &Vars.l.prexfer_exec,        NULL,0},
347 #endif
348  {"read only",         P_BOOL,   P_LOCAL, &Vars.l.read_only,           NULL,0},
349  {"refuse options",    P_STRING, P_LOCAL, &Vars.l.refuse_options,      NULL,0},
350  {"reverse lookup",    P_BOOL,   P_LOCAL, &Vars.l.reverse_lookup,      NULL,0},
351  {"secrets file",      P_STRING, P_LOCAL, &Vars.l.secrets_file,        NULL,0},
352  {"strict modes",      P_BOOL,   P_LOCAL, &Vars.l.strict_modes,        NULL,0},
353  {"syslog facility",   P_ENUM,   P_LOCAL, &Vars.l.syslog_facility,     enum_facilities,0},
354  {"temp dir",          P_PATH,   P_LOCAL, &Vars.l.temp_dir,            NULL,0},
355  {"timeout",           P_INTEGER,P_LOCAL, &Vars.l.timeout,             NULL,0},
356  {"transfer logging",  P_BOOL,   P_LOCAL, &Vars.l.transfer_logging,    NULL,0},
357  {"uid",               P_STRING, P_LOCAL, &Vars.l.uid,                 NULL,0},
358  {"use chroot",        P_BOOL,   P_LOCAL, &Vars.l.use_chroot,          NULL,0},
359  {"write only",        P_BOOL,   P_LOCAL, &Vars.l.write_only,          NULL,0},
360  {NULL,                P_BOOL,   P_NONE,  NULL,                        NULL,0}
361 };
362
363 /* Initialise the Default all_vars structure. */
364 static void reset_all_vars(void)
365 {
366         memcpy(&Vars, &Defaults, sizeof Vars);
367 }
368
369 /* Expand %VAR% references.  Any unknown vars or unrecognized
370  * syntax leaves the raw chars unchanged. */
371 static char *expand_vars(char *str)
372 {
373         char *buf, *t, *f;
374         int bufsize;
375
376         if (strchr(str, '%') == NULL)
377                 return str;
378
379         bufsize = strlen(str) + 2048;
380         if ((buf = new_array(char, bufsize+1)) == NULL) /* +1 for trailing '\0' */
381                 out_of_memory("expand_vars");
382
383         for (t = buf, f = str; bufsize && *f; ) {
384                 if (*f == '%' && *++f != '%') {
385                         char *percent = strchr(f, '%');
386                         if (percent) {
387                                 char *val;
388                                 *percent = '\0';
389                                 val = getenv(f);
390                                 *percent = '%';
391                                 if (val) {
392                                         int len = strlcpy(t, val, bufsize+1);
393                                         if (len > bufsize)
394                                                 break;
395                                         bufsize -= len;
396                                         t += len;
397                                         f = percent + 1;
398                                         continue;
399                                 }
400                         }
401                         f--;
402                 }
403                 *t++ = *f++;
404                 bufsize--;
405         }
406         *t = '\0';
407
408         if (*f) {
409                 rprintf(FLOG, "Overflowed buf in expand_vars() trying to expand: %s\n", str);
410                 exit_cleanup(RERR_MALLOC);
411         }
412
413         if (bufsize && (buf = realloc(buf, t - buf + 1)) == NULL)
414                 out_of_memory("expand_vars");
415
416         return buf;
417 }
418
419 /* In this section all the functions that are used to access the
420  * parameters from the rest of the program are defined. */
421
422 #define FN_GLOBAL_STRING(fn_name, ptr) \
423  char *fn_name(void) {return expand_vars(*(char **)(ptr) ? *(char **)(ptr) : "");}
424 #define FN_GLOBAL_BOOL(fn_name, ptr) \
425  BOOL fn_name(void) {return *(BOOL *)(ptr);}
426 #define FN_GLOBAL_CHAR(fn_name, ptr) \
427  char fn_name(void) {return *(char *)(ptr);}
428 #define FN_GLOBAL_INTEGER(fn_name, ptr) \
429  int fn_name(void) {return *(int *)(ptr);}
430
431 #define FN_LOCAL_STRING(fn_name, val) \
432  char *fn_name(int i) {return expand_vars(LP_SNUM_OK(i) && iSECTION(i).val ? iSECTION(i).val : Vars.l.val ? Vars.l.val : "");}
433 #define FN_LOCAL_BOOL(fn_name, val) \
434  BOOL fn_name(int i) {return LP_SNUM_OK(i)? iSECTION(i).val : Vars.l.val;}
435 #define FN_LOCAL_CHAR(fn_name, val) \
436  char fn_name(int i) {return LP_SNUM_OK(i)? iSECTION(i).val : Vars.l.val;}
437 #define FN_LOCAL_INTEGER(fn_name, val) \
438  int fn_name(int i) {return LP_SNUM_OK(i)? iSECTION(i).val : Vars.l.val;}
439
440 FN_GLOBAL_STRING(lp_bind_address, &Vars.g.bind_address)
441 FN_GLOBAL_STRING(lp_motd_file, &Vars.g.motd_file)
442 FN_GLOBAL_STRING(lp_pid_file, &Vars.g.pid_file)
443 FN_GLOBAL_STRING(lp_socket_options, &Vars.g.socket_options)
444
445 FN_GLOBAL_INTEGER(lp_rsync_port, &Vars.g.rsync_port)
446
447 FN_LOCAL_STRING(lp_auth_users, auth_users)
448 FN_LOCAL_STRING(lp_charset, charset)
449 FN_LOCAL_STRING(lp_comment, comment)
450 FN_LOCAL_STRING(lp_dont_compress, dont_compress)
451 FN_LOCAL_STRING(lp_exclude, exclude)
452 FN_LOCAL_STRING(lp_exclude_from, exclude_from)
453 FN_LOCAL_STRING(lp_filter, filter)
454 FN_LOCAL_STRING(lp_gid, gid)
455 FN_LOCAL_STRING(lp_hosts_allow, hosts_allow)
456 FN_LOCAL_STRING(lp_hosts_deny, hosts_deny)
457 FN_LOCAL_STRING(lp_include, include)
458 FN_LOCAL_STRING(lp_include_from, include_from)
459 FN_LOCAL_STRING(lp_incoming_chmod, incoming_chmod)
460 FN_LOCAL_STRING(lp_lock_file, lock_file)
461 FN_LOCAL_STRING(lp_log_file, log_file)
462 FN_LOCAL_STRING(lp_log_format, log_format)
463 FN_LOCAL_STRING(lp_name, name)
464 FN_LOCAL_STRING(lp_outgoing_chmod, outgoing_chmod)
465 FN_LOCAL_STRING(lp_path, path)
466 FN_LOCAL_STRING(lp_postxfer_exec, postxfer_exec)
467 FN_LOCAL_STRING(lp_prexfer_exec, prexfer_exec)
468 FN_LOCAL_STRING(lp_refuse_options, refuse_options)
469 FN_LOCAL_STRING(lp_secrets_file, secrets_file)
470 FN_LOCAL_STRING(lp_temp_dir, temp_dir)
471 FN_LOCAL_STRING(lp_uid, uid)
472
473 FN_LOCAL_INTEGER(lp_max_connections, max_connections)
474 FN_LOCAL_INTEGER(lp_max_verbosity, max_verbosity)
475 FN_LOCAL_INTEGER(lp_syslog_facility, syslog_facility)
476 FN_LOCAL_INTEGER(lp_timeout, timeout)
477
478 FN_LOCAL_BOOL(lp_fake_super, fake_super)
479 FN_LOCAL_BOOL(lp_ignore_errors, ignore_errors)
480 FN_LOCAL_BOOL(lp_ignore_nonreadable, ignore_nonreadable)
481 FN_LOCAL_BOOL(lp_list, list)
482 FN_LOCAL_BOOL(lp_munge_symlinks, munge_symlinks)
483 FN_LOCAL_BOOL(lp_numeric_ids, numeric_ids)
484 FN_LOCAL_BOOL(lp_read_only, read_only)
485 FN_LOCAL_BOOL(lp_reverse_lookup, reverse_lookup)
486 FN_LOCAL_BOOL(lp_strict_modes, strict_modes)
487 FN_LOCAL_BOOL(lp_transfer_logging, transfer_logging)
488 FN_LOCAL_BOOL(lp_use_chroot, use_chroot)
489 FN_LOCAL_BOOL(lp_write_only, write_only)
490
491 /* Assign a copy of v to *s.  Handles NULL strings.  We don't worry
492  * about overwriting a malloc'd string because the long-running
493  * (port-listening) daemon only loads the config file once, and the
494  * per-job (forked or xinitd-ran) daemon only re-reads the file at
495  * the start, so any lost memory is inconsequential. */
496 static inline void string_set(char **s, const char *v)
497 {
498         if (!v)
499                 *s = NULL;
500         else if (!(*s = strdup(v)))
501                 out_of_memory("string_set");
502 }
503
504 /* Copy the local_vars, strdup'ing any strings.  NOTE:  this depends on
505  * the structure starting with a contiguous list of the char* variables,
506  * and having an accurate count in the LOCAL_STRING_COUNT() macro. */
507 static void copy_section(local_vars *psectionDest, local_vars *psectionSource)
508 {
509         int count = LOCAL_STRING_COUNT();
510         char **strings = (char**)psectionDest;
511
512         memcpy(psectionDest, psectionSource, sizeof psectionDest[0]);
513         while (count--) {
514                 if (strings[count] && !(strings[count] = strdup(strings[count])))
515                         out_of_memory("copy_section");
516         }
517 }
518
519 /* Initialise a section to the defaults. */
520 static void init_section(local_vars *psection)
521 {
522         memset(psection, 0, sizeof (local_vars));
523         copy_section(psection, &Vars.l);
524 }
525
526 /* Do a case-insensitive, whitespace-ignoring string compare. */
527 static int strwicmp(char *psz1, char *psz2)
528 {
529         /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
530         /* appropriate value. */
531         if (psz1 == psz2)
532                 return 0;
533
534         if (psz1 == NULL)
535                 return -1;
536
537         if (psz2 == NULL)
538                 return 1;
539
540         /* sync the strings on first non-whitespace */
541         while (1) {
542                 while (isSpace(psz1))
543                         psz1++;
544                 while (isSpace(psz2))
545                         psz2++;
546                 if (toUpper(psz1) != toUpper(psz2) || *psz1 == '\0' || *psz2 == '\0')
547                         break;
548                 psz1++;
549                 psz2++;
550         }
551         return *psz1 - *psz2;
552 }
553
554 /* Find a section by name. Otherwise works like get_section. */
555 static int getsectionbyname(char *name)
556 {
557         int i;
558
559         for (i = section_list.count - 1; i >= 0; i--) {
560                 if (strwicmp(iSECTION(i).name, name) == 0)
561                         break;
562         }
563
564         return i;
565 }
566
567 /* Add a new section to the sections array w/the default values. */
568 static int add_a_section(char *name)
569 {
570         int i;
571         local_vars *s;
572
573         /* it might already exist */
574         if (name) {
575                 i = getsectionbyname(name);
576                 if (i >= 0)
577                         return i;
578         }
579
580         i = section_list.count;
581         s = EXPAND_ITEM_LIST(&section_list, local_vars, 2);
582
583         init_section(s);
584         if (name)
585                 string_set(&s->name, name);
586
587         return i;
588 }
589
590 /* Map a parameter's string representation to something we can use.
591  * Returns False if the parameter string is not recognised, else TRUE. */
592 static int map_parameter(char *parmname)
593 {
594         int iIndex;
595
596         if (*parmname == '-')
597                 return -1;
598
599         for (iIndex = 0; parm_table[iIndex].label; iIndex++) {
600                 if (strwicmp(parm_table[iIndex].label, parmname) == 0)
601                         return iIndex;
602         }
603
604         rprintf(FLOG, "Unknown Parameter encountered: \"%s\"\n", parmname);
605         return -1;
606 }
607
608 /* Set a boolean variable from the text value stored in the passed string.
609  * Returns True in success, False if the passed string does not correctly
610  * represent a boolean. */
611 static BOOL set_boolean(BOOL *pb, char *parmvalue)
612 {
613         if (strwicmp(parmvalue, "yes") == 0
614          || strwicmp(parmvalue, "true") == 0
615          || strwicmp(parmvalue, "1") == 0)
616                 *pb = True;
617         else if (strwicmp(parmvalue, "no") == 0
618               || strwicmp(parmvalue, "False") == 0
619               || strwicmp(parmvalue, "0") == 0)
620                 *pb = False;
621         else {
622                 rprintf(FLOG, "Badly formed boolean in configuration file: \"%s\".\n", parmvalue);
623                 return False;
624         }
625         return True;
626 }
627
628 /* Process a parameter. */
629 static BOOL do_parameter(char *parmname, char *parmvalue)
630 {
631         int parmnum, i;
632         void *parm_ptr; /* where we are going to store the result */
633         void *def_ptr;
634         char *cp;
635
636         parmnum = map_parameter(parmname);
637
638         if (parmnum < 0) {
639                 rprintf(FLOG, "IGNORING unknown parameter \"%s\"\n", parmname);
640                 return True;
641         }
642
643         def_ptr = parm_table[parmnum].ptr;
644
645         if (bInGlobalSection)
646                 parm_ptr = def_ptr;
647         else {
648                 if (parm_table[parmnum].class == P_GLOBAL) {
649                         rprintf(FLOG, "Global parameter %s found in module section!\n", parmname);
650                         return True;
651                 }
652                 parm_ptr = SECTION_PTR(&iSECTION(iSectionIndex), def_ptr);
653         }
654
655         /* now switch on the type of variable it is */
656         switch (parm_table[parmnum].type) {
657         case P_PATH:
658         case P_STRING:
659                 /* delay expansion of vars */
660                 break;
661         default:
662                 /* expand any %VARS% now */
663                 parmvalue = expand_vars(parmvalue);
664                 break;
665         }
666
667         switch (parm_table[parmnum].type) {
668         case P_BOOL:
669                 set_boolean(parm_ptr, parmvalue);
670                 break;
671
672         case P_BOOLREV:
673                 set_boolean(parm_ptr, parmvalue);
674                 *(BOOL *)parm_ptr = ! *(BOOL *)parm_ptr;
675                 break;
676
677         case P_INTEGER:
678                 *(int *)parm_ptr = atoi(parmvalue);
679                 break;
680
681         case P_CHAR:
682                 *(char *)parm_ptr = *parmvalue;
683                 break;
684
685         case P_OCTAL:
686                 sscanf(parmvalue, "%o", (int *)parm_ptr);
687                 break;
688
689         case P_PATH:
690                 string_set(parm_ptr, parmvalue);
691                 if ((cp = *(char**)parm_ptr) != NULL) {
692                         int len = strlen(cp);
693                         while (len > 1 && cp[len-1] == '/') len--;
694                         cp[len] = '\0';
695                 }
696                 break;
697
698         case P_STRING:
699                 string_set(parm_ptr, parmvalue);
700                 break;
701
702         case P_ENUM:
703                 for (i=0; parm_table[parmnum].enum_list[i].name; i++) {
704                         if (strequal(parmvalue, parm_table[parmnum].enum_list[i].name)) {
705                                 *(int *)parm_ptr = parm_table[parmnum].enum_list[i].value;
706                                 break;
707                         }
708                 }
709                 if (!parm_table[parmnum].enum_list[i].name) {
710                         if (atoi(parmvalue) > 0)
711                                 *(int *)parm_ptr = atoi(parmvalue);
712                 }
713                 break;
714         }
715
716         return True;
717 }
718
719 /* Process a new section (rsync module).
720  * Returns True on success, False on failure. */
721 static BOOL do_section(char *sectionname)
722 {
723         BOOL isglobal;
724
725         if (*sectionname == ']') { /* A special push/pop/reset directive from params.c */
726                 bInGlobalSection = 1;
727                 if (strcmp(sectionname+1, "push") == 0) {
728                         all_vars *vp = EXPAND_ITEM_LIST(&Vars_stack, all_vars, 2);
729                         memcpy(vp, &Vars, sizeof Vars);
730                 } else if (strcmp(sectionname+1, "pop") == 0
731                  || strcmp(sectionname+1, "reset") == 0) {
732                         all_vars *vp = ((all_vars*)Vars_stack.items) + Vars_stack.count - 1;
733                         if (!Vars_stack.count)
734                                 return False;
735                         memcpy(&Vars, vp, sizeof Vars);
736                         if (sectionname[1] == 'p')
737                                 Vars_stack.count--;
738                 } else
739                         return False;
740                 return True;
741         }
742
743         isglobal = strwicmp(sectionname, GLOBAL_NAME) == 0;
744
745         /* At the end of the global section, add any --dparam items. */
746         if (bInGlobalSection && !isglobal) {
747                 if (!section_list.count)
748                         set_dparams(0);
749         }
750
751         /* if we've just struck a global section, note the fact. */
752         bInGlobalSection = isglobal;
753
754         /* check for multiple global sections */
755         if (bInGlobalSection)
756                 return True;
757
758 #if 0
759         /* If we have a current section, tidy it up before moving on. */
760         if (iSectionIndex >= 0) {
761                 /* Add any tidy work as needed ... */
762                 if (problem)
763                         return False;
764         }
765 #endif
766
767         if (strchr(sectionname, '/') != NULL) {
768                 rprintf(FLOG, "Warning: invalid section name in configuration file: %s\n", sectionname);
769                 return False;
770         }
771
772         if ((iSectionIndex = add_a_section(sectionname)) < 0) {
773                 rprintf(FLOG, "Failed to add a new module\n");
774                 bInGlobalSection = True;
775                 return False;
776         }
777
778         return True;
779 }
780
781 /* Load the modules from the config file. Return True on success,
782  * False on failure. */
783 int lp_load(char *pszFname, int globals_only)
784 {
785         bInGlobalSection = True;
786
787         reset_all_vars();
788
789         /* We get sections first, so have to start 'behind' to make up. */
790         iSectionIndex = -1;
791         return pm_process(pszFname, globals_only ? NULL : do_section, do_parameter);
792 }
793
794 BOOL set_dparams(int syntax_check_only)
795 {
796         char *equal, *val, **params = dparam_list.items;
797         unsigned j;
798
799         for (j = 0; j < dparam_list.count; j++) {
800                 equal = strchr(params[j], '='); /* options.c verified this */
801                 *equal = '\0';
802                 if (syntax_check_only) {
803                         if (map_parameter(params[j]) < 0) {
804                                 rprintf(FERROR, "Unknown parameter \"%s\"\n", params[j]);
805                                 *equal = '=';
806                                 return False;
807                         }
808                 } else {
809                         for (val = equal+1; isSpace(val); val++) {}
810                         do_parameter(params[j], val);
811                 }
812                 *equal = '=';
813         }
814
815         return True;
816 }
817
818 /* Return the max number of modules (sections). */
819 int lp_num_modules(void)
820 {
821         return section_list.count;
822 }
823
824 /* Return the number of the module with the given name, or -1 if it doesn't
825  * exist. Note that this is a DIFFERENT ANIMAL from the internal function
826  * getsectionbyname()! This works ONLY if all sections have been loaded,
827  * and does not copy the found section. */
828 int lp_number(char *name)
829 {
830         int i;
831
832         for (i = section_list.count - 1; i >= 0; i--) {
833                 if (strcmp(lp_name(i), name) == 0)
834                         break;
835         }
836
837         return i;
838 }