/*
 * libnqs/misc/machpath.c
 * 
 * DESCRIPTION:
 *
 *	Determine the machine-id of the explicit or implied machine
 *	specification in the given path specification:
 *
 *		path_name			OR
 *		machine_name:path_name
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	November 5, 1985.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <string.h>
#include <netdb.h>			/* Network database */
#include <libnmap/nmap.h>

/*** machpath
 *
 *
 *	int machpath():
 *
 *	Determine the machine-id of the explicit or implied machine
 *	specification in the given path specification.
 *
 *		path_name			OR
 *		machine_name:path_name
 *
 *	Returns:
 *		1: if successful, and an explicit machine-name
 *		   appeared in the pathname specification.
 *		   The machine-id parameter is appropriately
 *		   updated.
 *
 *		0: if successful, but no explicit machine-name
 *		   appeared in the pathname specification (the
 *		   local machine is implicitly assumed).  The
 *		   machine-id parameter is appropriately
 *		   updated.
 *
 *	       -1: if a null machine-name was specified in the
 *		   path-name:
 *
 *			:path_name
 *
 *	       -2: if the explicit or implied machine-specification
 *		   is not recognized by the local system (NMAP_ENOMAP).
 *
 *	       -3: if the Network Mapping Procedures (NMAP_)
 *		   deny access to the caller (NMAP_ENOPRIV).
 *
 *	       -4: if some other general NMAP_ error occurs.
 */
int machpath (char *path_name, Mid_t *machine_id)
{
	struct hostent *ent;	/* Host table entry structure */
	char *end_machine;	/* End of machine-name */

  	assert (path_name  != NULL);
  	assert (machine_id != NULL);
  
	if ((end_machine = strchr (path_name, ':')) == (char *) 0) {
		/*
		 *  No machine-specification was given.  The
		 *  local machine is assumed.
		 */
		return (localmid (machine_id));
	}
	/*
	 *  A machine-name specification appears.
	 */
	if (path_name == end_machine) {
		/*
		 *  Missing machine-specification.
		 */
		return (-1);		/* Bad syntax */
	}
	/*
	 *  Determine the machine-id of the destination machine.
	 */
	*end_machine = '\0';		/* Temporarily zap ':' */
	ent = gethostbyname (path_name);/* Lookup machine-name */
	*end_machine = ':';		/* Restore ':' */
	if (ent == (struct hostent *) 0) {
		return (-2);		/* This machine is not */
					/* known to us */
	}
	switch (nmap_get_mid (ent, machine_id)) {
	case NMAP_SUCCESS:		/* Successfully got local machine-id */
		return (1);		/* for explicitly named machine */
	case NMAP_ENOMAP:		/* What?  No local mid defined! */
		return (-2);
	case NMAP_ENOPRIV:		/* No privilege */
		return (-3);
	}
	return (-4);			/* General NMAP_ error */
}
