/*
 * libnqs/req/gethdr.c
 * 
 * DESCRIPTION:
 *
 *	Open/read the common portion of an NQS request header.
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	August 12, 1985.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <libnqs/nqsxdirs.h>			/* Get Nqs_control defn */
#include <unistd.h>

/*** gethdr
 *
 *
 *	int gethdr():
 *	Open/read the common portion of an NQS request header.
 *
 *	Returns:
 *	      >=0: if successful, in which case the value returned
 *		   is the file descriptor opened for reading/writing
 *		   the control file;
 *	       -1: if the req control file was invalid, or an open
 *		   error occurred.
 *
 *			Note:	errno will be returned 0, unless a
 *				system call error occurred.
 */
int gethdr (
	long orig_seqno,	/* Original sequence number of req */
	Mid_t orig_mid,		/* Machine-id for req */
	struct rawreq *rawreq)	/* Raw request information to be returned */
{
	char path [MAX_PATHNAME+1];	/* Control directory pathname */
	register int fd;		/* File descriptor for control file */

  	assert (rawreq != NULL);
	pack6name (path, Nqs_control, (int) (orig_seqno % MAX_CTRLSUBDIRS),
		  (char *) 0, (long) orig_seqno, 5, (long) orig_mid, 6, 0, 0);
	if ((fd = open (path, O_RDWR)) == -1) {
		/*
		 *  Unable to open the control file.
		 *  Errno has error.
		 */
		return (-1);
	}
	if (readhdr (fd, rawreq) == 0) return (fd);	/* Success */
	close (fd);					/* Close the file */
	return (-1);					/* Bad control file */
}
