Blame view

main.c 79.6 KB
redmine authored
1
/*
redmine authored
2
    clsync - file tree sync utility based on inotify/kqueue/bsm
redmine authored
3

redmine authored
4
    Copyright (C) 2014  Dmitry Yu Okunev <dyokunev@ut.mephi.ru> 0x8E30679C
redmine authored
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

redmine authored
20

redmine authored
21
#include "common.h"
redmine authored
22

redmine authored
23 24
#ifdef CAPABILITIES_SUPPORT
#	include <sys/capability.h>	// for capset()/capget() for --preserve-file-access
redmine authored
25 26
#endif
#if defined(__linux__) | defined(CAPABILITIES_SUPPORT)
redmine authored
27 28 29
#	include <sys/prctl.h>		// for prctl() for --preserve-fil-access
#endif

redmine authored
30 31
#include <pwd.h>	// getpwnam()
#include <grp.h>	// getgrnam()
redmine authored
32
#include <glib.h>	// gkf
redmine authored
33

redmine authored
34 35 36 37

#ifdef UNSHARE_SUPPORT
#	include <sched.h>	// unshare()
#endif
redmine authored
38 39 40 41
#ifdef GETMNTENT_SUPPORT
#	include <mntent.h>	// getmntent()
#	include <sys/mount.h>	// umount2()
#endif
redmine authored
42

redmine authored
43
#include "error.h"
redmine authored
44
#include "stringex.h"
redmine authored
45
#include "sync.h"
redmine authored
46
#include "malloc.h"
redmine authored
47
#include "cluster.h"
redmine authored
48
#include "fileutils.h"
redmine authored
49
#include "socket.h"
redmine authored
50
#include "syscalls.h"
redmine authored
51
#include "rules.h"
redmine authored
52 53 54
#if CGROUP_SUPPORT
#	include "cgroup.h"
#endif
redmine authored
55
#include "posix-hacks.h"
redmine authored
56

redmine authored
57
//#include "revision.h"
redmine authored
58

redmine authored
59
static const struct option long_options[] =
redmine authored
60
{
redmine authored
61 62
	{"watch-dir",		required_argument,	NULL,	WATCHDIR},
	{"sync-handler",	required_argument,	NULL,	SYNCHANDLER},
redmine authored
63 64
	{"--",			required_argument,	NULL,	SYNCHANDLERARGS0},
	{"---",			required_argument,	NULL,	SYNCHANDLERARGS1},
redmine authored
65 66
	{"rules-file",		required_argument,	NULL,	RULESFILE},
	{"destination-dir",	required_argument,	NULL,	DESTDIR},
redmine authored
67
	{"mode",		required_argument,	NULL,	MODE},
redmine authored
68
	{"socket",		required_argument,	NULL,	SOCKETPATH},
redmine authored
69 70 71
	{"socket-auth",		required_argument,	NULL,	SOCKETAUTH},
	{"socket-mod",		required_argument,	NULL,	SOCKETMOD},
	{"socket-own",		required_argument,	NULL,	SOCKETOWN},
redmine authored
72
	{"status-file",		required_argument,	NULL,	STATUSFILE},
redmine authored
73

redmine authored
74
	{"background",		optional_argument,	NULL,	BACKGROUND},
redmine authored
75
	{"config-file",		required_argument,	NULL,	CONFIGFILE},
redmine authored
76
	{"config-block",	required_argument,	NULL,	CONFIGBLOCK},
redmine authored
77
	{"config-block-inherits",required_argument,	NULL,	CONFIGBLOCKINHERITS},
redmine authored
78
	{"custom-signals",	required_argument,	NULL,	CUSTOMSIGNALS},
redmine authored
79
	{"pid-file",		required_argument,	NULL,	PIDFILE},
redmine authored
80 81
	{"uid",			required_argument,	NULL,	UID},
	{"gid",			required_argument,	NULL,	GID},
redmine authored
82 83
	{"privileged-uid",	required_argument,	NULL,	PRIVILEGEDUID},
	{"privileged-gid",	required_argument,	NULL,	PRIVILEGEDGID},
redmine authored
84 85
	{"sync-handler-uid",	required_argument,	NULL,	SYNCHANDLERUID},
	{"sync-handler-gid",	required_argument,	NULL,	SYNCHANDLERGID},
redmine authored
86
	{"chroot",		required_argument,	NULL,	CHROOT},
redmine authored
87 88 89
#ifdef PIVOTROOT_OPT_SUPPORT
	{"pivot-root",		required_argument,	NULL,	PIVOT_ROOT},
#endif
redmine authored
90
#ifdef UNSHARE_SUPPORT
redmine authored
91
	{"detach-network",	required_argument,	NULL,	DETACH_NETWORK},
redmine authored
92
	{"detach-ipc",		required_argument,	NULL,	DETACH_IPC},
redmine authored
93 94
	{"detach-miscellanea",	optional_argument,	NULL,	DETACH_MISCELLANEA},
#endif
redmine authored
95
#ifdef CAPABILITIES_SUPPORT
redmine authored
96
# ifdef SECCOMP_SUPPORT
redmine authored
97
	{"secure-splitting",	no_argument,		NULL,	SECURESPLITTING},
redmine authored
98
# endif
redmine authored
99
	{"splitting",		required_argument,	NULL,	SPLITTING},
redmine authored
100
	{"check-execvp-args",	optional_argument,	NULL,	CHECK_EXECVP_ARGS},
redmine authored
101
	{"add-permitted-hook-files",required_argument,	NULL,	ADDPERMITTEDHOOKFILES},
redmine authored
102 103 104
# ifdef SECCOMP_SUPPORT
	{"seccomp-filter",	optional_argument,	NULL,	SECCOMP_FILTER},
# endif
redmine authored
105
	{"forget-privthread-info",optional_argument,	NULL,	FORGET_PRIVTHREAD_INFO},
redmine authored
106 107
	{"permit-mprotect",	optional_argument,	NULL,	PERMIT_MPROTECT},
	{"shm-mprotect",	optional_argument,	NULL,	SHM_MPROTECT},
redmine authored
108
#endif
redmine authored
109
#ifdef GETMNTENT_SUPPORT
redmine authored
110
	{"mountpoints",		required_argument,	NULL,	MOUNTPOINTS},
redmine authored
111
#endif
redmine authored
112
#ifdef CAPABILITIES_SUPPORT
redmine authored
113
	{"preserve-capabilities",required_argument,	NULL,	CAP_PRESERVE},
redmine authored
114
	{"inherit-capabilities",optional_argument,	NULL,	CAPS_INHERIT},
redmine authored
115
#endif
redmine authored
116 117
#ifdef CGROUP_SUPPORT
	{"forbid-devices",	optional_argument,	NULL,	FORBIDDEVICES},
redmine authored
118
	{"cgroup-group-name",	required_argument,	NULL,	CG_GROUPNAME},
redmine authored
119
#endif
redmine authored
120
	{"threading",		required_argument,	NULL,	THREADING},
Andrew Savchenko authored
121
	{"retries",		required_argument,	NULL,	RETRIES},
redmine authored
122
	{"ignore-failures",	optional_argument,	NULL,	IGNOREFAILURES},
redmine authored
123
	{"exit-on-sync-skipping",optional_argument,	NULL,	EXITONSYNCSKIP},
redmine authored
124
	{"output",		required_argument,	NULL,	OUTPUT_METHOD},
redmine authored
125
	{"one-file-system",	optional_argument,	NULL,	ONEFILESYSTEM},
redmine authored
126
	{"exclude-mount-points",optional_argument,	NULL,	EXCLUDEMOUNTPOINTS},
redmine authored
127
#ifdef CLUSTER_SUPPORT
redmine authored
128 129
	{"cluster-iface",	required_argument,	NULL,	CLUSTERIFACE},		// Not implemented, yet
	{"cluster-ip",		required_argument,	NULL,	CLUSTERMCASTIPADDR},	// Not implemented, yet
redmine authored
130
	{"cluster-port",	required_argument,	NULL,	CLUSTERMCASTIPPORT},	// Not implemented, yet
redmine authored
131
	{"cluster-timeout",	required_argument,	NULL,	CLUSTERTIMEOUT},	// Not implemented, yet
redmine authored
132
	{"cluster-node-name",	required_argument,	NULL,	CLUSTERNODENAME},	// Not implemented, yet
redmine authored
133 134 135
	{"cluster-hash-dl-min",	required_argument,	NULL,	CLUSTERHDLMIN},
	{"cluster-hash-dl-max",	required_argument,	NULL,	CLUSTERHDLMAX},
	{"cluster-scan-dl-max",	required_argument,	NULL,	CLUSTERSDLMAX},
redmine authored
136
#endif
Artyom A Anikeev authored
137
	{"max-iterations",	required_argument,	NULL,	MAXITERATIONS},
redmine authored
138
	{"standby-file",	required_argument,	NULL,	STANDBYFILE},
redmine authored
139
	{"modification-signature",required_argument,	NULL,	MODSIGN},
redmine authored
140 141 142 143 144
	{"timeout-sync",	required_argument,	NULL,	SYNCTIMEOUT},
	{"delay-sync",		required_argument,	NULL,	SYNCDELAY},
	{"delay-collect",	required_argument,	NULL,	DELAY},
	{"delay-collect-bigfile",required_argument,	NULL,	BFILEDELAY},
	{"threshold-bigfile",	required_argument,	NULL,	BFILETHRESHOLD},
redmine authored
145
	{"cancel-syscalls",	required_argument,	NULL,	CANCEL_SYSCALLS},
redmine authored
146
	{"lists-dir",		required_argument,	NULL,	OUTLISTSDIR},
redmine authored
147
	{"have-recursive-sync",	optional_argument,	NULL,	HAVERECURSIVESYNC},
redmine authored
148
	{"synclist-simplify",	optional_argument,	NULL,	SYNCLISTSIMPLIFY},
redmine authored
149
#ifdef AUTORULESW
redmine authored
150
	{"auto-add-rules-w",	optional_argument,	NULL,	AUTORULESW},
redmine authored
151
#endif
redmine authored
152
	{"rsync-inclimit",	required_argument,	NULL,	RSYNCINCLIMIT},
redmine authored
153
	{"rsync-prefer-include",optional_argument,	NULL,	RSYNCPREFERINCLUDE},
redmine authored
154
	{"ignore-exitcode",	required_argument,	NULL,	IGNOREEXITCODE},
redmine authored
155
	{"dont-unlink-lists",	optional_argument,	NULL,	DONTUNLINK},
redmine authored
156
	{"fts-experimental-optimization", optional_argument,	NULL,	FTS_EXPERIMENTAL_OPTIMIZATION},
redmine authored
157
	{"full-initialsync",	optional_argument,	NULL,	INITFULL},
redmine authored
158
	{"only-initialsync",	optional_argument,	NULL,	ONLYINITSYNC},
redmine authored
159
	{"skip-initialsync",	optional_argument,	NULL,	SKIPINITSYNC},
redmine authored
160
	{"exit-on-no-events",	optional_argument,	NULL,	EXITONNOEVENTS},
redmine authored
161
	{"exit-hook",		required_argument,	NULL,	EXITHOOK},
redmine authored
162
	{"pre-exit-hook",	required_argument,	NULL,	PREEXITHOOK},
redmine authored
163 164
	{"verbose",		optional_argument,	NULL,	VERBOSE},
	{"debug",		optional_argument,	NULL,	DEBUG},
redmine authored
165
	{"dump-dir",		required_argument,	NULL,	DUMPDIR},
redmine authored
166
	{"quiet",		optional_argument,	NULL,	QUIET},
redmine authored
167
	{"monitor",		required_argument,	NULL,	MONITOR},
redmine authored
168
	{"label",		required_argument,	NULL,	LABEL},
redmine authored
169 170
	{"help",		optional_argument,	NULL,	HELP},
	{"version",		optional_argument,	NULL,	SHOW_VERSION},
redmine authored
171

redmine authored
172
	{NULL,			0,			NULL,	0}
redmine authored
173 174
};

redmine authored
175
#ifdef UNSHARE_SUPPORT
redmine authored
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
static char *const detachnetworkways[] = {
	[DN_OFF]		= "off",
	[DN_NONPRIVILEGED]	= "non-privileged",
	[DN_EVERYWHERE]		= "everywhere",
	NULL,
};
#endif

#ifdef PIVOTROOT_OPT_SUPPORT
static char *const pivotrootways[] = {
	[PW_OFF]	= "off",
	[PW_DIRECT]	= "direct",
	[PW_AUTO]	= "auto",
	[PW_AUTORO]	= "auto-ro",
	NULL,
};
#endif

redmine authored
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
enum xstatfield {
	X_STAT_FIELD_RESET = 0,
	X_STAT_FIELD_DEV,
	X_STAT_FIELD_INO,
	X_STAT_FIELD_MODE,
	X_STAT_FIELD_NLINK,
	X_STAT_FIELD_UID,
	X_STAT_FIELD_GID,
	X_STAT_FIELD_RDEV,
	X_STAT_FIELD_SIZE,
	X_STAT_FIELD_BLKSIZE,
	X_STAT_FIELD_BLOCKS,
	X_STAT_FIELD_ATIME,
	X_STAT_FIELD_MTIME,
	X_STAT_FIELD_CTIME,
redmine authored
209
	X_STAT_FIELD_ALL,
redmine authored
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
};

uint32_t xstatfield_to_statfield[] = {
	[X_STAT_FIELD_RESET]		= STAT_FIELD_RESET,
	[X_STAT_FIELD_DEV]		= STAT_FIELD_DEV,
	[X_STAT_FIELD_INO]		= STAT_FIELD_INO,
	[X_STAT_FIELD_MODE]		= STAT_FIELD_MODE,
	[X_STAT_FIELD_NLINK]		= STAT_FIELD_NLINK,
	[X_STAT_FIELD_UID]		= STAT_FIELD_UID,
	[X_STAT_FIELD_GID]		= STAT_FIELD_GID,
	[X_STAT_FIELD_RDEV]		= STAT_FIELD_RDEV,
	[X_STAT_FIELD_SIZE]		= STAT_FIELD_SIZE,
	[X_STAT_FIELD_BLKSIZE]		= STAT_FIELD_BLKSIZE,
	[X_STAT_FIELD_BLOCKS]		= STAT_FIELD_BLOCKS,
	[X_STAT_FIELD_ATIME]		= STAT_FIELD_ATIME,
	[X_STAT_FIELD_MTIME]		= STAT_FIELD_MTIME,
	[X_STAT_FIELD_CTIME]		= STAT_FIELD_CTIME,
redmine authored
227
	[X_STAT_FIELD_ALL]		= STAT_FIELD_ALL,
redmine authored
228 229
};

redmine authored
230
static char *const stat_fields[] = {
redmine authored
231 232 233 234 235 236 237 238 239 240 241 242 243 244
	[X_STAT_FIELD_RESET]		= "",
	[X_STAT_FIELD_DEV]		= "dev",
	[X_STAT_FIELD_INO]		= "ino",
	[X_STAT_FIELD_MODE]		= "mode",
	[X_STAT_FIELD_NLINK]		= "nlink",
	[X_STAT_FIELD_UID]		= "uid",
	[X_STAT_FIELD_GID]		= "gid",
	[X_STAT_FIELD_RDEV]		= "rdev",
	[X_STAT_FIELD_SIZE]		= "size",
	[X_STAT_FIELD_BLKSIZE]		= "blksize",
	[X_STAT_FIELD_BLOCKS]		= "blocks",
	[X_STAT_FIELD_ATIME]		= "atime",
	[X_STAT_FIELD_MTIME]		= "mtime",
	[X_STAT_FIELD_CTIME]		= "ctime",
redmine authored
245
	[X_STAT_FIELD_ALL]		= "*",
redmine authored
246 247 248
	NULL
};

redmine authored
249 250 251 252 253 254 255 256 257 258
enum x_csc_bm {
	X_CSC_RESET = 0,
	X_CSC_MON_STAT,
};

uint32_t xcsc_to_csc[] = {
	[X_CSC_RESET]			= CSC_RESET,
	[X_CSC_MON_STAT]		= CSC_MON_STAT,
};

redmine authored
259
static char *const syscalls_bitmask[] = {
redmine authored
260 261
	[X_CSC_RESET]			= "",
	[X_CSC_MON_STAT]		= "mon_stat",	// disable {l,}stat{,64}()-s in mon_*.c
redmine authored
262 263 264
	NULL
};

redmine authored
265 266
#ifdef CAPABILITIES_SUPPORT

redmine authored
267 268 269 270 271
enum x_capabilities {
	X_CAP_RESET = 0,
	X_CAP_DAC_READ_SEARCH,
	X_CAP_SETUID,
	X_CAP_SETGID,
redmine authored
272
	X_CAP_KILL,
redmine authored
273 274 275 276 277 278 279

	X_CAP_MAX
};
__u32 xcap_to_cap[] = {
	[X_CAP_DAC_READ_SEARCH] = CAP_DAC_READ_SEARCH,
	[X_CAP_SETUID] 		= CAP_SETUID,
	[X_CAP_SETGID] 		= CAP_SETGID,
redmine authored
280
	[X_CAP_KILL] 		= CAP_KILL,
redmine authored
281 282 283 284 285 286
};
static char *const capabilities[] = {
	[X_CAP_RESET]		= "",
	[X_CAP_DAC_READ_SEARCH]	= "CAP_DAC_READ_SEARCH",
	[X_CAP_SETUID]		= "CAP_SETUID",
	[X_CAP_SETGID]		= "CAP_SETGID",
redmine authored
287
	[X_CAP_KILL]		= "CAP_KILL",
redmine authored
288 289 290
	NULL
};
#define XCAP_TO_CAP(x) (xcap_to_cap[x])
redmine authored
291 292 293 294 295 296 297 298

static char *const capsinherits[] = {
	[CI_PERMITTED]		= "permittied",
	[CI_DONTTOUCH]		= "dont-touch",
	[CI_CLSYNC]		= "clsync",
	[CI_EMPTY]		= "empty",
};

redmine authored
299 300
#endif

redmine authored
301 302 303 304 305 306 307
static char *const socketauth[] = {
	[SOCKAUTH_UNSET]	= "",
	[SOCKAUTH_NULL]		= "null",
//	[SOCKAUTH_PAM]		= "pam",
	NULL
};

redmine authored
308 309 310 311 312 313 314
static char *const threading_modes[] = {
	[PM_OFF]		= "off",
	[PM_SAFE]		= "safe",
	[PM_FULL]		= "full",
	NULL
};

redmine authored
315
#ifdef CAPABILITIES_SUPPORT
redmine authored
316 317 318 319 320 321
static char *const splitting_modes[] = {
	[SM_OFF]		= "off",
	[SM_THREAD]		= "thread",
	[SM_PROCESS]		= "process",
	NULL
};
redmine authored
322
#endif
redmine authored
323

redmine authored
324
static char *const notify_engines[] = {
redmine authored
325
	[NE_UNDEFINED]		= "",
redmine authored
326 327 328
	[NE_INOTIFY]		= "inotify",
	[NE_KQUEUE]		= "kqueue",
	[NE_FANOTIFY]		= "fanotify",
redmine authored
329
	[NE_BSM]		= "bsm",
redmine authored
330
	[NE_BSM_PREFETCH]	= "bsm_prefetch",
redmine authored
331
	[NE_DTRACEPIPE]		= "dtracepipe",
redmine authored
332
	[NE_GIO]		= "gio",
redmine authored
333
	NULL
redmine authored
334 335
};

redmine authored
336 337 338 339 340 341 342
static char *const output_methods[] = {
	[OM_STDERR]		= "stderr",
	[OM_STDOUT]		= "stdout",
	[OM_SYSLOG]		= "syslog",
	NULL
};

redmine authored
343 344 345
static char *const modes[] = {
	[MODE_UNSET]		= "",
	[MODE_SIMPLE]		= "simple",
redmine authored
346
	[MODE_DIRECT]		= "direct",
redmine authored
347 348 349
	[MODE_SHELL]		= "shell",
	[MODE_RSYNCSHELL]	= "rsyncshell",
	[MODE_RSYNCDIRECT]	= "rsyncdirect",
redmine authored
350
	[MODE_RSYNCSO]		= "rsyncso",
redmine authored
351 352 353 354
	[MODE_SO]		= "so",
	NULL
};

redmine authored
355 356 357 358
static char *const status_descr[] = {
	[STATE_EXIT]		= "exiting",
	[STATE_STARTING]	= "starting",
	[STATE_RUNNING]		= "running",
redmine authored
359
	[STATE_SYNCHANDLER_ERR]	= "synchandler error",
redmine authored
360 361
	[STATE_REHASH]		= "rehashing",
	[STATE_TERM]		= "terminating",
redmine authored
362
	[STATE_THREAD_GC]	= "thread gc",
redmine authored
363
	[STATE_INITSYNC]	= "initsync",
redmine authored
364
	[STATE_HOLDON]		= "hold on",
redmine authored
365 366 367
	NULL
};

redmine authored
368
int syntax() {
redmine authored
369
	info("possible options:");
redmine authored
370
	int i=-1;
redmine authored
371
	while (long_options[++i].name != NULL) {
redmine authored
372 373 374 375 376 377 378 379 380 381 382 383
		switch (long_options[i].val) {
			case SYNCHANDLERARGS0:
			case SYNCHANDLERARGS1:
				continue;
		}
		if (long_options[i].val & OPTION_CONFIGONLY)
			continue;

		info("\t--%-24s%c%c%s", long_options[i].name, 
				long_options[i].val & OPTION_LONGOPTONLY ? ' ' : '-', 
				long_options[i].val & OPTION_LONGOPTONLY ? ' ' : long_options[i].val, 
			(long_options[i].has_arg == required_argument ? " argument" : ""));
redmine authored
384
	}
redmine authored
385
	exit(EINVAL);
redmine authored
386 387
}

redmine authored
388
int ncpus;
redmine authored
389 390
pid_t parent_pid;

redmine authored
391
pid_t waitpid_timed(pid_t child_pid, int *status_p, long sec, long nsec) {
redmine authored
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
	struct timespec ts;
	int status;

	ts.tv_sec  = sec;
	ts.tv_nsec = nsec;

	while (ts.tv_sec >= 0) {
		if (waitpid(child_pid, &status, WNOHANG)<0) {
			if (errno==ECHILD)
				return child_pid;
			return -1;
		} else
			if (status_p != NULL)
				*status_p = status;

		ts.tv_nsec -= WAITPID_TIMED_GRANULARITY;
		if (ts.tv_nsec < 0) {
			ts.tv_nsec += 1000*1000*1000;
			ts.tv_sec--;
		}
	}

	return 0;
}

redmine authored
417 418 419 420 421
int parent_isalive() {
	int rc;
	debug(12, "parent_pid == %u", parent_pid);

	if ((rc=kill(parent_pid, 0))) {
redmine authored
422 423 424 425
		if (errno == ESRCH) {
			debug(1, "kill(%u, 0) => %i; errno => %s", parent_pid, rc, strerror(errno));
			return 0;
		}
redmine authored
426 427 428 429 430 431
	}

	return 1;
}

void child_sigchld() {
redmine authored
432 433 434
	if (getppid() != 1)
		return;

redmine authored
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
	debug(1, "Got SIGCHLD (parent ended). Exit.");
	exit(-1);
	return;
}

int sethandler_sigchld(void (*handler)()) {
	struct sigaction sa;
	sa.sa_handler = handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
	critical_on (sigaction(SIGCHLD, &sa, 0) == -1);

	return 0;
}

redmine authored
450 451 452
# ifndef __linux__
void *watchforparent(void *parent_pid_p) {
	while (1) {
redmine authored
453
		child_sigchld();
redmine authored
454
		sleep(SLEEP_SECONDS);
redmine authored
455 456 457 458 459 460 461 462
	}

	return NULL;
}
# endif

pthread_t pthread_watchforparent;
pid_t fork_helper() {
redmine authored
463 464
	pid_t pid = fork();

redmine authored
465 466
	if (!pid) {	// is child?

redmine authored
467
		parent_pid = getppid();
redmine authored
468 469 470

		// Anti-zombie:

redmine authored
471
# ifdef __linux__
redmine authored
472 473
		// Linux have support of "prctl(PR_SET_PDEATHSIG, signal);"
		sethandler_sigchld(child_sigchld);
redmine authored
474
		prctl(PR_SET_PDEATHSIG, SIGCHLD);
redmine authored
475 476
# else
		pthread_create(&pthread_watchforparent, NULL, watchforparent, &parent_pid);
redmine authored
477 478
# endif
		debug(20, "parent_pid == %u", parent_pid);
redmine authored
479
		return 0;
redmine authored
480 481 482 483
	}

	return pid;
}
redmine authored
484

redmine authored
485
int version() {
redmine authored
486
	info(PROGRAM" v%i.%i.%i"REVISION"\n\t"AUTHOR"\n\nCompiled with options"
redmine authored
487 488 489 490 491 492
#ifdef _DEBUG_SUPPORT
		" -D_DEBUG_SUPPORT"
#endif
#ifdef _DEBUG_FORCE
		" -D_DEBUG_FORCE"
#endif
redmine authored
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
#ifdef KQUEUE_SUPPORT
		" -DKQUEUE_SUPPORT"
#endif
#ifdef INOTIFY_SUPPORT
		" -DINOTIFY_SUPPORT"
#endif
#ifdef INOTIFY_OLD
		" -DINOTIFY_OLD"
#endif
#ifdef FANOTIFY_SUPPORT
		" -DFANOTIFY_SUPPORT"
#endif
#ifdef BSM_SUPPORT
		" -DBSM_SUPPORT"
#endif
redmine authored
508 509 510
#ifdef GIO_SUPPORT
		" -DGIO_SUPPORT"
#endif
redmine authored
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
#ifdef DTRACEPIPE_SUPPORT
		" -DDTRACEPIPE_SUPPORT"
#endif
#ifdef BACKTRACE_SUPPORT
		" -DBACKTRACE_SUPPORT"
#endif
#ifdef CAPABILITIES_SUPPORT
		" -DCAPABILITIES_SUPPORT"
#endif
#ifdef SECCOMP_SUPPORT
		" -DSECCOMP_SUPPORT"
#endif
#ifdef GETMNTENT_SUPPORT
		" -DGETMNTENT_SUPPORT"
#endif
#ifdef UNSHARE_SUPPORT
		" -DUNSHARE_SUPPORT"
#endif
#ifdef PIVOTROOT_OPT_SUPPORT
		" -DPIVOTROOT_OPT_SUPPORT"
#endif
redmine authored
532 533 534
#ifdef CGROUP_SUPPORT
		" -DCGROUP_SUPPORT"
#endif
redmine authored
535 536 537 538 539 540
#ifdef TRE_SUPPORT
		" -DTRE_SUPPORT"
#endif
#ifdef HL_LOCKS
		" -DHL_LOCKS"
#endif
redmine authored
541
		, VERSION_MAJ, VERSION_MID, VERSION_MIN);
redmine authored
542 543 544
	exit(0);
}

redmine authored
545 546 547 548
int clsyncapi_getapiversion() {
	return CLSYNC_API_VERSION;
}

redmine authored
549 550 551
/**
 * @brief 			Gets raw (string) an option value by an option name
 * 
redmine authored
552
 * @param[in]	_ctx_p		Context
redmine authored
553 554 555 556 557 558
 @ @param[in]	variable_name	The name of the option
 * 
 * @retval	char *		Pointer to newly allocated string, if successful
 * @retval	NULL		On error
 * 
 */
redmine authored
559 560
const char *parameter_get(const char *variable_name, void *_ctx_p) {
	const ctx_t *ctx_p = _ctx_p;
redmine authored
561 562
	const struct option *long_option_p = long_options;
	int param_id = -1;
redmine authored
563
	debug(8, "(\"%s\", %p)", variable_name, ctx_p);
redmine authored
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

	while (long_option_p->name != NULL) {
		if (!strcmp(long_option_p->name, variable_name)) {
			param_id = long_option_p->val;
			break;
		}

		long_option_p++;
	}

	if (param_id == -1) {
		errno = ENOENT;
		return NULL;
	}

redmine authored
579 580
	debug(9, "ctx_p->flags_values_raw[%i] == \"%s\"", param_id, ctx_p->flags_values_raw[param_id]);

redmine authored
581 582 583 584
	return ctx_p->flags_values_raw[param_id];
}

/**
redmine authored
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
 * @brief 			Gets raw (string) an option value by an option name and
 * 				updates ctx_p->synchandler_argf
 * 
 * @param[in]	_ctx_p		Context
 @ @param[in]	variable_name	The name of the option
 * 
 * @retval	char *		Pointer to newly allocated string, if successful
 * @retval	NULL		On error
 * 
 */
const char *parameter_get_wmacro(const char *variable_name, void *_ctx_p) {
	ctx_t *ctx_p = _ctx_p;
	static struct dosync_arg dosync_arg = {0};
	debug(9, "(\"%s\", %p)", variable_name, _ctx_p);

	if (*variable_name < 'A' || *variable_name > 'Z')
		return parameter_get(variable_name, _ctx_p);

	if (!strcmp(variable_name, "RSYNC-ARGS")) {
		ctx_p->synchandler_argf |= SHFL_RSYNC_ARGS;
		return NULL;
	}
	if (!strcmp(variable_name, "INCLUDE-LIST")) {
		ctx_p->synchandler_argf |= SHFL_INCLUDE_LIST;
		return NULL;
	}

	const char *r = sync_parameter_get(variable_name, &dosync_arg);

	if (r == dosync_arg.outf_path) {
		ctx_p->synchandler_argf |= SHFL_INCLUDE_LIST_PATH;
		return NULL;
	}

	if (r == dosync_arg.excf_path) {
		ctx_p->synchandler_argf |= SHFL_EXCLUDE_LIST_PATH;
		return NULL;
	}

	errno = ENOENT;
	return NULL;
}

/**
redmine authored
629 630 631
 * @brief 			Expands option values, e. g. "/var/log/clsync-%label%.pid" -> "/var/log/clsync-clone.pid"
 * 
 * @param[in]	ctx_p		Context
redmine authored
632 633 634 635 636
 * @param[in]	arg		An allocated string with unexpanded value. Will be free'd
 * @param[out]	macro_count_p	A pointer to count of found macro-s
 * @param[out]	expand_count_p	A pointer to count of expanded macro-s
 * @param[in]	parameter_get	A function to resolve macro-s
 * @param[in]	parameter_get_arg An argument to the function
redmine authored
637 638 639 640 641
 * 
 * @retval	char *		Pointer to newly allocated string, if successful
 * @retval	NULL		On error
 * 
 */
redmine authored
642 643 644 645 646 647 648 649 650 651
char *parameter_expand(
		ctx_t *ctx_p,
		char *arg,
		int exceptionflags,
		int *macro_count_p,
		int *expand_count_p,
		const char *(*parameter_get)(const char *variable_name, void *arg),
		void *parameter_get_arg
) {
	debug(9, "(ctx_p, \"%s\" [%p], ...)", arg, arg);
redmine authored
652 653 654
	char *ret = NULL;
	size_t ret_size = 0, ret_len = 0;

redmine authored
655 656 657 658 659 660 661
#ifdef PARANOID
	if (arg == NULL) {
		errno = EINVAL;
		return NULL;
	}
#endif

redmine authored
662 663 664 665 666
	if (macro_count_p != NULL)
		*macro_count_p  = 0;
	if (expand_count_p != NULL)
		*expand_count_p = 0;

redmine authored
667 668 669 670 671 672
	char *ptr = &arg[-1];
	while (1) {
		ptr++;

		switch (*ptr) {
			case 0:
redmine authored
673 674 675 676
				if (ret == NULL) {
					debug(3, "Expanding value \"%s\" to \"%s\" (case #1)", arg, arg);
					return arg;
				}
redmine authored
677
				ret[ret_len] = 0;
redmine authored
678
				debug(3, "Expanding value \"%s\" to \"%s\" (case #0)", arg, ret);
redmine authored
679 680 681 682 683 684 685 686
				free(arg);
				return ret;
			case '%': {
				if (ptr[1] == '%') {
					ret[ret_len++] = *(ptr++);
					break;
				}

redmine authored
687
				debug(25, "A macro");
redmine authored
688 689 690 691 692 693 694 695
				char nest_searching = 1;
				char *ptr_nest = ptr;
				while (nest_searching) {
					ptr_nest++;

					switch (*ptr_nest) {
						case 0:
							ret[ret_len] = 0;
redmine authored
696 697
							if (!(exceptionflags&1))
								warning("Unexpected end of macro-substitution \"%s\" in value \"%s\"; result value is \"%s\"", ptr, arg, ret);
redmine authored
698 699 700
							free(arg);
							return ret;
						case '%': {
redmine authored
701 702 703 704 705 706
							char       *variable_name;
							const char *variable_value;
							size_t      variable_value_len;

							if (macro_count_p != NULL)
								(*macro_count_p)++;
redmine authored
707

redmine authored
708
							nest_searching = 0;
redmine authored
709 710
							*ptr_nest = 0;
							variable_name  = &ptr[1];
redmine authored
711
							debug(15, "The macro is \"%s\"", variable_name);
redmine authored
712
							if (!strcmp(variable_name, "PID")) {
redmine authored
713
								debug(35, "\"PID\"", variable_name);
redmine authored
714 715 716 717 718 719 720 721
								if (!*ctx_p->pid_str) {
									snprintf(ctx_p->pid_str, 64, "%u", ctx_p->pid);
									ctx_p->pid_str_len = strlen(ctx_p->pid_str);
								}
								variable_value     = ctx_p->pid_str;
								variable_value_len = ctx_p->pid_str_len;
							} else
							if (*variable_name >= 'A' && *variable_name <= 'Z' && (exceptionflags&4)) {	// Lazy substitution, preserving the value
redmine authored
722
								debug(35, "Lazy substitution", variable_name);
redmine authored
723 724
								variable_value     =  ptr;
								variable_value_len = (ptr_nest - ptr + 1);
redmine authored
725
								parameter_get(variable_name, parameter_get_arg);
redmine authored
726
							} else {									// Substituting
redmine authored
727
								debug(35, "Substitution", variable_name);
redmine authored
728
								errno = 0;
redmine authored
729 730
								variable_value = parameter_get(variable_name, parameter_get_arg);
								if (variable_value == NULL) {
redmine authored
731
									if (!(exceptionflags&2) && (errno != ENOENT))
redmine authored
732 733 734 735 736 737
										warning("Variable \"%s\" is not set (%s)", variable_name, strerror(errno));
									*ptr_nest = '%';
									errno = 0;
									break;
								}
								variable_value_len = strlen(variable_value);
redmine authored
738 739 740

								if (expand_count_p != NULL)
									(*expand_count_p)++;
redmine authored
741
							}
redmine authored
742
							*ptr_nest = '%';
redmine authored
743 744
							if (ret_len+variable_value_len+1 >= ret_size) {
								ret_size = ret_len+variable_value_len+1 + ALLOC_PORTION;
redmine authored
745
								ret      = xrealloc(ret, ret_size);
redmine authored
746 747 748 749 750 751 752 753 754 755 756 757
							}
							memcpy(&ret[ret_len], variable_value, variable_value_len);
							ret_len += variable_value_len;
							break;
						}
					}
				}
				ptr = ptr_nest;
				break;
			}
			default: {
				if (ret_len+2 >= ret_size) {
redmine authored
758 759
					ret_size += ALLOC_PORTION+2;
					ret       = xrealloc(ret, ret_size);
redmine authored
760 761 762 763 764 765 766 767 768 769
				}
				ret[ret_len++] = *ptr;
				break;
			}
		}
	}
	error("Unknown internal error");
	return arg;
}

redmine authored
770
static inline int synchandler_arg(char *arg, size_t arg_len, void *_ctx_p, enum shargsid shargsid) {
redmine authored
771
	ctx_t *ctx_p = _ctx_p;
redmine authored
772
	debug(9, "(\"%s\" [%p], %u, %p, %u)", arg, arg, arg_len, _ctx_p, shargsid);
redmine authored
773

redmine authored
774
	if (!strcmp(arg, "%RSYNC-ARGS%")) {
redmine authored
775
		char *args_e[] = RSYNC_ARGS_E, *args_i[] = RSYNC_ARGS_I, **args_p;
redmine authored
776
		free(arg);
redmine authored
777 778 779 780 781

		args_p = ctx_p->flags[RSYNCPREFERINCLUDE] ? args_i : args_e;

		while (*args_p != NULL) {
#ifdef VERYPARANOID
redmine authored
782
			if (!strcmp(*args_p, "%RSYNC-ARGS%")) {
redmine authored
783 784 785 786
				errno = EINVAL;
				critical("Infinite recursion detected");
			}
#endif
redmine authored
787
			if (synchandler_arg(strdup(*args_p), strlen(*args_p), ctx_p, shargsid))
redmine authored
788 789 790 791 792 793 794
				return errno;
			args_p++;
		}
		return 0;
	}

	if (ctx_p->synchandler_args[shargsid].c >= MAXARGUMENTS-2) {
redmine authored
795 796 797 798 799 800 801
		errno = E2BIG;
		error("There're too many sync-handler arguments "
			"(%u > "XTOSTR(MAXARGUMENTS-2)"; arg == \"%s\").",
			arg);
		return errno;
	}

redmine authored
802
#ifdef _DEBUG_FORCE
redmine authored
803 804 805 806
	debug(14, "ctx_p->synchandler_args[%u].v[%u] = %p", shargsid, ctx_p->synchandler_args[shargsid].c, arg);
#endif
	ctx_p->synchandler_args[shargsid].v[ctx_p->synchandler_args[shargsid].c++] = arg;

redmine authored
807 808 809
	return 0;
}

redmine authored
810 811 812 813 814 815 816 817
static int synchandler_arg0(char *arg, size_t arg_len, void *_ctx_p) {
	return synchandler_arg(arg, arg_len, _ctx_p, SHARGS_PRIMARY);
}

static int synchandler_arg1(char *arg, size_t arg_len, void *_ctx_p) {
	return synchandler_arg(arg, arg_len, _ctx_p, SHARGS_INITIAL);
}

Andrew Savchenko authored
818 819 820 821 822
/* strtol wrapper with error checks */
static inline long xstrtol(const char *str, int *err) {
	long res;
	char *endptr;

Andrew Savchenko authored
823
	errno = 0;
Andrew Savchenko authored
824 825 826 827 828 829 830 831 832
	res = strtol(str, &endptr, 0);
	if (errno || *endptr) {
		error("argument \"%s\" can't be parsed as a number", str);
		*err = EINVAL;
	}
	return res;
}

static inline int parse_customsignals(ctx_t *ctx_p, char *arg) {
redmine authored
833
	char *ptr = arg, *start = arg;
Andrew Savchenko authored
834
	int ret = 0;
redmine authored
835 836 837 838 839 840
	unsigned int signal;
	do {
		switch (*ptr) {
			case 0:
			case ',':
			case ':':
redmine authored
841 842 843 844
				// TODO: use xstrtol() instead of atoi()

				//signal = (unsigned int)xstrtol(start, &ret);
				signal = (unsigned int)atoi(start);
Andrew Savchenko authored
845 846 847 848
				if (ret) {
					errno = ret;
					return errno;
				}
redmine authored
849 850 851 852 853 854 855 856 857 858
				if (signal == 0) {
					// flushing the setting
					int i = 0;
					while (i < 256) {
						if (ctx_p->customsignal[i]) {
							free(ctx_p->customsignal[i]);
							ctx_p->customsignal[i] = NULL;
						}
						i++;
					}
redmine authored
859
#ifdef _DEBUG_FORCE
redmine authored
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
					fprintf(stderr, "Force-Debug: parse_parameter(): Reset custom signals.\n");
#endif
				} else {
					if (*ptr != ':') {
						char ch = *ptr;

						*ptr = 0;
							errno = EINVAL;
							error("Expected \":\" in \"%s\"", start);
						*ptr = ch;
						return errno;
					}

					{
						char ch, *end;
						ptr++;

						end = ptr;
						while (*end && *end != ',') end++;

						if (end == ptr) {
							errno = EINVAL;
							error("Empty config block name on signal \"%u\"", signal);
							return errno;
						}

						if (signal > MAXSIGNALNUM) {
							errno = EINVAL;
							error("Too high value of the signal: \"%u\" > "XTOSTR(MAXSIGNALNUM)"", signal);
							return errno;
						}

						ch = *end; *end = 0;
						ctx_p->customsignal[signal] = strdup(ptr);
						*end = ch;
redmine authored
895
#ifdef _DEBUG_FORCE
redmine authored
896 897
						fprintf(stderr, "Force-Debug: parse_parameter(): Adding custom signal %u.\n", signal);
#endif
redmine authored
898
						ptr = end;
redmine authored
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
					}
				}
				start = ptr+1;
				break;
			case '0' ... '9':
				break;
			default:
				errno = EINVAL;
				error("Expected a digit, comma (or colon) but got \"%c\"", *ptr);
				return errno;
		}
	} while (*(ptr++));

	return 0;
}

Andrew Savchenko authored
915 916
static int parse_parameter(ctx_t *ctx_p, uint16_t param_id, char *arg, paramsource_t paramsource) {
	int ret = 0;
redmine authored
917
#ifdef _DEBUG_FORCE
redmine authored
918 919
	fprintf(stderr, "Force-Debug: parse_parameter(): %i: %i = \"%s\"\n", paramsource, param_id, arg);
#endif
redmine authored
920
	switch (paramsource) {
redmine authored
921
		case PS_CONTROL:
redmine authored
922
		case PS_ARGUMENT:
redmine authored
923
			if (param_id & OPTION_CONFIGONLY) {
redmine authored
924 925 926
				syntax();
				return 0;
			}
redmine authored
927
			ctx_p->flags_set[param_id] = 1;
redmine authored
928 929
			break;
		case PS_CONFIG:
redmine authored
930
			if (ctx_p->flags_set[param_id])
redmine authored
931
				return 0;
redmine authored
932
			ctx_p->flags_set[param_id] = 1;
redmine authored
933
			break;
redmine authored
934 935 936 937 938 939 940 941
		case PS_DEFAULTS:
#ifdef VERYPARANOID
			if (ctx_p->flags_set[param_id]) {
				error("Parameter #%i is already set. No need in setting the default value.", param_id);
				return 0;
			}
#endif
			break;
redmine authored
942 943 944 945 946 947 948 949 950 951 952 953
/*		case PS_REHASH:
			arg = ctx_p->flags_values_raw[param_id];
#ifdef VERYPARANOID
			critical_on (arg == NULL);
#endif

			debug(9, "Rehash setting %i -> \"%s\"", param_id, arg);
			break;*/
		case PS_CORRECTION:
			critical_on (arg == NULL);
			debug(9, "Correcting setting %i -> \"%s\"", param_id, arg);
			break;
redmine authored
954
		default:
redmine authored
955
			error("Unknown parameter #%i source (value \"%s\").", param_id, arg!=NULL ? arg : "");
redmine authored
956 957
			break;
	}
redmine authored
958

redmine authored
959
	if ((arg != NULL) /*&& (paramsource != PS_REHASH)*/) {
redmine authored
960 961
		if (param_id != SYNCHANDLERARGS0 && param_id != SYNCHANDLERARGS1)
			arg = parameter_expand(ctx_p, arg, 0, NULL, NULL, parameter_get, ctx_p);
redmine authored
962 963 964

		if (ctx_p->flags_values_raw[param_id] != NULL)
			free(ctx_p->flags_values_raw[param_id]);
redmine authored
965
		ctx_p->flags_values_raw[param_id] = arg;
redmine authored
966
	}
redmine authored
967

redmine authored
968
	switch (param_id) {
redmine authored
969 970 971 972
		case '?':
		case HELP:
			syntax();
			break;
redmine authored
973
		case CONFIGFILE:
redmine authored
974
			ctx_p->config_path    = *arg ? arg : NULL;
redmine authored
975 976
			break;
		case CONFIGBLOCK:
redmine authored
977 978 979
			ctx_p->config_block   = *arg ? arg : NULL;
			break;
		case CONFIGBLOCKINHERITS:
redmine authored
980
			break;
redmine authored
981 982 983 984 985 986 987 988 989
		case CUSTOMSIGNALS:
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"custom-signal\" in run-time. Ignoring.");
				return 0;
			}

			if (parse_customsignals(ctx_p, arg))
				return errno;
			break;
redmine authored
990 991
		case UID: {
			struct passwd *pwd = getpwnam(arg);
redmine authored
992
			ctx_p->flags[param_id]++;
redmine authored
993 994

			if (pwd == NULL) {
Andrew Savchenko authored
995
				ctx_p->uid = (unsigned int)xstrtol(arg, &ret);
redmine authored
996 997 998 999
				break;
			}

			ctx_p->uid = pwd->pw_uid;
redmine authored
1000
			break;
redmine authored
1001 1002 1003
		}
		case GID: {
			struct group *grp = getgrnam(arg);
redmine authored
1004
			ctx_p->flags[param_id]++;
redmine authored
1005 1006

			if (grp == NULL) {
Andrew Savchenko authored
1007
				ctx_p->gid = (unsigned int)xstrtol(arg, &ret);
redmine authored
1008 1009 1010 1011
				break;
			}

			ctx_p->gid = grp->gr_gid;
redmine authored
1012
			break;
redmine authored
1013
		}
redmine authored
1014
#ifdef CAPABILITIES_SUPPORT
redmine authored
1015
# ifdef SECCOMP_SUPPORT
redmine authored
1016
		case SECURESPLITTING: {
redmine authored
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
			if (ctx_p->flags_values_raw[CHECK_EXECVP_ARGS] == NULL)
				ctx_p->flags[CHECK_EXECVP_ARGS]++;

			if (ctx_p->flags_values_raw[SECCOMP_FILTER] == NULL)
				ctx_p->flags[SECCOMP_FILTER]++;

			if (ctx_p->flags_values_raw[FORBIDDEVICES] == NULL)
				ctx_p->flags[FORBIDDEVICES]++;

			if (ctx_p->flags_values_raw[SPLITTING] != NULL)
				break;

redmine authored
1029
			arg = "process";
redmine authored
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
		}
		case SPLITTING: {
			char *value, *arg_orig = arg;

			if (!*arg) {
				ctx_p->flags[param_id] = 0;
				return 0;
			}

			splittingmode_t splittingmode = getsubopt(&arg, splitting_modes, &value);
			if((int)splittingmode == -1) {
				errno = EINVAL;
				error("Invalid splitting mode entered: \"%s\"", arg_orig);
				return EINVAL;
			}
			ctx_p->flags[SPLITTING] = splittingmode;

			if (param_id != SECURESPLITTING)
				break;
			switch (splittingmode) {
				case SM_THREAD:
					ctx_p->flags[FORGET_PRIVTHREAD_INFO]++;
					break;
				case SM_PROCESS:
					break;
				case SM_OFF:
					errno = EINVAL;
					error("Cannot understand \"--secure-splitting=off\". This configuration line have no sence.");
					break;
			}
redmine authored
1060 1061
			if (ctx_p->flags_values_raw[PERMIT_MPROTECT] == NULL)
				ctx_p->flags[PERMIT_MPROTECT] = (splittingmode != SM_THREAD);
redmine authored
1062 1063 1064
			break;
		}
# endif
redmine authored
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
		case PRIVILEGEDUID: {
			struct passwd *pwd = getpwnam(arg);
			ctx_p->flags[param_id]++;

			if (pwd == NULL) {
				ctx_p->privileged_uid = (unsigned int)xstrtol(arg, &ret);
				break;
			}

			ctx_p->privileged_uid = pwd->pw_uid;
			break;
		}
		case PRIVILEGEDGID: {
			struct group *grp = getgrnam(arg);
			ctx_p->flags[param_id]++;

			if (grp == NULL) {
				ctx_p->privileged_gid = (unsigned int)xstrtol(arg, &ret);
				break;
			}

			ctx_p->privileged_gid = grp->gr_gid;
			break;
		}
redmine authored
1089 1090 1091 1092 1093
		case SYNCHANDLERUID: {
			struct passwd *pwd = getpwnam(arg);
			ctx_p->flags[param_id]++;

			if (pwd == NULL) {
Andrew Savchenko authored
1094
				ctx_p->synchandler_uid = (unsigned int)xstrtol(arg, &ret);
redmine authored
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
				break;
			}

			ctx_p->synchandler_uid = pwd->pw_uid;
			break;
		}
		case SYNCHANDLERGID: {
			struct group *grp = getgrnam(arg);
			ctx_p->flags[param_id]++;

			if (grp == NULL) {
Andrew Savchenko authored
1106
				ctx_p->synchandler_gid = (unsigned int)xstrtol(arg, &ret);
redmine authored
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
				break;
			}

			ctx_p->synchandler_gid = grp->gr_gid;
			break;
		}
		case CAP_PRESERVE: {
			char *subopts = arg;

			ctx_p->caps  = 0;

			while (*subopts != 0) {
				char *value;
				__u32 cap = getsubopt(&subopts, capabilities, &value);
				debug(4, "cap == 0x%x", cap);
				if (cap != X_CAP_RESET)
					ctx_p->caps |= CAP_TO_MASK(XCAP_TO_CAP(cap));
			}

			break;
		}
redmine authored
1128 1129 1130 1131
		case CAPS_INHERIT: {
			char *value, *arg_orig = arg;

			if (!*arg) {
redmine authored
1132
				ctx_p->flags[param_id] = 0;
redmine authored
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
				return 0;
			}

			capsinherit_t capsinherit = getsubopt(&arg, capsinherits, &value);
			if((int)capsinherit == -1) {
				errno = EINVAL;
				error("Invalid capabilities inheriting mode entered: \"%s\"", arg_orig);
				return EINVAL;
			}
			ctx_p->flags[CAPS_INHERIT] = capsinherit;

			break;
		}
redmine authored
1146
#endif
redmine authored
1147 1148 1149 1150 1151
		case CHROOT:
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"chroot\" in run-time. Ignoring.");
				return 0;
			}
redmine authored
1152
			if (!*arg) {
redmine authored
1153 1154
				free(ctx_p->chroot_dir);
				ctx_p->chroot_dir = NULL;
redmine authored
1155 1156 1157
				return 0;
			}

redmine authored
1158 1159
			ctx_p->chroot_dir	= arg;
			break;
redmine authored
1160 1161 1162 1163 1164
#ifdef PIVOTROOT_OPT_SUPPORT
		case PIVOT_ROOT: {
			char *value, *arg_orig = arg;

			if (!*arg) {
redmine authored
1165
				ctx_p->flags[PIVOT_ROOT] = DEFAULT_PIVOT_MODE;
redmine authored
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
				return 0;
			}

			pivotroot_way_t pivotway = getsubopt(&arg, pivotrootways, &value);
			if((int)pivotway == -1) {
				errno = EINVAL;
				error("Invalid pivot_root use way entered: \"%s\"", arg_orig);
				return EINVAL;
			}
			ctx_p->flags[PIVOT_ROOT] = pivotway;

			break;
		}
#endif
redmine authored
1180 1181
#ifdef UNSHARE_SUPPORT
		case DETACH_NETWORK: {
redmine authored
1182 1183 1184
			char *value, *arg_orig = arg;

			if (!*arg) {
redmine authored
1185
				ctx_p->flags[param_id] = 0;
redmine authored
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
				return 0;
			}

			detachnetwork_way_t detachnetwork_way = getsubopt(&arg, detachnetworkways, &value);
			if((int)detachnetwork_way == -1) {
				errno = EINVAL;
				error("Invalid network detach way entered: \"%s\"", arg_orig);
				return EINVAL;
			}
			ctx_p->flags[DETACH_NETWORK] = detachnetwork_way;

			break;
redmine authored
1198
		}
redmine authored
1199
#endif
redmine authored
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
#ifdef CAPABILITIES_SUPPORT
		case ADDPERMITTEDHOOKFILES: {
			char *ptr;
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"add-permitted-hook-files\" in run-time. Ignoring.");
				return 0;
			}

			while (ctx_p->permitted_hookfiles)
				free(ctx_p->permitted_hookfile[--ctx_p->permitted_hookfiles]);

			ptr = arg;
			while (1) {
				char *end = strchr(ptr, ',');

				if (end != NULL)
					*end =  0;

				if (!*ptr) {
					while (ctx_p->permitted_hookfiles)
						free(ctx_p->permitted_hookfile[--ctx_p->permitted_hookfiles]);

					if (end != NULL)
						ptr = &end[1];
					continue;
				}

				if (ctx_p->permitted_hookfiles >= MAXPERMITTEDHOOKFILES) {
					errno = EINVAL;
					error("Too many permitted hook files");
					return errno;
				}

				ctx_p->permitted_hookfile[ctx_p->permitted_hookfiles++] = strdup(ptr);

				if (end == NULL)
					break;

				*end = ',';
				ptr = &end[1];
			}
			break;
		}
#endif
redmine authored
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
#ifdef GETMNTENT_SUPPORT
		case MOUNTPOINTS: {
			char *ptr;
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"mountpoints\" in run-time. Ignoring.");
				return 0;
			}

			while (ctx_p->mountpoints)
				free(ctx_p->mountpoint[--ctx_p->mountpoints]);

redmine authored
1255 1256 1257
			if (!*arg)
				break;

redmine authored
1258 1259 1260 1261
			ptr = arg;
			while (1) {
				char *end = strchr(ptr, ',');

redmine authored
1262 1263
				if (end != NULL)
					*end =  0;
redmine authored
1264 1265 1266 1267

				if (!*ptr) {
					while (ctx_p->mountpoints)
						free(ctx_p->mountpoint[--ctx_p->mountpoints]);
redmine authored
1268 1269 1270

					if (end != NULL)
						ptr = &end[1];
redmine authored
1271 1272 1273
					continue;
				}

redmine authored
1274 1275 1276 1277 1278 1279
				if (ctx_p->mountpoints >= MAXMOUNTPOINTS) {
					errno = EINVAL;
					error("Too many mountpoints");
					return errno;
				}

redmine authored
1280 1281
				ctx_p->mountpoint[ctx_p->mountpoints++] = strdup(ptr);

redmine authored
1282 1283 1284 1285
				if (end == NULL)
					break;

				*end = ',';
redmine authored
1286 1287
				ptr = &end[1];
			}
redmine authored
1288
			break;
redmine authored
1289 1290
		}
#endif
redmine authored
1291
		case PIDFILE:
redmine authored
1292 1293 1294 1295
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"pid-file\" in run-time. Ignoring.");
				return 0;
			}
redmine authored
1296
			ctx_p->pidfile		= arg;
redmine authored
1297
			break;
redmine authored
1298
		case RETRIES:
Andrew Savchenko authored
1299
			ctx_p->retries		= (unsigned int)xstrtol(arg, &ret);
redmine authored
1300
			break;
redmine authored
1301 1302 1303
		case THREADING: {
			char *value, *arg_orig = arg;

redmine authored
1304
			if (!*arg) {
redmine authored
1305
				ctx_p->flags[param_id] = 0;
redmine authored
1306 1307 1308
				return 0;
			}

redmine authored
1309
			threadingmode_t threadingmode = getsubopt(&arg, threading_modes, &value);
redmine authored
1310
			if((int)threadingmode == -1) {
redmine authored
1311 1312 1313 1314 1315
				errno = EINVAL;
				error("Invalid threading mode entered: \"%s\"", arg_orig);
				return EINVAL;
			}
			ctx_p->flags[THREADING] = threadingmode;
redmine authored
1316 1317

			break;
redmine authored
1318
		}
redmine authored
1319 1320 1321
		case OUTPUT_METHOD: {
			char *value, *arg_orig = arg;

redmine authored
1322
			if (!*arg) {
redmine authored
1323
				ctx_p->flags[param_id] = 0;
redmine authored
1324 1325 1326
				return 0;
			}

redmine authored
1327
			outputmethod_t outputmethod = getsubopt(&arg, output_methods, &value);
redmine authored
1328
			if((int)outputmethod == -1) {
redmine authored
1329 1330 1331 1332
				errno = EINVAL;
				error("Invalid log writing destination entered: \"%s\"", arg_orig);
				return EINVAL;
			}
redmine authored
1333
			ctx_p->flags[OUTPUT_METHOD] = outputmethod;
redmine authored
1334 1335

			break;
redmine authored
1336
		}
redmine authored
1337 1338
#ifdef CLUSTER_SUPPORT
		case CLUSTERIFACE:
redmine authored
1339
			ctx_p->cluster_iface		= arg;
redmine authored
1340 1341
			break;
		case CLUSTERMCASTIPADDR:
redmine authored
1342
			ctx_p->cluster_mcastipaddr	= arg;
redmine authored
1343 1344
			break;
		case CLUSTERMCASTIPPORT:
Andrew Savchenko authored
1345
			ctx_p->cluster_mcastipport	= (uint16_t)xstrtol(arg, &ret);
redmine authored
1346 1347
			break;
		case CLUSTERTIMEOUT:
Andrew Savchenko authored
1348
			ctx_p->cluster_timeout		= (unsigned int)xstrtol(arg, &ret);
redmine authored
1349 1350
			break;
		case CLUSTERNODENAME:
redmine authored
1351
			ctx_p->cluster_nodename		= arg;
redmine authored
1352 1353
			break;
		case CLUSTERHDLMIN:
Andrew Savchenko authored
1354
			ctx_p->cluster_hash_dl_min	= (uint16_t)xstrtol(arg, &ret);
redmine authored
1355 1356
			break;
		case CLUSTERHDLMAX:
Andrew Savchenko authored
1357
			ctx_p->cluster_hash_dl_max	= (uint16_t)xstrtol(arg, &ret);
redmine authored
1358 1359
			break;
		case CLUSTERSDLMAX:
Andrew Savchenko authored
1360
			ctx_p->cluster_scan_dl_max	= (uint16_t)xstrtol(arg, &ret);
redmine authored
1361 1362 1363
			break;
#endif
		case OUTLISTSDIR:
redmine authored
1364
			ctx_p->listoutdir		= arg;
redmine authored
1365 1366
			break;
		case LABEL:
redmine authored
1367
			ctx_p->label			= arg;
redmine authored
1368
			break;
redmine authored
1369 1370 1371 1372 1373
#ifdef CGROUP_SUPPORT
		case CG_GROUPNAME:
			ctx_p->cg_groupname		= arg;
			break;
#endif
redmine authored
1374 1375
		case STANDBYFILE:
			if(strlen(arg)) {
redmine authored
1376 1377
				ctx_p->standbyfile		= arg;
				ctx_p->flags[STANDBYFILE]	= 1;
redmine authored
1378
			} else {
redmine authored
1379 1380
				ctx_p->standbyfile		= NULL;
				ctx_p->flags[STANDBYFILE]	= 0;
redmine authored
1381 1382
			}
			break;
redmine authored
1383 1384 1385 1386 1387 1388 1389 1390
		case MODSIGN: {
			char *subopts = arg;

			ctx_p->flags[MODSIGN] = 0;

			while (*subopts != 0) {
				char *value;
				typeof(ctx_p->flags[MODSIGN]) field = getsubopt(&subopts, stat_fields, &value);
redmine authored
1391 1392 1393
				debug(4, "field == %i -> %x (%s)", field, xstatfield_to_statfield[field], value);
				if (field != X_STAT_FIELD_RESET)
					ctx_p->flags[MODSIGN] |= xstatfield_to_statfield[field];
redmine authored
1394 1395
			}

redmine authored
1396
			debug(5, "ctx_p->flags[MODSIGN] == 0x%x", ctx_p->flags[MODSIGN]);
redmine authored
1397 1398
			break;
		}
redmine authored
1399
		case SYNCDELAY: 
Andrew Savchenko authored
1400
			ctx_p->syncdelay		= (unsigned int)xstrtol(arg, &ret);
redmine authored
1401 1402
			break;
		case DELAY:
Andrew Savchenko authored
1403
			ctx_p->_queues[QUEUE_NORMAL].collectdelay  = (unsigned int)xstrtol(arg, &ret);
redmine authored
1404 1405
			break;
		case BFILEDELAY:
Andrew Savchenko authored
1406
			ctx_p->_queues[QUEUE_BIGFILE].collectdelay = (unsigned int)xstrtol(arg, &ret);
redmine authored
1407 1408
			break;
		case BFILETHRESHOLD:
Andrew Savchenko authored
1409
			ctx_p->bfilethreshold = (unsigned long)xstrtol(arg, &ret);
redmine authored
1410
			break;
redmine authored
1411 1412 1413 1414 1415 1416
		case CANCEL_SYSCALLS: {
			char *subopts = arg;

			while (*subopts != 0) {
				char *value;
				typeof(ctx_p->flags[CANCEL_SYSCALLS]) syscall_bitmask = getsubopt(&subopts, syscalls_bitmask, &value);
redmine authored
1417 1418
				debug(4, "cancel syscall == %i -> 0x%x", syscall_bitmask, xcsc_to_csc[syscall_bitmask]);
				if (syscall_bitmask == X_CSC_RESET) {
redmine authored
1419 1420 1421 1422
					ctx_p->flags[CANCEL_SYSCALLS] = 0;
					continue;
				}

redmine authored
1423
				ctx_p->flags[CANCEL_SYSCALLS] |= xcsc_to_csc[syscall_bitmask];
redmine authored
1424 1425 1426 1427
			}

			break;
		}
redmine authored
1428 1429
		case MONITOR: {
			char *value, *arg_orig = arg;
redmine authored
1430 1431 1432 1433
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"monitor\" in run-time. Ignoring.");
				return 0;
			}
redmine authored
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447

			if (!*arg) {
				ctx_p->flags_set[param_id] = 0;
				return 0;
			}

			notifyengine_t notifyengine = getsubopt(&arg, notify_engines, &value);
			if((int)notifyengine == -1) {
				errno = EINVAL;
				error("Invalid FS monitor subsystem entered: \"%s\"", arg_orig);
				return EINVAL;
			}

			switch (notifyengine) {
redmine authored
1448
#ifdef FANOTIFY_SUPPORT
redmine authored
1449
				case NE_FANOTIFY:
redmine authored
1450
#endif
redmine authored
1451
#ifdef INOTIFY_SUPPORT
redmine authored
1452
				case NE_INOTIFY:
redmine authored
1453 1454
#endif
#ifdef KQUEUE_SUPPORT
redmine authored
1455
				case NE_KQUEUE:
redmine authored
1456
#endif
redmine authored
1457 1458
#ifdef BSM_SUPPORT
				case NE_BSM:
redmine authored
1459
				case NE_BSM_PREFETCH:
redmine authored
1460
#endif
redmine authored
1461 1462 1463
#ifdef GIO_SUPPORT
				case NE_GIO:
#endif
redmine authored
1464 1465 1466
#ifdef DTRACEPIPE_SUPPORT
				case NE_DTRACEPIPE:
#endif
redmine authored
1467 1468
					break;
				default:
redmine authored
1469 1470 1471 1472 1473 1474 1475 1476
					error(PROGRAM" is compiled without %s subsystem support. Recompile with option \"--with-%s\" if you're planning to use it.", arg_orig, arg_orig);
					return EINVAL;
			}

			ctx_p->flags[MONITOR] = notifyengine;

			break;
		}
redmine authored
1477
		case RSYNCINCLIMIT:
Andrew Savchenko authored
1478
			ctx_p->rsyncinclimit = (unsigned int)xstrtol(arg, &ret);
redmine authored
1479 1480
			break;
		case SYNCTIMEOUT:
Andrew Savchenko authored
1481
			ctx_p->synctimeout   = (unsigned int)xstrtol(arg, &ret);
redmine authored
1482
			break;
redmine authored
1483 1484 1485 1486 1487 1488 1489 1490 1491
		case PREEXITHOOK:
			if (strlen(arg)) {
				ctx_p->preexithookfile		= arg;
				ctx_p->flags[PREEXITHOOK]	= 1;
			} else {
				ctx_p->preexithookfile		= NULL;
				ctx_p->flags[PREEXITHOOK]	= 0;
			}
			break;
redmine authored
1492
		case EXITHOOK:
redmine authored
1493
			if (strlen(arg)) {
redmine authored
1494
				ctx_p->exithookfile		= arg;
redmine authored
1495
				ctx_p->flags[EXITHOOK]		= 1;
redmine authored
1496
			} else {
redmine authored
1497
				ctx_p->exithookfile		= NULL;
redmine authored
1498
				ctx_p->flags[EXITHOOK]		= 0;
redmine authored
1499 1500
			}
			break;
redmine authored
1501
		case IGNOREEXITCODE: {
redmine authored
1502 1503 1504 1505 1506 1507 1508 1509
			char *ptr = arg, *start = arg;
			unsigned char exitcode;
			do {
				switch(*ptr) {
					case 0:
					case ',':
//						*ptr=0;
						exitcode = (unsigned char)atoi(start);
redmine authored
1510
						if (exitcode == 0) {
redmine authored
1511 1512
							// flushing the setting
							int i = 0;
redmine authored
1513
							while (i < 256)
redmine authored
1514
								ctx_p->isignoredexitcode[i++] = 0;
redmine authored
1515
#ifdef _DEBUG_FORCE
redmine authored
1516 1517 1518
							fprintf(stderr, "Force-Debug: parse_parameter(): Reset ignored exitcodes.\n");
#endif
						} else {
redmine authored
1519
							ctx_p->isignoredexitcode[exitcode] = 1;
redmine authored
1520
#ifdef _DEBUG_FORCE
redmine authored
1521 1522 1523 1524 1525
							fprintf(stderr, "Force-Debug: parse_parameter(): Adding ignored exitcode %u.\n", exitcode);
#endif
						}
						start = ptr+1;
						break;
redmine authored
1526 1527 1528 1529 1530 1531
					case '0' ... '9':
						break;
					default:
						errno = EINVAL;
						error("Expected a digit or comma but got \"%c\"", *ptr);
						return errno;
redmine authored
1532 1533
				}
			} while(*(ptr++));
redmine authored
1534
			break;
redmine authored
1535
		}
redmine authored
1536 1537 1538 1539
		case SHOW_VERSION:
			version();
			break;
		case WATCHDIR:
redmine authored
1540 1541 1542 1543
			if (paramsource == PS_CONTROL) {
				warning("Cannot change \"watch-dir\" in run-time. Ignoring.");
				return 0;
			}
redmine authored
1544
			ctx_p->watchdir		= arg;
redmine authored
1545 1546
			break;
		case SYNCHANDLER:
redmine authored
1547
			ctx_p->handlerfpath	= arg;
redmine authored
1548
			break;
redmine authored
1549
		case RULESFILE:
redmine authored
1550
			ctx_p->rulfpath		= arg;
redmine authored
1551
			break;
redmine authored
1552 1553 1554 1555 1556 1557 1558 1559
		case DESTDIR: {
			char *sep = strstr(arg, "://");

			if (ctx_p->destproto != NULL) {
				free(ctx_p->destproto);
				ctx_p->destproto = NULL;
			}

redmine authored
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
			ctx_p->destdir	 = arg;

			if (sep == NULL) {
				char *at_ptr = strchr(arg, '@');
				char *cl_ptr = strchr(arg, ':');
				if (at_ptr != NULL && cl_ptr != NULL && at_ptr < cl_ptr) {
					ctx_p->destproto = strdup("rsync+ssh");
					debug(5, "Destination proto is: %s (case #0)", ctx_p->destproto);
				}
				break;
			}

			{
redmine authored
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
				char *ptr = arg;
				while (ptr < sep) {
					if (*ptr<'a' || *ptr>'z')
						break;
					ptr++;
				}
				if (ptr == sep) {
					size_t len = (ptr-arg)+1;
					ctx_p->destproto = xmalloc(len+1);
					memcpy(ctx_p->destproto, arg, len);
					ctx_p->destproto[len] = 0;
				}
redmine authored
1585
				debug(5, "Destination proto is: %s (case #1)", ctx_p->destproto);
redmine authored
1586 1587
			}

redmine authored
1588
			break;
redmine authored
1589
		}
redmine authored
1590
		case SOCKETPATH:
redmine authored
1591
			ctx_p->socketpath	= arg;
redmine authored
1592
			break;
redmine authored
1593 1594 1595
		case SOCKETAUTH: {
			char *value;

redmine authored
1596
			ctx_p->flags[SOCKETAUTH] = getsubopt(&arg, socketauth, &value);
redmine authored
1597
			if (ctx_p->flags[SOCKETAUTH] == -1) {
redmine authored
1598
				error("Wrong socket auth mech entered: \"%s\"", arg);
redmine authored
1599 1600 1601 1602
				return EINVAL;
			}
		}
		case SOCKETMOD:
redmine authored
1603
			if (!sscanf(arg, "%o", (unsigned int *)&ctx_p->socketmod)) {
redmine authored
1604
				error("Non octal value passed to --socket-mod: \"%s\"", arg);
redmine authored
1605 1606
				return EINVAL;
			}
redmine authored
1607
			ctx_p->flags[param_id]++;
redmine authored
1608 1609 1610 1611 1612 1613
			break;
		case SOCKETOWN: {
			char *colon = strchr(arg, ':');
			uid_t uid;
			gid_t gid;

redmine authored
1614
			if (colon == NULL) {
redmine authored
1615 1616 1617
				struct passwd *pwent = getpwnam(arg);

				if(pwent == NULL) {
redmine authored
1618 1619
					error("Cannot find username \"%s\" (case #0)", 
						arg);
redmine authored
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
					return EINVAL;
				}

				uid = pwent->pw_uid;
				gid = pwent->pw_gid;

			} else {

				char user[USER_LEN+2], group[GROUP_LEN+2];

				memcpy(user, arg, MIN(USER_LEN, colon-arg));
				user[colon-arg] = 0;

				strncpy(group, &colon[1], GROUP_LEN);

				errno=0;
				struct passwd *pwent = getpwnam(user);
				if(pwent == NULL) {
redmine authored
1638 1639
					error("Cannot find username \"%s\" (case #1)", 
						user);
redmine authored
1640 1641 1642 1643 1644 1645
					return EINVAL;
				}

				errno=0;
				struct group  *grent = getgrnam(group);
				if(grent == NULL) {
redmine authored
1646 1647
					error("Cannot find group \"%s\"", 
						group);
redmine authored
1648 1649 1650 1651 1652 1653 1654
					return EINVAL;
				}
	
				uid = pwent->pw_uid;
				gid = grent->gr_gid;
			}

redmine authored
1655 1656 1657
			ctx_p->socketuid = uid;
			ctx_p->socketgid = gid;
			ctx_p->flags[param_id]++;
redmine authored
1658

redmine authored
1659
			debug(2, "socket: uid == %u; gid == %u", uid, gid);
redmine authored
1660 1661 1662

			break;
		}
redmine authored
1663
		case STATUSFILE:
redmine authored
1664
			ctx_p->statusfile	= arg;
redmine authored
1665
			break;
redmine authored
1666 1667 1668
		case DUMPDIR:
			ctx_p->dump_path	= arg;
			break;
redmine authored
1669 1670 1671
		case MODE: {
			char *value;

redmine authored
1672
			ctx_p->flags[MODE]  = getsubopt(&arg, modes, &value);
redmine authored
1673
			if (ctx_p->flags[MODE] == -1) {
redmine authored
1674
				error("Wrong mode name entered: \"%s\"", arg);
redmine authored
1675 1676 1677 1678
				return EINVAL;
			}
			break;
		}
redmine authored
1679 1680 1681 1682 1683
		case SYNCHANDLERARGS0:
			str_splitargs(arg, synchandler_arg0, ctx_p);
			break;
		case SYNCHANDLERARGS1:
			str_splitargs(arg, synchandler_arg1, ctx_p);
redmine authored
1684
			break;
redmine authored
1685
		default:
redmine authored
1686
			if (arg == NULL)
redmine authored
1687
				ctx_p->flags[param_id]++;
redmine authored
1688
			else
Andrew Savchenko authored
1689
				ctx_p->flags[param_id] = xstrtol(arg, &ret);
redmine authored
1690
#ifdef _DEBUG_FORCE
redmine authored
1691
			fprintf(stderr, "Force-Debug: flag %i is set to %i\n", param_id&0xff, ctx_p->flags[param_id]);
redmine authored
1692
#endif
redmine authored
1693 1694
			break;
	}
Andrew Savchenko authored
1695
	return ret;
redmine authored
1696 1697
}

redmine authored
1698
int arguments_parse(int argc, char *argv[], struct ctx *ctx_p) {
redmine authored
1699 1700
	int c;
	int option_index = 0;
redmine authored
1701

redmine authored
1702
	// Generating "optstring" (man 3 getopt_long) with using information from struct array "long_options"
redmine authored
1703
	char *optstring     = alloca((('z'-'a'+1)*3 + '9'-'0'+1)*3 + 1);
redmine authored
1704 1705
	char *optstring_ptr = optstring;

redmine authored
1706
	const struct option *lo_ptr = long_options;
redmine authored
1707
	while (lo_ptr->name != NULL) {
redmine authored
1708
		if (!(lo_ptr->val & (OPTION_CONFIGONLY|OPTION_LONGOPTONLY))) {
redmine authored
1709
			*(optstring_ptr++) = lo_ptr->val & 0xff;
redmine authored
1710

redmine authored
1711
			if (lo_ptr->has_arg == required_argument)
redmine authored
1712 1713
				*(optstring_ptr++) = ':';

redmine authored
1714
			if (lo_ptr->has_arg == optional_argument) {
redmine authored
1715 1716 1717 1718
				*(optstring_ptr++) = ':';
				*(optstring_ptr++) = ':';
			}
		}
redmine authored
1719 1720 1721
		lo_ptr++;
	}
	*optstring_ptr = 0;
redmine authored
1722
#ifdef _DEBUG_FORCE
redmine authored
1723 1724
	fprintf(stderr, "Force-Debug: %s\n", optstring);
#endif
redmine authored
1725 1726

	// Parsing arguments
redmine authored
1727
	while (1) {
redmine authored
1728
		c = getopt_long(argc, argv, optstring, long_options, &option_index);
redmine authored
1729 1730
	
		if (c == -1) break;
redmine authored
1731
		int ret = parse_parameter(ctx_p, c, optarg == NULL ? NULL : strdup(optarg), PS_ARGUMENT);
redmine authored
1732 1733 1734 1735
		if (ret) return ret;
	}

	if (optind < argc) {
redmine authored
1736 1737 1738 1739
		synchandler_args_t *args_p = &ctx_p->synchandler_args[SHARGS_PRIMARY];

		while (args_p->c)
			free(args_p->v[--args_p->c]);
redmine authored
1740 1741 1742

		if ((optind+1 != argc) || (*argv[optind])) {	// If there's only "" after the "--", just reset "synchandler_argc" to "0", otherwise:
			do {
redmine authored
1743
				if (synchandler_arg0(strdup(argv[optind++]), 0, ctx_p))
redmine authored
1744 1745 1746
					return errno;
			} while (optind < argc);
		}
redmine authored
1747
	}
redmine authored
1748

redmine authored
1749
	return 0;
redmine authored
1750 1751
}

redmine authored
1752
void gkf_parse(ctx_t *ctx_p, GKeyFile *gkf, paramsource_t paramsource) {
redmine authored
1753
	debug(9, "");
redmine authored
1754
	char *config_block = (char *)ctx_p->config_block;
redmine authored
1755
	while (config_block != NULL) {
redmine authored
1756 1757
		const struct option *lo_ptr = long_options;

redmine authored
1758 1759 1760 1761
		if (config_block != ctx_p->config_block) {
			ctx_p->flags_values_raw[CONFIGBLOCKINHERITS] = NULL;
			ctx_p->flags_set[CONFIGBLOCKINHERITS] = 0;
		}
redmine authored
1762
		while (lo_ptr->name != NULL) {
redmine authored
1763 1764
			gchar *value = g_key_file_get_value(gkf, config_block, lo_ptr->name, NULL);
			if(value != NULL) {
redmine authored
1765
				int ret = parse_parameter(ctx_p, lo_ptr->val, value, paramsource);
redmine authored
1766 1767 1768
				if(ret) exit(ret);
			}
			lo_ptr++;
redmine authored
1769
		}
redmine authored
1770 1771 1772 1773 1774 1775 1776 1777

		if (config_block != ctx_p->config_block)
			free(config_block);

		config_block = ctx_p->flags_values_raw[CONFIGBLOCKINHERITS];

		if (config_block != NULL)
			debug(2, "Next block is: %s", config_block);
redmine authored
1778
	};
redmine authored
1779 1780 1781 1782

	return;
}

redmine authored
1783
int configs_parse(ctx_t *ctx_p, paramsource_t paramsource) {
redmine authored
1784 1785 1786 1787
	GKeyFile *gkf;

	gkf = g_key_file_new();

redmine authored
1788
	if (ctx_p->config_path) {
redmine authored
1789 1790
		GError *g_error = NULL;

redmine authored
1791
		if (!strcmp(ctx_p->config_path, "/NULL/")) {
redmine authored
1792 1793 1794 1795
			debug(2, "Empty path to config file. Don't read any of config files.");
			return 0;
		}

redmine authored
1796
		debug(1, "Trying config-file \"%s\" (case #0)", ctx_p->config_path);
redmine authored
1797 1798
		if (!g_key_file_load_from_file(gkf, ctx_p->config_path, G_KEY_FILE_NONE, &g_error)) {
			error("Cannot open/parse file \"%s\" (g_error #%u.%u: %s)", ctx_p->config_path, g_error->domain, g_error->code, g_error->message);
redmine authored
1799 1800 1801
			g_key_file_free(gkf);
			return -1;
		} else
redmine authored
1802
			gkf_parse(ctx_p, gkf, paramsource);
redmine authored
1803

redmine authored
1804
	} else {
redmine authored
1805
		char  *config_paths[] = CONFIG_PATHS;
redmine authored
1806 1807
		char **config_path_p = config_paths, *config_path_real = xmalloc(PATH_MAX);
		size_t config_path_real_size=PATH_MAX;
redmine authored
1808

redmine authored
1809 1810
		char  *homedir     = getenv("HOME");
		size_t homedir_len = (homedir == NULL ? 0 :strlen(homedir));
redmine authored
1811

redmine authored
1812
		while (*config_path_p != NULL) {
redmine authored
1813
			size_t config_path_len = strlen(*config_path_p);
redmine authored
1814

redmine authored
1815
			if (config_path_len+homedir_len+3 > config_path_real_size) {
redmine authored
1816 1817 1818
				config_path_real_size = config_path_len+homedir_len+3;