/*
 * libnqs/req/readhdr.c
 * 
 * DESCRIPTION:
 *
 *	Read and verify the common header portion of a request
 *	control file.
 *
 *	Orignal Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	August 12, 1985.
 */

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

/*** readhdr
 *
 *
 *	int readhdr():
 *
 *	Read and verify the common header portion of a request
 *	control file.
 *
 *	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 successful, and the request header is valid;
 *	       -1: otherwise.
 *
 *			Note:  errno will be returned 0 by this function
 *			       unless a system call error has occurred.
 */
int readhdr (int fd, struct rawreq *rawreq)
{
	register int size;		/* Size of common request header */

  	assert (rawreq != NULL);
  
	errno = 0;			/* Clear errno */
	if (lseek (fd, 0L, 0) == -1) {	/* Seek to the beginning of the file */
		return (-1);		/* Report EBADF */
	}
	/*
	 *  We read the common header of the control file in a single
	 *  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.
	 */
	size = ((char *) &rawreq->v) - ((char *) rawreq);
	if (read (fd, (char *) rawreq, size) != size) {
		/*
		 *  Something bad happened trying to read the control
		 *  file header.
		 */
		return (-1);
	}
	if (verifyhdr (rawreq) < 0) return (-1);
	/*
	 *  Leave the file pointer pointing at the varying part
	 *  of the request control file.
	 */
	if (rawreq->type == RTYPE_DEVICE) {
		/*
		 *  We are [re]writing the control file common
		 *  header of a device-oriented request.
		 */
		size = sizeof (struct rawdevreq);
	}
	else {
		/*
		 *  We are [re]writing the control file common
		 *  header of a non device-oriented request.
		 */
		size = sizeof (struct rawbatreq);
	}
	lseek (fd, (long) size, 1);	/* Relative seek */
	errno = 0;			/* Extreme paranoia */
	return (0);
}
