/*
 * libnqs/req/readreq.c
 * 
 * DESCRIPTION:
 *
 *	Read the request header portion of the control file for an
 *	NQS request.
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	August 12, 1985.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <unistd.h>
#include <errno.h>


/*** readreq
 *
 *
 *	int readreq():
 *
 *	Read the request header portion of the control file for an
 *	NQS request.
 *
 *	If the return value of this function is 0, then the lseek()
 *	position of the control file descriptor upon return, is
 *	ALWAYS left at the first byte of the varying portion of the
 *	control file.
 *
 *
 *	Returns:
 *		0: if the successful, and the request is valid;
 *	       -1: otherwise.
 *
 *			Note:	errno is returned 0, unless a
 *				system call error occurred.
 */
int readreq (int fd, struct rawreq *rawreq)
{
	register int sizeread;
	register int headersize;

	/*
	 *  Read the entire control file header in one read() system
	 *  call.
	 *
	 *  We do this for reasons of efficiency, and also so that the
	 *  first block of the control file is read in one atomic I/O
	 *  operation so that concurrent Qmod updates (being done by the
	 *  careful indivisible rewrite of the first control file block),
	 *  and multiple read accesses do not step on each other.
	 */
  
  	assert (rawreq != NULL);
  
	errno = 0;			/* Clear errno */
	if (lseek (fd, 0L, 0) == -1) {	/* Seek to the start of the file */
		return (-1);		/* Return EBADF */
	}
	sizeread = read (fd, (char *) rawreq, sizeof (struct rawreq));
	headersize = ((char *) &rawreq->v) - ((char *) rawreq);
	if (rawreq->type == RTYPE_DEVICE) {
		/*
		 *  The request is a device-oriented request.
		 */
		headersize += sizeof (struct rawdevreq);
		if (sizeread < headersize) {
			/*
			 *  Part of the control file is missing!
			 */
			return (-1);
		}
	}
	else {
		/*
		 *  The request is not device-oriented.
		 */
		headersize += sizeof (struct rawbatreq);
		if (sizeread < headersize) {
			/*
			 *  Part of the control file is missing!
			 */
			return (-1);
		}
	}
	/*
	 *  Move file pointer to the end of the header area.
	 *  This is CRITICAL.
	 */
	lseek (fd, (long) headersize, 0);
	/*
	 *  Return results of header verification.
	 */
	return (verifyreq (rawreq));
}
