filedat.c 38 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
#include "sauce.h"
32
#include "crc32.h"
33
#include "utf8.h"
34

35
36
37
/* libarchive: */
#include <archive.h>
#include <archive_entry.h>
38

39
 /****************************************************************************/
40
/****************************************************************************/
41
bool findfile(scfg_t* cfg, uint dirnum, const char *filename, file_t* file)
42
{
43
	smb_t smb;
44

45
46
	if(cfg == NULL || filename == NULL)
		return false;
47

48
49
50
51
52
53
54
55
	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;
}
56

57
58
59
60
61
62
// 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);
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
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;
134
135
136
	}
}

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// 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;
154
	}
155

156
157
158
	if(fseek(smb->sid_fp, start * sizeof(fileidxrec_t), SEEK_SET) != 0)
		return NULL;

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

163
164
	size_t offset = start;
	while(!feof(smb->sid_fp) && offset < smb->status.total_files) {
165
166
167
168
169
		fileidxrec_t fidx;

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

170
171
		offset++;

172
173
174
175
176
177
178
179
		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;
180
		}
181
182
		file_list[*count] = strdup(fidx.name);
		(*count)++;
183
	}
184
185
	if(order != FILE_SORT_NATURAL)
		sortfilenames(file_list, *count, order);
186

187
188
	return file_list;
}
189

190
191
192
// 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)
{
193
194
195
196
197
198
	// Liberal filespec matching when filespec does not contain wildcards and is at least 12 chars in length
	char newfilespec[SMB_FILEIDX_NAMELEN + 1] = "";
	if(filespec != NULL) {
		size_t len = strlen(filespec);
		if(len >= 12 && strcspn(filespec, "*?") == len) {
			SAFECOPY(newfilespec, filespec);
199
200
201
202
			char* ext = getfext(filespec);
			char* newext = getfext(newfilespec);
			if(ext != NULL && newext != NULL) {
				*newext = 0;
203
				SAFECAT(newfilespec, "*");
204
				SAFECAT(newfilespec, ext);
205
206
207
208
209
			} else
				SAFECAT(newfilespec, "*");
			filespec = newfilespec;
		}
	}
210
211
212
213
214
215
216
217
	*count = 0;

	long start = 0;	
	if(t) {
		idxrec_t idx;
		start = smb_getmsgidx_by_time(smb, &idx, t);
		if(start < 0)
			return NULL;
218
	}
219

220
221
222
	if(fseek(smb->sid_fp, start * sizeof(fileidxrec_t), SEEK_SET) != 0)
		return NULL;

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

227
228
229
230
	size_t offset = start;
	size_t cnt = 0;
	while(!feof(smb->sid_fp) && offset < smb->status.total_files) {
		file_t* f = &file_list[cnt];
231
232
233
234
235
236
237
238
239
240
241
242
243
244

		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;
245
		}
246
		cnt++;
247
	}
248
	if(order != FILE_SORT_NATURAL)
249
		sortfiles(file_list, cnt, order);
250

251
252
253
254
255
256
	// 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;
	}
257
	return file_list;
258
259
}

260
static int file_compare_name_a(const void* v1, const void* v2)
261
{
262
263
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;
264

265
	return stricmp(f1->file_idx.name, f2->file_idx.name);
266
267
}

268
static int file_compare_name_ac(const void* v1, const void* v2)
269
{
270
271
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;
272

273
	return strcmp(f1->file_idx.name, f2->file_idx.name);
274
275
276
277
278
279
280
}

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

281
	return stricmp(f2->file_idx.name, f1->file_idx.name);
282
283
284
285
286
287
288
}

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

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

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);
328
329
			break; 
	}
330
}
331

332
333
334
335
336
337
void freefiles(file_t* filelist, size_t count)
{
	for(size_t i = 0; i < count; i++)
		smb_freefilemem(&filelist[i]);
	free(filelist);
}
338

339
340
341
bool loadfile(scfg_t* cfg, uint dirnum, const char* filename, file_t* file, enum file_detail detail)
{
	smb_t smb;
342

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

346
347
348
349
350
	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;
351
352
}

353
354
355
356
357
358
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;
}
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
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;
}

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// 'n' is zero-based index of file to remove
bool batch_file_remove_n(scfg_t* cfg, uint usernumber, enum XFER_TYPE type, uint n)
{
	FILE* fp = batch_list_open(cfg, usernumber, type, /* create: */false);
	if(fp == NULL)
		return false;
	str_list_t ini = iniReadFile(fp);
	str_list_t files = iniGetSectionList(ini, NULL);
	bool result = false;
	if(n < strListCount(files))
		result = iniRemoveSection(&ini, files[n]);
	iniWriteFile(fp, ini);
	iniCloseFile(fp);
	iniFreeStringList(ini);
	iniFreeStringList(files);
	return result;
}


434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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;
451
452
453
454
	if(fseek(fp, 0, SEEK_END) != 0) {
		fclose(fp);
		return false;
	}
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
	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;

507
	int result = smb_updatemsg(&smb, file);
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
	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);
524
	}
525
526
	smb_close(&smb);
	return result == SMB_SUCCESS;
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
ulong getuserxfers(scfg_t* cfg, const char* from, uint to)
{
	smb_t smb;
	ulong found = 0;

	if(cfg == NULL)
		return 0;
	if(cfg->user_dir >= cfg->total_dirs)
		return 0;

	if(smb_open_dir(cfg, &smb, cfg->user_dir) != SMB_SUCCESS)
		return 0;

	char usernum[16];
	SAFEPRINTF(usernum, "%u", to);
	size_t count = 0;
	file_t* list = loadfiles(&smb, /* filespec */ NULL, /* since: */0, file_detail_normal, FILE_SORT_NATURAL, &count);
	for(size_t i = 0; i < count; i++) {
		file_t* f = &list[i];
		if(from != NULL && (f->from == NULL || stricmp(f->from, from) != 0))
			continue;
		if(to != 0) {
			str_list_t dest_user_list = strListSplitCopy(NULL, f->to_list, ",");
			int dest_user = strListFind(dest_user_list, usernum, /* case-sensitive: */true);
			strListFree(&dest_user_list);
			if(dest_user < 0)
				continue;
		}
		found++;
	}

	smb_close(&smb);
	freefiles(list, count);
	return found;
}

565
/****************************************************************************/
566
567
568
569
/* 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.								*/
570
/****************************************************************************/
571
572
573
574
575
576
577
578
579
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;
580
	}
581
582
583
584
585
	if(f->size == 0 && fchk && !fexistcase(path))
		f->size = -1;
	return path;
}

586
587
588
589
590
char* getfilevpath(scfg_t* cfg, file_t* f, char* path)
{
	const char* name = f->name == NULL ? f->file_idx.name : f->name;
	if(f->dir >= cfg->total_dirs)
		return "";
591
	safe_snprintf(path, MAX_PATH, "%s/%s/%s"
592
		,cfg->lib[cfg->dir[f->dir]->lib]->vdir, cfg->dir[f->dir]->vdir, name);
593
594
595
	return path;
}

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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
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;
}

644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
int file_client_hfields(file_t* f, client_t* client)
{
	int		i;

	if(client == NULL)
		return -1;

	if(*client->addr && (i = smb_hfield_str(f, SENDERIPADDR, client->addr)) != SMB_SUCCESS)
		return i;
	if(*client->host && (i = smb_hfield_str(f, SENDERHOSTNAME, client->host)) != SMB_SUCCESS)
		return i;
	if(client->protocol != NULL && (i = smb_hfield_str(f, SENDERPROTOCOL, client->protocol)) != SMB_SUCCESS)
		return i;
	if(client->port) {
		char	port[16];
		SAFEPRINTF(port,"%u",client->port);
		return smb_hfield_str(f, SENDERPORT, port);
	}
	return SMB_SUCCESS;
}

665
666
667
668
669
670
671
int file_sauce_hfields(file_t* f, struct sauce_charinfo* info)
{
	int		i;

	if(info == NULL)
		return -1;

672
	if(*info->author && (i = smb_new_hfield_str(f, SMB_AUTHOR, info->author)) != SMB_SUCCESS)
673
674
		return i;

675
	if(*info->group && (i = smb_new_hfield_str(f, SMB_AUTHOR_ORG, info->group)) != SMB_SUCCESS)
676
677
		return i;

678
	if(f->desc == NULL && *info->title && (i = smb_new_hfield_str(f, SMB_FILEDESC, info->title)) != SMB_SUCCESS)
679
680
681
682
683
		return i;

	return SMB_SUCCESS;
}

684
bool addfile(scfg_t* cfg, uint dirnum, file_t* f, const char* extdesc, const char* metadata, client_t* client)
685
686
687
688
689
690
691
692
{
	char fpath[MAX_PATH + 1];
	smb_t smb;

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

	getfilepath(cfg, f, fpath);
693
694
	if(f->from_ip == NULL)
		file_client_hfields(f, client);
695
	int result = smb_addfile(&smb, f, SMB_SELFPACK, extdesc, metadata, fpath);
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
	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;
729
	}
730
731
732
733
734
735
736
	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;
737
	}
738
739
740
741
742
743
744
745
746
747
748
749
750
751
	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));
		}
752
	}
753
754
	archive_read_free(ar);
	return result;
755
756
}

757
758
759
760
761
762
763
764
765
766
767
768
769
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;
770
771
}

772
const char* supported_archive_formats[] = { "zip", "7z", "tgz", NULL };
773
// Returns total number of successfully archived files
774
775
776
// 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)
777
{
778
779
	int result;
	struct archive *ar;
780

781
782
	if(file_list == NULL || *file_list == NULL)
		return 0;
783

784
785
786
	if((ar = archive_write_new()) == NULL) {
		safe_snprintf(error, maxerrlen, "archive_write_new returned NULL");
		return -1;
787
	}
788
789
790
791
792
793
794
795
796
797
798
799
800
	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;
801
	}
802
803
804
805
806
	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;
807
	}
808
	ulong file_count = 0;
809
	ulong archived = 0;
810
811
812
813
	for(;file_list[file_count] != NULL; file_count++) {
		struct archive_entry* entry;
		struct stat st;
		const char* filename = file_list[file_count];
814
815
		if(isdir(filename))
			continue;
816
817
818
819
820
		FILE* fp = fopen(filename, "rb");
		if(fp == NULL) {
			safe_snprintf(error, maxerrlen, "%d opening %s", errno, filename);
			break;
		}
821
822
823
824
825
		if(fstat(fileno(fp), &st) != 0) {
			safe_snprintf(error, maxerrlen, "%d fstat %s", errno, filename);
			fclose(fp);
			break;
		}
826
827
828
829
830
831
832
833
834
835
836
837
838
839
		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)
840
			safe_snprintf(error, maxerrlen, "archive_write_header returned %d: %s", result, archive_error_string(ar));
841
842
843
844
845
846
847
848
849
850
851
852
853
		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;
854
		archived++;
855
	}
856
857
858
859
	archive_write_close(ar);
	archive_write_free(ar);
	if(file_list[file_count] != NULL)
		return result < 0 ? result : -1;
860
	return archived;
861
862
863
}

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

872
873
874
	if(error == NULL)
		maxerrlen = 0;
	if(maxerrlen >= 1)
875
876
877
878
		*error = '\0';
	if((ar = archive_read_new()) == NULL) {
		safe_snprintf(error, maxerrlen, "archive_read_new returned NULL");
		return -1;
879
	}
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
	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;
895
		}
896
897
		const char* pathname = archive_entry_pathname(entry);
		if(pathname == NULL)
898
			continue;
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
		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;
			}
915
			continue;
916
917
918
919
920
921
922
923
924
925
926
927
928
929
		}
		if(filetype != AE_IFREG)
			continue;
		char* filename = getfname(pathname);
		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;
		}
930
931
932
933
934
935
		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;
		}
936
937
938
		SAFECOPY(fpath, outdir);
		backslash(fpath);
		SAFECAT(fpath, pathname);
939
940
		if(!overwrite && fexist(fpath))
			continue;
941
942
943
944
945
946
947
948
949
		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;
950
		int64_t offset;
951

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
		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;
976
977
}

978
bool extract_diz(scfg_t* cfg, file_t* f, str_list_t diz_fnames, char* path, size_t maxlen)
979
{
980
981
	int i;
	char archive[MAX_PATH + 1];
982
	char* default_diz_fnames[] = { "FILE_ID.ANS", "FILE_ID.DIZ", "DESC.SDI", NULL };
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

	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 */
1001
		,/* with_path: */true
1002
		,/* overwrite: */false
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
		,/* 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);
1015

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
	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;
1034
1035
}

1036
char* read_diz(const char* path, struct sauce_charinfo* sauce)
1037
{
1038
1039
1040
1041
	if(sauce != NULL)
		memset(sauce, 0, sizeof(*sauce));

	off_t len = flength(path);
Rob Swindell's avatar
Rob Swindell committed
1042
1043
1044
	if(len < 1)
		return NULL;

1045
	FILE* fp = fopen(path, "rb");
1046
1047
	if(fp == NULL)
		return NULL;
1048

1049
1050
1051
1052
1053
1054
1055
	if(sauce != NULL)
		sauce_fread_charinfo(fp, /* type: */NULL, sauce);

	if(len > LEN_EXTDESC)
		len = LEN_EXTDESC;

	char* buf = calloc((size_t)len + 1, 1);
Rob Swindell's avatar
Rob Swindell committed
1056
1057
1058
1059
1060
1061
1062
	if(buf != NULL) {
		size_t rd = fread(buf, 1, (size_t)len, fp);
		buf[rd] = 0;
		char* eof = strchr(buf, CTRL_Z);	// CP/M EOF
		if(eof != NULL)
			*eof = '\0';
	}
1063
	fclose(fp);
1064
1065

	return buf;
1066
}
1067

1068
char* format_diz(const char* src, char* dest, size_t maxlen, int width, bool ice)
1069
{
1070
1071
1072
	if(src == NULL) {
		*dest = '\0';
		return dest;
1073
	}
1074
1075
	convert_ansi(src, dest, maxlen - 1, width, ice);
	return dest;
1076
}
1077

1078
1079
// Take a verbose extended description (e.g. FILE_ID.DIZ)
// and convert to suitable short description
1080
char* prep_file_desc(const char* ext, char* dest)
1081
1082
{
	int out;
1083
1084
1085
	char* src;
	char* buf = strdup(ext);
	if(buf == NULL)
1086
1087
1088
1089
1090
1091
1092
		return NULL;
	src = buf;
	strip_ctrl(src, src);
	if(!str_is_ascii(src)) {
		if(utf8_str_is_valid(src))
			utf8_to_cp437_inplace(src);
		strip_cp437_graphics(src, src);
1093
	}
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110

	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';
1111
	free(buf);
1112
1113
	return dest;
}
1114

1115
1116
1117
1118
1119
1120
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);
1121
}
1122

1123
1124
1125
#define QUOTED_STRING(ch, str, buf, maxlen) \
	((IS_ALPHA(ch) && IS_UPPERCASE(ch)) ? str : quoted_string(str,buf,maxlen))

1126
/****************************************************************************/
1127
1128
/* Returns command line generated from instr with %c replacements           */
/* This is the C-exported version of sbbs_t::cmdstr()						*/
1129
/****************************************************************************/
1130
1131
char* cmdstr(scfg_t* cfg, user_t* user, const char* instr, const char* fpath
						,const char* fspec, char* cmd, size_t maxlen)
1132
{
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
	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;
1279
1280
1281
1282
				case '+':	/* Real name */
					if(user != NULL)
						strncat(cmd, quoted_string(user->name, str, sizeof(str)), avail);
					break;
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
                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;
1296

1297
    return(cmd);
1298
}
1299

1300
1301
1302
1303
1304
/****************************************************************************/
/* Is this filename made up of only the "safest" characters?				*/
/****************************************************************************/
bool safest_filename(const char* fname)
{
1305
	return (fname != NULL) && (strspn(fname, SAFEST_FILENAME_CHARS) == strlen(fname));
1306
1307
1308
1309
1310
1311
1312
}

/****************************************************************************/
/* Is this filename highly-suspicious?										*/
/****************************************************************************/
bool illegal_filename(const char *fname)
{
1313
1314
1315
	if(fname == NULL)
		return false;

1316
1317
	size_t len = strlen(fname);

1318
	if(len < 1)
1319
1320
1321
1322
1323
		return true;
	if(strcspn(fname, ILLEGAL_FILENAME_CHARS) != len)
		return true;
	if(strstr(fname, "..") != NULL)
		return true;
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
	if(*fname == '-') // leading dash is a problem for argument parsing
		return true;
	if(*fname == '.') // leading dot hides files on *nix
		return true;
	if(*fname == ' ') // leading space is a problem for argument parsing (shells)
		return true;
	if(fname[len - 1] == '.') // a trailing dot is a problem for Windows
		return true;
	if(fname[len - 1] == ' ') // a trailing space is a problem for argument parsing (shells)
		return true;
	for(size_t i = 0; i < len; i++) {
		if(IS_CONTROL(fname[i])) // control characters in filenames are evil
			return true;
	}

1339
1340
1341
	return false;
}

1342
1343
1344
1345
1346
/****************************************************************************/
/* Checks if the filename chars meet the system requirements for upload		*/
/* Assumes the filename has already been checked with illegal_filename()	*/
/****************************************************************************/
bool allowed_filename(scfg_t* cfg, const char *fname)
1347
{
1348
1349
1350
	if(fname == NULL)
		return false;

1351
	size_t len = strlen(fname);
1352
	if(len < 1 || len > cfg->filename_maxlen)
1353
1354
		return false;

1355
1356
1357
1358
1359
1360
	if(cfg->file_misc & FM_SAFEST)
		return safest_filename(fname);

	uchar min = (cfg->file_misc & FM_SPACES) ? ' ' : '!';
	uchar max = (cfg->file_misc & FM_EXASCII) ? 0xff : 0x7f;

1361
	for(size_t i = 0; i < len; i++) {
1362
		if((uchar)fname[i] < min || (uchar)fname[i] > max)
1363
1364
1365
1366
			return false;
	}
	return true;
}