filedat.c 34 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

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

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

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

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

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

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

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

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

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

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

169 170
		offset++;

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

186 187
	return file_list;
}
188

189 190 191 192 193 194 195 196 197 198 199
// 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;
200
	}
201

202 203 204
	if(fseek(smb->sid_fp, start * sizeof(fileidxrec_t), SEEK_SET) != 0)
		return NULL;

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

209 210 211 212
	size_t offset = start;
	size_t cnt = 0;
	while(!feof(smb->sid_fp) && offset < smb->status.total_files) {
		file_t* f = &file_list[cnt];
213 214 215 216 217 218 219 220 221 222 223 224 225 226

		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;
227
		}
228
		cnt++;
229
	}
230
	if(order != FILE_SORT_NATURAL)
231
		sortfiles(file_list, cnt, order);
232

233 234 235 236 237 238
	// 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;
	}
239
	return file_list;
240 241
}

242
static int file_compare_name_a(const void* v1, const void* v2)
243
{
244 245
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;
246

247
	return stricmp(f1->file_idx.name, f2->file_idx.name);
248 249
}

250
static int file_compare_name_ac(const void* v1, const void* v2)
251
{
252 253
	file_t* f1 = (file_t*)v1;
	file_t* f2 = (file_t*)v2;
254

255
	return strcmp(f1->file_idx.name, f2->file_idx.name);
256 257 258 259 260 261 262
}

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

263
	return stricmp(f2->file_idx.name, f1->file_idx.name);
264 265 266 267 268 269 270
}

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

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

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);
310 311
			break; 
	}
312
}
313

314 315 316 317 318 319
void freefiles(file_t* filelist, size_t count)
{
	for(size_t i = 0; i < count; i++)
		smb_freefilemem(&filelist[i]);
	free(filelist);
}
320

321 322 323
bool loadfile(scfg_t* cfg, uint dirnum, const char* filename, file_t* file, enum file_detail detail)
{
	smb_t smb;
324

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

328 329 330 331 332
	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;
333 334
}

335 336 337 338 339 340
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;
}
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
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;
414 415 416 417
	if(fseek(fp, 0, SEEK_END) != 0) {
		fclose(fp);
		return false;
	}
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
	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;

470
	int result = smb_updatemsg(&smb, file);
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	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);
487
	}
488 489
	smb_close(&smb);
	return result == SMB_SUCCESS;
490 491
}

492 493 494 495 496 497 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
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;
}

528
/****************************************************************************/
529 530 531 532
/* 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.								*/
533
/****************************************************************************/
534 535 536 537 538 539 540 541 542
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;
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 595 596
	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;
}

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
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;
}

618 619 620 621 622 623 624
int file_sauce_hfields(file_t* f, struct sauce_charinfo* info)
{
	int		i;

	if(info == NULL)
		return -1;

625
	if(*info->author && (i = smb_new_hfield_str(f, SMB_AUTHOR, info->author)) != SMB_SUCCESS)
626 627
		return i;

628
	if(*info->group && (i = smb_new_hfield_str(f, SMB_AUTHOR_ORG, info->group)) != SMB_SUCCESS)
629 630
		return i;

631
	if(f->desc == NULL && *info->title && (i = smb_new_hfield_str(f, SMB_FILEDESC, info->title)) != SMB_SUCCESS)
632 633 634 635 636
		return i;

	return SMB_SUCCESS;
}

637
bool addfile(scfg_t* cfg, uint dirnum, file_t* f, const char* extdesc, client_t* client)
638 639 640 641 642 643 644 645
{
	char fpath[MAX_PATH + 1];
	smb_t smb;

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

	getfilepath(cfg, f, fpath);
646 647
	if(f->from_ip == NULL)
		file_client_hfields(f, client);
648
	int result = smb_addfile(&smb, f, SMB_SELFPACK, extdesc, /* contents: */NULL, fpath);
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	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;
682
	}
683 684 685 686 687 688 689
	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;
690
	}
691 692 693 694 695 696 697 698 699 700 701 702 703 704
	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));
		}
705
	}
706 707
	archive_read_free(ar);
	return result;
708 709
}

710 711 712 713 714 715 716 717 718 719 720 721 722
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;
723 724
}

725 726 727 728
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)
729
{
730 731
	int result;
	struct archive *ar;
732

733 734
	if(file_list == NULL || *file_list == NULL)
		return 0;
735

736 737 738
	if((ar = archive_write_new()) == NULL) {
		safe_snprintf(error, maxerrlen, "archive_write_new returned NULL");
		return -1;
739
	}
740 741 742 743 744 745 746 747 748 749 750 751 752
	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;
753
	}
754 755 756 757 758
	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;
759
	}
760 761 762 763 764 765 766 767 768 769
	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;
		}
770 771 772 773 774
		if(fstat(fileno(fp), &st) != 0) {
			safe_snprintf(error, maxerrlen, "%d fstat %s", errno, filename);
			fclose(fp);
			break;
		}
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
		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;
803
	}
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
	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];

820 821 822
	if(error == NULL)
		maxerrlen = 0;
	if(maxerrlen >= 1)
823 824 825 826
		*error = '\0';
	if((ar = archive_read_new()) == NULL) {
		safe_snprintf(error, maxerrlen, "archive_read_new returned NULL");
		return -1;
827
	}
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
	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;
843
		}
844 845
		const char* pathname = archive_entry_pathname(entry);
		if(pathname == NULL)
846
			continue;
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
		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;
			}
863
			continue;
864 865 866 867 868 869 870 871 872 873 874 875 876 877
		}
		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;
		}
878 879 880 881 882 883
		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;
		}
884 885 886 887 888 889 890 891 892 893 894 895
		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;
896
		int64_t offset;
897

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
		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;
922 923
}

924
bool extract_diz(scfg_t* cfg, file_t* f, str_list_t diz_fnames, char* path, size_t maxlen)
925
{
926 927
	int i;
	char archive[MAX_PATH + 1];
928
	char* default_diz_fnames[] = { "FILE_ID.ANS", "FILE_ID.DIZ", "DESC.SDI", NULL };
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

	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);
960

961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
	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;
979 980
}

981
char* read_diz(const char* path, struct sauce_charinfo* sauce)
982
{
983 984 985 986
	if(sauce != NULL)
		memset(sauce, 0, sizeof(*sauce));

	off_t len = flength(path);
Rob Swindell's avatar
Rob Swindell committed
987 988 989
	if(len < 1)
		return NULL;

990
	FILE* fp = fopen(path, "rb");
991 992
	if(fp == NULL)
		return NULL;
993

994 995 996 997 998 999 1000
	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
1001 1002 1003 1004 1005 1006 1007
	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';
	}
1008
	fclose(fp);
1009 1010

	return buf;
1011
}
1012

1013
char* format_diz(const char* src, char* dest, size_t maxlen, int width, bool ice)
1014
{
1015 1016 1017
	if(src == NULL) {
		*dest = '\0';
		return dest;
1018
	}
1019 1020
	convert_ansi(src, dest, maxlen - 1, width, ice);
	return dest;
1021
}
1022

1023 1024
// Take a verbose extended description (e.g. FILE_ID.DIZ)
// and convert to suitable short description
1025
char* prep_file_desc(const char* ext, char* dest)
1026 1027
{
	int out;
1028 1029 1030 1031 1032 1033 1034 1035
	char* src;
	char* buf = strdup(ext);
	if(buf == NULL)
		src = (char*)ext;
	else {
		src = buf;
		strip_ctrl(src, src);
	}
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

	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';
1053
	free(buf);
1054 1055
	return dest;
}
1056

1057 1058 1059 1060 1061 1062
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);
1063
}
1064

1065 1066 1067
#define QUOTED_STRING(ch, str, buf, maxlen) \
	((IS_ALPHA(ch) && IS_UPPERCASE(ch)) ? str : quoted_string(str,buf,maxlen))

1068
/****************************************************************************/
1069 1070
/* Returns command line generated from instr with %c replacements           */
/* This is the C-exported version of sbbs_t::cmdstr()						*/
1071
/****************************************************************************/
1072 1073
char* cmdstr(scfg_t* cfg, user_t* user, const char* instr, const char* fpath
						,const char* fspec, char* cmd, size_t maxlen)
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 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 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
	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;
1234

1235
    return(cmd);
1236
}
1237