filedat.c 31.5 KB
Newer Older
1
2
3
4
5
6
/* Synchronet file database-related exported functions */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
7
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *																			*
 * 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 2			*
 * of the License, or (at your option) any later version.					*
 * See the GNU General Public License for more details: gpl.txt or			*
 * http://www.fsf.org/copyleft/gpl.html										*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

22
#include "filedat.h"
23
#include "userdat.h"
24
25
26
27
#include "dat_rec.h"
#include "datewrap.h"	// time32()
#include "str_util.h"
#include "nopen.h"
28
29
30
#include "smblib.h"
#include "load_cfg.h"	// smb_open_dir()
#include "scfglib.h"
31

32
33
34
/* libarchive: */
#include <archive.h>
#include <archive_entry.h>
35

36
 /****************************************************************************/
37
/****************************************************************************/
38
bool findfile(scfg_t* cfg, uint dirnum, const char *filename, file_t* file)
39
{
40
	smb_t smb;
41

42
43
	if(cfg == NULL || filename == NULL)
		return false;
44

45
46
47
48
49
50
51
52
	if(!smb_init_dir(cfg, &smb, dirnum))
		return false;
	if(smb_open_index(&smb) != SMB_SUCCESS)
		return false;
	int result = smb_findfile(&smb, filename, file);
	smb_close(&smb);
	return result == SMB_SUCCESS;
}
53

54
55
56
57
58
59
// This function may be called without opening the file base (for fast new-scans)
time_t newfiletime(smb_t* smb)
{
	char str[MAX_PATH + 1];
	SAFEPRINTF(str, "%s.sid", smb->file);
	return fdate(str);
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
time_t dir_newfiletime(scfg_t* cfg, uint dirnum)
{
	smb_t smb;

	if(!smb_init_dir(cfg, &smb, dirnum))
		return -1;
	return newfiletime(&smb);
}

// This function may be called without opening the file base (for fast new-scans)
bool newfiles(smb_t* smb, time_t t)
{
	return newfiletime(smb) > t;
}

// This function *must* be called with file base closed
bool update_newfiletime(smb_t* smb, time_t t)
{
	char path[MAX_PATH + 1];
	SAFEPRINTF(path, "%s.sid", smb->file);
	return setfdate(path, t) == 0;
}

time_t lastfiletime(smb_t* smb)
{
	idxrec_t idx;
	if(smb_getlastidx(smb, &idx) != SMB_SUCCESS)
		return (time_t)-1;
	return idx.time;
}

static int filename_compare_a(const void *arg1, const void *arg2)
{
   return stricmp(*(char**) arg1, *(char**) arg2);
}

static int filename_compare_d(const void *arg1, const void *arg2)
{
   return stricmp(*(char**) arg2, *(char**) arg1);
}

static int filename_compare_ac(const void *arg1, const void *arg2)
{
   return strcmp(*(char**) arg1, *(char**) arg2);
}

static int filename_compare_dc(const void *arg1, const void *arg2)
{
   return strcmp(*(char**) arg2, *(char**) arg1);
}

// Note: does not support sorting by date
void sortfilenames(str_list_t filelist, size_t count, enum file_sort order)
{
	switch(order) {
		case FILE_SORT_NAME_A:
			qsort(filelist, count, sizeof(*filelist), filename_compare_a);
			break;
		case FILE_SORT_NAME_D:
			qsort(filelist, count, sizeof(*filelist), filename_compare_d);
			break;
		case FILE_SORT_NAME_AC:
			qsort(filelist, count, sizeof(*filelist), filename_compare_ac);
			break;
		case FILE_SORT_NAME_DC:
			qsort(filelist, count, sizeof(*filelist), filename_compare_dc);
			break;
		default:
			break;
131
132
133
	}
}

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// Return an optionally-sorted dynamically-allocated string list of filenames added since date/time (t)
// Note: does not support sorting by date (exception: natural sort order of date-ascending)
str_list_t loadfilenames(smb_t* smb, const char* filespec, time_t t, enum file_sort order, size_t* count)
{
	size_t count_;

	if(count == NULL)
		count = &count_;

	*count = 0;

	long start = 0;	
	if(t > 0) {
		idxrec_t idx;
		start = smb_getmsgidx_by_time(smb, &idx, t);
		if(start < 0)
			return NULL;
151
	}
152
153
154
155
156
157

	char** file_list = calloc(smb->status.total_files + 1, sizeof(char*));
	if(file_list == NULL)
		return NULL;

	fseek(smb->sid_fp, start * sizeof(fileidxrec_t), SEEK_SET);
158
159
	size_t offset = start;
	while(!feof(smb->sid_fp) && offset < smb->status.total_files) {
160
161
162
163
164
		fileidxrec_t fidx;

		if(smb_fread(smb, &fidx, sizeof(fidx), smb->sid_fp) != sizeof(fidx))
			break;

165
166
		offset++;

167
168
169
170
171
172
173
174
		if(fidx.idx.number == 0)	/* invalid message number, ignore */
			continue;

		TERMINATE(fidx.name);

		if(filespec != NULL && *filespec != '\0') {
			if(!wildmatch(fidx.name, filespec, /* path: */false, /* case-sensitive: */false))
				continue;
175
		}
176
177
		file_list[*count] = strdup(fidx.name);
		(*count)++;
178
	}
179
180
	if(order != FILE_SORT_NATURAL)
		sortfilenames(file_list, *count, order);
181

182
183
	return file_list;
}
184

185
186
187
188
189
190
191
192
193
194
195
// Load and optionally-sort files from an open filebase into a dynamically-allocated list of "objects"
file_t* loadfiles(smb_t* smb, const char* filespec, time_t t, enum file_detail detail, enum file_sort order, size_t* count)
{
	*count = 0;

	long start = 0;	
	if(t) {
		idxrec_t idx;
		start = smb_getmsgidx_by_time(smb, &idx, t);
		if(start < 0)
			return NULL;
196
	}
197
198
199
200
201
202

	file_t* file_list = calloc(smb->status.total_files, sizeof(file_t));
	if(file_list == NULL)
		return NULL;

	fseek(smb->sid_fp, start * sizeof(fileidxrec_t), SEEK_SET);
203
204
205
206
	size_t offset = start;
	size_t cnt = 0;
	while(!feof(smb->sid_fp) && offset < smb->status.total_files) {
		file_t* f = &file_list[cnt];
207
208
209
210
211
212
213
214
215
216
217
218
219
220

		if(smb_fread(smb, &f->file_idx, sizeof(f->file_idx), smb->sid_fp) != sizeof(f->file_idx))
			break;

		f->idx_offset = offset++;

		if(f->idx.number == 0)	/* invalid message number, ignore */
			continue;

		TERMINATE(f->file_idx.name);

		if(filespec != NULL && *filespec != '\0') {
			if(!wildmatch(f->file_idx.name, filespec, /* path: */false, /* case-sensitive: */false))
				continue;
221
		}
222
		cnt++;
223
	}
224
	if(order != FILE_SORT_NATURAL)
225
		sortfiles(file_list, cnt, order);
226

227
228
229
230
231
232
	// Read (and set convenience pointers) *after* sorting the list
	for((*count) = 0; (*count) < cnt; (*count)++) {
		int result = smb_getfile(smb, &file_list[*count], detail);
		if(result != SMB_SUCCESS)
			break;
	}
233
	return file_list;
234
235
}

236
static int file_compare_name_a(const void* v1, const void* v2)
237
{
238
239
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;
240

241
	return stricmp(f1->file_idx.name, f2->file_idx.name);
242
243
}

244
static int file_compare_name_ac(const void* v1, const void* v2)
245
{
246
247
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;
248

249
	return strcmp(f1->file_idx.name, f2->file_idx.name);
250
251
252
253
254
255
256
}

static int file_compare_name_d(const void* v1, const void* v2)
{
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;

257
	return stricmp(f2->file_idx.name, f1->file_idx.name);
258
259
260
261
262
263
264
}

static int file_compare_name_dc(const void* v1, const void* v2)
{
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;

265
	return strcmp(f2->file_idx.name, f1->file_idx.name);
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
}

static int file_compare_date_a(const void* v1, const void* v2)
{
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;

	return f1->hdr.when_imported.time - f2->hdr.when_imported.time;
}

static int file_compare_date_d(const void* v1, const void* v2)
{
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;

	return f2->hdr.when_imported.time - f1->hdr.when_imported.time;
}

void sortfiles(file_t* filelist, size_t count, enum file_sort order)
{
	switch(order) {
		case FILE_SORT_NAME_A:
			qsort(filelist, count, sizeof(*filelist), file_compare_name_a);
			break;
		case FILE_SORT_NAME_D:
			qsort(filelist, count, sizeof(*filelist), file_compare_name_d);
			break;
		case FILE_SORT_NAME_AC:
			qsort(filelist, count, sizeof(*filelist), file_compare_name_ac);
			break;
		case FILE_SORT_NAME_DC:
			qsort(filelist, count, sizeof(*filelist), file_compare_name_dc);
			break;
		case FILE_SORT_DATE_A:
			qsort(filelist, count, sizeof(*filelist), file_compare_date_a);
			break;
		case FILE_SORT_DATE_D:
			qsort(filelist, count, sizeof(*filelist), file_compare_date_d);
304
305
			break; 
	}
306
}
307

308
309
310
311
312
313
void freefiles(file_t* filelist, size_t count)
{
	for(size_t i = 0; i < count; i++)
		smb_freefilemem(&filelist[i]);
	free(filelist);
}
314

315
316
317
bool loadfile(scfg_t* cfg, uint dirnum, const char* filename, file_t* file, enum file_detail detail)
{
	smb_t smb;
318

319
320
	if(smb_open_dir(cfg, &smb, dirnum) != SMB_SUCCESS)
		return false;
321

322
323
324
325
326
	int result = smb_loadfile(&smb, filename, file, detail);
	smb_close(&smb);
	if(cfg->dir[dirnum]->misc & DIR_FREE)
		file->cost = 0;
	return result == SMB_SUCCESS;
327
328
}

329
330
331
332
333
334
char* batch_list_name(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, char* fname, size_t size)
{
	safe_snprintf(fname, size, "%suser/%04u.%sload", cfg->data_dir, usernumber
		,(type == XFER_UPLOAD || type == XFER_BATCH_UPLOAD) ? "up" : "dn");
	return fname;
}
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
FILE* batch_list_open(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, bool create)
{
	char path[MAX_PATH + 1];
	return iniOpenFile(batch_list_name(cfg, usernumber, type, path, sizeof(path)), create);
}

str_list_t batch_list_read(scfg_t* cfg, uint usernumber, enum XFER_TYPE type)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */false);
	if(fp == NULL)
		return NULL;
	str_list_t ini = iniReadFile(fp);
	iniCloseFile(fp);
	return ini;
}

bool batch_list_write(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, str_list_t list)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */true);
	if(fp == NULL)
		return false;
	bool result = iniWriteFile(fp, list);
	iniCloseFile(fp);
	return result;
}

bool batch_list_clear(scfg_t* cfg, uint usernumber, enum XFER_TYPE type)
{
	char path[MAX_PATH + 1];
	return remove(batch_list_name(cfg, usernumber, type, path, sizeof(path))) == 0;
}

size_t batch_file_count(scfg_t* cfg, uint usernumber, enum XFER_TYPE type)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */false);
	if(fp == NULL)
		return 0;
	size_t result = iniReadSectionCount(fp, /* prefix: */NULL);
	iniCloseFile(fp);
	return result;
}

bool batch_file_remove(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, const char* filename)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */false);
	if(fp == NULL)
		return false;
	str_list_t ini = iniReadFile(fp);
	bool result = iniRemoveSection(&ini, filename);
	iniWriteFile(fp, ini);
	iniCloseFile(fp);
	iniFreeStringList(ini);
	return result;
}

bool batch_file_exists(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, const char* filename)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */false);
	if(fp == NULL)
		return false;
	str_list_t ini = iniReadFile(fp);
	bool result = iniSectionExists(ini, filename);
	iniCloseFile(fp);
	iniFreeStringList(ini);
	return result;
}

bool batch_file_add(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, file_t* f)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */true);
	if(fp == NULL)
		return false;
	fseek(fp, 0, SEEK_END);
	fprintf(fp, "\n[%s]\n", f->name);
	if(f->dir >= 0 && f->dir < cfg->total_dirs)
		fprintf(fp, "dir=%s\n", cfg->dir[f->dir]->code);
	if(f->desc != NULL)
		fprintf(fp, "desc=%s\n", f->desc);
	if(f->tags != NULL)
		fprintf(fp, "tags=%s\n", f->tags);
	fclose(fp);
	return true;
}

bool batch_file_get(scfg_t* cfg, str_list_t ini, const char* filename, file_t* f)
{
	char* p;
	char value[INI_MAX_VALUE_LEN + 1];

	if(!iniSectionExists(ini, filename))
		return false;
	f->dir = batch_file_dir(cfg, ini, filename);
	if(f->dir < 0 || f->dir >= cfg->total_dirs)
		return false;
	smb_hfield_str(f, SMB_FILENAME, filename);
	if((p = iniGetString(ini, filename, "desc", NULL, value)) != NULL)
		smb_hfield_str(f, SMB_FILEDESC, p);
	if((p = iniGetString(ini, filename, "tags", NULL, value)) != NULL)
		smb_hfield_str(f, SMB_TAGS, p);
	return true;
}

int batch_file_dir(scfg_t* cfg, str_list_t ini, const char* filename)
{
	char value[INI_MAX_VALUE_LEN + 1];
	return getdirnum(cfg, iniGetString(ini, filename, "dir", NULL, value));
}

bool batch_file_load(scfg_t* cfg, str_list_t ini, const char* filename, file_t* f)
{
	if(!iniSectionExists(ini, filename))
		return false;
	f->dir = batch_file_dir(cfg, ini, filename);
	if(f->dir < 0)
		return false;
	return loadfile(cfg, f->dir, filename, f, file_detail_normal);
}

bool updatefile(scfg_t* cfg, file_t* file)
{
	smb_t smb;

	if(smb_open_dir(cfg, &smb, file->dir) != SMB_SUCCESS)
		return false;

	int result = smb_updatemsg(&smb, file) == SMB_SUCCESS;
	smb_close(&smb);
	return result == SMB_SUCCESS;
}

bool removefile(scfg_t* cfg, uint dirnum, const char* filename)
{
	smb_t smb;

	if(smb_open_dir(cfg, &smb, dirnum) != SMB_SUCCESS)
		return false;

	int result;
	file_t file;
	if((result = smb_loadfile(&smb, filename, &file, file_detail_normal)) == SMB_SUCCESS) {
		result = smb_removefile(&smb, &file);
		smb_freefilemem(&file);
478
	}
479
480
	smb_close(&smb);
	return result == SMB_SUCCESS;
481
482
483
}

/****************************************************************************/
484
485
486
487
/* Returns full (case-corrected) path to specified file						*/
/* 'path' should be MAX_PATH + 1 chars in size								*/
/* If the directory is configured to allow file-checking and the file does	*/
/* not exist, the size element is set to -1.								*/
488
/****************************************************************************/
489
490
491
492
493
494
495
496
497
char* getfilepath(scfg_t* cfg, file_t* f, char* path)
{
	bool fchk = true;
	const char* name = f->name == NULL ? f->file_idx.name : f->name;
	if(f->dir >= cfg->total_dirs)
		safe_snprintf(path, MAX_PATH, "%s%s", cfg->temp_dir, name);
	else {
		safe_snprintf(path, MAX_PATH, "%s%s", cfg->dir[f->dir]->path, name);
		fchk = (cfg->dir[f->dir]->misc & DIR_FCHK) != 0;
498
	}
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
	if(f->size == 0 && fchk && !fexistcase(path))
		f->size = -1;
	return path;
}

off_t getfilesize(scfg_t* cfg, file_t* f)
{
	char fpath[MAX_PATH + 1];
	if(f->size > 0)
		return f->size;
	f->size = flength(getfilepath(cfg, f, fpath));
	return f->size;
}

time_t getfiletime(scfg_t* cfg, file_t* f)
{
	char fpath[MAX_PATH + 1];
	if(f->time > 0)
		return f->time;
	f->time = fdate(getfilepath(cfg, f, fpath));
	return f->time;
}

ulong gettimetodl(scfg_t* cfg, file_t* f, uint rate_cps)
{
	if(getfilesize(cfg, f) < 1)
		return 0;
	if(f->size <= (off_t)rate_cps)
		return 1;
	return (ulong)(f->size / rate_cps);
}

bool hashfile(scfg_t* cfg, file_t* f)
{
	bool result = false;
	smb_t smb;

	if(cfg->dir[f->dir]->misc & DIR_NOHASH)
		return false;

	if(smb_open_dir(cfg, &smb, f->dir) != SMB_SUCCESS)
		return false;

	if(!(smb.status.attr & SMB_NOHASH)) {
		char fpath[MAX_PATH + 1];
		getfilepath(cfg, f, fpath);
		if((f->file_idx.hash.flags = smb_hashfile(fpath, getfilesize(cfg, f), &f->file_idx.hash.data)) != 0)
			result = true;
	}
	smb_close(&smb);
	return result;
}

bool addfile(scfg_t* cfg, uint dirnum, file_t* f, const char* extdesc)
{
	char fpath[MAX_PATH + 1];
	smb_t smb;

	if(smb_open_dir(cfg, &smb, dirnum) != SMB_SUCCESS)
		return false;

	getfilepath(cfg, f, fpath);
	int result = smb_addfile(&smb, f, SMB_SELFPACK, extdesc, fpath);
	smb_close(&smb);
	return result == SMB_SUCCESS;
}

/* 'size' does not include the NUL-terminator */
char* format_filename(const char* fname, char* buf, size_t size, bool pad)
{
	size_t fnlen = strlen(fname);
	char* ext = getfext(fname);
	if(ext != NULL) {
		size_t extlen = strlen(ext);
		if(extlen >= size)
			safe_snprintf(buf, size + 1, "%s", fname);
		else {
			fnlen -= extlen;
			if(fnlen > size - extlen)
				fnlen = size - extlen;
			safe_snprintf(buf, size + 1, "%-*.*s%s", (int)(pad ? (size - extlen) : 0), (int)fnlen, fname, ext);
		}
	} else	/* no extension */
		snprintf(buf, size + 1, "%s", fname);
	return buf;
}

int archive_type(const char* archive, char* str, size_t size)
{
	int result;
	struct archive *ar;
	struct archive_entry *entry;

	if((ar = archive_read_new()) == NULL) {
		safe_snprintf(str, size, "archive_read_new returned NULL");
		return -1;
595
	}
596
597
598
599
600
601
602
	archive_read_support_filter_all(ar);
	archive_read_support_format_all(ar);
	if((result = archive_read_open_filename(ar, archive, 10240)) != ARCHIVE_OK) {
		safe_snprintf(str, size, "archive_read_open_filename returned %d: %s"
			,result, archive_error_string(ar));
		archive_read_free(ar);
		return result;
603
	}
604
605
606
607
608
609
610
611
612
613
614
615
616
617
	result = archive_filter_code(ar, 0);
	if(result >= 0) {
		int comp = result;
		result = archive_read_next_header(ar, &entry);
		if(result != ARCHIVE_OK)
			safe_snprintf(str, size, "archive_read_next_header returned %d: %s"
				,result, archive_error_string(ar));
		else {
			result = archive_format(ar);
			if(comp > 0)
				safe_snprintf(str, size, "%s/%s", archive_filter_name(ar, 0), archive_format_name(ar));
			else
				safe_snprintf(str, size, "%s", archive_format_name(ar));
		}
618
	}
619
620
	archive_read_free(ar);
	return result;
621
622
}

623
624
625
626
627
628
629
630
631
632
633
634
635
str_list_t directory(const char* path)
{
	int			flags = GLOB_MARK;
	glob_t		g;

	if(glob(path, flags, NULL, &g) != 0)
		return NULL;
	str_list_t list = strListInit();
	for(size_t i = 0; i < g.gl_pathc; i++) {
		strListPush(&list, g.gl_pathv[i]);
	}
	globfree(&g);
	return list;
636
637
}

638
639
640
641
const char* supported_archive_formats[] = { "zip", "7z", "tgz", "tbz", NULL };
// Returns negative on error
long create_archive(const char* archive, const char* format
	,bool with_path, str_list_t file_list, char* error, size_t maxerrlen)
642
{
643
644
	int result;
	struct archive *ar;
645

646
647
	if(file_list == NULL || *file_list == NULL)
		return 0;
648

649
650
651
	if((ar = archive_write_new()) == NULL) {
		safe_snprintf(error, maxerrlen, "archive_write_new returned NULL");
		return -1;
652
	}
653
654
655
656
657
658
659
660
661
662
663
664
665
	if(stricmp(format, "tgz") == 0) {
		archive_write_add_filter_gzip(ar);
		archive_write_set_format_pax_restricted(ar);
	} else if(stricmp(format, "tbz") == 0) {
		archive_write_add_filter_bzip2(ar);
		archive_write_set_format_pax_restricted(ar);
	} else if(stricmp(format, "zip") == 0) {
		archive_write_set_format_zip(ar);
	} else if(stricmp(format, "7z") == 0) {
		archive_write_set_format_7zip(ar);
	} else {
		safe_snprintf(error, maxerrlen, "unsupported format: %s", format);
		return -2;
666
	}
667
668
669
670
671
	if((result = archive_write_open_filename(ar, archive)) != ARCHIVE_OK) {
		safe_snprintf(error, maxerrlen, "archive_write_open_filename(%s) returned %d: %s"
			,archive, result, archive_error_string(ar));
		archive_write_free(ar);
		return result;
672
	}
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
	ulong file_count = 0;
	for(;file_list[file_count] != NULL; file_count++) {
		struct archive_entry* entry;
		struct stat st;
		const char* filename = file_list[file_count];
		FILE* fp = fopen(filename, "rb");
		if(fp == NULL) {
			safe_snprintf(error, maxerrlen, "%d opening %s", errno, filename);
			break;
		}
		fstat(fileno(fp), &st);
		if((entry = archive_entry_new()) == NULL) {
			safe_snprintf(error, maxerrlen, "archive_entry_new returned NULL");
			fclose(fp);
			break;
		}
		if(with_path)
			archive_entry_set_pathname(entry, filename);
		else
			archive_entry_set_pathname(entry, getfname(filename));
		archive_entry_set_size(entry, st.st_size);
		archive_entry_set_mtime(entry, st.st_mtime, 0);
		archive_entry_set_filetype(entry, AE_IFREG);
		archive_entry_set_perm(entry, 0644);
		if((result = archive_write_header(ar, entry)) != ARCHIVE_OK)
			safe_snprintf(error, maxerrlen, "archive_write_header returned %d", result);
		else while(!feof(fp)) {
			char buf[256 * 1024];
			size_t len = fread(buf, 1, sizeof(buf), fp);
			if((result = archive_write_data(ar, buf, len)) != len) {
				safe_snprintf(error, maxerrlen, "archive_write_data returned %d instead of %d", result, (int)len);
				break;
			} else
				result = ARCHIVE_OK;
		}
		fclose(fp);
		archive_entry_free(entry);
		if(result != ARCHIVE_OK)
			break;
712
	}
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
	archive_write_close(ar);
	archive_write_free(ar);
	if(file_list[file_count] != NULL)
		return result < 0 ? result : -1;
	return file_count;
}

long extract_files_from_archive(const char* archive, const char* outdir, const char* allowed_filename_chars
	,bool with_path, long max_files, str_list_t file_list, char* error, size_t maxerrlen)
{
	int result;
	struct archive *ar;
	struct archive_entry *entry;
	long extracted = 0;
	char fpath[MAX_PATH + 1];

729
730
731
	if(error == NULL)
		maxerrlen = 0;
	if(maxerrlen >= 1)
732
733
734
735
		*error = '\0';
	if((ar = archive_read_new()) == NULL) {
		safe_snprintf(error, maxerrlen, "archive_read_new returned NULL");
		return -1;
736
	}
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
	archive_read_support_filter_all(ar);
	archive_read_support_format_all(ar);
	if((result = archive_read_open_filename(ar, archive, 10240)) != ARCHIVE_OK) {
		safe_snprintf(error, maxerrlen, "archive_read_open_filename returned %d: %s"
			,result, archive_error_string(ar));
		archive_read_free(ar);
		return result >= 0 ? -1 : result;
	}
	while(1) {
		result = archive_read_next_header(ar, &entry);
		if(result != ARCHIVE_OK) {
			if(result != ARCHIVE_EOF)
				safe_snprintf(error, maxerrlen, "archive_read_next_header returned %d: %s"
					,result, archive_error_string(ar));
			break;
752
		}
753
754
		const char* pathname = archive_entry_pathname(entry);
		if(pathname == NULL)
755
			continue;
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
		int filetype = archive_entry_filetype(entry);
		if(filetype == AE_IFDIR) {
			if(!with_path)
				continue;
			if(strstr(pathname, "..") != NULL) {
				safe_snprintf(error, maxerrlen, "Illegal double-dots in path '%s'", pathname);
				break;
			}
			SAFECOPY(fpath, outdir);
			backslash(fpath);
			SAFECAT(fpath, pathname);
			if(mkpath(fpath) != 0) {
				char err[256];
				safe_snprintf(error, maxerrlen, "%d (%s) creating path '%s'", errno, safe_strerror(errno, err, sizeof(err)), fpath);
				break;
			}
772
			continue;
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
		}
		if(filetype != AE_IFREG)
			continue;
		char* filename = getfname(pathname);
		if(allowed_filename_chars != NULL
			&& *allowed_filename_chars != '\0'
			&& strspn(filename, allowed_filename_chars) != strlen(filename)) {
			safe_snprintf(error, maxerrlen, "disallowed filename '%s'", pathname);
			break;
		}
		if(!with_path)
			pathname = filename;
		if(file_list != NULL) {
			int i;
			for (i = 0; file_list[i] != NULL; i++)
				if(wildmatch(pathname, file_list[i], with_path, /* case-sensitive: */false))
					break;
			if(file_list[i] == NULL)
				continue;
		}
		SAFECOPY(fpath, outdir);
		backslash(fpath);
		SAFECAT(fpath, pathname);
		FILE* fp = fopen(fpath, "wb");
		if(fp == NULL) {
			char err[256];
			safe_snprintf(error, maxerrlen, "%d (%s) opening/creating '%s'", errno, safe_strerror(errno, err, sizeof(err)), fpath);
			break;
		}

		const void *buff;
		size_t size;
		la_int64_t offset;
806

807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
		for(;;) {
			result = archive_read_data_block(ar, &buff, &size, &offset);
			if(result == ARCHIVE_EOF) {
				extracted++;
				break;
			}
			if(result < ARCHIVE_OK) {
				safe_snprintf(error, maxerrlen, "archive_read_data_block returned %d: %s"
					,result, archive_error_string(ar));
				break;
			}
			if(fwrite(buff, 1, size, fp) != size)
				break;
		}
		fclose(fp);
		if(result != ARCHIVE_EOF)
			(void)remove(fpath);
		if(max_files && extracted >= max_files) {
			safe_snprintf(error, maxerrlen, "maximum number of files (%lu) extracted", max_files);
			break;
		}
	}
	archive_read_free(ar);
	return extracted;
831
832
}

833
bool extract_diz(scfg_t* cfg, file_t* f, str_list_t diz_fnames, char* path, size_t maxlen)
834
{
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
	int i;
	char archive[MAX_PATH + 1];
	char* default_diz_fnames[] = { "FILE_ID.DIZ", "DESC.SDI", NULL };

	getfilepath(cfg, f, archive);
	if(diz_fnames == NULL)
		diz_fnames = default_diz_fnames;

	if(!fexistcase(archive))
		return false;

	for(i = 0; diz_fnames[i] != NULL; i++) {
		safe_snprintf(path, maxlen, "%s%s", cfg->temp_dir, diz_fnames[i]); // no slash
		removecase(path);
		if(fexistcase(path))	// failed to delete?
			return false;
	}

	if(extract_files_from_archive(archive
		,/* outdir: */cfg->temp_dir
		,/* allowed_filename_chars: */NULL /* any */
		,/* with_path: */false
		,/* max_files: */strListCount(diz_fnames)
		,/* file_list: */diz_fnames
		,/* error: */NULL, 0) >= 0) {
		for(i = 0; diz_fnames[i] != NULL; i++) {
			safe_snprintf(path, maxlen, "%s%s", cfg->temp_dir, diz_fnames[i]); // no slash
			if(fexistcase(path))
				return true;
		}
		return false;
	}

	char* fext = getfext(f->name);
869

870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
	if(fext == NULL)
		return false;

	for(i = 0; i < cfg->total_fextrs; i++)
		if(stricmp(cfg->fextr[i]->ext, fext + 1) == 0 && chk_ar(cfg, cfg->fextr[i]->ar, /* user: */NULL, /* client: */NULL))
			break;
	if(i >= cfg->total_fextrs)
		return false;

	fextr_t* fextr = cfg->fextr[i];
	char cmd[512];
	for(i = 0; diz_fnames[i] != NULL; i++) {
		safe_snprintf(path, maxlen, "%s%s", cfg->temp_dir, diz_fnames[i]);
		system(cmdstr(cfg, /* user: */NULL, fextr->cmd, archive, diz_fnames[i], cmd, sizeof(cmd)));
		if(fexistcase(path))
			return true;
	}
	return false;
888
889
}

890
str_list_t read_diz(const char* path, size_t max_line_len)
891
{
892
893
894
	FILE* fp = fopen(path, "r");
	if(fp == NULL)
		return NULL;
895

896
897
898
	str_list_t lines = strListReadFile(fp, NULL, max_line_len);
	fclose(fp);
	return lines;
899
}
900

901
902
903
904
905
char* format_diz(str_list_t lines, char* str, size_t maxlen, bool allow_ansi)
{
	if(lines == NULL) {
		*str = '\0';
		return NULL;
906
	}
907
908
909
910
911
912
	strListTruncateTrailingWhitespaces(lines);
	if(!allow_ansi) {
		for(size_t i = 0; lines[i] != NULL; i++) {
			strip_ansi(lines[i]);
			strip_ctrl(lines[i], lines[i]);
		}
913
	}
914
915
916
	strListFastDeleteBlanks(lines);
	return strListCombine(lines, str, maxlen, "\r\n");
}
917

918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
// Take a verbose extended description (e.g. FILE_ID.DIZ)
// and convert to suitable short description
char* prep_file_desc(const char *src, char* dest)
{
	int out;

	FIND_ALPHANUMERIC(src);
	for(out = 0; *src != '\0' && out < LEN_FDESC; src++) {
		if(IS_WHITESPACE(*src) && out && IS_WHITESPACE(dest[out - 1]))
			continue;
		if(!IS_ALPHANUMERIC(*src) && out && *src == dest[out - 1])
			continue;
		if(*src == '\n') {
			if(out && !IS_WHITESPACE(dest[out - 1]))
				dest[out++] = ' ';
			continue;
		}
		if(IS_CONTROL(*src))
			continue;
		dest[out++] = *src;
	}
	dest[out] = '\0';
	return dest;
}
942

943
944
945
946
947
948
static const char* quoted_string(const char* str, char* buf, size_t maxlen)
{
	if(strchr(str,' ')==NULL)
		return(str);
	safe_snprintf(buf,maxlen,"\"%s\"",str);
	return(buf);
949
}
950

951
952
953
#define QUOTED_STRING(ch, str, buf, maxlen) \
	((IS_ALPHA(ch) && IS_UPPERCASE(ch)) ? str : quoted_string(str,buf,maxlen))

954
/****************************************************************************/
955
956
/* Returns command line generated from instr with %c replacements           */
/* This is the C-exported version of sbbs_t::cmdstr()						*/
957
/****************************************************************************/
958
959
char* cmdstr(scfg_t* cfg, user_t* user, const char* instr, const char* fpath
						,const char* fspec, char* cmd, size_t maxlen)
960
{
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
	char	str[MAX_PATH+1];
    int		i,j,len;

	len=strlen(instr);
	for(i=j=0; i < len && j < (int)maxlen; i++) {
        if(instr[i]=='%') {
            i++;
            cmd[j]=0;
			int avail = maxlen - j;
			char ch=instr[i];
			if(IS_ALPHA(ch))
				ch=toupper(ch);
            switch(ch) {
                case 'A':   /* User alias */
					if(user!=NULL)
						strncat(cmd,QUOTED_STRING(instr[i],user->alias,str,sizeof(str)), avail);
                    break;
                case 'B':   /* Baud (DTE) Rate */
                    break;
                case 'C':   /* Connect Description */
					if(user!=NULL)
						strncat(cmd,user->modem, avail);
                    break;
                case 'D':   /* Connect (DCE) Rate */
                    break;
                case 'E':   /* Estimated Rate */
                    break;
                case 'F':   /* File path */
                    strncat(cmd,QUOTED_STRING(instr[i],fpath,str,sizeof(str)), avail);
                    break;
                case 'G':   /* Temp directory */
                    strncat(cmd,cfg->temp_dir, avail);
                    break;
                case 'H':   /* Port Handle or Hardware Flow Control */
                    break;
                case 'I':   /* IP address */
					if(user!=NULL)
						strncat(cmd,user->note, avail);
                    break;
                case 'J':
                    strncat(cmd,cfg->data_dir, avail);
                    break;
                case 'K':
                    strncat(cmd,cfg->ctrl_dir, avail);
                    break;
                case 'L':   /* Lines per message */
					if(user!=NULL)
						strncat(cmd,ultoa(cfg->level_linespermsg[user->level],str,10), avail);
                    break;
                case 'M':   /* Minutes (credits) for user */
					if(user!=NULL)
						strncat(cmd,ultoa(user->min,str,10), avail);
                    break;
                case 'N':   /* Node Directory (same as SBBSNODE environment var) */
                    strncat(cmd,cfg->node_dir, avail);
                    break;
                case 'O':   /* SysOp */
                    strncat(cmd,QUOTED_STRING(instr[i],cfg->sys_op,str,sizeof(str)), avail);
                    break;
                case 'P':   /* Client protocol */
                    break;
                case 'Q':   /* QWK ID */
                    strncat(cmd,cfg->sys_id, avail);
                    break;
                case 'R':   /* Rows */
					if(user!=NULL)
						strncat(cmd,ultoa(user->rows,str,10), avail);
                    break;
                case 'S':   /* File Spec */
                    strncat(cmd, fspec, avail);
                    break;
                case 'T':   /* Time left in seconds */
                    break;
                case 'U':   /* UART I/O Address (in hex) */
                    strncat(cmd,ultoa(cfg->com_base,str,16), avail);
                    break;
                case 'V':   /* Synchronet Version */
                    sprintf(str,"%s%c",VERSION,REVISION);
					strncat(cmd,str, avail);
                    break;
                case 'W':   /* Columns/width */
                    break;
                case 'X':
					if(user!=NULL)
						strncat(cmd,cfg->shell[user->shell]->code, avail);
                    break;
                case '&':   /* Address of msr */
                    break;
                case 'Y':
                    break;
                case 'Z':
                    strncat(cmd,cfg->text_dir, avail);
                    break;
				case '~':	/* DOS-compatible (8.3) filename */
				{
#ifdef _WIN32
					char sfpath[MAX_PATH+1];
					SAFECOPY(sfpath,fpath);
					GetShortPathName(fpath,sfpath,sizeof(sfpath));
					strncat(cmd,sfpath, avail);
#else
                    strncat(cmd,QUOTED_STRING(instr[i],fpath,str,sizeof(str)), avail);
#endif
					break;
				}
                case '!':   /* EXEC Directory */
                    strncat(cmd,cfg->exec_dir, avail);
                    break;
                case '@':   /* EXEC Directory for DOS/OS2/Win32, blank for Unix */
#ifndef __unix__
                    strncat(cmd,cfg->exec_dir, avail);
#endif
                    break;

                case '#':   /* Node number (same as SBBSNNUM environment var) */
                    sprintf(str,"%d",cfg->node_num);
                    strncat(cmd,str, avail);
                    break;
                case '*':
                    sprintf(str,"%03d",cfg->node_num);
                    strncat(cmd,str, avail);
                    break;
                case '$':   /* Credits */
					if(user!=NULL)
						strncat(cmd,ultoa(user->cdt+user->freecdt,str,10), avail);
                    break;
                case '%':   /* %% for percent sign */
                    strncat(cmd,"%", avail);
                    break;
				case '.':	/* .exe for DOS/OS2/Win32, blank for Unix */
#ifndef __unix__
					strncat(cmd,".exe", avail);
#endif
					break;
				case '?':	/* Platform */
#ifdef __OS2__
					strcpy(str,"OS2");
#else
					strcpy(str,PLATFORM_DESC);
#endif
					strlwr(str);
					strncat(cmd,str, avail);
					break;
				case '^':	/* Architecture */
					strncat(cmd, ARCHITECTURE_DESC, avail);
					break;
                default:    /* unknown specification */
                    if(IS_DIGIT(instr[i]) && user!=NULL) {
                        sprintf(str,"%0*d",instr[i]&0xf,user->number);
                        strncat(cmd,str, avail);
					}
                    break;
			}
            j=strlen(cmd);
		}
        else
            cmd[j++]=instr[i];
	}
    cmd[j]=0;
1120

1121
    return(cmd);
1122
}
1123