/* cpio.c - Common java file IO native functions
   Copyright (C) 2005 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath 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; either version 2, or (at your option)
any later version.
 
GNU Classpath 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 GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

/* do not move; needed here because of some macro definitions */
#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>

#include <jni.h>

#if defined(HAVE_SYS_IOCTL_H)
#define BSD_COMP /* Get FIONREAD on Solaris2 */
#include <sys/ioctl.h>
#endif
#if defined(HAVE_SYS_FILIO_H) /* Get FIONREAD on Solaris 2.5 */
#include <sys/filio.h>
#endif

#if defined(HAVE_SYS_STAT_H)
#include <sys/stat.h>
#endif

#if defined(HAVE_FCNTL_H)
#include <fcntl.h>
#endif

#if defined(HAVE_UNISTD_H)
#include <unistd.h>
#endif

#if defined(HAVE_SYS_SELECT_H)
#include <sys/select.h>
#endif

#include <utime.h>

#include "cpnative.h"
#include "cpio.h"
#include "wm.h"

// WindowsのFindFirstFile()/FindNextFile()を
// openDir()/readDir()にマップするための構造体
typedef struct win32_open_dir_t {
	HANDLE	hFind;				// FindFirstFile()の戻り値
	_TCHAR dirname[MAX_PATH + 1];
	WIN32_FIND_DATA find_data;
	char utf8_filename[MAX_PATH + 1];	// UTF-8に変換したファイル名
} win32_open_dir;


JNIEXPORT int cpio_openFile (const char *filename, int *fd, int flags, int permissions)
{
	HANDLE hFile;
	int rwflags = flags & CPFILE_FLAG_READWRITE;
	DWORD dwDesiredAccess = 0;
	DWORD dwCreationDisposition = 0;
	_TCHAR unicode_filename[MAX_PATH+1];

	switch (rwflags) {
    case CPFILE_FLAG_READ:
      dwDesiredAccess |= GENERIC_READ;
      break;
    case CPFILE_FLAG_WRITE:
      dwDesiredAccess |= GENERIC_WRITE;
      break;
    case CPFILE_FLAG_READWRITE:
	  dwDesiredAccess |= (GENERIC_READ | GENERIC_WRITE);
	  break;
    }

	if (flags & CPFILE_FLAG_CREATE) { \
		dwCreationDisposition = OPEN_ALWAYS; \
		OutputDebugString(_T("dwCreationDisposition=OPEN_ALWAYS\n")); \
	} else if (flags & CPFILE_FLAG_TRUNCATE) { \
		dwCreationDisposition = CREATE_ALWAYS; \
		OutputDebugString(_T("dwCreationDisposition=CREATE_ALWAYS\n")); \
	} else { \
		dwCreationDisposition = OPEN_EXISTING; \
		OutputDebugString(_T("dwCreationDisposition=OPEN_EXISTING\n")); \
	} \

	to_unicode(filename, unicode_filename); \
	hFile = CreateFile(unicode_filename,\
                                    dwDesiredAccess, \
		  						    FILE_SHARE_READ | FILE_SHARE_WRITE, \
		  						    NULL,\
								    dwCreationDisposition, \
								    FILE_ATTRIBUTE_NORMAL, \
								    NULL); \
    if (hFile != INVALID_HANDLE_VALUE) {
	  *fd = (int) hFile;
      if (flags & CPFILE_FLAG_APPEND) {
	     SetFilePointer(hFile, 0, NULL, FILE_END);
	  } else if (flags & CPFILE_FLAG_TRUNCATE) {
	     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
		 SetEndOfFile(hFile);
	  }
	} else {
	    LPTSTR buff;
        FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			0,
			GetLastError(),
			0,
			(LPTSTR) &buff,
			0,
			NULL);
		OutputDebugString(_T("Failed to open file ")); \
		OutputDebugString(unicode_filename); \
		OutputDebugString(_T("\n")); \
		OutputDebugString(buff); \
		LocalFree(buff); \
	}
    return (hFile != INVALID_HANDLE_VALUE) ? CPNATIVE_OK : !CPNATIVE_OK;
}

JNIEXPORT int cpio_closeFile (int fd)
{
  return CloseHandle((HANDLE) fd) ? CPNATIVE_OK:GetLastError(); \
}

JNIEXPORT int cpio_availableBytes (int fd, jlong *bytes_available)
{
	DWORD pointer = SetFilePointer((HANDLE) fd, 0, NULL, FILE_CURRENT); \
	*bytes_available = GetFileSize((HANDLE) fd, NULL) - pointer; \
	return (pointer != 0xFFFFFFFF) ? CPNATIVE_OK : GetLastError(); \
}

JNIEXPORT int cpio_getFileSize (int fd, jlong *filesize)
{
	DWORD low, high; \
	low = GetFileSize((HANDLE) fd, &high); \
	if (low == 0xffffffff && GetLastError() != NO_ERROR) { \
		return GetLastError();
	} \
	*filesize = high; \
	*filesize <<= 32; \
	*filesize |= (low & 0xffffffffi64); \

	return CPNATIVE_OK;
}

JNIEXPORT int cpio_getFilePosition (int fd, jlong *offset)
{
	DWORD result = SetFilePointer((HANDLE) fd, 0, NULL, FILE_CURRENT);
	*offset = (jlong) result;
	return ((result) != INVALID_SET_FILE_POINTER) ? CPNATIVE_OK : GetLastError();
}

JNIEXPORT int cpio_setFilePosition (int fd, jlong position)
{
	DWORD newoffset = SetFilePointer((HANDLE) fd, (LONG) position, NULL, FILE_BEGIN);
	return ((newoffset)!=INVALID_SET_FILE_POINTER) ? CPNATIVE_OK : GetLastError();
}

#ifndef _WIN32_WCE
JNIEXPORT int cpio_read (int fd, void *buffer, jint length, jint *bytes_read)
{
  *bytes_read = read (fd, buffer, length);
  
  if (*bytes_read < 0)
  {
    return errno;
  }

  return CPNATIVE_OK;
}
#endif

#ifndef _WIN32_WCE
JNIEXPORT int cpio_write (int fd, const void *buffer, jint length, jint *bytes_written)
{
  *bytes_written = write (fd, buffer, length);
  
  if (*bytes_written < 0)
    return errno;

  return CPNATIVE_OK;
}
#endif

#ifndef _WIN32_WCE
JNIEXPORT int cpio_fsync (int fd)
{
	return FlushFileBuffers((HANDLE) fd) ? CPNATIVE_OK : GetLastError();
}
#endif

#ifndef _WIN32_WCE
JNIEXPORT int cpio_truncate (int fd, jlong size)
{
	int result;
	DWORD dwPointer = SetFilePointer((HANDLE) fd, 0, NULL, FILE_CURRENT);
	SetFilePointer((HANDLE) fd, (LONG) size, NULL, FILE_BEGIN);
	result = (SetEndOfFile((HANDLE) fd)) ? CPNATIVE_OK : GetLastError();
	SetFilePointer((HANDLE) fd, dwPointer, NULL, FILE_BEGIN);

	return CPNATIVE_OK;
}
#endif

#ifndef _WIN32_WCE
JNIEXPORT int cpio_setFileSize (int native_fd, jlong new_size)
{
  jlong file_size;
  jlong save_offset;
  int result;
  char data;
  jint bytes_written;
  
  result = cpio_getFileSize (native_fd, &file_size);
  if (result != CPNATIVE_OK)
    return result;

  /* Save off current position */
  result = cpio_getFilePosition (native_fd, &save_offset);
  if (result != CPNATIVE_OK)
    return result;

  if (file_size < new_size)
    {
      /* File is too short -- seek to one byte short of where we want,
       * then write a byte */

      /* move to position n-1 */
      result = cpio_setFilePosition (native_fd, new_size-1);
      if (result != CPNATIVE_OK)
	return result;

      /* write a byte
         Note: This will fail if we somehow get here in read only mode
         * That shouldn't happen */
      data = '\0';
      result = cpio_write (native_fd, &data, 1, &bytes_written);
      if (result != CPNATIVE_OK)
	return result;

      /* Reposition file pointer to where we started if not beyond new len. */
      if (save_offset < new_size)
	{
	  result = cpio_setFilePosition (native_fd, save_offset);
	  if (result != CPNATIVE_OK)
	    return result;
	}
    }
  else if (new_size < file_size)
    {
      /* File is too long - use ftruncate if available */
      result = cpio_truncate (native_fd, new_size);
      if (result != CPNATIVE_OK)
	  return result;

      /* Reposition file pointer when it now is beyond the end of file. */
      if (new_size < save_offset)
	{
	  result = cpio_setFilePosition (native_fd, new_size);
	  if (result != CPNATIVE_OK)
	    return result;
	}
    }

  return CPNATIVE_OK;
}
#endif

int cpio_setFileReadonly (const char *filename)
{
	_TCHAR unicode_filename[MAX_PATH+1];
	int result;
	DWORD attr;
	to_unicode(filename, unicode_filename);
	attr = GetFileAttributes(unicode_filename);
	if (attr != 0xffffffff) {
		result = SetFileAttributes(unicode_filename, attr | FILE_ATTRIBUTE_READONLY) ? CPNATIVE_OK : GetLastError();
	} else {
		result = GetLastError();
	}
	return result;
}

int cpio_chmod (const char *filename, int permissions)
{
	// FILE_ATTRIBUTE_READONLY の設定のみを変更する
	_TCHAR unicode_filename[MAX_PATH+1];
	BOOL readOnly;
	DWORD originalAttributes, newAttributes;

	to_unicode(filename, unicode_filename);

	// FILE_ATTRIBUTE_READONLYを設定するかどうかを決める
	if (((permissions & CPFILE_FLAG_OFF) && (permissions & CPFILE_FLAG_WRITE))
			|| ((! (permissions & CPFILE_FLAG_OFF)) && (! (permissions & CPFILE_FLAG_WRITE)))) {
		readOnly = TRUE;
	} else if ((permissions & CPFILE_FLAG_WRITE) && (! (permissions & CPFILE_FLAG_OFF))) {
		readOnly = FALSE;
	}

	originalAttributes = GetFileAttributes(unicode_filename);
	if (readOnly) {
		newAttributes = originalAttributes | FILE_ATTRIBUTE_READONLY;
	} else {
		newAttributes = originalAttributes & ~FILE_ATTRIBUTE_READONLY;
	}
	return SetFileAttributes(unicode_filename, newAttributes) ? CPNATIVE_OK : GetLastError();
}

int cpio_checkAccess (const char *filename, unsigned int flag)
{
	// FILE_ATTRIBUTE_READONLY の設定のみを変更する
	int result;

	switch (flag)
    {
    case CPFILE_FLAG_WRITE:
	{
		_TCHAR unicode_filename[MAX_PATH+1];
		DWORD attributes;
		to_unicode(filename, unicode_filename);
		attributes = GetFileAttributes(unicode_filename);
		if (attributes == 0xFFFFFFFF || (attributes & FILE_ATTRIBUTE_READONLY)) {
			result = !CPNATIVE_OK;
		} else {
			result = CPNATIVE_OK;
		}
		break;
	}
    default:
      result = CPNATIVE_OK;
	  break;
    }
	return result;
}

int cpio_isFileExists (const char *filename)
{
	_TCHAR unicode_filename[MAX_PATH+1];
	to_unicode(filename, unicode_filename);
	return GetFileAttributes(unicode_filename) != 0xFFFFFFFF ? CPNATIVE_OK : !CPNATIVE_OK;
}

int cpio_checkType (const char *filename, jint *entryType)
{
	DWORD attributes;
	_TCHAR unicode_filename[MAX_PATH+1];
	
	to_unicode(filename, unicode_filename);
	attributes = GetFileAttributes(unicode_filename);
	if (attributes == 0xFFFFFFFF) {
		return GetLastError();
	}

	if (attributes & FILE_ATTRIBUTE_DIRECTORY) {
		*entryType = CPFILE_DIRECTORY;
	} else {
		*entryType = CPFILE_FILE;
	}
	return CPNATIVE_OK;
}

int cpio_getModificationTime (const char *filename, jlong *mtime)
{
	_TCHAR unicode_filename[MAX_PATH + 1];
	WIN32_FILE_ATTRIBUTE_DATA attribute_data;

	to_unicode(filename, unicode_filename);
	if (GetFileAttributesEx(unicode_filename, GetFileExInfoStandard, &attribute_data)) {
		FILETIME ft = attribute_data.ftLastWriteTime;
		jlong time = ft.dwHighDateTime;
		time <<= 32;
		time |= ft.dwLowDateTime & 0x00000000ffffffffi64;
		time -= 116444736000000000i64;
		time /= (10 * 1000);
		*mtime = time;

		return CPNATIVE_OK;

	} else {
		return GetLastError();
	}
}

int cpio_setModificationTime (const char *filename, jlong mtime)
{
	// 現在サポートしていない
	return -1;
}

int cpio_removeFile (const char *filename)
{
	_TCHAR unicode_filename[MAX_PATH+1];
	to_unicode(filename, unicode_filename);
	return DeleteFile(unicode_filename) ? CPNATIVE_OK : GetLastError();
}

int cpio_mkdir (const char *path)
{
	_TCHAR unicode_name[MAX_PATH+1];
	to_unicode(path, unicode_name);
    return CreateDirectory(unicode_name, NULL) ? CPNATIVE_OK : GetLastError();
}

int cpio_rename (const char *old_name, const char *new_name)
{
	_TCHAR old_unicode_filename[MAX_PATH+1];
	_TCHAR new_unicode_filename[MAX_PATH+1];
	to_unicode(old_name, old_unicode_filename);
	to_unicode(new_name, new_unicode_filename);
    return MoveFile(old_unicode_filename, new_unicode_filename) ? CPNATIVE_OK : GetLastError();
}

int cpio_openDir (const char *dirname, void **handle)
{
	win32_open_dir* d = (win32_open_dir*) malloc(sizeof(win32_open_dir));
	if (d != NULL) {
		to_unicode(dirname, d->dirname);
        if (d->dirname[_tcslen(d->dirname) - 1] != _T('\\')) {
			_tcscat(d->dirname, _T("\\"));
		}
		_tcscat(d->dirname, _T("*"));
		d->hFind = NULL;
	  }
	  *handle = d;
      
	  return (d != NULL) ? CPNATIVE_OK : errno;
}

int cpio_closeDir (void *handle)
{
	win32_open_dir* d = (win32_open_dir*) handle;
	int result = FindClose(d->hFind) ? CPNATIVE_OK : GetLastError();
	free(handle);
	return result;
}


int cpio_readDir (void *handle, char *filename)
{
	win32_open_dir* d = (win32_open_dir*) handle;
	int result = CPNATIVE_OK;
	if (d->hFind == NULL) {
		if ((d->hFind = FindFirstFile(d->dirname, &d->find_data)) == INVALID_HANDLE_VALUE) {
			result = GetLastError();
		}
	} else if (! FindNextFile(d->hFind, &d->find_data)) {
		result = GetLastError();
	}
	if (result == CPNATIVE_OK) {
        to_utf8(d->find_data.cFileName, d->utf8_filename);
		strcpy(filename, d->utf8_filename);
	}
	return result;
}


#ifndef _WIN32_WCE
int
cpio_closeOnExec(int fd)
{
	// 現在サポートされていない（が、CPNATIVE_OKを返す）
	return CPNATIVE_OK;
}
#endif