/* 
 * FILE:   pathalloc.c
 * AUTHOR: Alan Shutko <ats@hubert.wustl.edu>
 *
 * ID: $Id$
 *
 * Functions:
 *
 */

#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include "ats.h"

#ifdef	PATH_MAX
static int pathmax = PATH_MAX;
#else
static int pathmax = 0;
#endif

#define	PATH_MAX_GUESS	1024	/* if PATH_MAX is indeterminate */
                                /* this may not be enough       */

/*
 * ****
 *      NAME
 *        pathalloc - allocate buffer large enough for path
 *      SYNOPSIS
 *        char *pathalloc(int *size)
 *      DESCRIPTION
 *        pathalloc allocates a buffer large enough for the longest
 *        pathname on the system.  If passed a pointer to an integer,
 *        it will store the length of the buffer in the integer.
 *      RETURNS
 *        pathalloc returns a pointer to the buffer allocated.
 * ****
 */

char *pathalloc(int *size)
{
    char *ptr;

    if (pathmax == 0)           /* ndef PATH_MAX and first time ran */
    {
        errno = 0;
        if ((pathmax = pathconf("/", _PC_PATH_MAX)) < 0)
        {
            if (errno == 0)     /* pathmax indeterminate */
                pathmax = PATH_MAX_GUESS;
            else
                error_system(ERR_QUIT, "pathconf error for _PC_PATH_MAX");
        }
        else
            pathmax++;          /* add one since it is relative to / */
    }

    if ((ptr = malloc(pathmax + 1)) == NULL)
        error_system(ERR_QUIT, "could not allocate memory for path");

    if (size != NULL)
        *size = pathmax + 1;
    return(ptr);
}
