aboutsummaryrefslogtreecommitdiff
path: root/src/mfdbtool.c
blob: 67e41ca2e567dec2c99465502aefda9443e9782f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/* This file is part of Mailfromd.
   Copyright (C) 2005-2011, 2015-2016 Sergey Poznyakoff

   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, 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/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <unistd.h>
#include <stdlib.h>
#include <sysexits.h>

#include <argp.h>
#include <mailutils/mailutils.h>
#include <mailutils/cli.h>
#include <mailutils/daemon.h>

#include "libmf.h"
#include "mfdb.h"

char *state_dir = DEFAULT_STATE_DIR;
char *file_option;               /* File name for DB management commands */
struct db_format *format_option;
time_t expire_interval = 0;      /* When set, overrides the expire interval
				    for the selected database */
int all_option;                  /* Process all databases */
int predict_next_option; 
double predict_rate;             /* Prediction rate for --list --format=rates*/
char *db_type_str = DEFAULT_DB_TYPE;

void (*run)(int argc, char **argv) = NULL;

void
assert_db_format()
{
	if (!format_option) {
		mu_error(_("operation is not applicable"));
		exit(EX_USAGE);
	}
}

char *
get_db_name()
{
	assert_db_format();
	if (file_option)
		return file_option;
	if (format_option->dbname)
		return format_option->dbname;
	mu_error(_("database file name is not given"));
	exit(EX_USAGE);
}

int
convert_rate(const char *arg, double *rate)
{
        double count;
        char *p;

        count = strtod(arg, &p);
        if (*p) {
                time_t div;
                const char *endp;

                while (*p && mu_isspace(*p))
                        p++;
                if (mu_isalpha(*p)) {
                        if (strlen(p) > 3
                            && memcmp(p, "per", 3) == 0 && mu_isspace(p[3]))
                                p += 3;
                } else if (mu_ispunct(*p))
                        p++;

                if (parse_time_interval(p, &div, &endp)) {
                        mu_error(_("unrecognized time format (near `%s')"),
                                 endp);
                        return 1;
                }
                count /= div;
        }
        *rate = count;
        return 0;
}
                

void
mfdbtool_delete(int argc, char **argv)
{
	int i;
	char *name = get_db_name();

	for (i = 0; i < argc; i++)
		db_delete(name, argv[i]);
}

void
mfdbtool_list(int argc, char **argv)
{
	int rc;
	char *name = get_db_name();
	
	if (!format_option->print_item) {
		/* Should not happen */
		mu_error(_("list is not applicable to this DB format"));
		exit(EX_USAGE);
	}		

	rc = 0;
	if (argc) {
		int i;
		for (i = 0; i < argc; i++) 
			rc += db_list_item(name, argv[i],
					   format_option->print_item);
	} else
		rc = db_list(name, format_option->print_item);
	exit(rc != 0);
}

static int
db_proc_enumerator(struct db_format *fmt, void *data)
{
	int (*func)(char *name, db_expire_t exp) = data;
	
	if (fmt->expire) 
		func(fmt->dbname, fmt->expire);
	return 0;
}

void
mfdbtool_expire(int argc, char **argv)
{
	/*FIXME: priv_setup(); */
	if (all_option) 
		db_format_enumerate(db_proc_enumerator, db_expire);
	else {
		if (!format_option->expire) {
			mu_error(_("expire is not applicable to this DB format"));
			exit(EX_USAGE);
		}		
		exit(db_expire(get_db_name(), format_option->expire) != 0);
	}
}	

void
mfdbtool_compact(int argc, char **argv)
{
	/* FIXME: priv_setup(); */
	if (all_option) 
		db_format_enumerate(db_proc_enumerator, db_compact);
	else {
		if (!format_option->expire) {
			mu_error(_("compact is not applicable to this DB format"));
			exit(EX_USAGE);
		}
		exit(db_compact(get_db_name(), format_option->expire) != 0);
	}
}


const char *program_version = "mfdbtool (" PACKAGE_STRING ")";
static char doc[] = N_("mfdbtool -- Mailfromd database management tool");
static char args_doc[] = "";

enum {
	OPTION_STATE_DIRECTORY = 256,
	OPTION_DELETE,
	OPTION_LIST,
	OPTION_EXPIRE,
	OPTION_COMPACT,
	OPTION_IGNORE_FAILED_READS,
	OPTION_PREDICT_NEXT,
	OPTION_ALL,
	OPTION_TIME_FORMAT
};

static struct argp_option options[] = {
#define GRP 10
	{ NULL, 0, NULL, 0,
	  N_("Database management commands"), GRP },
	{ "delete", OPTION_DELETE, NULL, 0,
	  N_("delete given entries from the database"), GRP+1 },
	{ "list", OPTION_LIST, NULL, 0,
	  N_("list given database (default cache)"), GRP+1 },
	{ "expire", OPTION_EXPIRE, NULL, 0,
	  N_("delete expired entries from the database"), GRP+1 },
	{ "compact", OPTION_COMPACT, NULL, 0,
	  N_("compact the database"), GRP+1 },
#undef GRP
#define GRP 20
	{ NULL, 0, NULL, 0,
	  N_("Command modifiers"), GRP },
	{ "file", 'f', N_("FILE"), 0,
	  N_("DB file name to operate upon"),
	  GRP+1 },
	{ "format", 'H', N_("FORMAT"), 0,
	  N_("format of the DB file to operate upon"), GRP+1 },
	{ "ignore-failed-reads", OPTION_IGNORE_FAILED_READS, NULL, 0,
	  N_("ignore failed reads while compacting the database"), GRP+1 },
	{ "predict", OPTION_PREDICT_NEXT, N_("RATE"), 0,
	  N_("predict when the user will be able to send next message"),
	  GRP+1 },
	{ "all", OPTION_ALL, NULL, 0,
	  N_("with --compact or --expire: apply the operation to all "
	     "available databases"), GRP+1 },
	{ "time-format", OPTION_TIME_FORMAT, N_("FMT"), 0,
	  N_("output timestamps using given format (default \"%c\")"), GRP+1 },
	{ "debug", 'd', N_("LEVEL"), 0,
	  N_("set debugging level"), GRP+1 },
	
#undef GRP
#define GRP 30
	{ NULL, 0, NULL, 0,
	  N_("Configuration modifiers"), GRP },
	{ "state-directory", OPTION_STATE_DIRECTORY, N_("DIR"), 0,
	  N_("set new program state directory"), GRP+1 },
	{ "expire-interval", 'e', N_("NUMBER"), 0,
	  N_("set database expiration interval to NUMBER seconds"), GRP+1 },
#undef GRP
	{ NULL }
};

static int
db_proc_set_expire(struct db_format *fmt, void *data)
{
	fmt->expire_interval = expire_interval;
	return 0;
}

static error_t
parse_opt(int key, char *arg, struct argp_state *state)
{
	switch (key) {
	case OPTION_STATE_DIRECTORY:
		mf_optcache_set_option("state-directory", arg);
		break;
		
	case 'd':
		mf_optcache_set_option("debug", arg);
		break;
		
	case 'e': {
		time_t interval;
		const char *endp;
		if (parse_time_interval(arg, &interval, &endp)) {
			argp_error(state,
				   _("unrecognized time format (near `%s')"),
				   endp);
		}
		expire_interval = interval;
		break;
	}
		
	case OPTION_PREDICT_NEXT:
		format_option = db_format_lookup("rate");
		if (convert_rate(arg, &predict_rate) == 0)
			predict_next_option = 1;
		break;
		
	case OPTION_IGNORE_FAILED_READS:
		ignore_failed_reads_option = 1;
		break;

	case OPTION_ALL:
		all_option = 1;
		break;
		
	case OPTION_TIME_FORMAT:
		ignore_failed_reads_option = 1;
		break;
		
	case 'f':
		file_option = arg;
		break;

	case 'H':
		format_option = db_format_lookup(arg);
		if (format_option == NULL)
			argp_error(state, _("unknown database format: %s"),
				   arg);
		break;
		
	case OPTION_DELETE:
		run = mfdbtool_delete;
		break;
		
	case OPTION_LIST:
		run = mfdbtool_list;
		break;
		
	case OPTION_EXPIRE:
		run = mfdbtool_expire;
		break;
		
	case OPTION_COMPACT:
		run = mfdbtool_compact;
		break;
		
	case ARGP_KEY_FINI:
		break;
		
	default:
		return ARGP_ERR_UNKNOWN;
	}
	return 0;
}


static int
cb_debug(void *data, mu_config_value_t *arg)
{
	if (mu_cfg_assert_value_type(arg, MU_CFG_STRING))
		return 1;
	mu_debug_parse_spec(arg->v.string);
	return 0;
}


struct mu_cfg_param mfdbtool_cfg_param[] = {
	{ "database-type", mu_c_string, &db_type_str, 0, NULL,
	  N_("Default database type"),
	  N_("type") },
	{ "database", mu_cfg_section, NULL, 0, NULL, NULL },
	{ "state-directory", mu_c_string, &state_dir, 0, NULL,
	  N_("Set program state directory."),
	  N_("dir") },
	{ "debug", mu_cfg_callback, NULL, 0, cb_debug,
	  N_("Set Mailfromd debug verbosity level.  Argument is a comma-"
             "separated list of debug specifications, each of which has the "
	     "following form:\n"
	     "  <module: string>[=<level: number>]\n"
	     "where <module> is the name of a Mailfromd module, and <level> "
	     "is the desired verbosity level for that module."),
	  N_("spec: list") },

        { "lock-retry-count", mu_cfg_callback, NULL, 0,
	  config_cb_lock_retry_count,
	  N_("Retry acquiring DBM file lock this number of times."),
	  N_("arg: number")},
	{ "lock-retry-timeout", mu_cfg_callback, NULL, 0,
	  config_cb_lock_retry_timeout,
	  N_("Set the time span between the two DBM locking attempts."),
	  N_("time: interval") },
	
	{ NULL }
};

static void
set_state_directory(union mf_option_value *val)
{
	state_dir = val->ov_string;
}

static void
set_debug(union mf_option_value *val)
{
	mu_debug_parse_spec(val->ov_string);
	free(val->ov_string);
}

static struct mf_option_cache option_cache[] = {
	{ "state-directory", mf_option_string, set_state_directory },
	{ "debug", mf_option_string, set_debug },

	{ NULL }
};

static const char *capa[] = {
	"common",
	"debug",
	"locking",
	NULL
};

static struct argp argp = {
	options,
	parse_opt,
	args_doc,
	doc,
	NULL,
	NULL,
	NULL
};

static void
version(FILE *stream, struct argp_state *state)
{
	mailfromd_version("mfdbtool", stream);
}

void
alloc_die_fun()
{
	mu_error(_("not enough memory"));
        abort();
}

extern char *program_invocation_short_name;//FIXME

int
main(int argc, char **argv)
{
	int rc, index;
	
	mf_init_nls();
	mu_alloc_die_hook = alloc_die_fun;
	if (!program_invocation_short_name)
		program_invocation_short_name = argv[0];
	argp_program_version_hook = version;

	db_format_setup();
	database_cfg_init();
	mf_init_lock_options();
	mf_optcache_add(option_cache, 0, MF_OCF_NULL|MF_OCF_STATIC);
	
	mu_argp_init(program_version, "<" PACKAGE_BUGREPORT ">");
        /* FIXME: Use mailfromd.conf somehow? */
	mu_site_rcfile = SYSCONFDIR "/mfdbtool.conf";
	rc = mu_app_init(&argp, capa, mfdbtool_cfg_param, argc, argv,
			 0, &index, NULL);
	if (rc)
		exit(EX_CONFIG);
	
	if (db_type_str) {
		mu_url_t dbhint;

		if ((rc = mu_url_create_null(&dbhint)) ||
		    (rc = mu_url_set_scheme(dbhint, db_type_str))) {
			mu_error(_("cannot initialize DBM hint: %s"),
				 mu_strerror(rc));
			exit(EX_SOFTWARE);
		}
		mu_url_destroy(&mu_dbm_hint);
		mu_dbm_hint = dbhint;
	}

	if (!run) {
		mu_error(_("you must specify one of --list, --delete,"
			   " --expire or --compat"));
		exit(EX_USAGE);
	}
	if (all_option &&
	    !(run == mfdbtool_compact || run == mfdbtool_expire)) {
		mu_error(_("--all is meaningful only with "
			   "--expire or --compact option"));
		exit(EX_USAGE);
	}		
	if (all_option && format_option) {
		mu_error(_("--format is incompatible with --all"));
		exit(EX_USAGE);
	}
	if (!format_option)
		format_option = db_format_lookup("cache");
	if (!format_option) {
		mu_error("INTERNAL ERROR: cache database not defined");
		exit(EX_SOFTWARE);
	}
	if (expire_interval)
		db_format_enumerate(db_proc_set_expire, NULL);

	mf_optcache_flush();

	argv += index;
	argc -= index;

	if (chdir(state_dir)) {
		mu_error(_("cannot change to %s: %s"),
			 state_dir, strerror(errno));
		exit(EX_OSERR);
	}

	run(argc, argv);
	
	exit(0);
}
	
	

Return to:

Send suggestions and report system problems to the System administrator.