/*
 * Copyright (c) 2002, The EROS Group, LLC and Johns Hopkins
 * University. All rights reserved.
 * 
 * This software was developed to support the EROS secure operating
 * system project (http://www.eros-os.org). The latest version of
 * the OpenCM software can be found at http://www.opencm.org.
 * 
 * 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. Neither the name of the The EROS Group, LLC nor the name of
 *    Johns Hopkins University, 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */

#include <opencm.h>
#include <repos/Repository.h>
#include <repos/FSRepos.h>
#include <client/KeyGen.h>
#include <common/SSLcommon.h>
#include <sys/file.h>
#include <opencm-version.h>
#include "../../zlib/zlib.h"

static const char *
find_subdir(const char *entdir, const char *fileName, OC_bool creating)
{
  const char *trueDirChar;

  /* len(sha1_) == 5 */
  for(trueDirChar = fileName + 5; *trueDirChar; trueDirChar++) {
    const char *nextDir = path_join(entdir, xstrndup(trueDirChar, 1));

    /* If we are not doing a store operation, check each directory on
       the way down for an entity that may have been orphaned by an
       interrupted directory reorganization. This also solves the
       problem of legacy installations where all of the entities are
       sitting in the top-level directory. */
    if (!creating && path_exists(path_join(entdir, fileName)))
      return entdir;

    if (creating && !path_exists(nextDir)) {
      const char *subdirMarker = path_join(entdir, R_SUBDIR);
      if (path_exists(subdirMarker))
	path_smkdir(nextDir);
    }

    if (!path_exists(nextDir))
      break;

    entdir = nextDir;
  }

  return entdir;
}

/* maybe_remove_dirtree(): After a file is removed, remove all
   containing directories recursively upwards, up to but not including
   TOP */
void
fsrepos_maybe_remove_dirtree(const char *top, const char *dirPath)
{
  /* Make sure that dirPath lies somewhere within top: */
  if (! path_isprefix(top, dirPath))
    return;

  while (!path_isprefix(dirPath, top)) {
    OC_bool canDelete = TRUE;
    OC_DIR *dir;
    const char* ent;

    dir = path_opendir(dirPath, TRUE);
    while ((ent = path_readdir(dir))) {
      if (path_should_skip_dirent(ent))
	continue;

      /* There is a non-skippable entry, so we cannot remove this
	 directory yet. */
      canDelete = FALSE;
    }
    path_closedir(dir);

    if (canDelete == FALSE)
      return;

    path_rmdir(dirPath);

    dirPath = path_dirname(dirPath);
  }
}

/* maybe_split_subdir(): If the number of entity files in a given
   directory has exceeded a pre-specified bound, expand that directory
   into subdirectories. 

   I had initially hoped to avoid any need to ever do this
   recursively. Then I looked at the e2fsck program and learned that
   some nimwit placed an unreasonably small limit on directory
   sizes. 

   Unfortunately, Todd Fries is converting a CVS tree with 53,000
   commits, so we could be looking at existing entities/ directories
   that are big enough to require a recursive split even among the
   alpha users. I therefore made recursive splitting an
   option. Recursion only occurs if the containing directory was too
   big.

   The really *stupid* part is that the file system itself seems to
   handle directories that are much larger than e2fsck will accept. Go
   figure.
*/

static OC_bool
maybe_split_subdir(const char *baseEntDir, const char *entSubDir, 
		   OC_bool recurse)
{
  StrVec *sv = strvec_create();	/* elements in entSubDir */

  /* The directory we are now looking at is a "leaf" directory, but if
     it has gotten too big we need to transform it. Check for that
     possibility: */

  OC_DIR *dir;
  const char* ent;
    
  dir = path_opendir(entSubDir, TRUE);
  while ((ent = path_readdir(dir))) {
    const char *fullname = path_join(entSubDir, ent);

    if (path_should_skip_dirent(ent))
      continue;

    if (!path_isfile(fullname))
      continue;

    strvec_append(sv, xstrdup(ent));
  }
  path_closedir(dir);

  if (vec_size(sv) > FS_MAX_DIRSIZE) {
    unsigned u;

    log_trace(DBG_REPOS, "Splitting directory %s\n", entSubDir);

    WriteOneLineFile(path_join(entSubDir, R_SUBDIR), "1");

    for (u = 0; u < vec_size(sv); u++) {
      const char *fileName = vec_fetch(sv, u, const char *);
      const char *curDir = find_subdir(baseEntDir, fileName, FALSE);
      const char *newDir = find_subdir(baseEntDir, fileName, TRUE);
      const char *curPath = path_join(curDir, fileName);
      const char *newPath = path_join(newDir, fileName);

      path_rename(curPath, newPath);
    }

    if (recurse) {
      unsigned u;
      StrVec *dv = strvec_create();

      dir = path_opendir(entSubDir, TRUE);

      while ((ent = path_readdir(dir))) {
	const char *fullname = path_join(entSubDir, ent);

	if (path_should_skip_dirent(ent))
	  continue;

	if (!path_isdir(fullname))
	  continue;

	strvec_append(dv, path_join(entSubDir, ent));
      }

      path_closedir(dir);

      for (u = 0; u < vec_size(dv); u++) {
	const char *subDirName = vec_fetch(dv, u, const char *);
	maybe_split_subdir(baseEntDir, subDirName, recurse);
      }
    }

    return TRUE;
  }

  return FALSE;
}

const char *
entity_remove_store_suffix(const char *s)
{
  const char *suffix = strstr(s, ".gz");

  if (suffix)
    return xstrndup(s, suffix - s);

  suffix = strstr(s, ",x");
  if (suffix)
    return xstrndup(s, suffix - s);

  return s;
}

OC_bool
entity_frag_in_current_format(Repository *r, const char *frag)
{
  if (strcmp(r->storeType, CM_REPOS_FS) == 0) {
    if (strstr(frag, ",x2"))	/* matches ,x2 or ,x2a */
      return FALSE;
    if (strstr(frag, ".gz"))
      return FALSE;
    return TRUE;
  }
  else if (strcmp(r->storeType, CM_REPOS_GZFS) == 0) {
    if (strstr(frag, ".gz") != 0)
      return TRUE;
    return FALSE;
  }
  else if (strcmp(r->storeType, CM_REPOS_SXD2) == 0) {
    if (strstr(frag, ",x2"))	/* matches ,x2 or ,x2a */
      return TRUE;
    return FALSE;
  }

  THROW(ExBadValue, "Entity fragment in unknown format");
}

static OC_bool
gc_resurrect(Repository *r, const char *entClassDir, const char *fileName)
{
  const char *gcDir = path_join(r->uri->path, R_GCDIR);
  const char *gcpath;

  /* If no GC dir, we are done: */
  if (!path_exists(gcDir))
    return FALSE;

  gcDir = path_join(gcDir, entClassDir);
  gcDir = find_subdir(gcDir, fileName, FALSE);
  gcpath = path_join(gcDir, fileName);

  if (!path_exists(gcpath))
    return FALSE;

  {
    const char *truepath;
    const char *entDir = path_join(r->uri->path, entClassDir);
    entDir = find_subdir(entDir, fileName, TRUE);
    truepath = path_join(entDir, fileName);

    path_srename(gcpath, truepath);

    maybe_split_subdir(path_join(r->uri->path, entClassDir), entDir, FALSE);

    fsrepos_maybe_remove_dirtree(path_join(r->uri->path, R_GCDIR), gcDir);
  }

  return TRUE;
}

/* Flat file storage */
Buffer *
flatfile_GetEntityBuffer(Repository *r, const char *mURI /* unused */,
			 const char *trueName)
{
  Buffer *buf = 0;
  const char *fileName = trueName;

  const char *baseEntPath = path_join(r->uri->path, R_FLATENTITIES);
  const char *entpath;

  entpath = find_subdir(baseEntPath, fileName, FALSE);
  entpath = path_join(entpath, fileName);

  if ((path_exists(entpath) == FALSE) &&
      gc_resurrect(r, R_FLATENTITIES, fileName)) {
    /* Re-try the search */
    entpath = find_subdir(baseEntPath, fileName, FALSE);
    entpath = path_join(entpath, fileName);
  }

  if (!path_exists(entpath))
    THROW(ExNoObject, format("Entity %s not found", trueName));

  buf = buffer_FromFile(entpath, 'B');
  return buf;
}

/* Entity management: */
void
flatfile_ReviseEntity(Repository *r,
		      const char *mURI,
		      const char *prevTrueName, void *s)
{
  /* This must be robust in the face of being handed a bogus value for
   * prevTrueName. In particular, it must be prepared to handle:
   *
   *    1. prevTrueName == 0
   *    2. prevTrueName == something this server doesn't have.
   *
   * It must also be prepared for a repeat upload of a previously seen
   * entity.
   */

  const char *baseEntPath = path_join(r->uri->path, R_FLATENTITIES);
  /* Unwind occurs in fsrepos_ReviseEntity() */
  const char *tmppath = path_mktmpnm(baseEntPath, "tmpent-");
  const char *trueName = ser_getTrueName(s);
  const char *fileName = trueName;
  const char *entpath;
  const char *truepath;

  SDR_stream *strm = 0;
  
  if (!path_exists(baseEntPath))
    path_smkdir(baseEntPath);

  /* First, check if it exists: */
  entpath = find_subdir(baseEntPath, fileName, FALSE);
  truepath = path_join(entpath, fileName);

  if (path_exists(truepath))
    return;

  /* If it doesn't exist, insert it: */
  entpath = find_subdir(baseEntPath, fileName, TRUE);
  truepath = path_join(entpath, fileName);

  TRY {
    strm = stream_createBuffer(SDR_CONTENT);
    sdr_write("ENTITY", strm, s);
  }
  DEFAULT(ex) {
    if (strm) stream_close(strm);
    RETHROW(ex);
  }
  END_CATCH;

#if 0
  flatfile_ReviseEntityBuffer(r, mURI, prevTrueName, stream_asBuffer(strm));
#else
  {
    Buffer *buf = stream_asBuffer(strm);
    ocmoff_t end = buffer_length(buf);
    ocmoff_t pos = 0;
    FILE *f = NULL;

    TRY {
      f = xfopen(tmppath, 'w', 'b');

      while (pos < end) {
	BufferChunk bc = buffer_getChunk(buf, pos, end - pos);

	if (fwrite((void *)bc.ptr, 1, (unsigned) bc.len, f) < bc.len)
	  THROW(ExTruncated, format("Could not write all of \"%s\"", 
				    tmppath));

	pos += bc.len;
      }

      fclose(f);
    }
    DEFAULT(ex) {
      if (f != NULL) fclose(f);

      RETHROW(ex);
    }
    END_CATCH;
  }
#endif
  stream_close(strm);

  path_rename(tmppath, truepath);

  maybe_split_subdir(baseEntPath, entpath, FALSE);
}

Buffer *
gzfile_GetEntityBuffer(Repository *r, const char *mURI /* unused */,
		       const char *trueName)
{
  Buffer *buf = 0;
  const char *baseEntPath = path_join(r->uri->path, R_GZENTITIES);
  const char *entpath;
  const char *truePath;
  const char *gzFileName = xstrcat(trueName, ".gz");
  char iobuf[1024];
  gzFile entFile;
  size_t len;

  entpath = find_subdir(baseEntPath, gzFileName, FALSE);
  truePath = path_join(entpath, gzFileName);

  if ((path_exists(truePath) == FALSE) &&
      gc_resurrect(r, R_GZENTITIES, gzFileName)) {
    /* Re-try the search */
    entpath = find_subdir(baseEntPath, gzFileName, FALSE);
    truePath = path_join(entpath, gzFileName);
  }

  if (!path_exists(truePath))
    THROW(ExNoObject, format("Entity %s not found", trueName));

  buf = buffer_create();

  entFile = gzopen(truePath, "rb");

  do {
    len = gzread(entFile, iobuf, sizeof(iobuf));
    buffer_append(buf, iobuf, len);
  } while (len > 0);

  gzclose(entFile);
  buffer_freeze(buf);

  return buf;
}

/* Entity management: */
void
gzfile_ReviseEntity(Repository *r,
		    const char *mURI,
		    const char *prevTrueName, void *s)
{
  /* This must be robust in the face of being handed a bogus value for
   * prevTrueName. In particular, it must be prepared to handle:
   *
   *    1. prevTrueName == 0
   *    2. prevTrueName == something this server doesn't have.
   *
   * It must also be prepared for a repeat upload of a previously seen
   * entity.
   */

  const char *baseEntPath = path_join(r->uri->path, R_GZENTITIES);
  const char *entpath = 0;
  const char *tmppath = path_mktmpnm(baseEntPath, "tmpent-");
  const char *trueName = ser_getTrueName(s);
  const char *gzFileName = xstrcat(trueName, ".gz");
  const char *truepath;

  SDR_stream *strm = 0;
  
  if (!path_exists(baseEntPath))
    path_smkdir(baseEntPath);

  entpath = find_subdir(baseEntPath, gzFileName, FALSE);
  truepath = path_join(entpath, gzFileName);

  if (path_exists(truepath))
    return;

  entpath = find_subdir(baseEntPath, gzFileName, TRUE);
  truepath = path_join(entpath, gzFileName);

  TRY {
    strm = stream_createBuffer(SDR_CONTENT);
    sdr_write("ENTITY", strm, s);
  }
  DEFAULT(ex) {
    if (strm) stream_close(strm);
    RETHROW(ex);
  }
  END_CATCH;

  {
    Buffer *buf = stream_asBuffer(strm);
    ocmoff_t end = buffer_length(buf);
    ocmoff_t pos = 0;
    gzFile entFile = gzopen(tmppath, "wb");

    if (entFile < 0)
      THROW(ExNoAccess, format("Could not write all of \"%s\"", 
			       tmppath));

    while (pos < end) {
      BufferChunk bc = buffer_getChunk(buf, pos, end - pos);

      if (gzwrite(entFile, (void *)bc.ptr, (unsigned) bc.len) < bc.len)
	THROW(ExTruncated, format("Could not write all of \"%s\"", 
				  tmppath));

      pos += bc.len;
    }

    gzclose(entFile);
  }

  stream_close(strm);

  path_rename(tmppath, truepath);

  maybe_split_subdir(baseEntPath, entpath, FALSE);
}

Buffer *
sxd2_GetEntityBuffer(Repository *r, const char *mURI /* unused */,
		     const char *trueName)
{
  const char *baseEntPath = path_join(r->uri->path, R_SXD2ENTITIES);
  const char *entPath;
  const char *sxdFileName = xstrcat(trueName, ",x2");
  const char *truePath;
  const char *archiveName;
  SDR_stream *out = NULL;
  SDR_stream *archive = NULL;
  Buffer *buf = 0;

  log_trace(DBG_REPOS, "SXD2FS Enter GetEntity %s", trueName);

  if (strncmp(trueName, "sha1_", 5) != 0)
    THROW(ExMalformed, "Bad or unknown hash type");

  TRY {
    XDeltaArchive_t *xda = 0;

    entPath = find_subdir(baseEntPath, sxdFileName, FALSE);
    truePath = path_join(entPath, sxdFileName);

    if (!path_exists(truePath))
      THROW(ExNoObject, format("Entity %s not found", trueName));

    out = stream_createBuffer(SDR_RAW);

    log_trace(DBG_XDFS, "Begin reconstruction of %s\n", trueName);

    archiveName = ReadOneLineFile(truePath);

    log_trace(DBG_XDFS, "Searching for archive file [%s]...\n", archiveName);
    entPath = find_subdir(baseEntPath, archiveName, FALSE);
    truePath = path_join(entPath, archiveName);

    if (!path_exists(truePath))
      THROW(ExNoObject, format("Archive file [%s] not found", archiveName));

    archive = stream_fromfile(truePath, SDR_XDCS);
    xda = xda_fromStream(archive);
    xdcs_extract(xda, trueName, out);
    stream_close(archive);
    archive = NULL;

    log_trace(DBG_XDFS, "Extract object from buffer for %s\n", trueName);
    
    /* out now holds the serialized version of the object AS A RAW
       BYTE STREAM. In theory, we now need to open a typed byte stream
       out of this buffer so we can deserialize it. */
    stream_reread(out);

    buf = stream_asBuffer(out);
  }
  DEFAULT(ex) {
    if (out) stream_close(out);
    RETHROW(ex);
  }
  END_CATCH;

  log_trace(DBG_XDFS, "SXD2FS Exit GetEntity %s", trueName);

  return buf;
}

void
sxd2_ReviseEntity(Repository *r,
		  const char *mURI,
		  const char *prevTrueName, void *s)
{
  const char *baseEntPath = path_join(r->uri->path, R_SXD2ENTITIES);
  const char *entpath = 0;
  const char *trueName = ser_getTrueName(s);
  const char *tmppath = path_join(baseEntPath, trueName);
  const char *sxdFileName = xstrcat(trueName, ",x2");
  const char *newTruePath = 0;
  const char *prevTruePath = 0;
  const char *xdfs_toarchive;
  const char *xdfs_fromarchive;

  SDR_stream *archive = 0;
  SDR_stream *out = NULL;

  if (!path_exists(baseEntPath))
    path_smkdir(baseEntPath);

  entpath = find_subdir(baseEntPath, sxdFileName, FALSE);
  newTruePath = path_join(entpath, sxdFileName);

  if (path_exists(newTruePath))
    return;

  /* If path doesn't exist, create it: */
  entpath = find_subdir(baseEntPath, sxdFileName, TRUE);
  newTruePath = path_join(entpath, sxdFileName);

  /* Until proven otherwise, we are creating a new archive: */
  xdfs_toarchive = path_join(entpath, xstrcat(trueName, ",x2a"));
  xdfs_fromarchive = "/dev/null";

  tmppath = xstrcat(tmppath, ",x2-tmp");
  onthrow_remove(tmppath);

  assert(prevTrueName == 0 || !nmequal(prevTrueName, trueName));

  /* See if there is an existing archive file to modify: */
  if (prevTrueName) {
    const char *prvSxdFileName = xstrcat(prevTrueName, ",x2");
    const char *nm = 0;

    entpath = find_subdir(baseEntPath, prvSxdFileName, FALSE);
    prevTruePath = path_join(entpath, prvSxdFileName);

    if (!path_exists(prevTruePath))
      THROW(ExNoObject, 
	    format("Parent Entity [%s] not found.\n", prvSxdFileName));

      /* Need to read 'path' to get name of actual archive */
    nm = ReadOneLineFile(prevTruePath);

    entpath = find_subdir(baseEntPath, nm, FALSE);
    prevTruePath = path_join(entpath, nm);

    if (!path_exists(prevTruePath))
      THROW(ExNoObject, 
	    format("Archive [%s] not found.\n", nm));

    xdfs_fromarchive = prevTruePath;
    xdfs_toarchive = xdfs_fromarchive;
  }

  report(3, "SXD2FS Enter ReviseEntity %s", trueName);

  TRY {
    SDR_stream *strm = NULL;

    /* Prepare to write the entity by doing the in-memory serialization: */
    TRY {
      strm = stream_createBuffer(SDR_CONTENT);
      sdr_write("ENTITY", strm, s);
    }
    DEFAULT(ex) {
      if (strm) stream_close(strm);
      RETHROW(ex);
    }
    END_CATCH;

    stream_close(strm);
    stream_reread(strm);

    archive = NULL;
    {
      archive = stream_fromfile(xdfs_fromarchive, SDR_XDCS);
      out = stream_createfile(tmppath, SDR_XDCS);

#if 1
      /* At some threshold the size of the archive becomes a
	 processing bottleneck. We are still figuring out where that
	 threshold is. For the moment, if 

	 sizeof(archive) > THRESH * sizeof(strm)

	 then punt and create a new archive.

	 Also, create a new archive if the absolute size of the
	 archive file exceeds 2 Mbytes.
      */

      if (stream_length(archive) > XDCS_ARCHIVE_MAX) {
	stream_close(archive);
	archive = stream_fromfile("/dev/null", SDR_XDCS);
	xprintf("*** Archive max exceeded\n");
      }
      else if (stream_length(archive) > (stream_length(strm) * XDCS_THRESH)) {
	stream_close(archive);
	archive = stream_fromfile("/dev/null", SDR_XDCS);
	xprintf("*** Archive ratio exceeded\n");
      }
#endif

      xdcs_insert(archive, strm, trueName, out);
      stream_close(archive);
      stream_close(out);

      if (path_file_length(tmppath) == 0) {
	xprintf("Object file \"%s\" has zero size\n", tmppath);
#if 1
	THROW(ExNoObject, 
	      format("Object write failed for \"%s\"", tmppath));
#endif
      }
      else
	path_rename(tmppath, xdfs_toarchive);
    }

    /* Write a one line file that contains the name of the actual
       archive file. */
    WriteOneLineFile(newTruePath, path_tail(xdfs_toarchive));

  }
  DEFAULT(ex) {
    if (archive) stream_close(archive);
    if (out) stream_close(out);
    RETHROW(ex);
  }
  END_CATCH;

  maybe_split_subdir(baseEntPath, path_dirname(newTruePath), FALSE);

  report(3, "SXD2FS Exit ReviseEntity %s", trueName);
}

void 
upgrade_from_pre_0_1_6(Repository *r) 
{
#ifndef NDEBUG
  const char *schema_v = repos_GetVersion(r);
#endif

  if (do_Upgrade == FALSE)
    THROW(ExVersionError, 
	  "OpenCM repository upgrade needed. "
	  "Backup is recommended. See OpenCM manual.");

  assert (compare_rpm_versions(schema_v, "0.1.6") < 0);

  /* Repositories created prior to 0.1.6 have directories (and some
     user objects) with trails set by default. Turn that off. 

     This fix has the side effect of forcibly deleting dead revisions. */
  {
    StrVec *sv = strvec_create();
    unsigned u;

    /* Pass 1: Enumerate the mutables so that we can fix them. */
    sv = repos_Enumerate(r, 0, RENUM_MUTABLES, 0);

    /* Pass 2: For each mutable, fetch the mutable and its current
       content. If the current content is of type Directory or User,
       perform a SetMutableFlags() to turn on the MF_NOTRAILS flag. */

    for (u = 0; u < vec_size(sv); u++) {
      const char *mutName = vec_fetch(sv, u, const char *);
      Mutable *m = repos_GetMutable(r, mutName);
      Serializable *s = repos_GetMutableContent(r, m);

      if (m->flags & MF_NOTRAIL)
	continue;

      if (GETTYPE(s) == TY_Directory || GETTYPE(s) == TY_User) {
	const char *kind = 
	  (GETTYPE(s) == TY_Directory) ? "Directory" : "User";

	log_trace(TRC_UPGRADE, "Setting NOTRAILS on %s mutable %s\n",
		  kind, mutName);

	repos_SetMutableFlags(r, mutName, m->flags | MF_NOTRAIL);
      }
    }
   }
}
