/*
 * Copyright (c) 1998 - 2000 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the Kungliga Tekniska
 *      Högskolan and its contributors.
 * 
 * 4. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define __LIBRARY__ 1

#include <stdio.h>
#include <unistd.h>
#include <linux/unistd.h>
#include <sys/types.h>
#include <linux/stat.h>
#include <errno.h>
#include <dlfcn.h>

RCSID("$Id: getcwd.c,v 1.13 2000/03/05 05:44:30 assar Exp $");

#ifdef __NR_getcwd

#define __NR_sys_getcwd __NR_getcwd

static
_syscall2(int, sys_getcwd, char *, buf, size_t, size)

#endif /* __NR_getcwd */

#define __NR_sys_lstat __NR_lstat

typedef struct stat kern_stat;

static
_syscall2(int, sys_lstat, char *, filename, kern_stat *, statbuf)

/* apwd */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>

#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif

#ifndef min
#define min(a,b) (((a)<(b))?(a):(b))
#endif

/* Stolen from Id: apwd.c,v 1.2 1999/02/12 14:37:17 assar Exp */

static int
initial_string (char **buf, size_t *size, size_t new_size)
{
    char *tmp = malloc (new_size);

    if (tmp == NULL)
	return -1;
    *buf  = tmp;
    *size = new_size;
    return 0;
}

static int
expand_string (char **buf, size_t *size, size_t new_size)
{
    char *tmp = realloc (*buf, new_size);

    if (tmp == NULL)
	return -1;
    *buf  = tmp;
    *size = new_size;
    return 0;
}

/*
 * Verify that the dynamically allocated string `buf' of length
 * `size', has room for `len' bytes.  Returns -1 if realloc fails.
 */

static int
guarantee_room (char **buf, size_t *size, size_t len)
{
    if (*size > len)
	return 0;

    return expand_string (buf, size, min(*size * 2, len));
}

static char *
getcwd_classic (char *buf, size_t size)
{
    int dynamic_buf = 0;
    kern_stat root_sb, dot_sb, dotdot_sb;
    char *work_string;
    size_t work_length;
    char slash_dot_dot[] = "/..";
    char *curp;
    char *endp;
    DIR *dir = NULL;

    if (initial_string (&work_string, &work_length, MAXPATHLEN) < 0)
	return NULL;

    if (buf == NULL) {
	dynamic_buf = 1;
	if (initial_string (&buf, &size, MAXPATHLEN) < 0) {
	    free (work_string);
	    return NULL;
	}
    }

    endp = curp = buf + size - 1;

    if (sys_lstat (".", &dot_sb) < 0)
	goto err_ret;
    if (sys_lstat ("/", &root_sb) < 0)
	goto err_ret;
    strcpy (work_string, "..");
    while (dot_sb.st_dev != root_sb.st_dev
	   || dot_sb.st_ino != root_sb.st_ino) {
	struct dirent *dp;
	int found = 0;
	int change_dev = 0;
	int pattern_len = strlen (work_string);

	if (sys_lstat (work_string, &dotdot_sb) < 0)
	    goto err_ret;
	if (dot_sb.st_dev != dotdot_sb.st_dev)
	    change_dev = 1;
	dir = opendir (work_string);
	if (dir == NULL)
	    goto err_ret;
	while ((dp = readdir (dir)) != NULL) {
	    size_t name_len = strlen (dp->d_name);

	    if (change_dev) {
		kern_stat sb;

		if (guarantee_room (&work_string, &work_length,
				    pattern_len + name_len + 2) < 0) {
		    goto err_ret;
		}

		strcat (work_string, "/");
		strcat (work_string, dp->d_name);

		if (sys_lstat (work_string, &sb) < 0) {
		    goto err_ret;
		}
		work_string[pattern_len] = '\0';

		if (sb.st_dev == dot_sb.st_dev)
		    found = 1;
	    } else if (dp->d_ino == dot_sb.st_ino) {
		found = 1;
	    }

	    if (found) {
		while (buf + name_len >= curp) {
		    size_t old_len;

		    if (!dynamic_buf) {
			errno = ERANGE;
			goto err_ret;
		    }
		    old_len = endp - curp + 1;
		    if (expand_string (&buf, &size, size * 2) < 0)
			goto err_ret;
		    memmove (buf + size - old_len,
			     buf + size / 2 - old_len,
			     old_len);
		    endp = buf + size - 1;
		    curp = endp - old_len + 1;
		}
		memcpy (curp - name_len, dp->d_name, name_len);
		curp[-(name_len + 1)] = '/';
		curp -= name_len + 1;
		break;
	    }
	}
	closedir (dir);
	dir = NULL;

	if (!found)
	    goto err_ret;

	dot_sb = dotdot_sb;
	if (guarantee_room (&work_string, &work_length,
			    pattern_len + strlen(slash_dot_dot) + 1) < 0)
	    goto err_ret;
	strcat (work_string, slash_dot_dot);
    }
    if (curp == endp) {
	while (buf >= curp) {
	    if (!dynamic_buf) {
		errno = ERANGE;
		goto err_ret;
	    }
	    if (expand_string (&buf, &size, size * 2) < 0)
		goto err_ret;
	}
	*--curp = '/';
    }
    *endp = '\0';
    memmove (buf, curp, endp - curp + 1);
    free (work_string);
    return buf;

err_ret:
    if (dir)
	closedir (dir);
    if (dynamic_buf)
	free (buf);
    free (work_string);
    return NULL;
}

static char *
getcwd_proc (char *buf, size_t size)
{
    int dynamic_buf = 0;

    if (buf == NULL) {
	dynamic_buf = 1;
	if (initial_string (&buf, &size, MAXPATHLEN) < 0)
	    return NULL;
    } else if (size <= 1) {
	errno = ERANGE;
	return NULL;
    }

    for (;;) {
	int ret;

	ret = readlink ("/proc/self/cwd", buf, size);
	if (ret == -1)
	    goto err_ret;
	if (buf[0] != '/') {
	    errno = EINVAL;
	    goto err_ret;
	}
	if (buf[ret-1] != '\0' && ret >= size) {
	    if (!dynamic_buf) {
		errno = ERANGE;
		goto err_ret;
	    }
	    if (expand_string (&buf, &size, size * 2) < 0)
		goto err_ret;
	} else {
	    if (buf[ret - 1] != '\0')
		buf[ret] = '\0';
	    return buf;
	}
    }
err_ret:
    if (dynamic_buf)
	free (buf);
    return NULL;
}

#ifdef __NR_getcwd

static char *
getcwd_syscall (char *buf, size_t size)
{
    int dynamic_buf = 0;

    if (buf == NULL) {
	dynamic_buf = 1;
	if (initial_string (&buf, &size, MAXPATHLEN) < 0)
	    return NULL;
    }

    for (;;) {
	int ret;

	ret = sys_getcwd (buf, size);
	if (ret >= 0)
	    return buf;
	else if (errno == ERANGE) {
	    if (!dynamic_buf)
		return NULL;
	    if (expand_string (&buf, &size, size * 2) < 0)
		return NULL;
	} else
	    return NULL;
    }
}

#else

static char *
getcwd_syscall (char *buf, size_t size)
{
    return NULL;
}

#endif /* __NR_getcwd */

char *getcwd(char * buf, size_t size)
{
    char *ret;

    ret = getcwd_syscall (buf, size);
    if (ret != NULL)
	return ret;
    ret = getcwd_proc (buf, size);
    if (ret != NULL)
	return ret;
    ret = getcwd_classic (buf, size);
    if (ret != NULL)
	return ret;

    return NULL;
}
