Synchronet now requires the libarchive development package (e.g. libarchive-dev on Debian-based Linux distros, libarchive.org for more info) to build successfully.

smblib.c 49.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* smblib.c */

/* Synchronet message base (SMB) library routines */

/* $Id$ */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
 * Copyright 2000 Rob Swindell - http://www.synchro.net/copyright.html		*
 *																			*
 * This library is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details: lgpl.txt or	*
 * http://www.fsf.org/copyleft/lesser.html									*
 *																			*
 * Anonymous FTP access to the most recent released source is available at	*
 * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net	*
 *																			*
 * Anonymous CVS access to the development source and modification history	*
 * is available at cvs.synchro.net:/cvsroot/sbbs, example:					*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login			*
 *     (just hit return, no password is necessary)							*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src		*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * You are encouraged to submit any modifications (preferably in Unix diff	*
 * format) via e-mail to mods@synchro.net									*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

38 39 40 41 42 43 44 45 46 47 48 49 50
#if defined __WATCOMC__ || defined __TURBOC__
	#include <mem.h>
#else
	#include <memory.h>
#endif

#ifdef __WATCOMC__
	#include <dos.h>
#elif defined __TURBOC__
	#include <dir.h>
#endif

/* ANSI C Library headers */
51

52
#ifndef __unix__
53 54 55
	#include <malloc.h>
#endif

56 57 58 59 60 61 62
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
63
#include <sys/stat.h>	/* must come after sys/types.h */
64 65

/* SMB-specific headers */
66
#include "smblib.h"
rswindell's avatar
rswindell committed
67 68
#include "genwrap.h"
#include "filewrap.h"
69 70

/* Use smb_ver() and smb_lib_ver() to obtain these values */
71
#define SMBLIB_VERSION		"2.16"      /* SMB library version */
72 73 74 75 76 77 78 79
#define SMB_VERSION 		0x0121		/* SMB format version */
										/* High byte major, low byte minor */

int SMBCALL smb_ver(void)
{
	return(SMB_VERSION);
}

80
char* SMBCALL smb_lib_ver(void)
81 82 83 84 85 86 87 88 89 90 91 92 93 94
{
	return(SMBLIB_VERSION);
}

/****************************************************************************/
/* Open a message base of name 'smb->file'                                  */
/* Opens files for READing messages or updating message indices only        */
/****************************************************************************/
int SMBCALL smb_open(smb_t* smb)
{
    int file;
    char str[128];
	smbhdr_t hdr;

95
	/* Set default values, if uninitialized */
96
	if(!smb->retry_time)
97 98 99 100
		smb->retry_time=10;		/* seconds */
	if(!smb->retry_delay 
		|| smb->retry_delay>(smb->retry_time*100))	/* at least ten retries */
		smb->retry_delay=250;	/* milliseconds */
101
	smb->shd_fp=smb->sdt_fp=smb->sid_fp=NULL;
102
	smb->last_error[0]=0;
103
	sprintf(str,"%s.shd",smb->file);
104
	if((file=sopen(str,O_RDWR|O_CREAT|O_BINARY,SH_DENYNO))==-1) {
105 106 107 108
		sprintf(smb->last_error,"%d opening %s",errno,str);
		return(2); 
	}

109 110 111 112 113 114
	if((smb->shd_fp=fdopen(file,"r+b"))==NULL) {
		sprintf(smb->last_error,"%d fdopening %s (%d)",errno,str,file);
		close(file);
		return(4); 
	}

115 116 117 118 119 120 121 122 123 124 125 126 127
	if(filelength(file)>=sizeof(smbhdr_t)) {
		setvbuf(smb->shd_fp,smb->shd_buf,_IONBF,SHD_BLOCK_LEN);
		if(smb_locksmbhdr(smb)!=0) {
			smb_close(smb);
			/* smb_lockmsghdr set last_error */
			return(-1); 
		}
		memset(&hdr,0,sizeof(smbhdr_t));
		if(fread(&hdr,sizeof(smbhdr_t),1,smb->shd_fp)!=1) {
			sprintf(smb->last_error,"reading header");
			smb_close(smb);
			return(-10);
		}
128 129
		if(memcmp(hdr.id,SMB_HEADER_ID,LEN_HEADER_ID)) {
			sprintf(smb->last_error,"corrupt SMB header ID: %.*s",LEN_HEADER_ID,hdr.id);
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
			smb_close(smb);
			return(-2); 
		}
		if(hdr.version<0x110) {         /* Compatibility check */
			sprintf(smb->last_error,"insufficient header version: %X",hdr.version);
			smb_close(smb);
			return(-3); 
		}
		if(fread(&(smb->status),1,sizeof(smbstatus_t),smb->shd_fp)
			!=sizeof(smbstatus_t)) {
			sprintf(smb->last_error,"failed to read status");
			smb_close(smb);
			return(-4); 
		}
		smb_unlocksmbhdr(smb);
		rewind(smb->shd_fp); 
	}

	setvbuf(smb->shd_fp,smb->shd_buf,_IOFBF,SHD_BLOCK_LEN);

150
	sprintf(str,"%s.sdt",smb->file);
151
	if((file=sopen(str,O_RDWR|O_CREAT|O_BINARY,SH_DENYNO))==-1) {
152 153 154 155
		sprintf(smb->last_error,"%d opening %s",errno,str);
		smb_close(smb);
		return(1); 
	}
156 157 158 159 160 161 162 163

	if((smb->sdt_fp=fdopen(file,"r+b"))==NULL) {
		sprintf(smb->last_error,"%d fdopening %s (%d)",errno,str,file);
		close(file);
		smb_close(smb);
		return(5);
	}

164 165
	setvbuf(smb->sdt_fp,NULL,_IOFBF,2*1024);

166
	sprintf(str,"%s.sid",smb->file);
167
	if((file=sopen(str,O_RDWR|O_CREAT|O_BINARY,SH_DENYNO))==-1) {
168 169 170 171
		sprintf(smb->last_error,"%d opening %s",errno,str);
		smb_close(smb);
		return(3); 
	}
172 173 174 175 176 177 178 179

	if((smb->sid_fp=fdopen(file,"r+b"))==NULL) {
		sprintf(smb->last_error,"%d fdopening %s (%d)",errno,str,file);
		close(file);
		smb_close(smb);
		return(6); 
	}

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
	setvbuf(smb->sid_fp,NULL,_IOFBF,2*1024);

	return(0);
}

/****************************************************************************/
/* Closes the currently open message base									*/
/****************************************************************************/
void SMBCALL smb_close(smb_t* smb)
{
	if(smb->shd_fp!=NULL) {
		smb_unlocksmbhdr(smb);		   /* In case it's been locked */
		fclose(smb->shd_fp); 
	}
	if(smb->sid_fp!=NULL)
		fclose(smb->sid_fp);
	if(smb->sdt_fp!=NULL)
		fclose(smb->sdt_fp);
	smb->sid_fp=smb->shd_fp=smb->sdt_fp=NULL;
}

/****************************************************************************/
/* Opens the data block allocation table message base 'smb->file'           */
/* Retrys for retry_time number of seconds									*/
/* Return 0 on success, non-zero otherwise									*/
/****************************************************************************/
int SMBCALL smb_open_da(smb_t* smb)
{
	int 	file;
	char	str[128];
210
	time_t	start=0;
211

212
	sprintf(str,"%s.sda",smb->file);
213
	while(1) {
214
		if((file=sopen(str,O_RDWR|O_CREAT|O_BINARY,SH_DENYRW))!=-1)
215
			break;
216
		if(errno!=EACCES && errno!=EAGAIN) {
217 218 219 220 221 222
			sprintf(smb->last_error,"%d opening %s",errno,str);
			return(-1);
		}
		if(!start)
			start=time(NULL);
		else
223
			if(time(NULL)-start>=(time_t)smb->retry_time) {
224
				sprintf(smb->last_error,"timeout opening %s (retry_time=%ld)"
225
					,str,smb->retry_time);
226 227
				return(-2); 
			}
rswindell's avatar
rswindell committed
228
		SLEEP(smb->retry_delay);
229 230
	}
	if((smb->sda_fp=fdopen(file,"r+b"))==NULL) {
231
		sprintf(smb->last_error,"%d fdopening %s (%d)",errno,str,file);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
		close(file);
		return(-3); 
	}
	setvbuf(smb->sda_fp,NULL,_IOFBF,2*1024);
	return(0);
}

void SMBCALL smb_close_da(smb_t* smb)
{
	if(smb->sda_fp!=NULL)
		fclose(smb->sda_fp);
	smb->sda_fp=NULL;
}

/****************************************************************************/
/* Opens the header block allocation table for message base 'smb.file'      */
/* Retrys for smb.retry_time number of seconds								*/
/* Return 0 on success, non-zero otherwise									*/
/****************************************************************************/
int SMBCALL smb_open_ha(smb_t* smb)
{
	int 	file;
	char	str[128];
255
	time_t	start=0;
256

257
	sprintf(str,"%s.sha",smb->file);
258
	while(1) {
259
		if((file=sopen(str,O_RDWR|O_CREAT|O_BINARY,SH_DENYRW))!=-1)
260
			break;
261
		if(errno!=EACCES && errno!=EAGAIN) {
262 263 264 265 266 267
			sprintf(smb->last_error,"%d opening %s",errno,str);
			return(-1);
		}
		if(!start)
			start=time(NULL);
		else
268
			if(time(NULL)-start>=(time_t)smb->retry_time) {
269
				sprintf(smb->last_error,"timeout opening %s (retry_time=%ld)"
270
					,str,smb->retry_time);
271 272
				return(-2); 
			}
rswindell's avatar
rswindell committed
273
		SLEEP(smb->retry_delay);
274 275
	}
	if((smb->sha_fp=fdopen(file,"r+b"))==NULL) {
276
		sprintf(smb->last_error,"%d fdopening %s (%d)",errno,str,file);
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
		close(file);
		return(-3); 
	}
	setvbuf(smb->sha_fp,NULL,_IOFBF,2*1024);
	return(0);
}

void SMBCALL smb_close_ha(smb_t* smb)
{
	if(smb->sha_fp!=NULL)
		fclose(smb->sha_fp);
	smb->sha_fp=NULL;
}

/****************************************************************************/
/* If the parameter 'push' is non-zero, this function stores the currently  */
/* open message base to the "virtual" smb stack. Up to SMB_STACK_LEN        */
/* message bases may be stored (defined in SMBDEFS.H).						*/
/* The parameter 'op' is the operation to perform on the stack. Either      */
/* SMB_STACK_PUSH, SMB_STACK_POP, or SMB_STACK_XCHNG						*/
/* If the operation is SMB_STACK_POP, this function restores a message base */
/* previously saved with a SMB_STACK_PUSH call to this same function.		*/
/* If the operation is SMB_STACK_XCHNG, then the current message base is	*/
/* exchanged with the message base on the top of the stack (most recently	*/
/* pushed.																	*/
/* If the current message base is not open, the SMB_STACK_PUSH and			*/
/* SMB_STACK_XCHNG operations do nothing									*/
/* Returns 0 on success, non-zero if stack full.                            */
/* If operation is SMB_STACK_POP or SMB_STACK_XCHNG, it always returns 0.	*/
/****************************************************************************/
int SMBCALL smb_stack(smb_t* smb, int op)
{
309
	static smb_t stack[SMB_STACK_LEN];
310
	static int	stack_idx;
311
	smb_t		tmp_smb;
312 313 314 315 316 317 318 319

	if(op==SMB_STACK_PUSH) {
		if(stack_idx>=SMB_STACK_LEN) {
			sprintf(smb->last_error,"SMB stack overflow");
			return(1);
		}
		if(smb->shd_fp==NULL || smb->sdt_fp==NULL || smb->sid_fp==NULL)
			return(0);	  /* Msg base not open */
320
		memcpy(&stack[stack_idx],smb,sizeof(smb_t));
321 322 323 324 325 326 327
		stack_idx++;
		return(0); 
	}
	/* pop or xchng */
	if(!stack_idx)	/* Nothing on the stack, so do nothing */
		return(0);
	if(op==SMB_STACK_XCHNG) {
328
		if(smb->shd_fp==NULL)
329
			return(0);
330
		memcpy(&tmp_smb,smb,sizeof(smb_t));
331 332 333
	}

	stack_idx--;
334
	memcpy(smb,&stack[stack_idx],sizeof(smb_t));
335
	if(op==SMB_STACK_XCHNG) {
336
		memcpy(&stack[stack_idx],&tmp_smb,sizeof(smb_t));
337 338 339 340 341 342 343 344 345 346 347 348
		stack_idx++;
	}
	return(0);
}

/****************************************************************************/
/* Truncates header file													*/
/* Retrys for smb.retry_time number of seconds								*/
/* Return 0 on success, non-zero otherwise									*/
/****************************************************************************/
int SMBCALL smb_trunchdr(smb_t* smb)
{
349
	time_t	start=0;
350

351 352 353 354
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
355 356 357 358
	rewind(smb->shd_fp);
	while(1) {
		if(!chsize(fileno(smb->shd_fp),0L))
			break;
359
		if(errno!=EACCES && errno!=EAGAIN) {
360 361 362 363 364 365
			sprintf(smb->last_error,"%d changing header file size",errno);
			return(-1);
		}
		if(!start)
			start=time(NULL);
		else
366
			if(time(NULL)-start>=(time_t)smb->retry_time) {	 /* Time-out */
367
				sprintf(smb->last_error,"timeout changing header file size (retry_time=%ld)"
368
					,smb->retry_time);
369 370
				return(-2); 
			}
rswindell's avatar
rswindell committed
371
		SLEEP(smb->retry_delay);
372 373 374 375 376 377 378 379 380 381 382 383 384
	}
	return(0);
}

/*********************************/
/* Message Base Header Functions */
/*********************************/

/****************************************************************************/
/* Attempts for smb.retry_time number of seconds to lock the msg base hdr	*/
/****************************************************************************/
int SMBCALL smb_locksmbhdr(smb_t* smb)
{
385
	time_t	start=0;
386

387 388 389 390
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
391
	while(1) {
392 393
		if(lock(fileno(smb->shd_fp),0L,sizeof(smbhdr_t)+sizeof(smbstatus_t))==0) {
			smb->locked=1;	/* TRUE */
394
			return(0);
395
		}
396 397 398
		if(!start)
			start=time(NULL);
		else
399
			if(time(NULL)-start>=(time_t)smb->retry_time) 
400 401
				break;						
		/* In case we've already locked it */
402 403
		if(unlock(fileno(smb->shd_fp),0L,sizeof(smbhdr_t)+sizeof(smbstatus_t))==0)
			smb->locked=0;	/* FALSE */
rswindell's avatar
rswindell committed
404
		SLEEP(smb->retry_delay);
405 406 407 408 409 410 411 412 413 414 415 416
	}
	sprintf(smb->last_error,"timeout locking header");
	return(-1);
}

/****************************************************************************/
/* Read the SMB header from the header file and place into smb.status		*/
/****************************************************************************/
int SMBCALL smb_getstatus(smb_t* smb)
{
	int 	i;

417 418 419 420
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
421 422 423 424 425 426 427
	setvbuf(smb->shd_fp,smb->shd_buf,_IONBF,SHD_BLOCK_LEN);
	clearerr(smb->shd_fp);
	fseek(smb->shd_fp,sizeof(smbhdr_t),SEEK_SET);
	i=fread(&(smb->status),1,sizeof(smbstatus_t),smb->shd_fp);
	setvbuf(smb->shd_fp,smb->shd_buf,_IOFBF,SHD_BLOCK_LEN);
	if(i==sizeof(smbstatus_t))
		return(0);
428
	sprintf(smb->last_error,"read %d instead of %d",i,(int)sizeof(smbstatus_t));
429 430 431 432 433 434 435 436 437 438
	return(1);
}

/****************************************************************************/
/* Writes message base header												*/
/****************************************************************************/
int SMBCALL smb_putstatus(smb_t* smb)
{
	int i;

439 440 441 442
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
443 444 445 446 447 448
	clearerr(smb->shd_fp);
	fseek(smb->shd_fp,sizeof(smbhdr_t),SEEK_SET);
	i=fwrite(&(smb->status),1,sizeof(smbstatus_t),smb->shd_fp);
	fflush(smb->shd_fp);
	if(i==sizeof(smbstatus_t))
		return(0);
449
	sprintf(smb->last_error,"wrote %d instead of %d",i,(int)sizeof(smbstatus_t));
450 451 452 453 454 455 456 457
	return(1);
}

/****************************************************************************/
/* Unlocks previously locks message base header 							*/
/****************************************************************************/
int SMBCALL smb_unlocksmbhdr(smb_t* smb)
{
458 459
	int result;

460 461 462 463
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
464 465 466 467
	result = unlock(fileno(smb->shd_fp),0L,sizeof(smbhdr_t)+sizeof(smbstatus_t));
	if(result==0)
		smb->locked=0;	/* FALSE */
	return(result);
468 469 470 471 472 473 474 475 476 477 478
}

/********************************/
/* Individual Message Functions */
/********************************/

/****************************************************************************/
/* Attempts for smb.retry_time number of seconds to lock the hdr for 'msg'  */
/****************************************************************************/
int SMBCALL smb_lockmsghdr(smb_t* smb, smbmsg_t* msg)
{
479
	time_t	start=0;
480

481 482 483 484
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
485 486 487 488 489 490
	while(1) {
		if(!lock(fileno(smb->shd_fp),msg->idx.offset,sizeof(msghdr_t)))
			return(0);
		if(!start)
			start=time(NULL);
		else
491
			if(time(NULL)-start>=(time_t)smb->retry_time) 
492 493 494
				break;
		/* In case we've already locked it */
		unlock(fileno(smb->shd_fp),msg->idx.offset,sizeof(msghdr_t)); 
rswindell's avatar
rswindell committed
495
		SLEEP(smb->retry_delay);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
	}
	sprintf(smb->last_error,"timeout locking header");
	return(-1);
}

/****************************************************************************/
/* Fills msg->idx with message index based on msg->hdr.number				*/
/* OR if msg->hdr.number is 0, based on msg->offset (record offset).		*/
/* if msg.hdr.number does not equal 0, then msg->offset is filled too.		*/
/* Either msg->hdr.number or msg->offset must be initialized before 		*/
/* calling this function													*/
/* Returns 1 if message number wasn't found, 0 if it was                    */
/****************************************************************************/
int SMBCALL smb_getmsgidx(smb_t* smb, smbmsg_t* msg)
{
	idxrec_t idx;
	ulong	 l,length,total,bot,top;

514 515
	if(smb->sid_fp==NULL) {
		sprintf(smb->last_error,"index not open");
516
		return(SMB_ERR_NOT_OPEN);
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
	clearerr(smb->sid_fp);
	if(!msg->hdr.number) {
		fseek(smb->sid_fp,msg->offset*sizeof(idxrec_t),SEEK_SET);
		if(!fread(&msg->idx,sizeof(idxrec_t),1,smb->sid_fp)) {
			sprintf(smb->last_error,"reading index");
			return(1);
		}
		return(0); 
	}

	length=filelength(fileno(smb->sid_fp));
	if(!length) {
		sprintf(smb->last_error,"invalid index file length: %ld",length);
		return(1);
	}
	total=length/sizeof(idxrec_t);
	if(!total) {
		sprintf(smb->last_error,"invalid index file length: %ld",length);
		return(1);
	}

	bot=0;
	top=total;
	l=total/2; /* Start at middle index */
	while(1) {
		fseek(smb->sid_fp,l*sizeof(idxrec_t),SEEK_SET);
		if(!fread(&idx,sizeof(idxrec_t),1,smb->sid_fp)) {
			sprintf(smb->last_error,"reading index");
			return(1);
		}
		if(bot==top-1 && idx.number!=msg->hdr.number) {
rswindell's avatar
rswindell committed
549
			sprintf(smb->last_error,"msg %ld not found",msg->hdr.number);
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
			return(1);
		}
		if(idx.number>msg->hdr.number) {
			top=l;
			l=bot+((top-bot)/2);
			continue; 
		}
		if(idx.number<msg->hdr.number) {
			bot=l;
			l=top-((top-bot)/2);
			continue; 
		}
		break; 
	}
	msg->idx=idx;
	msg->offset=l;
	return(0);
}

569 570 571 572 573
/****************************************************************************/
/* Reads the first index record in the open message base 					*/
/****************************************************************************/
int SMBCALL smb_getfirstidx(smb_t* smb, idxrec_t *idx)
{
574 575 576 577
	if(smb->sid_fp==NULL) {
		sprintf(smb->last_error,"index not open");
		return(SMB_ERR_NOT_OPEN);
	}
578 579 580 581 582 583 584 585 586
	clearerr(smb->sid_fp);
	fseek(smb->sid_fp,0,SEEK_SET);
	if(!fread(idx,sizeof(idxrec_t),1,smb->sid_fp)) {
		sprintf(smb->last_error,"reading index");
		return(-2);
	}
	return(0);
}

587 588 589 590 591 592 593
/****************************************************************************/
/* Reads the last index record in the open message base 					*/
/****************************************************************************/
int SMBCALL smb_getlastidx(smb_t* smb, idxrec_t *idx)
{
	long length;

594 595 596 597
	if(smb->sid_fp==NULL) {
		sprintf(smb->last_error,"index not open");
		return(SMB_ERR_NOT_OPEN);
	}
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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
	clearerr(smb->sid_fp);
	length=filelength(fileno(smb->sid_fp));
	if(length<sizeof(idxrec_t)) {
		sprintf(smb->last_error,"invalid index file length: %ld",length);
		return(-1);
	}
	fseek(smb->sid_fp,length-sizeof(idxrec_t),SEEK_SET);
	if(!fread(idx,sizeof(idxrec_t),1,smb->sid_fp)) {
		sprintf(smb->last_error,"reading index");
		return(-2);
	}
	return(0);
}

/****************************************************************************/
/* Figures out the total length of the header record for 'msg'              */
/* Returns length															*/
/****************************************************************************/
uint SMBCALL smb_getmsghdrlen(smbmsg_t* msg)
{
	int i;

	/* fixed portion */
	msg->hdr.length=sizeof(msghdr_t);
	/* data fields */
	msg->hdr.length+=msg->hdr.total_dfields*sizeof(dfield_t);
	/* header fields */
	for(i=0;i<msg->total_hfields;i++) {
		msg->hdr.length+=sizeof(hfield_t);
		msg->hdr.length+=msg->hfield[i].length; 
	}
	return(msg->hdr.length);
}

/****************************************************************************/
/* Figures out the total length of the data buffer for 'msg'                */
/* Returns length															*/
/****************************************************************************/
ulong SMBCALL smb_getmsgdatlen(smbmsg_t* msg)
{
	int i;
	ulong length=0L;

	for(i=0;i<msg->hdr.total_dfields;i++)
		length+=msg->dfield[i].length;
	return(length);
}

/****************************************************************************/
/* Read header information into 'msg' structure                             */
/* msg->idx.offset must be set before calling this function 				*/
/* Must call smb_freemsgmem() to free memory allocated for var len strs 	*/
/* Returns 0 on success, non-zero if error									*/
/****************************************************************************/
int SMBCALL smb_getmsghdr(smb_t* smb, smbmsg_t* msg)
{
	void	*vp,**vpp;
	ushort	i;
	ulong	l,offset;
	idxrec_t idx;

659 660 661 662
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
663 664 665 666 667 668 669 670 671 672 673
	rewind(smb->shd_fp);
	fseek(smb->shd_fp,msg->idx.offset,SEEK_SET);
	idx=msg->idx;
	offset=msg->offset;
	memset(msg,0,sizeof(smbmsg_t));
	msg->idx=idx;
	msg->offset=offset;
	if(!fread(&msg->hdr,sizeof(msghdr_t),1,smb->shd_fp)) {
		sprintf(smb->last_error,"reading msg header");
		return(-1);
	}
674 675
	if(memcmp(msg->hdr.id,SHD_HEADER_ID,LEN_HEADER_ID)) {
		sprintf(smb->last_error,"corrupt message header ID: %.*s",LEN_HEADER_ID,msg->hdr.id);
676 677 678 679 680 681 682 683 684 685 686
		return(-2);
	}
	if(msg->hdr.version<0x110) {
		sprintf(smb->last_error,"insufficient header version: %X",msg->hdr.version);
		return(-9);
	}
	l=sizeof(msghdr_t);
	if(msg->hdr.total_dfields && (msg->dfield
		=(dfield_t *)MALLOC(sizeof(dfield_t)*msg->hdr.total_dfields))==NULL) {
		smb_freemsgmem(msg);
		sprintf(smb->last_error,"malloc failure of %d bytes for %d data fields"
687
			,(int)sizeof(dfield_t)*msg->hdr.total_dfields, msg->hdr.total_dfields);
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
		return(-3); 
	}
	i=0;
	while(i<msg->hdr.total_dfields && l<msg->hdr.length) {
		if(!fread(&msg->dfield[i],sizeof(dfield_t),1,smb->shd_fp)) {
			smb_freemsgmem(msg);
			sprintf(smb->last_error,"reading data field %d",i);
			return(-4); 
		}
		i++;
		l+=sizeof(dfield_t); 
	}
	if(i<msg->hdr.total_dfields) {
		smb_freemsgmem(msg);
		sprintf(smb->last_error,"insufficient data fields read (%d instead of %d)"
			,i,msg->hdr.total_dfields);
		return(-8); 
	}
	while(l<msg->hdr.length) {
		i=msg->total_hfields;
		if((vpp=(void* *)REALLOC(msg->hfield_dat,sizeof(void* )*(i+1)))==NULL) {
			smb_freemsgmem(msg);
			sprintf(smb->last_error
				,"realloc failure of %d bytes for header field data"
712
				,(int)sizeof(void*)*(i+1));
713 714 715 716 717 718 719
			return(-3); 
		}
		msg->hfield_dat=vpp;
		if((vp=(hfield_t *)REALLOC(msg->hfield,sizeof(hfield_t)*(i+1)))==NULL) {
			smb_freemsgmem(msg);
			sprintf(smb->last_error
				,"realloc failure of %d bytes for header fields"
720
				,(int)sizeof(hfield_t)*(i+1));
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
			return(-3); 
		}
		msg->hfield=vp;
		msg->total_hfields++;
		if(!fread(&msg->hfield[i],sizeof(hfield_t),1,smb->shd_fp)) {
			smb_freemsgmem(msg);
			sprintf(smb->last_error,"reading header field");
			return(-5); 
		}
		l+=sizeof(hfield_t);
		if((msg->hfield_dat[i]=(char*)MALLOC(msg->hfield[i].length+1))
			==NULL) {			/* Allocate 1 extra for NULL terminator */
			sprintf(smb->last_error
				,"malloc failure of %d bytes for header field %d"
				,msg->hfield[i].length+1, i);
			smb_freemsgmem(msg);  /* or 0 length field */
			return(-3); 
		}
		memset(msg->hfield_dat[i],0,msg->hfield[i].length+1);  /* init to NULL */
		if(msg->hfield[i].length
			&& !fread(msg->hfield_dat[i],msg->hfield[i].length,1,smb->shd_fp)) {
			smb_freemsgmem(msg);
			sprintf(smb->last_error,"reading header field data");
			return(-6); 
		}
		switch(msg->hfield[i].type) {	/* convenience variables */
			case SENDER:
				if(!msg->from) {
749
					msg->from=(char*)msg->hfield_dat[i];
750 751 752 753 754 755 756 757 758 759 760
					break; 
				}
			case FORWARDED: 	/* fall through */
				msg->forwarded=1;
				break;
			case SENDERAGENT:
				if(!msg->forwarded)
					msg->from_agent=*(ushort *)msg->hfield_dat[i];
				break;
			case SENDEREXT:
				if(!msg->forwarded)
761
					msg->from_ext=(char*)msg->hfield_dat[i];
762 763 764 765 766 767 768
				break;
			case SENDERNETTYPE:
				if(!msg->forwarded)
					msg->from_net.type=*(ushort *)msg->hfield_dat[i];
				break;
			case SENDERNETADDR:
				if(!msg->forwarded)
769
					msg->from_net.addr=(char*)msg->hfield_dat[i];
770 771
				break;
			case REPLYTO:
772
				msg->replyto=(char*)msg->hfield_dat[i];
773 774
				break;
			case REPLYTOEXT:
775
				msg->replyto_ext=(char*)msg->hfield_dat[i];
776 777 778 779 780 781 782 783
				break;
			case REPLYTOAGENT:
				msg->replyto_agent=*(ushort *)msg->hfield_dat[i];
				break;
			case REPLYTONETTYPE:
				msg->replyto_net.type=*(ushort *)msg->hfield_dat[i];
				break;
			case REPLYTONETADDR:
784
				msg->replyto_net.addr=(char*)msg->hfield_dat[i];
785 786
				break;
			case RECIPIENT:
787
				msg->to=(char*)msg->hfield_dat[i];
788 789
				break;
			case RECIPIENTEXT:
790
				msg->to_ext=(char*)msg->hfield_dat[i];
791 792 793 794 795 796 797 798
				break;
			case RECIPIENTAGENT:
				msg->to_agent=*(ushort *)msg->hfield_dat[i];
				break;
			case RECIPIENTNETTYPE:
				msg->to_net.type=*(ushort *)msg->hfield_dat[i];
				break;
			case RECIPIENTNETADDR:
799
				msg->to_net.addr=(char*)msg->hfield_dat[i];
800 801
				break;
			case SUBJECT:
802
				msg->subj=(char*)msg->hfield_dat[i];
803 804
				break;
			case RFC822MSGID:
805
				msg->id=(char*)msg->hfield_dat[i];
806 807
				break;
			case RFC822REPLYID:
808
				msg->reply_id=(char*)msg->hfield_dat[i];
809
				break;
810
			case SMTPREVERSEPATH:
811
				msg->reverse_path=(char*)msg->hfield_dat[i];
812
				break;
813
			case USENETPATH:
814
				msg->path=(char*)msg->hfield_dat[i];
815 816
				break;
			case USENETNEWSGROUPS:
817
				msg->newsgroups=(char*)msg->hfield_dat[i];
818
				break;
819
			case FIDOMSGID:
820
				msg->ftn_msgid=(char*)msg->hfield_dat[i];
821 822
				break;
			case FIDOREPLYID:
823
				msg->ftn_reply=(char*)msg->hfield_dat[i];
824
				break;
825
			case FIDOAREA:
826
				msg->ftn_area=(char*)msg->hfield_dat[i];
827 828
				break;
			case FIDOPID:
829
				msg->ftn_pid=(char*)msg->hfield_dat[i];
830 831
				break;
			case FIDOFLAGS:
832
				msg->ftn_flags=(char*)msg->hfield_dat[i];
833 834
				break;
			
835 836 837 838 839 840 841 842 843
		}
		l+=msg->hfield[i].length; 
	}

	if(!msg->from || !msg->to || !msg->subj) {
		sprintf(smb->last_error,"missing required header field (from/to/subj)");
		smb_freemsgmem(msg);
		return(-7); 
	}
844 845 846 847 848

	/* If no reverse path specified, use sender's address */
	if(msg->reverse_path == NULL)
		msg->reverse_path = msg->from_net.addr;

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
	return(0);
}

/****************************************************************************/
/* Frees memory allocated for 'msg'                                         */
/****************************************************************************/
void SMBCALL smb_freemsgmem(smbmsg_t* msg)
{
	ushort	i;

	if(msg->dfield) {
		FREE(msg->dfield);
		msg->dfield=NULL;
	}
	for(i=0;i<msg->total_hfields;i++)
		if(msg->hfield_dat[i]) {
			FREE(msg->hfield_dat[i]);
			msg->hfield_dat[i]=NULL;
		}
	msg->total_hfields=0;
	if(msg->hfield) {
		FREE(msg->hfield);
		msg->hfield=NULL;
	}
	if(msg->hfield_dat) {
		FREE(msg->hfield_dat);
		msg->hfield_dat=NULL;
	}
}

/****************************************************************************/
/* Copies memory allocated for 'srcmsg' to 'msg'							*/
/****************************************************************************/
int SMBCALL smb_copymsgmem(smbmsg_t* msg, smbmsg_t* srcmsg)
{
	int i;

	memcpy(msg,srcmsg,sizeof(smbmsg_t));

	/* data field types/lengths */
889
	if((msg->dfield=(dfield_t *)MALLOC(msg->hdr.total_dfields*sizeof(dfield_t)))==NULL)
890 891 892 893
		return(1);
	memcpy(msg->dfield,srcmsg->dfield,msg->hdr.total_dfields*sizeof(dfield_t));

	/* header field types/lengths */
894
	if((msg->hfield=(hfield_t *)MALLOC(msg->total_hfields*sizeof(hfield_t)))==NULL)
895 896 897 898
		return(2);
	memcpy(msg->hfield,srcmsg->hfield,msg->total_hfields*sizeof(hfield_t));

	/* header field data */
899
	if((msg->hfield_dat=(void**)MALLOC(msg->total_hfields*sizeof(void*)))==NULL)
900 901 902
		return(3);

	for(i=0;i<msg->total_hfields;i++) {
903
		if((msg->hfield_dat[i]=(void*)MALLOC(msg->hfield[i].length))==NULL)
904 905 906 907 908 909 910 911 912 913 914 915
			return(4);
		memcpy(msg->hfield_dat[i],srcmsg->hfield_dat[i],msg->hfield[i].length);
	}

	return(0);
}

/****************************************************************************/
/* Unlocks header for 'msg'                                                 */
/****************************************************************************/
int SMBCALL smb_unlockmsghdr(smb_t* smb, smbmsg_t* msg)
{
916 917 918 919
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
920 921 922 923 924 925 926
	return(unlock(fileno(smb->shd_fp),msg->idx.offset,sizeof(msghdr_t)));
}


/****************************************************************************/
/* Adds a header field to the 'msg' structure (in memory only)              */
/****************************************************************************/
927
int SMBCALL smb_hfield(smbmsg_t* msg, ushort type, size_t length, void* data)
928
{
929 930
	void**		vpp;
	hfield_t*	hp;
931 932 933
	int i;

	i=msg->total_hfields;
934
	if((hp=(hfield_t *)REALLOC(msg->hfield,sizeof(hfield_t)*(i+1)))==NULL) 
935 936
		return(1);

937
	msg->hfield=hp;
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
	if((vpp=(void* *)REALLOC(msg->hfield_dat,sizeof(void* )*(i+1)))==NULL) 
		return(2);
	
	msg->hfield_dat=vpp;
	msg->total_hfields++;
	msg->hfield[i].type=type;
	msg->hfield[i].length=length;
	if(length) {
		if((msg->hfield_dat[i]=(void* )MALLOC(length))==NULL) 
			return(4);
		memcpy(msg->hfield_dat[i],data,length); 
	}
	else
		msg->hfield_dat[i]=NULL;
	return(0);
}

955 956 957 958 959 960 961 962 963
/****************************************************************************/
/* Searches for a specific header field (by type) and returns it			*/
/****************************************************************************/
void* SMBCALL smb_get_hfield(smbmsg_t* msg, ushort type, hfield_t* hfield)
{
	int i;

	for(i=0;i<msg->total_hfields;i++)
		if(msg->hfield[i].type == type) {
964 965
			if(hfield != NULL)
				hfield = &msg->hfield[i];
966 967 968 969 970 971
			return(msg->hfield_dat[i]);
		}

	return(NULL);
}

972 973 974 975 976 977 978
/****************************************************************************/
/* Adds a data field to the 'msg' structure (in memory only)                */
/* Automatically figures out the offset into the data buffer from existing	*/
/* dfield lengths															*/
/****************************************************************************/
int SMBCALL smb_dfield(smbmsg_t* msg, ushort type, ulong length)
{
979
	dfield_t* dp;
980 981 982
	int i,j;

	i=msg->hdr.total_dfields;
983
	if((dp=(dfield_t *)REALLOC(msg->dfield,sizeof(dfield_t)*(i+1)))==NULL) 
984 985
		return(1);
	
986
	msg->dfield=dp;
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
	msg->hdr.total_dfields++;
	msg->dfield[i].type=type;
	msg->dfield[i].length=length;
	for(j=msg->dfield[i].offset=0;j<i;j++)
		msg->dfield[i].offset+=msg->dfield[j].length;
	return(0);
}

/****************************************************************************/
/* Checks CRC history file for duplicate crc. If found, returns 1.			*/
/* If no dupe, adds to CRC history and returns 0, or negative if error. 	*/
/****************************************************************************/
int SMBCALL smb_addcrc(smb_t* smb, ulong crc)
{
	char	str[128];
	int 	file;
	long	length;
	ulong	l,*buf;
1005
	time_t	start=0;
1006 1007 1008 1009

	if(!smb->status.max_crcs)
		return(0);

1010
	sprintf(str,"%s.sch",smb->file);
1011
	while(1) {
1012
		if((file=sopen(str,O_RDWR|O_CREAT|O_BINARY,SH_DENYRW))!=-1)
1013
			break;
1014
		if(errno!=EACCES && errno!=EAGAIN) {
1015 1016 1017 1018 1019 1020
			sprintf(smb->last_error,"%d opening %s", errno, str);
			return(-1);
		}
		if(!start)
			start=time(NULL);
		else
1021
			if(time(NULL)-start>=(time_t)smb->retry_time) {
1022
				sprintf(smb->last_error,"timeout opening %s (retry_time=%ld)"
1023
					,str,smb->retry_time);
1024 1025
				return(-2); 
			}
rswindell's avatar
rswindell committed
1026
		SLEEP(smb->retry_delay);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	}

	length=filelength(file);
	if(length<0L) {
		close(file);
		sprintf(smb->last_error,"invalid file length: %ld", length);
		return(-4); 
	}
	if((buf=(ulong*)MALLOC(smb->status.max_crcs*4))==NULL) {
		close(file);
		sprintf(smb->last_error
rswindell's avatar
rswindell committed
1038
			,"malloc failure of %ld bytes"
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
			,smb->status.max_crcs*4);
		return(-3); 
	}
	if((ulong)length>=smb->status.max_crcs*4L) { /* Reached or exceeds max crcs */
		read(file,buf,smb->status.max_crcs*4);
		for(l=0;l<smb->status.max_crcs;l++)
			if(crc==buf[l])
				break;
		if(l<smb->status.max_crcs) {				/* Dupe CRC found */
			close(file);
			FREE(buf);
1050 1051
			sprintf(smb->last_error
				,"duplicate message detected");
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
			return(1); 
		}
		chsize(file,0L);				/* truncate it */
		lseek(file,0L,SEEK_SET);
		write(file,buf+4,(smb->status.max_crcs-1)*4); 
	}

	else if(length/4) { 					/* Less than max crcs */
		read(file,buf,length);
		for(l=0;l<(ulong)(length/4);l++)
			if(crc==buf[l])
				break;
		if(l<(ulong)(length/4L)) {					/* Dupe CRC found */
			close(file);
			FREE(buf);
1067 1068
			sprintf(smb->last_error
				,"duplicate message detected");
1069 1070 1071 1072 1073
			return(1); 
		} 
	}

	lseek(file,0L,SEEK_END);
1074
	write(file,&crc,sizeof(crc)); 			   /* Write to the end */
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
	FREE(buf);
	close(file);
	return(0);
}

/****************************************************************************/
/* Creates a new message header record in the header file.					*/
/* If storage is SMB_SELFPACK, self-packing conservative allocation is used */
/* If storage is SMB_FASTALLOC, fast allocation is used 					*/
/* If storage is SMB_HYPERALLOC, no allocation tables are used (fastest)	*/
1085
/* This function will UN-lock the SMB header								*/
1086 1087 1088 1089 1090 1091
/****************************************************************************/
int SMBCALL smb_addmsghdr(smb_t* smb, smbmsg_t* msg, int storage)
{
	int i;
	long l;

1092
	if(!smb->locked && smb_locksmbhdr(smb))
1093
		return(1);
1094 1095
	if(smb_getstatus(smb)) {
		smb_unlocksmbhdr(smb);
1096
		return(2);
1097
	}
1098

1099 1100
	if(storage!=SMB_HYPERALLOC && (i=smb_open_ha(smb))!=0) {
		smb_unlocksmbhdr(smb);
1101
		return(i);
1102
	}
1103 1104 1105 1106 1107 1108 1109 1110

	msg->hdr.length=smb_getmsghdrlen(msg);
	if(storage==SMB_HYPERALLOC)
		l=smb_hallochdr(smb);
	else if(storage==SMB_FASTALLOC)
		l=smb_fallochdr(smb,msg->hdr.length);
	else
		l=smb_allochdr(smb,msg->hdr.length);
1111 1112
	if(storage!=SMB_HYPERALLOC)
		smb_close_ha(smb);
1113 1114 1115 1116 1117
	if(l==-1L) {
		smb_unlocksmbhdr(smb);
		return(-1); 
	}

1118
	msg->idx.number=msg->hdr.number=smb->status.last_msg+1;
1119 1120 1121 1122 1123
	msg->idx.offset=smb->status.header_offset+l;
	msg->idx.time=msg->hdr.when_imported.time;
	msg->idx.attr=msg->hdr.attr;
	msg->offset=smb->status.total_msgs;
	i=smb_putmsg(smb,msg);
1124 1125 1126 1127 1128
	if(i==0) {	/* success */
		smb->status.last_msg++;
		smb->status.total_msgs++;
		smb_putstatus(smb);
	}
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
	smb_unlocksmbhdr(smb);
	return(i);
}

/****************************************************************************/
/* Writes both header and index information for msg 'msg'                   */
/****************************************************************************/
int SMBCALL smb_putmsg(smb_t* smb, smbmsg_t* msg)
{
	int i;

	i=smb_putmsghdr(smb,msg);
	if(i)
		return(i);
	return(smb_putmsgidx(smb,msg));
}

/****************************************************************************/
/* Writes index information for 'msg'                                       */
1148 1149
/* msg->idx 																*/
/* and msg->offset must be set prior to calling to this function			*/
1150 1151 1152 1153
/* Returns 0 if everything ok                                               */
/****************************************************************************/
int SMBCALL smb_putmsgidx(smb_t* smb, smbmsg_t* msg)
{
1154 1155 1156 1157
	if(smb->sid_fp==NULL) {
		sprintf(smb->last_error,"index not open");
		return(SMB_ERR_NOT_OPEN);
	}
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
	clearerr(smb->sid_fp);
	fseek(smb->sid_fp,msg->offset*sizeof(idxrec_t),SEEK_SET);
	if(!fwrite(&msg->idx,sizeof(idxrec_t),1,smb->sid_fp)) {
		sprintf(smb->last_error,"writing index");
		return(1);
	}
	fflush(smb->sid_fp);
	return(0);
}

/****************************************************************************/
/* Writes header information for 'msg'                                      */
1170 1171 1172
/* msg->hdr.length															*/
/* msg->idx.offset															*/
/* and msg->offset must be set prior to calling to this function			*/
1173 1174 1175 1176 1177 1178 1179
/* Returns 0 if everything ok                                               */
/****************************************************************************/
int SMBCALL smb_putmsghdr(smb_t* smb, smbmsg_t* msg)
{
	ushort	i;
	ulong	l;

1180 1181 1182 1183
	if(smb->shd_fp==NULL) {
		sprintf(smb->last_error,"msgbase not open");
		return(SMB_ERR_NOT_OPEN);
	}
1184 1185 1186 1187 1188
	if(msg->idx.offset<sizeof(smbhdr_t)+sizeof(smbstatus_t) 
		|| msg->idx.offset<smb->status.header_offset) {
		sprintf(smb->last_error,"invalid header offset: %ld",msg->idx.offset);
		return(-7);
	}
1189 1190
	clearerr(smb->shd_fp);
	if(fseek(smb->shd_fp,msg->idx.offset,SEEK_SET)) {
rswindell's avatar
rswindell committed
1191
		sprintf(smb->last_error,"seeking to %ld in index",msg->idx.offset);
1192 1193 1194
		return(-1);
	}