/** BEGIN COPYRIGHT BLOCK
 * This Program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 2 of the License.
 * 
 * This Program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA.
 * 
 * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * END COPYRIGHT BLOCK **/

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

#include <prtypes.h>

#if defined( XP_WIN32 )
#include <windows.h>
#include <io.h>
#else /* XP_WIN32 */
#   if defined( AIXV4 )
#   include <fcntl.h>
#   else /* AIXV4 */
#   include <sys/fcntl.h>
#   endif /* AIXV4 */
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#endif /* XP_WIN3 */
#include "dsalib.h"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <ctype.h>

#include "nspr.h"
#include "plstr.h"

#define COPY_BUFFER_SIZE        4096
/* This is the separator string to use when outputting key/value pairs
   to be read by the non-HTML front end (Java console)
*/
static const char *SEPARATOR = ":"; /* from AdmTask.java */

#define LOGFILEENVVAR "DEBUG_LOGFILE" /* used for logfp */

/* return a FILE * opened in append mode to the log file
   caller must use fclose to close it
*/
static FILE *
get_logfp(void)
{
	FILE *logfp = NULL;
	char *logfile = getenv(LOGFILEENVVAR);

	if (logfile) {
		logfp = fopen(logfile, "a");
	}
	return logfp;
}

DS_EXPORT_SYMBOL int 
ds_file_exists(char *filename)
{
    struct stat finfo;

    if ( filename == NULL )
	return 0;

    if ( stat(filename, &finfo) == 0 )	/* successful */
        return 1;
    else
        return 0;
}

/*
 * Given the name of a directory, return a NULL-terminated array of
 * the file names contained in that directory.  Returns NULL if the directory
 * does not exist or an error occurs, and returns an array with a
 * single NULL string if the directory exists but is empty.  The caller
 * is responsible for freeing the returned array of strings.
 * File names "." and ".." are not returned.
 */
#if !defined( XP_WIN32 )
DS_EXPORT_SYMBOL char **
ds_get_file_list( char *dir )
{
    DIR *dirp;
    struct dirent *direntp;
    char **ret = NULL;
    int nfiles = 0;

    if (( dirp = opendir( dir )) == NULL ) {
	return NULL;
    }
    
    if (( ret = malloc( sizeof( char * ))) == NULL ) {
	closedir(dirp);
	return NULL;
    };

    while (( direntp = readdir( dirp )) != NULL ) {
	if ( strcmp( direntp->d_name, "." ) &&
		strcmp( direntp->d_name, ".." )) {
	    if (( ret = (char **) realloc( ret,
		    sizeof( char * ) * ( nfiles + 2 ))) != NULL ) {
	        ret[ nfiles ] = strdup( direntp->d_name );
	        nfiles++;
            }
	}
    }
    (void) closedir( dirp );

    if (ret) {
        ret[ nfiles ] = NULL;
    }

    return ret;
}
#else
DS_EXPORT_SYMBOL char **
ds_get_file_list( char *dir )
{
	char szWildcardFileSpec[MAX_PATH];
	char **ret = NULL;
	long hFile;
	struct _finddata_t	fileinfo;
	int	nfiles = 0;

	if( ( dir == NULL ) || (strlen( dir ) == 0) )
		return NULL;

    if( ( ret = malloc( sizeof( char * ) ) ) == NULL ) 
		return NULL;

	PL_strncpyz(szWildcardFileSpec, dir, sizeof(szWildcardFileSpec));
	PL_strcatn(szWildcardFileSpec, sizeof(szWildcardFileSpec), "/*");

	hFile = _findfirst( szWildcardFileSpec, &fileinfo);
	if( hFile == -1 )
		return NULL;

	if( ( strcmp( fileinfo.name, "." ) != 0 ) &&
		( strcmp( fileinfo.name, ".." ) != 0 ) )
	{
	    ret[ nfiles++ ] = strdup( fileinfo.name );
	}

	while( _findnext( hFile, &fileinfo ) == 0 )
	{
		if( ( strcmp( fileinfo.name, "." ) != 0 ) &&
			( strcmp( fileinfo.name, ".." ) != 0 ) )
		{
			if( ( ret = (char **) realloc( ret, sizeof( char * ) * ( nfiles + 2 ) ) ) != NULL ) 
				ret[ nfiles++ ] = strdup( fileinfo.name);
		}
	}

	_findclose( hFile );
    ret[ nfiles ] = NULL;
	return ret;
}
#endif /* ( XP_WIN32 ) */

/* converts '\' chars to '/' */
DS_EXPORT_SYMBOL void 
ds_dostounixpath(char *szText)
{
	if(szText)
	{
		while(*szText)
   		{
   			if( *szText == '\\' )
   				*szText = '/';
   			szText++;
		}
	}
}

#if !defined( XP_WIN32 )
#include <errno.h> /* errno */
#include <pwd.h> /* getpwnam */

static int   saved_uid_valid = 0;
static uid_t saved_uid;
static int   saved_gid_valid = 0;
static gid_t saved_gid;

#if defined( HPUX )
#define SETEUID(id) setresuid((uid_t) -1, id, (uid_t) -1)
#else
#define SETEUID(id) seteuid(id)
#endif

#endif

DS_EXPORT_SYMBOL char*
ds_become_localuser_name (char *localuser)
{
#if !defined( XP_WIN32 )
    if (localuser != NULL) {
	struct passwd* pw = getpwnam (localuser);
	if (pw == NULL) {
	    fprintf (stderr, "getpwnam(%s) == NULL; errno %d",
		     localuser, errno);
		fprintf (stderr, "\n");
	    fflush (stderr);
	} else {
	    if ( ! saved_uid_valid) saved_uid = geteuid();
	    if ( ! saved_gid_valid) saved_gid = getegid();
	    if (setgid (pw->pw_gid) == 0) {
		saved_gid_valid = 1;
	    } else {
		fprintf (stderr, "setgid(%li) != 0; errno %d",
			 (long)pw->pw_gid, errno);
		fprintf (stderr, "\n");
		fflush (stderr);
	    }
	    if (SETEUID (pw->pw_uid) == 0) {
		saved_uid_valid = 1;
	    } else {
		fprintf (stderr, "seteuid(%li) != 0; errno %d",
			 (long)pw->pw_uid, errno);
		fprintf (stderr, "\n");
		fflush (stderr);
	    }
	}
    }
    return NULL;
#else
    return NULL;
#endif
}

DS_EXPORT_SYMBOL char*
ds_become_localuser (char **ds_config)
{
#if !defined( XP_WIN32 )
    char* localuser = ds_get_value (ds_config, ds_get_var_name(DS_LOCALUSER), 0, 1);
    if (localuser != NULL) {
	char	*rv = ds_become_localuser_name(localuser);

	free(localuser);
	return rv;
    }
    return NULL;
#else
    return NULL;
#endif
}

DS_EXPORT_SYMBOL char*
ds_become_original (char **ds_config)
{
#if !defined( XP_WIN32 )
    if (saved_uid_valid) {
	if (SETEUID (saved_uid) == 0) {
	    saved_uid_valid = 0;
	} else {
	    fprintf (stderr, "seteuid(%li) != 0; errno %d<br>n",
		     (long)saved_uid, errno);
	    fflush (stderr);
	}
    }
    if (saved_gid_valid) {
	if (setgid (saved_gid) == 0) {
	    saved_gid_valid = 0;
	} else {
	    fprintf (stderr, "setgid(%li) != 0; errno %d<br>\n",
		     (long)saved_gid, errno);
	    fflush (stderr);
	}
    }
    return NULL;
#else
    return NULL;
#endif
}

/*
 * on linux when running as root, doing something like 
 * system("date > out.log 2>&1") will fail, because of an 
 * ambigious redirect.  This works for /bin/sh, but not /bin/csh or /bin/tcsh
 *
 * using this would turn
 * 	system("date > out.log 2>&1");
 * into
 * 	system("/bin/sh/ -c \"date > out.log 2>&1\"")
 *
 */
DS_EXPORT_SYMBOL void
alter_startup_line(char *startup_line)
{
#if (defined Linux && !defined LINUX2_4)
        char temp_startup_line[BIG_LINE+40];
 
        PR_snprintf(temp_startup_line, sizeof(temp_startup_line), "/bin/sh -c \"%s\"", startup_line);
        PL_strncpyz(startup_line, temp_startup_line, BIG_LINE);
#else
	/* do nothing */
#endif /* Linux */
}

DS_EXPORT_SYMBOL void
ds_send_error(char *errstr, int print_errno)
{
	FILE *logfp;
	fprintf(stdout, "error%s%s\n", SEPARATOR, errstr);
	if (print_errno && errno)
		fprintf(stdout, "system_errno%s%d\n", SEPARATOR, errno);

    fflush(stdout);

	if ((logfp = get_logfp())) {
		fprintf(logfp, "error%s%s\n", SEPARATOR, errstr);
		if (print_errno && errno)
			fprintf(logfp, "system_errno%s%d\n", SEPARATOR, errno);
		fclose(logfp);
	}

}

DS_EXPORT_SYMBOL void
ds_send_status(char *str)
{
	FILE *logfp;
    fprintf(stdout, "[%s]: %s\n", ds_get_server_name(), str);
    fflush(stdout);

	if ((logfp = get_logfp())) {
	    fprintf(logfp, "[%s]: %s\n", ds_get_server_name(), str);
		fclose(logfp);
	}
}

/* type and doexit are unused
   I'm not sure what type is supposed to be used for
   removed the doexit code because we don't want to
   exit abruptly anymore, we must exit by returning an
   exit code from the return in main()
*/
static void
report_error(int type, char *msg, char *details, int doexit)
{
    char error[BIG_LINE*4] = {0};

	if (msg)
	{
		PL_strcatn(error, BIG_LINE*4, msg);
		PL_strcatn(error, BIG_LINE*4, SEPARATOR);
	}
	if (details)
		PL_strcatn(error, BIG_LINE*4, details);
	ds_send_error(error, 1);
}

DS_EXPORT_SYMBOL void
ds_report_error(int type, char *msg, char *details)
{
	/* richm - changed exit flag to 0 - we must not exit
	   abruptly, we should instead exit by returning a code
	   as the return value of main - this ensures that callers
	   are properly notified of the status
	*/
	report_error(type, msg, details, 0);
}

DS_EXPORT_SYMBOL void
ds_report_warning(int type, char *msg, char *details)
{
	report_error(type, msg, details, 0);
}

DS_EXPORT_SYMBOL void
ds_show_message(const char *message)
{
	FILE *logfp;
	printf("%s\n", message);
	fflush(stdout);

	if ((logfp = get_logfp())) {
		fprintf(logfp, "%s\n", message);
		fclose(logfp);
	}

	return;
}

DS_EXPORT_SYMBOL char *
ds_system_errmsg(void)
{
    static char static_error[BUFSIZ];
    char *lmsg = 0; /* Local message pointer */
    size_t msglen = 0;
#ifdef XP_WIN32
    LPTSTR sysmsg = 0;
#endif

#if defined(XP_WIN32)
    msglen = FormatMessage(
	FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER,
	NULL, 
	GetLastError(), 
	LOCALE_SYSTEM_DEFAULT, 
	(LPTSTR)&sysmsg, 
	0, 
	0);
    if (msglen > 0)
	lmsg = sysmsg;
    SetLastError(0);
#else
    lmsg = strerror(errno);
    errno = 0;
#endif

    if (!lmsg)
	static_error[0] = 0;
    else
    {
	/* At this point lmsg points to something. */
	int min = 0;
	msglen = strlen(lmsg);

	min = msglen > BUFSIZ ? BUFSIZ : msglen;
	strncpy(static_error, lmsg, min-1);
	static_error[min-1] = 0;
    }

#ifdef XP_WIN32
    /* NT's FormatMessage() dynamically allocated the msg; free it */
    if (sysmsg)
        LocalFree(sysmsg);
#endif

    return static_error;
}

#ifndef MAXPATHLEN
#define MAXPATHLEN  1024
#endif

enum {
	DB_DIRECTORY = 0,
	DB_LOGDIRECTORY,
	DB_CHANGELOGDIRECTORY,
	DB_HOME_DIRECTORY
};

DS_EXPORT_SYMBOL int
ds_remove_reg_key(void *base, const char *format, ...)
{
	int rc = 0;
#ifdef XP_WIN32
	int retries = 3;
	HKEY hkey = (HKEY)base;
	char *key;
	va_list ap;

	va_start(ap, format);
	key = PR_vsmprintf(format, ap);
	va_end(ap);

	do {
		if (ERROR_SUCCESS != RegDeleteKey(hkey, key)) {
			rc = GetLastError();
			if (rc == ERROR_BADKEY || rc == ERROR_CANTOPEN ||
				rc == ERROR_CANTREAD ||
				rc == ERROR_CANTWRITE || rc == ERROR_KEY_DELETED ||
				rc == ERROR_ALREADY_EXISTS || rc == ERROR_NO_MORE_FILES) {
				rc = 0; /* key already deleted - no error */
			} else if ((retries > 1) && (rc == ERROR_IO_PENDING)) {
				/* the key is busy - lets wait and try again */
				PR_Sleep(PR_SecondsToInterval(3));
				retries--;
			} else {
				char *errmsg = PR_smprintf("Could not remove registry key %s - error %d (%s)",
									   	key, rc, ds_system_errmsg());
				ds_send_error(errmsg, 0);
				PR_smprintf_free(errmsg);
				break; /* no retry, just fail */
			}
		}
	} while (rc && retries);
	PR_smprintf_free(key);
#endif
	return rc;
}
