void UploadItemIO::prepare_subdir(apr_pool_t *pool, const char *dir_path,
                                 apr_size_t item_id)
{
    apr_finfo_t info;
    const char *sub_dir_path;

    sub_dir_path = get_sub_dir_path(pool, dir_path, item_id);

    if (!APR_STATUS_IS_ENOENT(apr_stat(&info, sub_dir_path, APR_FINFO_MIN,
                                       pool))) {
        return;
    }

    if (apr_dir_make(sub_dir_path, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
        THROW(MESSAGE_UPLOAD_ITEM_SUB_DIR_CREATION_FAILED);
    }
}
void nx_expr_proc__xm_fileop_dir_remove(nx_expr_eval_ctx_t *eval_ctx,
					nx_module_t *module,
					nx_expr_arg_list_t *args)
{
    nx_expr_arg_t *arg;
    nx_value_t path;
    apr_status_t rv;
    apr_pool_t *pool;

    ASSERT(module != NULL);

    ASSERT(args != NULL);
    arg = NX_DLIST_FIRST(args);
    ASSERT(arg != NULL);
    ASSERT(arg->expr != NULL);

    nx_expr_evaluate(eval_ctx, &path, arg->expr);

    if ( path.defined != TRUE )
    {
	throw_msg("'path' is undef");
    }
    if ( path.type != NX_VALUE_TYPE_STRING )
    {
	nx_value_kill(&path);
	throw_msg("string type required for 'path'");
    }

    // TODO: remove contents before

    pool = nx_pool_create_core();
    rv = apr_dir_remove(path.string->buf, pool);
    if ( APR_STATUS_IS_ENOENT(rv) )
    {
    }
    else if ( rv == APR_SUCCESS )
    {
    }
    else
    {
	    log_aprerror(rv, "failed to remove directory '%s'", path.string->buf);
    }
    apr_pool_destroy(pool);
    nx_value_kill(&path);
}
Beispiel #3
0
term_t bif_list_dir2_1(term_t Dir, process_t *ctx)
{
	apr_status_t rs;
	apr_pool_t *p;
	const char *path;
	apr_dir_t *dir;
	term_t r = nil;
	if (!is_string(Dir))
		return A_BADARG;
	apr_pool_create(&p, 0);
	path = ltoz(Dir, p);
	rs = apr_dir_open(&dir, path, p);
	if (rs == 0)
	{
		term_t cons = nil;
		apr_finfo_t fi;
		for (;;)
		{
			term_t v;
			term_t name;
			rs = apr_dir_read(&fi, APR_FINFO_NAME | APR_FINFO_SIZE, dir);
			if (rs != 0)
				break;
			name = ztol(fi.name, proc_gc_pool(ctx));
			if (fi.filetype == APR_DIR)
				v = make_tuple2(A_DIR, name, proc_gc_pool(ctx));
			else if (fi.filetype == APR_REG)
				v = make_tuple3(A_FILE, name, intnum(fi.size), proc_gc_pool(ctx));	//TODO: large size
			else
				v = make_tuple2(A_UNKNOWN, name, proc_gc_pool(ctx));
			lst_add(r, cons, v, proc_gc_pool(ctx));
		}

		apr_dir_close(dir);
	}

	if (rs != 0 && !APR_STATUS_IS_ENOENT(rs))
		result(make_tuple2(A_ERROR, decipher_status(rs), proc_gc_pool(ctx)));
	else
		result(make_tuple2(A_OK, r, proc_gc_pool(ctx)));

	apr_pool_destroy(p);
	return AI_OK;
}
Beispiel #4
0
static void test_file_readwrite(abts_case *tc, void *data)
{
    apr_file_t *file1 = NULL;
    apr_file_t *file3 = NULL;
    apr_status_t rv;
    apr_finfo_t finfo;
    apr_size_t txtlen = sizeof(TEST);
    char buff[50];
    apr_off_t fpos;

    /* First, create a new file, empty... */
    rv = apr_file_open(&file1, FILEPATH "testdup.readwrite.file",
                       APR_FOPEN_READ | APR_FOPEN_WRITE | APR_FOPEN_CREATE |
                       APR_FOPEN_DELONCLOSE, APR_OS_DEFAULT, p);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
    ABTS_PTR_NOTNULL(tc, file1);

    rv = apr_file_dup(&file3, file1, p);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
    ABTS_PTR_NOTNULL(tc, file3);

    rv = apr_file_write(file3, TEST, &txtlen);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
    ABTS_SIZE_EQUAL(tc, sizeof(TEST), txtlen);

    fpos = 0;
    rv = apr_file_seek(file1, APR_SET, &fpos);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
    ABTS_ASSERT(tc, "File position mismatch, expected 0", fpos == 0);

    txtlen = 50;
    rv = apr_file_read(file1, buff, &txtlen);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
    ABTS_STR_EQUAL(tc, TEST, buff);

    /* cleanup after ourselves */
    rv = apr_file_close(file1);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);

    rv = apr_file_close(file3);
    ABTS_INT_EQUAL(tc, APR_SUCCESS, rv);
    rv = apr_stat(&finfo, FILEPATH "testdup.readwrite.file", APR_FINFO_NORM, p);
    ABTS_INT_EQUAL(tc, 1, APR_STATUS_IS_ENOENT(rv));
}
Beispiel #5
0
int lua_apr_env_get(lua_State *L)
{
  apr_pool_t *memory_pool;
  apr_status_t status;
  const char *name;
  char *value;

  memory_pool = to_pool(L);
  name = luaL_checkstring(L, 1);
  status = apr_env_get(&value, name, memory_pool);
  if (APR_STATUS_IS_ENOENT(status)) {
    return 0;
  } else if (status != APR_SUCCESS) {
    return push_error_status(L, status);
  } else {
    lua_pushstring(L, value);
    return 1;
  }
}
Beispiel #6
0
svn_error_t *
svn_fs_type(const char **fs_type, const char *path, apr_pool_t *pool)
{
  const char *filename;
  char buf[128];
  svn_error_t *err;
  apr_file_t *file;
  apr_size_t len;

  /* Read the fsap-name file to get the FSAP name, or assume the (old)
     default.  For old repositories I suppose we could check some
     other file, DB_CONFIG or strings say, but for now just check the
     directory exists. */
  filename = svn_dirent_join(path, FS_TYPE_FILENAME, pool);
  err = svn_io_file_open(&file, filename, APR_READ|APR_BUFFERED, 0, pool);
  if (err && APR_STATUS_IS_ENOENT(err->apr_err))
    {
      svn_node_kind_t kind;
      svn_error_t *err2 = svn_io_check_path(path, &kind, pool);
      if (err2)
        {
          svn_error_clear(err2);
          return err;
        }
      if (kind == svn_node_dir)
        {
          svn_error_clear(err);
          *fs_type = SVN_FS_TYPE_BDB;
          return SVN_NO_ERROR;
        }
      return err;
    }
  else if (err)
    return err;

  len = sizeof(buf);
  SVN_ERR(svn_io_read_length_line(file, buf, &len, pool));
  SVN_ERR(svn_io_file_close(file, pool));
  *fs_type = apr_pstrdup(pool, buf);

  return SVN_NO_ERROR;
}
Beispiel #7
0
APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m,
        const char *file,
        apr_pool_t *pool,
        apr_int32_t flags)
{
    apr_status_t rv;
    int can_create_global;
    int try_global_local[3] = {-1, -1, -1};
    int cur;

    if (!file) {
        return APR_EINVAL;
    }

    if (flags & APR_SHM_NS_LOCAL) {
        try_global_local[0] = 0; /* only search local */
    }
    else if (flags & APR_SHM_NS_GLOBAL) {
        try_global_local[0] = 1; /* only search global */
    }
    else {
        can_create_global = can_create_global_maps();
        if (!can_create_global) { /* unprivileged process */
            try_global_local[0] = 0; /* search local before global */
            try_global_local[1] = 1;
        }
        else {
            try_global_local[0] = 1; /* search global before local */
            try_global_local[1] = 0;
        }
    }

    for (cur = 0; try_global_local[cur] != -1; cur++) {
        rv = shm_attach_internal(m, file, pool, try_global_local[cur]);
        if (!APR_STATUS_IS_ENOENT(rv)) {
            break;
        }
    }

    return rv;
}
//static
bool LLAPRFile::remove(const std::string& filename, LLVolatileAPRPool* pool)
{
	apr_status_t s;

	pool = pool ? pool : LLAPRFile::sAPRFilePoolp ;
	s = apr_file_remove(filename.c_str(), pool->getVolatileAPRPool());
	pool->clearVolatileAPRPool() ;

	if (s != APR_SUCCESS)
	{
		if (!APR_STATUS_IS_ENOENT(s))
		{
			// We only care about the error if it's not because
			//  the file doesn't exist.
			ll_apr_warn_status(s);
			LL_WARNS("APR") << " Attempting to remove filename: " << filename << LL_ENDL;
		}
		return false;
	}
	return true;
}
Beispiel #9
0
static svn_error_t *
file_textdelta(void *file_baton,
               const char *base_checksum,
               apr_pool_t *result_pool,
               svn_txdelta_window_handler_t *handler,
               void **handler_baton)
{
  struct file_baton_t *fb = file_baton;
  const char *target_dir = svn_dirent_dirname(fb->local_abspath, fb->pool);
  svn_error_t *err;
  svn_stream_t *source;
  svn_stream_t *target;

  SVN_ERR_ASSERT(! fb->writing_file);

  err = svn_stream_open_readonly(&source, fb->local_abspath,
                                 fb->pool, fb->pool);
  if (err && APR_STATUS_IS_ENOENT(err->apr_err))
    {
      svn_error_clear(err);
      source = svn_stream_empty(fb->pool);
    }
  else
    SVN_ERR(err);

  SVN_ERR(svn_stream_open_unique(&target, &fb->writing_file,
                                 target_dir, svn_io_file_del_none,
                                 fb->pool, fb->pool));

  svn_txdelta_apply(source,
                    target,
                    fb->digest,
                    fb->local_abspath,
                    fb->pool,
                    /* Provide the handler directly */
                    handler, handler_baton);

  return SVN_NO_ERROR;
}
Beispiel #10
0
static int dir_read(lua_State *L)
{
  apr_status_t status;
  lua_apr_dir *directory;
  lua_apr_stat_context *context, backup_ctx;
  int raise_errors;

  directory = checkdir(L, 1, 1);

  if (lua_isuserdata(L, lua_upvalueindex(1))) {
    /* Iterator for directory:entries()  */
    context = lua_touserdata(L, lua_upvalueindex(1));
    raise_errors = 1;
  } else {
    /* Standalone call to directory:read() */
    backup_ctx.firstarg = 2;
    backup_ctx.lastarg = lua_gettop(L);
    check_stat_request(L, &backup_ctx);
    context = &backup_ctx;
    raise_errors = 0;
  }

  for (;;) {
    status = apr_dir_read(&context->info, context->wanted, directory->handle);
    if (APR_SUCCESS == status || APR_STATUS_IS_INCOMPLETE(status)) {
      if (!(context->info.valid & APR_FINFO_NAME \
          && filename_symbolic(context->info.name)))
        return push_stat_results(L, context, directory->filepath);
    } else if (APR_STATUS_IS_ENOENT(status)) {
      return 0;
    } else if (raise_errors) {
      return raise_error_status(L, status);
    } else {
      return push_error_status(L, status);
    }
  }
}
Beispiel #11
0
svn_error_t *
svn_client__handle_externals(apr_hash_t *externals_new,
                             apr_hash_t *ambient_depths,
                             const char *repos_root_url,
                             const char *target_abspath,
                             svn_depth_t requested_depth,
                             svn_boolean_t *timestamp_sleep,
                             svn_client_ctx_t *ctx,
                             apr_pool_t *scratch_pool)
{
  apr_hash_t *old_external_defs;
  apr_hash_index_t *hi;
  apr_pool_t *iterpool;

  SVN_ERR_ASSERT(repos_root_url);

  iterpool = svn_pool_create(scratch_pool);

  SVN_ERR(svn_wc__externals_defined_below(&old_external_defs,
                                          ctx->wc_ctx, target_abspath,
                                          scratch_pool, iterpool));

  for (hi = apr_hash_first(scratch_pool, externals_new);
       hi;
       hi = apr_hash_next(hi))
    {
      const char *local_abspath = svn__apr_hash_index_key(hi);
      const char *desc_text = svn__apr_hash_index_val(hi);
      svn_depth_t ambient_depth = svn_depth_infinity;

      svn_pool_clear(iterpool);

      if (ambient_depths)
        {
          const char *ambient_depth_w;

          ambient_depth_w = apr_hash_get(ambient_depths, local_abspath,
                                         svn__apr_hash_index_klen(hi));

          if (ambient_depth_w == NULL)
            {
              return svn_error_createf(
                        SVN_ERR_WC_CORRUPT, NULL,
                        _("Traversal of '%s' found no ambient depth"),
                        svn_dirent_local_style(local_abspath, scratch_pool));
            }
          else
            {
              ambient_depth = svn_depth_from_word(ambient_depth_w);
            }
        }

      SVN_ERR(handle_externals_change(ctx, repos_root_url, timestamp_sleep,
                                      local_abspath,
                                      desc_text, old_external_defs,
                                      ambient_depth, requested_depth,
                                      iterpool));
    }

  /* Remove the remaining externals */
  for (hi = apr_hash_first(scratch_pool, old_external_defs);
       hi;
       hi = apr_hash_next(hi))
    {
      const char *item_abspath = svn__apr_hash_index_key(hi);
      const char *defining_abspath = svn__apr_hash_index_val(hi);
      const char *parent_abspath;

      svn_pool_clear(iterpool);

      SVN_ERR(wrap_external_error(
                          ctx, item_abspath,
                          handle_external_item_removal(ctx, defining_abspath,
                                                       item_abspath, iterpool),
                          iterpool));

      /* Are there any unversioned directories between the removed
       * external and the DEFINING_ABSPATH which we can remove? */
      parent_abspath = item_abspath;
      do {
        svn_node_kind_t kind;

        parent_abspath = svn_dirent_dirname(parent_abspath, iterpool);
        SVN_ERR(svn_wc_read_kind2(&kind, ctx->wc_ctx, parent_abspath,
                                  FALSE /* show_deleted*/,
                                  FALSE /* show_hidden */,
                                  iterpool));
        if (kind == svn_node_none)
          {
            svn_error_t *err;

            err = svn_io_dir_remove_nonrecursive(parent_abspath, iterpool);
            if (err)
              {
                if (APR_STATUS_IS_ENOTEMPTY(err->apr_err))
                  {
                    svn_error_clear(err);
                    break; /* No parents to delete */
                  }
                else if (APR_STATUS_IS_ENOENT(err->apr_err)
                         || APR_STATUS_IS_ENOTDIR(err->apr_err))
                  {
                    svn_error_clear(err);
                    /* Fall through; parent dir might be unversioned */
                  }
                else
                  return svn_error_trace(err);
              }
          }
      } while (strcmp(parent_abspath, defining_abspath) != 0);
    }


  svn_pool_destroy(iterpool);
  return SVN_NO_ERROR;
}
Beispiel #12
0
svn_error_t *
svn_config__parse_registry(svn_config_t *cfg, const char *file,
                           svn_boolean_t must_exist, apr_pool_t *pool)
{
  apr_pool_t *subpool;
  svn_stringbuf_t *section, *option, *value;
  svn_error_t *svn_err = SVN_NO_ERROR;
  HKEY base_hkey, hkey;
  DWORD index;
  LONG err;

  if (0 == strncmp(file, SVN_REGISTRY_HKLM, SVN_REGISTRY_HKLM_LEN))
    {
      base_hkey = HKEY_LOCAL_MACHINE;
      file += SVN_REGISTRY_HKLM_LEN;
    }
  else if (0 == strncmp(file, SVN_REGISTRY_HKCU, SVN_REGISTRY_HKCU_LEN))
    {
      base_hkey = HKEY_CURRENT_USER;
      file += SVN_REGISTRY_HKCU_LEN;
    }
  else
    {
      return svn_error_createf(SVN_ERR_BAD_FILENAME, NULL,
                               "Unrecognised registry path '%s'",
                               svn_path_local_style(file, pool));
    }

  err = RegOpenKeyEx(base_hkey, file, 0,
                     KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
                     &hkey);
  if (err != ERROR_SUCCESS)
    {
      const int is_enoent = APR_STATUS_IS_ENOENT(APR_FROM_OS_ERROR(err));
      if (!is_enoent)
        return svn_error_createf(SVN_ERR_BAD_FILENAME, NULL,
                                 "Can't open registry key '%s'",
                                 svn_path_local_style(file, pool));
      else if (must_exist && is_enoent)
        return svn_error_createf(SVN_ERR_BAD_FILENAME, NULL,
                                 "Can't find registry key '%s'",
                                 svn_path_local_style(file, pool));
      else
        return SVN_NO_ERROR;
    }


  subpool = svn_pool_create(pool);
  section = svn_stringbuf_create("", subpool);
  option = svn_stringbuf_create("", subpool);
  value = svn_stringbuf_create("", subpool);

  /* The top-level values belong to the [DEFAULT] section */
  svn_err = parse_section(cfg, hkey, SVN_CONFIG__DEFAULT_SECTION,
                          option, value);
  if (svn_err)
    goto cleanup;

  /* Now enumerate the rest of the keys. */
  svn_stringbuf_ensure(section, SVN_REG_DEFAULT_NAME_SIZE);
  for (index = 0; ; ++index)
    {
      DWORD section_len = section->blocksize;
      FILETIME last_write_time;
      HKEY sub_hkey;

      err = RegEnumKeyEx(hkey, index, section->data, &section_len,
                         NULL, NULL, NULL, &last_write_time);
      if (err == ERROR_NO_MORE_ITEMS)
          break;
      if (err == ERROR_MORE_DATA)
        {
          svn_stringbuf_ensure(section, section_len);
          err = RegEnumKeyEx(hkey, index, section->data, &section_len,
                             NULL, NULL, NULL, &last_write_time);
        }
      if (err != ERROR_SUCCESS)
        {
          svn_err =  svn_error_create(SVN_ERR_MALFORMED_FILE, NULL,
                                      "Can't enumerate registry keys");
          goto cleanup;
        }

      err = RegOpenKeyEx(hkey, section->data, 0,
                         KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
                         &sub_hkey);
      if (err != ERROR_SUCCESS)
        {
          svn_err =  svn_error_create(SVN_ERR_MALFORMED_FILE, NULL,
                                      "Can't open existing subkey");
          goto cleanup;
        }

      svn_err = parse_section(cfg, sub_hkey, section->data, option, value);
      RegCloseKey(sub_hkey);
      if (svn_err)
        goto cleanup;
    }

 cleanup:
  RegCloseKey(hkey);
  svn_pool_destroy(subpool);
  return svn_err;
}
/* Parse the file at DIGEST_PATH, populating the lock LOCK_P in that
   file (if it exists, and if *LOCK_P is non-NULL) and the hash of
   CHILDREN_P (if any exist, and if *CHILDREN_P is non-NULL).  Use POOL
   for all allocations.  */
static svn_error_t *
read_digest_file(apr_hash_t **children_p,
                 svn_lock_t **lock_p,
                 const char *fs_path,
                 const char *digest_path,
                 apr_pool_t *pool)
{
  svn_error_t *err = SVN_NO_ERROR;
  svn_lock_t *lock;
  apr_hash_t *hash;
  svn_stream_t *stream;
  const char *val;

  if (lock_p)
    *lock_p = NULL;
  if (children_p)
    *children_p = apr_hash_make(pool);

  err = svn_stream_open_readonly(&stream, digest_path, pool, pool);
  if (err && APR_STATUS_IS_ENOENT(err->apr_err))
    {
      svn_error_clear(err);
      return SVN_NO_ERROR;
    }
  SVN_ERR(err);

  /* If our caller doesn't care about anything but the presence of the
     file... whatever. */
  if (! (lock_p || children_p))
    return svn_stream_close(stream);

  hash = apr_hash_make(pool);
  if ((err = svn_hash_read2(hash, stream, SVN_HASH_TERMINATOR, pool)))
    {
      svn_error_clear(svn_stream_close(stream));
      return svn_error_createf(err->apr_err,
                               err,
                               _("Can't parse lock/entries hashfile '%s'"),
                               svn_dirent_local_style(digest_path, pool));
    }
  SVN_ERR(svn_stream_close(stream));

  /* If our caller cares, see if we have a lock path in our hash. If
     so, we'll assume we have a lock here. */
  val = hash_fetch(hash, PATH_KEY, pool);
  if (val && lock_p)
    {
      const char *path = val;

      /* Create our lock and load it up. */
      lock = svn_lock_create(pool);
      lock->path = path;

      if (! ((lock->token = hash_fetch(hash, TOKEN_KEY, pool))))
        return svn_error_trace(err_corrupt_lockfile(fs_path, path));

      if (! ((lock->owner = hash_fetch(hash, OWNER_KEY, pool))))
        return svn_error_trace(err_corrupt_lockfile(fs_path, path));

      if (! ((val = hash_fetch(hash, IS_DAV_COMMENT_KEY, pool))))
        return svn_error_trace(err_corrupt_lockfile(fs_path, path));
      lock->is_dav_comment = (val[0] == '1');

      if (! ((val = hash_fetch(hash, CREATION_DATE_KEY, pool))))
        return svn_error_trace(err_corrupt_lockfile(fs_path, path));
      SVN_ERR(svn_time_from_cstring(&(lock->creation_date), val, pool));

      if ((val = hash_fetch(hash, EXPIRATION_DATE_KEY, pool)))
        SVN_ERR(svn_time_from_cstring(&(lock->expiration_date), val, pool));

      lock->comment = hash_fetch(hash, COMMENT_KEY, pool);

      *lock_p = lock;
    }

  /* If our caller cares, see if we have any children for this path. */
  val = hash_fetch(hash, CHILDREN_KEY, pool);
  if (val && children_p)
    {
      apr_array_header_t *kiddos = svn_cstring_split(val, "\n", FALSE, pool);
      int i;

      for (i = 0; i < kiddos->nelts; i++)
        {
          apr_hash_set(*children_p, APR_ARRAY_IDX(kiddos, i, const char *),
                       APR_HASH_KEY_STRING, (void *)1);
        }
    }
Beispiel #14
0
void nx_config_cache_read()
{
    nx_ctx_t *ctx;
    apr_off_t offset = 0;
    char *buf = NULL;
    apr_status_t rv;
    apr_size_t nbytes, bytesread, bytesleft;
    nx_value_t *version = NULL;
    apr_file_t *ccfile;
    nx_exception_t e;

    ctx = nx_ctx_get();

    if ( ctx->nocache == TRUE )
    {
	return;
    }

    log_debug("reading config cache from %s", ctx->ccfilename);
    rv = apr_file_open(&ccfile, ctx->ccfilename,
		       APR_READ, APR_OS_DEFAULT, ctx->pool);
    if ( APR_STATUS_IS_ENOENT(rv) )
    { // nothing to read
	return;
    }
    CHECKERR_MSG(rv, "couldn't open config cache '%s'", ctx->ccfilename);

    try
    {
	CHECKERR_MSG(apr_file_seek(ccfile, APR_END, &offset),
		     "couldn't seek in cache file");
	if ( offset > NX_CONFIG_CACHE_LIMIT )
	{
	    throw_msg("cache file is too large (%d bytes)", offset);
	}
	if ( offset > 0 )
	{
	    nbytes = (apr_size_t) offset;
	    
	    buf = malloc((size_t) offset);

	    // seek back to start
	    offset = 0;
	    CHECKERR_MSG(apr_file_seek(ccfile, APR_SET, &offset),
			 "couldn't seek in cache file");

	    // read cache file into memory
	    if ( (rv = apr_file_read_full(ccfile, buf, nbytes, &bytesread)) != APR_SUCCESS )
	    {
		if ( rv != APR_EOF )
		{
		    CHECKERR_MSG(rv, "failed to read config cache file");
		}
	    }
	    
	    if ( nbytes != bytesread )
	    {
		throw_msg("read %d bytes, wanted %d", (int) bytesread, (int) nbytes);
	    }
	    bytesleft = nbytes;
	    
	    version = nx_value_from_membuf(buf, nbytes, &bytesread);
	    if ( version->type != NX_VALUE_TYPE_STRING )
	    {
		throw_msg("string expected for config cache version");
	    }
	    if ( strcmp(version->string->buf, NX_CONFIG_CACHE_VERSION) != 0 )
	    {
		throw_msg("config cache version mismatch, expected %s, got %s",
			  NX_CONFIG_CACHE_VERSION, version->string->buf);
	    }
	    
	    bytesleft -= bytesread;
	    while ( bytesleft > 0 )
	    {
		_read_item(buf + (nbytes - bytesleft), bytesleft,
			   ctx->config_cache, &bytesread);
		ASSERT(bytesread <= bytesleft);
		bytesleft -= bytesread;
	    }
	}
    }
    catch(e)
    {
	apr_file_close(ccfile);
	apr_file_remove(ctx->ccfilename, NULL);
	if ( buf != NULL )
	{
	    free(buf);
	}
	if ( version != NULL )
	{
	    nx_value_free(version);
	}
	rethrow_msg(e, "failed to read config cache");
    }

    if ( buf != NULL )
    {
	free(buf);
    }
    if ( version != NULL )
    {
	nx_value_free(version);
    }
    apr_file_close(ccfile);
    //apr_file_remove(ctx->ccfilename, NULL);
}
Beispiel #15
0
/**
 * \brief get file content of given tile
 *
 * fills the mapcache_tile::data of the given tile with content stored in the file
 * \private \memberof mapcache_cache_disk
 * \sa mapcache_cache::tile_get()
 */
static int _mapcache_cache_disk_get(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
  char *filename;
  apr_file_t *f;
  apr_finfo_t finfo;
  apr_status_t rv;
  apr_size_t size;
  apr_mmap_t *tilemmap;
  mapcache_cache_disk *cache = (mapcache_cache_disk*)pcache;

  cache->tile_key(ctx, cache, tile, &filename);
  if(GC_HAS_ERROR(ctx)) {
    return MAPCACHE_FAILURE;
  }
  ctx->log(ctx,MAPCACHE_DEBUG,"checking for tile %s",filename);
  if((rv=apr_file_open(&f, filename,
#ifndef NOMMAP
                       APR_FOPEN_READ, APR_UREAD | APR_GREAD,
#else
                       APR_FOPEN_READ|APR_FOPEN_BUFFERED|APR_FOPEN_BINARY,APR_OS_DEFAULT,
#endif
                       ctx->pool)) == APR_SUCCESS) {
    rv = apr_file_info_get(&finfo, APR_FINFO_SIZE|APR_FINFO_MTIME, f);
    if(!finfo.size) {
      ctx->set_error(ctx, 500, "tile %s has no data",filename);
      return MAPCACHE_FAILURE;
    }

    size = finfo.size;
    /*
     * at this stage, we have a handle to an open file that contains data.
     * idealy, we should aquire a read lock, in case the data contained inside the file
     * is incomplete (i.e. if another process is currently writing to the tile).
     * currently such a lock is not set, as we don't want to loose performance on tile accesses.
     * any error that might happen at this stage should only occur if the tile isn't already cached,
     * i.e. normally only once.
     */
    tile->mtime = finfo.mtime;
    tile->encoded_data = mapcache_buffer_create(size,ctx->pool);

#ifndef NOMMAP

    rv = apr_mmap_create(&tilemmap,f,0,finfo.size,APR_MMAP_READ,ctx->pool);
    if(rv != APR_SUCCESS) {
      char errmsg[120];
      ctx->set_error(ctx, 500,  "mmap error: %s",apr_strerror(rv,errmsg,120));
      return MAPCACHE_FAILURE;
    }
    tile->encoded_data->buf = tilemmap->mm;
    tile->encoded_data->size = tile->encoded_data->avail = finfo.size;
#else
    //manually add the data to our buffer
    apr_file_read(f,(void*)tile->encoded_data->buf,&size);
    tile->encoded_data->size = size;
    tile->encoded_data->avail = size;
#endif
    apr_file_close(f);
    if(tile->encoded_data->size != finfo.size) {
      ctx->set_error(ctx, 500,  "failed to copy image data, got %d of %d bytes",(int)size, (int)finfo.size);
      return MAPCACHE_FAILURE;
    }
    return MAPCACHE_SUCCESS;
  } else {
    if(APR_STATUS_IS_ENOENT(rv)) {
      /* the file doesn't exist on the disk */
      return MAPCACHE_CACHE_MISS;
    } else {
      char *error = strerror(rv);
      ctx->set_error(ctx, 500,  "failed to open file %s: %s",filename, error);
      return MAPCACHE_FAILURE;
    }
  }
}
Beispiel #16
0
/* Core implementation of svn_fs_fs__open_pack_or_rev_file working on an
 * existing, initialized FILE structure.  If WRITABLE is TRUE, give write
 * access to the file - temporarily resetting the r/o state if necessary.
 */
static svn_error_t *
open_pack_or_rev_file(svn_fs_x__revision_file_t *file,
                      svn_fs_t *fs,
                      svn_revnum_t rev,
                      svn_boolean_t writable,
                      apr_pool_t *result_pool,
                      apr_pool_t *scratch_pool)
{
  svn_error_t *err;
  svn_boolean_t retry = FALSE;

  do
    {
      const char *path = svn_fs_x__path_rev_absolute(fs, rev, scratch_pool);
      apr_file_t *apr_file;
      apr_int32_t flags = writable
                        ? APR_READ | APR_WRITE | APR_BUFFERED
                        : APR_READ | APR_BUFFERED;

      /* We may have to *temporarily* enable write access. */
      err = writable ? auto_make_writable(path, result_pool, scratch_pool)
                     : SVN_NO_ERROR;

      /* open the revision file in buffered r/o or r/w mode */
      if (!err)
        err = svn_io_file_open(&apr_file, path, flags, APR_OS_DEFAULT,
                               result_pool);

      if (!err)
        {
          file->file = apr_file;
          file->stream = svn_stream_from_aprfile2(apr_file, TRUE,
                                                  result_pool);

          return SVN_NO_ERROR;
        }

      if (err && APR_STATUS_IS_ENOENT(err->apr_err))
        {
          /* Could not open the file. This may happen if the
            * file once existed but got packed later. */
          svn_error_clear(err);

          /* if that was our 2nd attempt, leave it at that. */
          if (retry)
            return svn_error_createf(SVN_ERR_FS_NO_SUCH_REVISION, NULL,
                                     _("No such revision %ld"), rev);

          /* We failed for the first time. Refresh cache & retry. */
          SVN_ERR(svn_fs_x__update_min_unpacked_rev(fs, scratch_pool));
              file->start_revision = svn_fs_x__packed_base_rev(fs, rev);

          retry = TRUE;
        }
      else
        {
          retry = FALSE;
        }
    }
  while (retry);

  return svn_error_trace(err);
}
Beispiel #17
0
svn_error_t *
svn_wc__db_wcroot_parse_local_abspath(svn_wc__db_wcroot_t **wcroot,
                                      const char **local_relpath,
                                      svn_wc__db_t *db,
                                      const char *local_abspath,
                                      apr_pool_t *result_pool,
                                      apr_pool_t *scratch_pool)
{
  const char *local_dir_abspath;
  const char *original_abspath = local_abspath;
  svn_node_kind_t kind;
  const char *build_relpath;
  svn_wc__db_wcroot_t *probe_wcroot;
  svn_wc__db_wcroot_t *found_wcroot = NULL;
  const char *scan_abspath;
  svn_sqlite__db_t *sdb = NULL;
  svn_boolean_t moved_upwards = FALSE;
  svn_boolean_t always_check = FALSE;
  int wc_format = 0;
  const char *adm_relpath;
  /* Non-NULL if WCROOT is found through a symlink: */
  const char *symlink_wcroot_abspath = NULL;

  /* ### we need more logic for finding the database (if it is located
     ### outside of the wcroot) and then managing all of that within DB.
     ### for now: play quick & dirty. */

  probe_wcroot = svn_hash_gets(db->dir_data, local_abspath);
  if (probe_wcroot != NULL)
    {
      *wcroot = probe_wcroot;

      /* We got lucky. Just return the thing BEFORE performing any I/O.  */
      /* ### validate SMODE against how we opened wcroot->sdb? and against
         ### DB->mode? (will we record per-dir mode?)  */

      /* ### for most callers, we could pass NULL for result_pool.  */
      *local_relpath = compute_relpath(probe_wcroot, local_abspath,
                                       result_pool);

      return SVN_NO_ERROR;
    }

  /* ### at some point in the future, we may need to find a way to get
     ### rid of this stat() call. it is going to happen for EVERY call
     ### into wc_db which references a file. calls for directories could
     ### get an early-exit in the hash lookup just above.  */
  SVN_ERR(get_path_kind(&kind, db, local_abspath, scratch_pool));
  if (kind != svn_node_dir)
    {
      /* If the node specified by the path is NOT present, then it cannot
         possibly be a directory containing ".svn/wc.db".

         If it is a file, then it cannot contain ".svn/wc.db".

         For both of these cases, strip the basename off of the path and
         move up one level. Keep record of what we strip, though, since
         we'll need it later to construct local_relpath.  */
      svn_dirent_split(&local_dir_abspath, &build_relpath, local_abspath,
                       scratch_pool);

      /* Is this directory in our hash?  */
      probe_wcroot = svn_hash_gets(db->dir_data, local_dir_abspath);
      if (probe_wcroot != NULL)
        {
          const char *dir_relpath;

          *wcroot = probe_wcroot;

          /* Stashed directory's local_relpath + basename. */
          dir_relpath = compute_relpath(probe_wcroot, local_dir_abspath,
                                        NULL);
          *local_relpath = svn_relpath_join(dir_relpath,
                                            build_relpath,
                                            result_pool);
          return SVN_NO_ERROR;
        }

      /* If the requested path is not on the disk, then we don't know how
         many ancestors need to be scanned until we start hitting content
         on the disk. Set ALWAYS_CHECK to keep looking for .svn/entries
         rather than bailing out after the first check.  */
      if (kind == svn_node_none)
        always_check = TRUE;

      /* Start the scanning at LOCAL_DIR_ABSPATH.  */
      local_abspath = local_dir_abspath;
    }
  else
    {
      /* Start the local_relpath empty. If *this* directory contains the
         wc.db, then relpath will be the empty string.  */
      build_relpath = "";

      /* Remember the dir containing LOCAL_ABSPATH (they're the same).  */
      local_dir_abspath = local_abspath;
    }

  /* LOCAL_ABSPATH refers to a directory at this point. At this point,
     we've determined that an associated WCROOT is NOT in the DB's hash
     table for this directory. Let's find an existing one in the ancestors,
     or create one when we find the actual wcroot.  */

  /* Assume that LOCAL_ABSPATH is a directory, and look for the SQLite
     database in the right place. If we find it... great! If not, then
     peel off some components, and try again. */

  adm_relpath = svn_wc_get_adm_dir(scratch_pool);
  while (TRUE)
    {
      svn_error_t *err;
      svn_node_kind_t adm_subdir_kind;

      const char *adm_subdir = svn_dirent_join(local_abspath, adm_relpath,
                                               scratch_pool);

      SVN_ERR(svn_io_check_path(adm_subdir, &adm_subdir_kind, scratch_pool));

      if (adm_subdir_kind == svn_node_dir)
        {
          /* We always open the database in read/write mode.  If the database
             isn't writable in the filesystem, SQLite will internally open
             it as read-only, and we'll get an error if we try to do a write
             operation.

             We could decide what to do on a per-operation basis, but since
             we're caching database handles, it make sense to be as permissive
             as the filesystem allows. */
          err = svn_wc__db_util_open_db(&sdb, local_abspath, SDB_FILE,
                                        svn_sqlite__mode_readwrite,
                                        db->exclusive, db->timeout, NULL,
                                        db->state_pool, scratch_pool);
          if (err == NULL)
            {
#ifdef SVN_DEBUG
              /* Install self-verification trigger statements. */
              err = svn_sqlite__exec_statements(sdb,
                                                STMT_VERIFICATION_TRIGGERS);
              if (err && err->apr_err == SVN_ERR_SQLITE_ERROR)
                {
                  /* Verification triggers can fail to install on old 1.7-dev
                   * formats which didn't have a NODES table yet. Ignore sqlite
                   * errors so such working copies can be upgraded. */
                  svn_error_clear(err);
                }
              else
                SVN_ERR(err);
#endif
              break;
            }
          if (err->apr_err != SVN_ERR_SQLITE_ERROR
              && !APR_STATUS_IS_ENOENT(err->apr_err))
            return svn_error_trace(err);
          svn_error_clear(err);

          /* If we have not moved upwards, then check for a wc-1 working copy.
             Since wc-1 has a .svn in every directory, and we didn't find one
             in the original directory, then we aren't looking at a wc-1.

             If the original path is not present, then we have to check on every
             iteration. The content may be the immediate parent, or possibly
             five ancetors higher. We don't test for directory presence (just
             for the presence of subdirs/files), so we don't know when we can
             stop checking ... so just check always.  */
          if (!moved_upwards || always_check)
            {
              SVN_ERR(get_old_version(&wc_format, local_abspath,
                                      scratch_pool));
              if (wc_format != 0)
                break;
            }
        }

      /* We couldn't open the SDB within the specified directory, so
         move up one more directory. */
      if (svn_dirent_is_root(local_abspath, strlen(local_abspath)))
        {
          /* Hit the root without finding a wcroot. */

          /* The wcroot could be a symlink to a directory.
           * (Issue #2557, #3987). If so, try again, this time scanning
           * for a db within the directory the symlink points to,
           * rather than within the symlink's parent directory. */
          if (kind == svn_node_symlink)
            {
              svn_node_kind_t resolved_kind;

              local_abspath = original_abspath;

              SVN_ERR(svn_io_check_resolved_path(local_abspath,
                                                 &resolved_kind,
                                                 scratch_pool));
              if (resolved_kind == svn_node_dir)
                {
                  /* Is this directory recorded in our hash?  */
                  found_wcroot = svn_hash_gets(db->dir_data, local_abspath);
                  if (found_wcroot)
                    break;

                  symlink_wcroot_abspath = local_abspath;
                  SVN_ERR(read_link_target(&local_abspath, local_abspath,
                                           scratch_pool));
try_symlink_as_dir:
                  kind = svn_node_dir;
                  moved_upwards = FALSE;
                  local_dir_abspath = local_abspath;
                  build_relpath = "";

                  continue;
                }
            }

          return svn_error_createf(SVN_ERR_WC_NOT_WORKING_COPY, NULL,
                                   _("'%s' is not a working copy"),
                                   svn_dirent_local_style(original_abspath,
                                                          scratch_pool));
        }

      local_abspath = svn_dirent_dirname(local_abspath, scratch_pool);

      moved_upwards = TRUE;
      symlink_wcroot_abspath = NULL;

      /* Is the parent directory recorded in our hash?  */
      found_wcroot = svn_hash_gets(db->dir_data, local_abspath);
      if (found_wcroot != NULL)
        break;
    }

  if (found_wcroot != NULL)
    {
      /* We found a hash table entry for an ancestor, so we stopped scanning
         since all subdirectories use the same WCROOT.  */
      *wcroot = found_wcroot;
    }
  else if (wc_format == 0)
    {
      /* We finally found the database. Construct a wcroot_t for it.  */

      apr_int64_t wc_id;
      int format;
      svn_error_t *err;

      err = fetch_sdb_info(&wc_id, &format, sdb, scratch_pool);
      if (err)
        {
          if (err->apr_err == SVN_ERR_WC_CORRUPT)
            return svn_error_quick_wrapf(
              err, _("Missing a row in WCROOT for '%s'."),
              svn_dirent_local_style(original_abspath, scratch_pool));
          return svn_error_trace(err);
        }

      /* WCROOT.local_abspath may be NULL when the database is stored
         inside the wcroot, but we know the abspath is this directory
         (ie. where we found it).  */

      err = svn_wc__db_pdh_create_wcroot(wcroot,
                            apr_pstrdup(db->state_pool,
                                        symlink_wcroot_abspath
                                          ? symlink_wcroot_abspath
                                          : local_abspath),
                            sdb, wc_id, format,
                            db->verify_format,
                            db->state_pool, scratch_pool);
      if (err && (err->apr_err == SVN_ERR_WC_UNSUPPORTED_FORMAT ||
                  err->apr_err == SVN_ERR_WC_UPGRADE_REQUIRED) &&
          kind == svn_node_symlink)
        {
          /* We found an unsupported WC after traversing upwards from a
           * symlink. Fall through to code below to check if the symlink
           * points at a supported WC. */
          svn_error_clear(err);
          *wcroot = NULL;
        }
      else if (err)
        {
          /* Close handle if we are not going to use it to support
             upgrading with exclusive wc locking. */
          return svn_error_compose_create(err, svn_sqlite__close(sdb));
        }
    }
  else
    {
      /* We found something that looks like a wc-1 working copy directory.
         However, if the format version is 12 and the .svn/entries file
         is only 3 bytes long, then it's a breadcrumb in a wc-ng working
         copy that's missing an .svn/wc.db, or its .svn/wc.db is corrupt. */
      if (wc_format == SVN_WC__WC_NG_VERSION /* 12 */)
        {
          apr_finfo_t info;

          /* Check attributes of .svn/entries */
          const char *admin_abspath = svn_wc__adm_child(
              local_abspath, SVN_WC__ADM_ENTRIES, scratch_pool);
          svn_error_t *err = svn_io_stat(&info, admin_abspath, APR_FINFO_SIZE,
                                         scratch_pool);

          /* If the former does not succeed, something is seriously wrong. */
          if (err)
            return svn_error_createf(
                SVN_ERR_WC_CORRUPT, err,
                _("The working copy at '%s' is corrupt."),
                svn_dirent_local_style(local_abspath, scratch_pool));
          svn_error_clear(err);

          if (3 == info.size)
            {
              /* Check existence of .svn/wc.db */
              admin_abspath = svn_wc__adm_child(local_abspath, SDB_FILE,
                                                scratch_pool);
              err = svn_io_stat(&info, admin_abspath, APR_FINFO_SIZE,
                                scratch_pool);
              if (err && APR_STATUS_IS_ENOENT(err->apr_err))
                {
                  svn_error_clear(err);
                  return svn_error_createf(
                      SVN_ERR_WC_CORRUPT, NULL,
                      _("The working copy database at '%s' is missing."),
                      svn_dirent_local_style(local_abspath, scratch_pool));
                }
              else
                /* We should never have reached this point in the code
                   if .svn/wc.db exists; therefore it's best to assume
                   it's corrupt. */
                return svn_error_createf(
                    SVN_ERR_WC_CORRUPT, err,
                    _("The working copy database at '%s' is corrupt."),
                    svn_dirent_local_style(local_abspath, scratch_pool));
            }
        }

      SVN_ERR(svn_wc__db_pdh_create_wcroot(wcroot,
                            apr_pstrdup(db->state_pool,
                                        symlink_wcroot_abspath
                                          ? symlink_wcroot_abspath
                                          : local_abspath),
                            NULL, UNKNOWN_WC_ID, wc_format,
                            db->verify_format,
                            db->state_pool, scratch_pool));
    }

  if (*wcroot)
    {
      const char *dir_relpath;

      if (symlink_wcroot_abspath)
        {
          /* The WCROOT was found through a symlink pointing at the root of
           * the WC. Cache the WCROOT under the symlink's path. */
          local_dir_abspath = symlink_wcroot_abspath;
        }

      /* The subdirectory's relpath is easily computed relative to the
         wcroot that we just found.  */
      dir_relpath = compute_relpath(*wcroot, local_dir_abspath, NULL);

      /* And the result local_relpath may include a filename.  */
      *local_relpath = svn_relpath_join(dir_relpath, build_relpath, result_pool);
    }

  if (kind == svn_node_symlink)
    {
      svn_boolean_t retry_if_dir = FALSE;
      svn_wc__db_status_t status;
      svn_boolean_t conflicted;
      svn_error_t *err;

      /* Check if the symlink is versioned or obstructs a versioned node
       * in this DB -- in that case, use this wcroot. Else, if the symlink
       * points to a directory, try to find a wcroot in that directory
       * instead. */

      if (*wcroot)
        {
          err = svn_wc__db_read_info_internal(&status, NULL, NULL, NULL, NULL,
                                              NULL, NULL, NULL, NULL, NULL,
                                              NULL, NULL, NULL, NULL, NULL,
                                              NULL, NULL, NULL, &conflicted,
                                              NULL, NULL, NULL, NULL, NULL,
                                              NULL, *wcroot, *local_relpath,
                                              scratch_pool, scratch_pool);
          if (err)
            {
              if (err->apr_err != SVN_ERR_WC_PATH_NOT_FOUND
                  && !SVN_WC__ERR_IS_NOT_CURRENT_WC(err))
                return svn_error_trace(err);

              svn_error_clear(err);
              retry_if_dir = TRUE; /* The symlink is unversioned. */
            }
          else
            {
              /* The symlink is versioned, or obstructs a versioned node.
               * Ignore non-conflicted not-present/excluded nodes.
               * This allows the symlink to redirect the wcroot query to a
               * directory, regardless of 'invisible' nodes in this WC. */
              retry_if_dir = ((status == svn_wc__db_status_not_present ||
                               status == svn_wc__db_status_excluded ||
                               status == svn_wc__db_status_server_excluded)
                              && !conflicted);
            }
        }
      else
        retry_if_dir = TRUE;

      if (retry_if_dir)
        {
          svn_node_kind_t resolved_kind;

          SVN_ERR(svn_io_check_resolved_path(original_abspath,
                                             &resolved_kind,
                                             scratch_pool));
          if (resolved_kind == svn_node_dir)
            {
              symlink_wcroot_abspath = original_abspath;
              SVN_ERR(read_link_target(&local_abspath, original_abspath,
                                       scratch_pool));
              /* This handle was opened in this function but is not going
                 to be used further so close it. */
              if (sdb)
                SVN_ERR(svn_sqlite__close(sdb));
              goto try_symlink_as_dir;
            }
        }
    }

  /* We've found the appropriate WCROOT for the requested path. Stash
     it into that path's directory.  */
  svn_hash_sets(db->dir_data,
                apr_pstrdup(db->state_pool, local_dir_abspath),
                *wcroot);

  /* Did we traverse up to parent directories?  */
  if (!moved_upwards)
    {
      /* We did NOT move to a parent of the original requested directory.
         We've constructed and filled in a WCROOT for the request, so we
         are done.  */
      return SVN_NO_ERROR;
    }

  /* The WCROOT that we just found/built was for the LOCAL_ABSPATH originally
     passed into this function. We stepped *at least* one directory above that.
     We should now associate the WROOT for each parent directory that does
     not (yet) have one.  */

  scan_abspath = local_dir_abspath;

  do
    {
      const char *parent_dir = svn_dirent_dirname(scan_abspath, scratch_pool);
      svn_wc__db_wcroot_t *parent_wcroot;

      parent_wcroot = svn_hash_gets(db->dir_data, parent_dir);
      if (parent_wcroot == NULL)
        {
          svn_hash_sets(db->dir_data, apr_pstrdup(db->state_pool, parent_dir),
                        *wcroot);
        }

      /* Move up a directory, stopping when we reach the directory where
         we found/built the WCROOT.  */
      scan_abspath = parent_dir;
    }
  while (strcmp(scan_abspath, local_abspath) != 0);

  return SVN_NO_ERROR;
}
Beispiel #18
0
/* Perform a hotcopy, either normal or incremental.
 *
 * Normal hotcopy assumes that the destination exists as an empty
 * directory. It behaves like an incremental hotcopy except that
 * none of the copied files already exist in the destination.
 *
 * An incremental hotcopy copies only changed or new files to the destination,
 * and removes files from the destination no longer present in the source.
 * While the incremental hotcopy is running, readers should still be able
 * to access the destintation repository without error and should not see
 * revisions currently in progress of being copied. Readers are able to see
 * new fully copied revisions even if the entire incremental hotcopy procedure
 * has not yet completed.
 *
 * Writers are blocked out completely during the entire incremental hotcopy
 * process to ensure consistency. This function assumes that the repository
 * write-lock is held.
 */
static svn_error_t *
hotcopy_body(void *baton, apr_pool_t *pool)
{
  struct hotcopy_body_baton *hbb = baton;
  svn_fs_t *src_fs = hbb->src_fs;
  fs_fs_data_t *src_ffd = src_fs->fsap_data;
  svn_fs_t *dst_fs = hbb->dst_fs;
  fs_fs_data_t *dst_ffd = dst_fs->fsap_data;
  svn_boolean_t incremental = hbb->incremental;
  svn_fs_hotcopy_notify_t notify_func = hbb->notify_func;
  void* notify_baton = hbb->notify_baton;
  svn_cancel_func_t cancel_func = hbb->cancel_func;
  void* cancel_baton = hbb->cancel_baton;
  svn_revnum_t src_youngest;
  apr_uint64_t src_next_node_id;
  apr_uint64_t src_next_copy_id;
  svn_revnum_t dst_youngest;
  const char *src_revprops_dir;
  const char *dst_revprops_dir;
  const char *src_revs_dir;
  const char *dst_revs_dir;
  const char *src_subdir;
  const char *dst_subdir;
  svn_node_kind_t kind;

  /* Try to copy the config.
   *
   * ### We try copying the config file before doing anything else,
   * ### because higher layers will abort the hotcopy if we throw
   * ### an error from this function, and that renders the hotcopy
   * ### unusable anyway. */
  if (src_ffd->format >= SVN_FS_FS__MIN_CONFIG_FILE)
    {
      svn_error_t *err;

      err = svn_io_dir_file_copy(src_fs->path, dst_fs->path, PATH_CONFIG,
                                 pool);
      if (err)
        {
          if (APR_STATUS_IS_ENOENT(err->apr_err))
            {
              /* 1.6.0 to 1.6.11 did not copy the configuration file during
               * hotcopy. So if we're hotcopying a repository which has been
               * created as a hotcopy itself, it's possible that fsfs.conf
               * does not exist. Ask the user to re-create it.
               *
               * ### It would be nice to make this a non-fatal error,
               * ### but this function does not get an svn_fs_t object
               * ### so we have no way of just printing a warning via
               * ### the fs->warning() callback. */

              const char *src_abspath;
              const char *dst_abspath;
              const char *config_relpath;
              svn_error_t *err2;

              config_relpath = svn_dirent_join(src_fs->path, PATH_CONFIG, pool);
              err2 = svn_dirent_get_absolute(&src_abspath, src_fs->path, pool);
              if (err2)
                return svn_error_trace(svn_error_compose_create(err, err2));
              err2 = svn_dirent_get_absolute(&dst_abspath, dst_fs->path, pool);
              if (err2)
                return svn_error_trace(svn_error_compose_create(err, err2));

              /* ### hack: strip off the 'db/' directory from paths so
               * ### they make sense to the user */
              src_abspath = svn_dirent_dirname(src_abspath, pool);
              dst_abspath = svn_dirent_dirname(dst_abspath, pool);

              return svn_error_quick_wrapf(err,
                                 _("Failed to create hotcopy at '%s'. "
                                   "The file '%s' is missing from the source "
                                   "repository. Please create this file, for "
                                   "instance by running 'svnadmin upgrade %s'"),
                                 dst_abspath, config_relpath, src_abspath);
            }
          else
            return svn_error_trace(err);
        }
    }

  if (cancel_func)
    SVN_ERR(cancel_func(cancel_baton));

  /* Find the youngest revision in the source and destination.
   * We only support hotcopies from sources with an equal or greater amount
   * of revisions than the destination.
   * This also catches the case where users accidentally swap the
   * source and destination arguments. */
  SVN_ERR(svn_fs_fs__read_current(&src_youngest, &src_next_node_id,
                                  &src_next_copy_id, src_fs, pool));
  if (incremental)
    {
      SVN_ERR(svn_fs_fs__youngest_rev(&dst_youngest, dst_fs, pool));
      if (src_youngest < dst_youngest)
        return svn_error_createf(SVN_ERR_UNSUPPORTED_FEATURE, NULL,
                 _("The hotcopy destination already contains more revisions "
                   "(%lu) than the hotcopy source contains (%lu); are source "
                   "and destination swapped?"),
                   dst_youngest, src_youngest);
    }
  else
    dst_youngest = 0;

  src_revs_dir = svn_dirent_join(src_fs->path, PATH_REVS_DIR, pool);
  dst_revs_dir = svn_dirent_join(dst_fs->path, PATH_REVS_DIR, pool);
  src_revprops_dir = svn_dirent_join(src_fs->path, PATH_REVPROPS_DIR, pool);
  dst_revprops_dir = svn_dirent_join(dst_fs->path, PATH_REVPROPS_DIR, pool);

  /* Ensure that the required folders exist in the destination
   * before actually copying the revisions and revprops. */
  SVN_ERR(svn_io_make_dir_recursively(dst_revs_dir, pool));
  SVN_ERR(svn_io_make_dir_recursively(dst_revprops_dir, pool));

  if (cancel_func)
    SVN_ERR(cancel_func(cancel_baton));

  /* Split the logic for new and old FS formats. The latter is much simpler
   * due to the absense of sharding and packing. However, it requires special
   * care when updating the 'current' file (which contains not just the
   * revision number, but also the next-ID counters). */
  if (src_ffd->format >= SVN_FS_FS__MIN_NO_GLOBAL_IDS_FORMAT)
    {
      SVN_ERR(hotcopy_revisions(src_fs, dst_fs, src_youngest, dst_youngest,
                                incremental, src_revs_dir, dst_revs_dir,
                                src_revprops_dir, dst_revprops_dir,
                                notify_func, notify_baton,
                                cancel_func, cancel_baton, pool));
      SVN_ERR(svn_fs_fs__write_current(dst_fs, src_youngest, 0, 0, pool));
    }
  else
    {
      SVN_ERR(hotcopy_revisions_old(src_fs, dst_fs, src_youngest,
                                    src_revs_dir, dst_revs_dir,
                                    src_revprops_dir, dst_revprops_dir,
                                    notify_func, notify_baton,
                                    cancel_func, cancel_baton, pool));
      SVN_ERR(svn_fs_fs__write_current(dst_fs, src_youngest, src_next_node_id,
                                       src_next_copy_id, pool));
    }

  /* Replace the locks tree.
   * This is racy in case readers are currently trying to list locks in
   * the destination. However, we need to get rid of stale locks.
   * This is the simplest way of doing this, so we accept this small race. */
  dst_subdir = svn_dirent_join(dst_fs->path, PATH_LOCKS_DIR, pool);
  SVN_ERR(svn_io_remove_dir2(dst_subdir, TRUE, cancel_func, cancel_baton,
                             pool));
  src_subdir = svn_dirent_join(src_fs->path, PATH_LOCKS_DIR, pool);
  SVN_ERR(svn_io_check_path(src_subdir, &kind, pool));
  if (kind == svn_node_dir)
    SVN_ERR(svn_io_copy_dir_recursively(src_subdir, dst_fs->path,
                                        PATH_LOCKS_DIR, TRUE,
                                        cancel_func, cancel_baton, pool));

  /* Now copy the node-origins cache tree. */
  src_subdir = svn_dirent_join(src_fs->path, PATH_NODE_ORIGINS_DIR, pool);
  SVN_ERR(svn_io_check_path(src_subdir, &kind, pool));
  if (kind == svn_node_dir)
    SVN_ERR(hotcopy_io_copy_dir_recursively(NULL, src_subdir, dst_fs->path,
                                            PATH_NODE_ORIGINS_DIR, TRUE,
                                            cancel_func, cancel_baton, pool));

  /*
   * NB: Data copied below is only read by writers, not readers.
   *     Writers are still locked out at this point.
   */

  if (dst_ffd->format >= SVN_FS_FS__MIN_REP_SHARING_FORMAT)
    {
      /* Copy the rep cache and then remove entries for revisions
       * that did not make it into the destination. */
      src_subdir = svn_dirent_join(src_fs->path, REP_CACHE_DB_NAME, pool);
      dst_subdir = svn_dirent_join(dst_fs->path, REP_CACHE_DB_NAME, pool);
      SVN_ERR(svn_io_check_path(src_subdir, &kind, pool));
      if (kind == svn_node_file)
        {
          SVN_ERR(svn_sqlite__hotcopy(src_subdir, dst_subdir, pool));

          /* The source might have r/o flags set on it - which would be
             carried over to the copy. */
          SVN_ERR(svn_io_set_file_read_write(dst_subdir, FALSE, pool));
          SVN_ERR(svn_fs_fs__del_rep_reference(dst_fs, src_youngest, pool));
        }
    }

  /* Copy the txn-current file. */
  if (dst_ffd->format >= SVN_FS_FS__MIN_TXN_CURRENT_FORMAT)
    SVN_ERR(svn_io_dir_file_copy(src_fs->path, dst_fs->path,
                                 PATH_TXN_CURRENT, pool));

  return SVN_NO_ERROR;
}
Beispiel #19
0
/* Like svn_io_copy_dir_recursively() but doesn't copy regular files that
 * exist in the destination and do not differ from the source in terms of
 * kind, size, and mtime. Set *SKIPPED_P to FALSE only if at least one
 * file was copied, do not change the value in *SKIPPED_P otherwise.
 * SKIPPED_P may be NULL if not required. */
static svn_error_t *
hotcopy_io_copy_dir_recursively(svn_boolean_t *skipped_p,
                                const char *src,
                                const char *dst_parent,
                                const char *dst_basename,
                                svn_boolean_t copy_perms,
                                svn_cancel_func_t cancel_func,
                                void *cancel_baton,
                                apr_pool_t *pool)
{
  svn_node_kind_t kind;
  apr_status_t status;
  const char *dst_path;
  apr_dir_t *this_dir;
  apr_finfo_t this_entry;
  apr_int32_t flags = APR_FINFO_TYPE | APR_FINFO_NAME;

  /* Make a subpool for recursion */
  apr_pool_t *subpool = svn_pool_create(pool);

  /* The 'dst_path' is simply dst_parent/dst_basename */
  dst_path = svn_dirent_join(dst_parent, dst_basename, pool);

  /* Sanity checks:  SRC and DST_PARENT are directories, and
     DST_BASENAME doesn't already exist in DST_PARENT. */
  SVN_ERR(svn_io_check_path(src, &kind, subpool));
  if (kind != svn_node_dir)
    return svn_error_createf(SVN_ERR_NODE_UNEXPECTED_KIND, NULL,
                             _("Source '%s' is not a directory"),
                             svn_dirent_local_style(src, pool));

  SVN_ERR(svn_io_check_path(dst_parent, &kind, subpool));
  if (kind != svn_node_dir)
    return svn_error_createf(SVN_ERR_NODE_UNEXPECTED_KIND, NULL,
                             _("Destination '%s' is not a directory"),
                             svn_dirent_local_style(dst_parent, pool));

  SVN_ERR(svn_io_check_path(dst_path, &kind, subpool));

  /* Create the new directory. */
  /* ### TODO: copy permissions (needs apr_file_attrs_get()) */
  SVN_ERR(svn_io_make_dir_recursively(dst_path, pool));

  /* Loop over the dirents in SRC.  ('.' and '..' are auto-excluded) */
  SVN_ERR(svn_io_dir_open(&this_dir, src, subpool));

  for (status = apr_dir_read(&this_entry, flags, this_dir);
       status == APR_SUCCESS;
       status = apr_dir_read(&this_entry, flags, this_dir))
    {
      if ((this_entry.name[0] == '.')
          && ((this_entry.name[1] == '\0')
              || ((this_entry.name[1] == '.')
                  && (this_entry.name[2] == '\0'))))
        {
          continue;
        }
      else
        {
          const char *entryname_utf8;

          if (cancel_func)
            SVN_ERR(cancel_func(cancel_baton));

          SVN_ERR(entry_name_to_utf8(&entryname_utf8, this_entry.name,
                                     src, subpool));
          if (this_entry.filetype == APR_REG) /* regular file */
            {
              SVN_ERR(hotcopy_io_dir_file_copy(skipped_p, src, dst_path,
                                               entryname_utf8, subpool));
            }
          else if (this_entry.filetype == APR_LNK) /* symlink */
            {
              const char *src_target = svn_dirent_join(src, entryname_utf8,
                                                       subpool);
              const char *dst_target = svn_dirent_join(dst_path,
                                                       entryname_utf8,
                                                       subpool);
              SVN_ERR(svn_io_copy_link(src_target, dst_target,
                                       subpool));
            }
          else if (this_entry.filetype == APR_DIR) /* recurse */
            {
              const char *src_target;

              /* Prevent infinite recursion by filtering off our
                 newly created destination path. */
              if (strcmp(src, dst_parent) == 0
                  && strcmp(entryname_utf8, dst_basename) == 0)
                continue;

              src_target = svn_dirent_join(src, entryname_utf8, subpool);
              SVN_ERR(hotcopy_io_copy_dir_recursively(skipped_p,
                                                      src_target,
                                                      dst_path,
                                                      entryname_utf8,
                                                      copy_perms,
                                                      cancel_func,
                                                      cancel_baton,
                                                      subpool));
            }
          /* ### support other APR node types someday?? */

        }
    }

  if (! (APR_STATUS_IS_ENOENT(status)))
    return svn_error_wrap_apr(status, _("Can't read directory '%s'"),
                              svn_dirent_local_style(src, pool));

  status = apr_dir_close(this_dir);
  if (status)
    return svn_error_wrap_apr(status, _("Error closing directory '%s'"),
                              svn_dirent_local_style(src, pool));

  /* Free any memory used by recursion */
  svn_pool_destroy(subpool);

  return SVN_NO_ERROR;
}
Beispiel #20
0
void status_to_name(lua_State *L, apr_status_t status)
{
  /* Use a switch statement for fast number to string mapping: */
  switch (status) {
#   ifdef APR_ANONYMOUS
    case APR_ANONYMOUS:
      lua_pushliteral(L, "ANONYMOUS");
      return;
#   endif
#   ifdef APR_BADARG
    case APR_BADARG:
      lua_pushliteral(L, "BADARG");
      return;
#   endif
#   ifdef APR_BADCH
    case APR_BADCH:
      lua_pushliteral(L, "BADCH");
      return;
#   endif
#   ifdef APR_DETACH
    case APR_DETACH:
      lua_pushliteral(L, "DETACH");
      return;
#   endif
#   ifdef APR_EABOVEROOT
    case APR_EABOVEROOT:
      lua_pushliteral(L, "EABOVEROOT");
      return;
#   endif
#   ifdef APR_EABSOLUTE
    case APR_EABSOLUTE:
      lua_pushliteral(L, "EABSOLUTE");
      return;
#   endif
#   ifdef APR_EACCES
    case APR_EACCES:
      lua_pushliteral(L, "EACCES");
      return;
#   endif
#   ifdef APR_EAFNOSUPPORT
    case APR_EAFNOSUPPORT:
      lua_pushliteral(L, "EAFNOSUPPORT");
      return;
#   endif
#   ifdef APR_EAGAIN
    case APR_EAGAIN:
      lua_pushliteral(L, "EAGAIN");
      return;
#   endif
#   ifdef APR_EBADDATE
    case APR_EBADDATE:
      lua_pushliteral(L, "EBADDATE");
      return;
#   endif
#   ifdef APR_EBADF
    case APR_EBADF:
      lua_pushliteral(L, "EBADF");
      return;
#   endif
#   ifdef APR_EBADIP
    case APR_EBADIP:
      lua_pushliteral(L, "EBADIP");
      return;
#   endif
#   ifdef APR_EBADMASK
    case APR_EBADMASK:
      lua_pushliteral(L, "EBADMASK");
      return;
#   endif
#   ifdef APR_EBADPATH
    case APR_EBADPATH:
      lua_pushliteral(L, "EBADPATH");
      return;
#   endif
#   ifdef APR_EBUSY
    case APR_EBUSY:
      lua_pushliteral(L, "EBUSY");
      return;
#   endif
#   ifdef APR_ECONNABORTED
    case APR_ECONNABORTED:
      lua_pushliteral(L, "ECONNABORTED");
      return;
#   endif
#   ifdef APR_ECONNREFUSED
    case APR_ECONNREFUSED:
      lua_pushliteral(L, "ECONNREFUSED");
      return;
#   endif
#   ifdef APR_ECONNRESET
    case APR_ECONNRESET:
      lua_pushliteral(L, "ECONNRESET");
      return;
#   endif
#   ifdef APR_EDSOOPEN
    case APR_EDSOOPEN:
      lua_pushliteral(L, "EDSOOPEN");
      return;
#   endif
#   ifdef APR_EEXIST
    case APR_EEXIST:
      lua_pushliteral(L, "EEXIST");
      return;
#   endif
#   ifdef APR_EFTYPE
    case APR_EFTYPE:
      lua_pushliteral(L, "EFTYPE");
      return;
#   endif
#   ifdef APR_EGENERAL
    case APR_EGENERAL:
      lua_pushliteral(L, "EGENERAL");
      return;
#   endif
#   ifdef APR_EHOSTUNREACH
    case APR_EHOSTUNREACH:
      lua_pushliteral(L, "EHOSTUNREACH");
      return;
#   endif
#   ifdef APR_EINCOMPLETE
    case APR_EINCOMPLETE:
      lua_pushliteral(L, "EINCOMPLETE");
      return;
#   endif
#   ifdef APR_EINIT
    case APR_EINIT:
      lua_pushliteral(L, "EINIT");
      return;
#   endif
#   ifdef APR_EINPROGRESS
    case APR_EINPROGRESS:
      lua_pushliteral(L, "EINPROGRESS");
      return;
#   endif
#   ifdef APR_EINTR
    case APR_EINTR:
      lua_pushliteral(L, "EINTR");
      return;
#   endif
#   ifdef APR_EINVAL
    case APR_EINVAL:
      lua_pushliteral(L, "EINVAL");
      return;
#   endif
#   ifdef APR_EINVALSOCK
    case APR_EINVALSOCK:
      lua_pushliteral(L, "EINVALSOCK");
      return;
#   endif
#   ifdef APR_EMFILE
    case APR_EMFILE:
      lua_pushliteral(L, "EMFILE");
      return;
#   endif
#   ifdef APR_EMISMATCH
    case APR_EMISMATCH:
      lua_pushliteral(L, "EMISMATCH");
      return;
#   endif
#   ifdef APR_ENAMETOOLONG
    case APR_ENAMETOOLONG:
      lua_pushliteral(L, "ENAMETOOLONG");
      return;
#   endif
#   ifdef APR_ENETUNREACH
    case APR_ENETUNREACH:
      lua_pushliteral(L, "ENETUNREACH");
      return;
#   endif
#   ifdef APR_ENFILE
    case APR_ENFILE:
      lua_pushliteral(L, "ENFILE");
      return;
#   endif
#   ifdef APR_ENODIR
    case APR_ENODIR:
      lua_pushliteral(L, "ENODIR");
      return;
#   endif
#   ifdef APR_ENOENT
    case APR_ENOENT:
      lua_pushliteral(L, "ENOENT");
      return;
#   endif
#   ifdef APR_ENOLOCK
    case APR_ENOLOCK:
      lua_pushliteral(L, "ENOLOCK");
      return;
#   endif
#   ifdef APR_ENOMEM
    case APR_ENOMEM:
      lua_pushliteral(L, "ENOMEM");
      return;
#   endif
#   ifdef APR_ENOPOLL
    case APR_ENOPOLL:
      lua_pushliteral(L, "ENOPOLL");
      return;
#   endif
#   ifdef APR_ENOPOOL
    case APR_ENOPOOL:
      lua_pushliteral(L, "ENOPOOL");
      return;
#   endif
#   ifdef APR_ENOPROC
    case APR_ENOPROC:
      lua_pushliteral(L, "ENOPROC");
      return;
#   endif
#   ifdef APR_ENOSHMAVAIL
    case APR_ENOSHMAVAIL:
      lua_pushliteral(L, "ENOSHMAVAIL");
      return;
#   endif
#   ifdef APR_ENOSOCKET
    case APR_ENOSOCKET:
      lua_pushliteral(L, "ENOSOCKET");
      return;
#   endif
#   ifdef APR_ENOSPC
    case APR_ENOSPC:
      lua_pushliteral(L, "ENOSPC");
      return;
#   endif
#   ifdef APR_ENOSTAT
    case APR_ENOSTAT:
      lua_pushliteral(L, "ENOSTAT");
      return;
#   endif
#   ifdef APR_ENOTDIR
    case APR_ENOTDIR:
      lua_pushliteral(L, "ENOTDIR");
      return;
#   endif
#   ifdef APR_ENOTEMPTY
    case APR_ENOTEMPTY:
      lua_pushliteral(L, "ENOTEMPTY");
      return;
#   endif
#   ifdef APR_ENOTENOUGHENTROPY
    case APR_ENOTENOUGHENTROPY:
      lua_pushliteral(L, "ENOTENOUGHENTROPY");
      return;
#   endif
#   ifdef APR_ENOTHDKEY
    case APR_ENOTHDKEY:
      lua_pushliteral(L, "ENOTHDKEY");
      return;
#   endif
#   ifdef APR_ENOTHREAD
    case APR_ENOTHREAD:
      lua_pushliteral(L, "ENOTHREAD");
      return;
#   endif
#   ifdef APR_ENOTIME
    case APR_ENOTIME:
      lua_pushliteral(L, "ENOTIME");
      return;
#   endif
#   ifdef APR_ENOTIMPL
    case APR_ENOTIMPL:
      lua_pushliteral(L, "ENOTIMPL");
      return;
#   endif
#   ifdef APR_ENOTSOCK
    case APR_ENOTSOCK:
      lua_pushliteral(L, "ENOTSOCK");
      return;
#   endif
#   ifdef APR_EOF
    case APR_EOF:
      lua_pushliteral(L, "EOF");
      return;
#   endif
#   ifdef APR_EPATHWILD
    case APR_EPATHWILD:
      lua_pushliteral(L, "EPATHWILD");
      return;
#   endif
#   ifdef APR_EPIPE
    case APR_EPIPE:
      lua_pushliteral(L, "EPIPE");
      return;
#   endif
#   ifdef APR_EPROC_UNKNOWN
    case APR_EPROC_UNKNOWN:
      lua_pushliteral(L, "EPROC_UNKNOWN");
      return;
#   endif
#   ifdef APR_ERELATIVE
    case APR_ERELATIVE:
      lua_pushliteral(L, "ERELATIVE");
      return;
#   endif
#   ifdef APR_ESPIPE
    case APR_ESPIPE:
      lua_pushliteral(L, "ESPIPE");
      return;
#   endif
#   ifdef APR_ESYMNOTFOUND
    case APR_ESYMNOTFOUND:
      lua_pushliteral(L, "ESYMNOTFOUND");
      return;
#   endif
#   ifdef APR_ETIMEDOUT
    case APR_ETIMEDOUT:
      lua_pushliteral(L, "ETIMEDOUT");
      return;
#   endif
#   ifdef APR_EXDEV
    case APR_EXDEV:
      lua_pushliteral(L, "EXDEV");
      return;
#   endif
#   ifdef APR_FILEBASED
    case APR_FILEBASED:
      lua_pushliteral(L, "FILEBASED");
      return;
#   endif
#   ifdef APR_INCHILD
    case APR_INCHILD:
      lua_pushliteral(L, "INCHILD");
      return;
#   endif
#   ifdef APR_INCOMPLETE
    case APR_INCOMPLETE:
      lua_pushliteral(L, "INCOMPLETE");
      return;
#   endif
#   ifdef APR_INPARENT
    case APR_INPARENT:
      lua_pushliteral(L, "INPARENT");
      return;
#   endif
#   ifdef APR_KEYBASED
    case APR_KEYBASED:
      lua_pushliteral(L, "KEYBASED");
      return;
#   endif
#   ifdef APR_NOTDETACH
    case APR_NOTDETACH:
      lua_pushliteral(L, "NOTDETACH");
      return;
#   endif
#   ifdef APR_NOTFOUND
    case APR_NOTFOUND:
      lua_pushliteral(L, "NOTFOUND");
      return;
#   endif
#   ifdef APR_SUCCESS
    case APR_SUCCESS:
      lua_pushliteral(L, "SUCCESS");
      return;
#   endif
#   ifdef APR_TIMEUP
    case APR_TIMEUP:
      lua_pushliteral(L, "TIMEUP");
      return;
#   endif
  }

  /* If the switch statement fails we fall back to the following monstrosity :-) */
  if (0) ;
# ifdef APR_STATUS_IS_ANONYMOUS
  else if (APR_STATUS_IS_ANONYMOUS(status)) {
    lua_pushliteral(L, "ANONYMOUS");
    return;
  }
# endif
# ifdef APR_STATUS_IS_BADARG
  else if (APR_STATUS_IS_BADARG(status)) {
    lua_pushliteral(L, "BADARG");
    return;
  }
# endif
# ifdef APR_STATUS_IS_BADCH
  else if (APR_STATUS_IS_BADCH(status)) {
    lua_pushliteral(L, "BADCH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_DETACH
  else if (APR_STATUS_IS_DETACH(status)) {
    lua_pushliteral(L, "DETACH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EABOVEROOT
  else if (APR_STATUS_IS_EABOVEROOT(status)) {
    lua_pushliteral(L, "EABOVEROOT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EABSOLUTE
  else if (APR_STATUS_IS_EABSOLUTE(status)) {
    lua_pushliteral(L, "EABSOLUTE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EACCES
  else if (APR_STATUS_IS_EACCES(status)) {
    lua_pushliteral(L, "EACCES");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EAFNOSUPPORT
  else if (APR_STATUS_IS_EAFNOSUPPORT(status)) {
    lua_pushliteral(L, "EAFNOSUPPORT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EAGAIN
  else if (APR_STATUS_IS_EAGAIN(status)) {
    lua_pushliteral(L, "EAGAIN");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EBADDATE
  else if (APR_STATUS_IS_EBADDATE(status)) {
    lua_pushliteral(L, "EBADDATE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EBADF
  else if (APR_STATUS_IS_EBADF(status)) {
    lua_pushliteral(L, "EBADF");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EBADIP
  else if (APR_STATUS_IS_EBADIP(status)) {
    lua_pushliteral(L, "EBADIP");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EBADMASK
  else if (APR_STATUS_IS_EBADMASK(status)) {
    lua_pushliteral(L, "EBADMASK");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EBADPATH
  else if (APR_STATUS_IS_EBADPATH(status)) {
    lua_pushliteral(L, "EBADPATH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EBUSY
  else if (APR_STATUS_IS_EBUSY(status)) {
    lua_pushliteral(L, "EBUSY");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ECONNABORTED
  else if (APR_STATUS_IS_ECONNABORTED(status)) {
    lua_pushliteral(L, "ECONNABORTED");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ECONNREFUSED
  else if (APR_STATUS_IS_ECONNREFUSED(status)) {
    lua_pushliteral(L, "ECONNREFUSED");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ECONNRESET
  else if (APR_STATUS_IS_ECONNRESET(status)) {
    lua_pushliteral(L, "ECONNRESET");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EDSOOPEN
  else if (APR_STATUS_IS_EDSOOPEN(status)) {
    lua_pushliteral(L, "EDSOOPEN");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EEXIST
  else if (APR_STATUS_IS_EEXIST(status)) {
    lua_pushliteral(L, "EEXIST");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EFTYPE
  else if (APR_STATUS_IS_EFTYPE(status)) {
    lua_pushliteral(L, "EFTYPE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EGENERAL
  else if (APR_STATUS_IS_EGENERAL(status)) {
    lua_pushliteral(L, "EGENERAL");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EHOSTUNREACH
  else if (APR_STATUS_IS_EHOSTUNREACH(status)) {
    lua_pushliteral(L, "EHOSTUNREACH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EINCOMPLETE
  else if (APR_STATUS_IS_EINCOMPLETE(status)) {
    lua_pushliteral(L, "EINCOMPLETE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EINIT
  else if (APR_STATUS_IS_EINIT(status)) {
    lua_pushliteral(L, "EINIT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EINPROGRESS
  else if (APR_STATUS_IS_EINPROGRESS(status)) {
    lua_pushliteral(L, "EINPROGRESS");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EINTR
  else if (APR_STATUS_IS_EINTR(status)) {
    lua_pushliteral(L, "EINTR");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EINVAL
  else if (APR_STATUS_IS_EINVAL(status)) {
    lua_pushliteral(L, "EINVAL");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EINVALSOCK
  else if (APR_STATUS_IS_EINVALSOCK(status)) {
    lua_pushliteral(L, "EINVALSOCK");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EMFILE
  else if (APR_STATUS_IS_EMFILE(status)) {
    lua_pushliteral(L, "EMFILE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EMISMATCH
  else if (APR_STATUS_IS_EMISMATCH(status)) {
    lua_pushliteral(L, "EMISMATCH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENAMETOOLONG
  else if (APR_STATUS_IS_ENAMETOOLONG(status)) {
    lua_pushliteral(L, "ENAMETOOLONG");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENETUNREACH
  else if (APR_STATUS_IS_ENETUNREACH(status)) {
    lua_pushliteral(L, "ENETUNREACH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENFILE
  else if (APR_STATUS_IS_ENFILE(status)) {
    lua_pushliteral(L, "ENFILE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENODIR
  else if (APR_STATUS_IS_ENODIR(status)) {
    lua_pushliteral(L, "ENODIR");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOENT
  else if (APR_STATUS_IS_ENOENT(status)) {
    lua_pushliteral(L, "ENOENT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOLOCK
  else if (APR_STATUS_IS_ENOLOCK(status)) {
    lua_pushliteral(L, "ENOLOCK");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOMEM
  else if (APR_STATUS_IS_ENOMEM(status)) {
    lua_pushliteral(L, "ENOMEM");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOPOLL
  else if (APR_STATUS_IS_ENOPOLL(status)) {
    lua_pushliteral(L, "ENOPOLL");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOPOOL
  else if (APR_STATUS_IS_ENOPOOL(status)) {
    lua_pushliteral(L, "ENOPOOL");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOPROC
  else if (APR_STATUS_IS_ENOPROC(status)) {
    lua_pushliteral(L, "ENOPROC");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOSHMAVAIL
  else if (APR_STATUS_IS_ENOSHMAVAIL(status)) {
    lua_pushliteral(L, "ENOSHMAVAIL");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOSOCKET
  else if (APR_STATUS_IS_ENOSOCKET(status)) {
    lua_pushliteral(L, "ENOSOCKET");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOSPC
  else if (APR_STATUS_IS_ENOSPC(status)) {
    lua_pushliteral(L, "ENOSPC");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOSTAT
  else if (APR_STATUS_IS_ENOSTAT(status)) {
    lua_pushliteral(L, "ENOSTAT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTDIR
  else if (APR_STATUS_IS_ENOTDIR(status)) {
    lua_pushliteral(L, "ENOTDIR");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTEMPTY
  else if (APR_STATUS_IS_ENOTEMPTY(status)) {
    lua_pushliteral(L, "ENOTEMPTY");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTENOUGHENTROPY
  else if (APR_STATUS_IS_ENOTENOUGHENTROPY(status)) {
    lua_pushliteral(L, "ENOTENOUGHENTROPY");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTHDKEY
  else if (APR_STATUS_IS_ENOTHDKEY(status)) {
    lua_pushliteral(L, "ENOTHDKEY");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTHREAD
  else if (APR_STATUS_IS_ENOTHREAD(status)) {
    lua_pushliteral(L, "ENOTHREAD");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTIME
  else if (APR_STATUS_IS_ENOTIME(status)) {
    lua_pushliteral(L, "ENOTIME");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTIMPL
  else if (APR_STATUS_IS_ENOTIMPL(status)) {
    lua_pushliteral(L, "ENOTIMPL");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ENOTSOCK
  else if (APR_STATUS_IS_ENOTSOCK(status)) {
    lua_pushliteral(L, "ENOTSOCK");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EOF
  else if (APR_STATUS_IS_EOF(status)) {
    lua_pushliteral(L, "EOF");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EPATHWILD
  else if (APR_STATUS_IS_EPATHWILD(status)) {
    lua_pushliteral(L, "EPATHWILD");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EPIPE
  else if (APR_STATUS_IS_EPIPE(status)) {
    lua_pushliteral(L, "EPIPE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EPROC_UNKNOWN
  else if (APR_STATUS_IS_EPROC_UNKNOWN(status)) {
    lua_pushliteral(L, "EPROC_UNKNOWN");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ERELATIVE
  else if (APR_STATUS_IS_ERELATIVE(status)) {
    lua_pushliteral(L, "ERELATIVE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ESPIPE
  else if (APR_STATUS_IS_ESPIPE(status)) {
    lua_pushliteral(L, "ESPIPE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ESYMNOTFOUND
  else if (APR_STATUS_IS_ESYMNOTFOUND(status)) {
    lua_pushliteral(L, "ESYMNOTFOUND");
    return;
  }
# endif
# ifdef APR_STATUS_IS_ETIMEDOUT
  else if (APR_STATUS_IS_ETIMEDOUT(status)) {
    lua_pushliteral(L, "ETIMEDOUT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_EXDEV
  else if (APR_STATUS_IS_EXDEV(status)) {
    lua_pushliteral(L, "EXDEV");
    return;
  }
# endif
# ifdef APR_STATUS_IS_FILEBASED
  else if (APR_STATUS_IS_FILEBASED(status)) {
    lua_pushliteral(L, "FILEBASED");
    return;
  }
# endif
# ifdef APR_STATUS_IS_INCHILD
  else if (APR_STATUS_IS_INCHILD(status)) {
    lua_pushliteral(L, "INCHILD");
    return;
  }
# endif
# ifdef APR_STATUS_IS_INCOMPLETE
  else if (APR_STATUS_IS_INCOMPLETE(status)) {
    lua_pushliteral(L, "INCOMPLETE");
    return;
  }
# endif
# ifdef APR_STATUS_IS_INPARENT
  else if (APR_STATUS_IS_INPARENT(status)) {
    lua_pushliteral(L, "INPARENT");
    return;
  }
# endif
# ifdef APR_STATUS_IS_KEYBASED
  else if (APR_STATUS_IS_KEYBASED(status)) {
    lua_pushliteral(L, "KEYBASED");
    return;
  }
# endif
# ifdef APR_STATUS_IS_NOTDETACH
  else if (APR_STATUS_IS_NOTDETACH(status)) {
    lua_pushliteral(L, "NOTDETACH");
    return;
  }
# endif
# ifdef APR_STATUS_IS_NOTFOUND
  else if (APR_STATUS_IS_NOTFOUND(status)) {
    lua_pushliteral(L, "NOTFOUND");
    return;
  }
# endif
# ifdef APR_STATUS_IS_TIMEUP
  else if (APR_STATUS_IS_TIMEUP(status)) {
    lua_pushliteral(L, "TIMEUP");
    return;
  }
# endif

  lua_pushinteger(L, status);
}
Beispiel #21
0
/**
 * \brief write tile data to disk
 *
 * writes the content of mapcache_tile::data to disk.
 * \returns MAPCACHE_FAILURE if there is no data to write, or if the tile isn't locked
 * \returns MAPCACHE_SUCCESS if the tile has been successfully written to disk
 * \private \memberof mapcache_cache_disk
 * \sa mapcache_cache::tile_set()
 */
static void _mapcache_cache_disk_set(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
  apr_size_t bytes;
  apr_file_t *f;
  apr_status_t ret;
  char errmsg[120];
  char *filename, *hackptr1, *hackptr2=NULL;
  mapcache_cache_disk *cache = (mapcache_cache_disk*)pcache;
  const int creation_retry = cache->creation_retry;
  int retry_count_create_file = 0;

#ifdef DEBUG
  /* all this should be checked at a higher level */
  if(!tile->encoded_data && !tile->raw_image) {
    ctx->set_error(ctx,500,"attempting to write empty tile to disk");
    return;
  }
  if(!tile->encoded_data && !tile->tileset->format) {
    ctx->set_error(ctx,500,"received a raw tile image for a tileset with no format");
    return;
  }
#endif

  cache->tile_key(ctx, cache, tile, &filename);
  GC_CHECK_ERROR(ctx);

  /* find the location of the last '/' in the string */
  hackptr1 = filename;
  while(*hackptr1) {
    if(*hackptr1 == '/')
      hackptr2 = hackptr1;
    hackptr1++;
  }
  *hackptr2 = '\0';

  if(APR_SUCCESS != (ret = apr_dir_make_recursive(filename,APR_OS_DEFAULT,ctx->pool))) {
    /*
     * apr_dir_make_recursive sometimes sends back this error, although it should not.
     * ignore this one
     */
    if(!APR_STATUS_IS_EEXIST(ret)) {
      ctx->set_error(ctx, 500, "failed to create directory %s: %s",filename, apr_strerror(ret,errmsg,120));
      return;
    }
  }
  *hackptr2 = '/';

  ret = apr_file_remove(filename,ctx->pool);
  if(ret != APR_SUCCESS && !APR_STATUS_IS_ENOENT(ret)) {
    ctx->set_error(ctx, 500,  "failed to remove file %s: %s",filename, apr_strerror(ret,errmsg,120));
  }


#ifdef HAVE_SYMLINK
  if(cache->symlink_blank) {
    if(!tile->raw_image) {
      tile->raw_image = mapcache_imageio_decode(ctx, tile->encoded_data);
      GC_CHECK_ERROR(ctx);
    }
    if(mapcache_image_blank_color(tile->raw_image) != MAPCACHE_FALSE) {
      char *blankname;
      int retry_count_create_symlink = 0;
      char *blankname_rel = NULL;
      _mapcache_cache_disk_blank_tile_key(ctx,cache,tile,tile->raw_image->data,&blankname);
      if(apr_file_open(&f, blankname, APR_FOPEN_READ, APR_OS_DEFAULT, ctx->pool) != APR_SUCCESS) {
        int isLocked;
        void *lock;
        char *blankdirname;
        if(!tile->encoded_data) {
          tile->encoded_data = tile->tileset->format->write(ctx, tile->raw_image, tile->tileset->format);
          GC_CHECK_ERROR(ctx);
        }
        /* create the blank file */
        blankdirname = apr_psprintf(ctx->pool, "%s/%s/%s/blanks",
                                          cache->base_directory,
                                          tile->tileset->name,
                                          tile->grid_link->grid->name);
        if(APR_SUCCESS != (ret = apr_dir_make_recursive(
                                   blankdirname, APR_OS_DEFAULT,ctx->pool))) {
          if(!APR_STATUS_IS_EEXIST(ret)) {
            ctx->set_error(ctx, 500,  "failed to create directory %s for blank tiles",blankdirname, apr_strerror(ret,errmsg,120));
            return;
          }
        }

        /* aquire a lock on the blank file */
        isLocked = mapcache_lock_or_wait_for_resource(ctx,ctx->config->locker,blankname, &lock);

        if(isLocked == MAPCACHE_TRUE) {

          if((ret = apr_file_open(&f, blankname,
                                  APR_FOPEN_CREATE|APR_FOPEN_WRITE|APR_FOPEN_BUFFERED|APR_FOPEN_BINARY,
                                  APR_OS_DEFAULT, ctx->pool)) != APR_SUCCESS) {
            ctx->set_error(ctx, 500,  "failed to create file %s: %s",blankname, apr_strerror(ret,errmsg,120));
            mapcache_unlock_resource(ctx,ctx->config->locker,blankname, lock);
            return; /* we could not create the file */
          }

          bytes = (apr_size_t)tile->encoded_data->size;
          ret = apr_file_write(f,(void*)tile->encoded_data->buf,&bytes);
          if(ret != APR_SUCCESS) {
            ctx->set_error(ctx, 500,  "failed to write data to file %s (wrote %d of %d bytes): %s",blankname, (int)bytes, (int)tile->encoded_data->size, apr_strerror(ret,errmsg,120));
            mapcache_unlock_resource(ctx,ctx->config->locker,blankname, lock);
            return; /* we could not create the file */
          }

          if(bytes != tile->encoded_data->size) {
            ctx->set_error(ctx, 500,  "failed to write image data to %s, wrote %d of %d bytes", blankname, (int)bytes, (int)tile->encoded_data->size);
            mapcache_unlock_resource(ctx,ctx->config->locker,blankname, lock);
            return;
          }
          apr_file_close(f);
          mapcache_unlock_resource(ctx,ctx->config->locker,blankname, lock);
#ifdef DEBUG
          ctx->log(ctx,MAPCACHE_DEBUG,"created blank tile %s",blankname);
#endif
        }
      } else {
        apr_file_close(f);
      }


      /*
       * compute the relative path between tile and blank tile
       */
      blankname_rel = relative_path(ctx,filename, blankname);
      GC_CHECK_ERROR(ctx);

      /*
       * depending on configuration symlink creation will retry if it fails.
       * this can happen on nfs mounted network storage.
       * the solution is to create the containing directory again and retry the symlink creation.
       */
      while(symlink(blankname_rel, filename) != 0) {
        retry_count_create_symlink++;

        if(retry_count_create_symlink > creation_retry) {
          char *error = strerror(errno);
          ctx->set_error(ctx, 500, "failed to link tile %s to %s: %s",filename, blankname_rel, error);
          return; /* we could not create the file */
        }

        *hackptr2 = '\0';

        if(APR_SUCCESS != (ret = apr_dir_make_recursive(filename,APR_OS_DEFAULT,ctx->pool))) {
          if(!APR_STATUS_IS_EEXIST(ret)) {
            ctx->set_error(ctx, 500, "failed to create symlink, can not create directory %s: %s",filename, apr_strerror(ret,errmsg,120));
            return; /* we could not create the file */
          }
        }

        *hackptr2 = '/';
      }
#ifdef DEBUG
      ctx->log(ctx, MAPCACHE_DEBUG, "linked blank tile %s to %s",filename,blankname);
#endif
      return;
    }
  }
#endif /*HAVE_SYMLINK*/

  /* go the normal way: either we haven't configured blank tile detection, or the tile was not blank */

  if(!tile->encoded_data) {
    tile->encoded_data = tile->tileset->format->write(ctx, tile->raw_image, tile->tileset->format);
    GC_CHECK_ERROR(ctx);
  }

  /*
   * depending on configuration file creation will retry if it fails.
   * this can happen on nfs mounted network storage.
   * the solution is to create the containing directory again and retry the file creation.
   */
  while((ret = apr_file_open(&f, filename,
                             APR_FOPEN_CREATE|APR_FOPEN_WRITE|APR_FOPEN_BUFFERED|APR_FOPEN_BINARY,
                             APR_OS_DEFAULT, ctx->pool)) != APR_SUCCESS) {

    retry_count_create_file++;

    if(retry_count_create_file > creation_retry) {
      ctx->set_error(ctx, 500, "failed to create file %s: %s",filename, apr_strerror(ret,errmsg,120));
      return; /* we could not create the file */
    }

    *hackptr2 = '\0';

    if(APR_SUCCESS != (ret = apr_dir_make_recursive(filename,APR_OS_DEFAULT,ctx->pool))) {
      if(!APR_STATUS_IS_EEXIST(ret)) {
        ctx->set_error(ctx, 500, "failed to create file, can not create directory %s: %s",filename, apr_strerror(ret,errmsg,120));
        return; /* we could not create the file */
      }
    }

    *hackptr2 = '/';
  }

  bytes = (apr_size_t)tile->encoded_data->size;
  ret = apr_file_write(f,(void*)tile->encoded_data->buf,&bytes);
  if(ret != APR_SUCCESS) {
    ctx->set_error(ctx, 500,  "failed to write data to file %s (wrote %d of %d bytes): %s",filename, (int)bytes, (int)tile->encoded_data->size, apr_strerror(ret,errmsg,120));
    return; /* we could not create the file */
  }

  if(bytes != tile->encoded_data->size) {
    ctx->set_error(ctx, 500, "failed to write image data to %s, wrote %d of %d bytes", filename, (int)bytes, (int)tile->encoded_data->size);
  }
  ret = apr_file_close(f);
  if(ret != APR_SUCCESS) {
    ctx->set_error(ctx, 500,  "failed to close file %s:%s",filename, apr_strerror(ret,errmsg,120));
    return; /* we could not create the file */
  }

}
/**
 * Try obtain a cache wide lock on the given cache key.
 *
 * If we return APR_SUCCESS, we obtained the lock, and we are clear to
 * proceed to the backend. If we return APR_EEXIST, then the lock is
 * already locked, someone else has gone to refresh the backend data
 * already, so we must return stale data with a warning in the mean
 * time. If we return anything else, then something has gone pear
 * shaped, and we allow the request through to the backend regardless.
 *
 * This lock is created from the request pool, meaning that should
 * something go wrong and the lock isn't deleted on return of the
 * request headers from the backend for whatever reason, at worst the
 * lock will be cleaned up when the request dies or finishes.
 *
 * If something goes truly bananas and the lock isn't deleted when the
 * request dies, the lock will be trashed when its max-age is reached,
 * or when a request arrives containing a Cache-Control: no-cache. At
 * no point is it possible for this lock to permanently deny access to
 * the backend.
 */
apr_status_t cache_try_lock(cache_server_conf *conf, cache_request_rec *cache,
        request_rec *r)
{
    apr_status_t status;
    const char *lockname;
    const char *path;
    char dir[5];
    apr_time_t now = apr_time_now();
    apr_finfo_t finfo;
    apr_file_t *lockfile;
    void *dummy;

    finfo.mtime = 0;

    if (!conf || !conf->lock || !conf->lockpath) {
        /* no locks configured, leave */
        return APR_SUCCESS;
    }

    /* lock already obtained earlier? if so, success */
    apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
    if (dummy) {
        return APR_SUCCESS;
    }

    /* create the key if it doesn't exist */
    if (!cache->key) {
        cache_generate_key(r, r->pool, &cache->key);
    }

    /* create a hashed filename from the key, and save it for later */
    lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);

    /* lock files represent discrete just-went-stale URLs "in flight", so
     * we support a simple two level directory structure, more is overkill.
     */
    dir[0] = '/';
    dir[1] = lockname[0];
    dir[2] = '/';
    dir[3] = lockname[1];
    dir[4] = 0;

    /* make the directories */
    path = apr_pstrcat(r->pool, conf->lockpath, dir, NULL);
    if (APR_SUCCESS != (status = apr_dir_make_recursive(path,
            APR_UREAD|APR_UWRITE|APR_UEXECUTE, r->pool))) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(00778)
                "Could not create a cache lock directory: %s",
                path);
        return status;
    }
    lockname = apr_pstrcat(r->pool, path, "/", lockname, NULL);
    apr_pool_userdata_set(lockname, CACHE_LOCKNAME_KEY, NULL, r->pool);

    /* is an existing lock file too old? */
    status = apr_stat(&finfo, lockname,
                APR_FINFO_MTIME | APR_FINFO_NLINK, r->pool);
    if (!(APR_STATUS_IS_ENOENT(status)) && APR_SUCCESS != status) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EEXIST, r, APLOGNO(00779)
                "Could not stat a cache lock file: %s",
                lockname);
        return status;
    }
    if ((status == APR_SUCCESS) && (((now - finfo.mtime) > conf->lockmaxage)
                                  || (now < finfo.mtime))) {
        ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r, APLOGNO(00780)
                "Cache lock file for '%s' too old, removing: %s",
                r->uri, lockname);
        apr_file_remove(lockname, r->pool);
    }

    /* try obtain a lock on the file */
    if (APR_SUCCESS == (status = apr_file_open(&lockfile, lockname,
            APR_WRITE | APR_CREATE | APR_EXCL | APR_DELONCLOSE,
            APR_UREAD | APR_UWRITE, r->pool))) {
        apr_pool_userdata_set(lockfile, CACHE_LOCKFILE_KEY, NULL, r->pool);
    }
    return status;

}
void nx_expr_proc__xm_fileop_file_remove(nx_expr_eval_ctx_t *eval_ctx,
					 nx_module_t *module,
					 nx_expr_arg_list_t *args)
{
    nx_expr_arg_t *arg;
    nx_value_t file;
    apr_status_t rv;
    apr_pool_t *pool = NULL;
    apr_dir_t *dir;
    nx_exception_t e;
    nx_string_t *dirname = NULL;
    nx_string_t *fname = NULL;
    char *filename;
    char *idx;
    int flags = 0;
    apr_finfo_t finfo;
    nx_expr_arg_t *older;
    nx_value_t olderval;
    apr_time_t older_time = 0LL;

    ASSERT(module != NULL);

    ASSERT(args != NULL);
    arg = NX_DLIST_FIRST(args);
    ASSERT(arg != NULL);
    ASSERT(arg->expr != NULL);

    nx_expr_evaluate(eval_ctx, &file, arg->expr);

    if ( file.defined != TRUE )
    {
	throw_msg("'file' is undef");
    }

    try
    {
	if ( file.type != NX_VALUE_TYPE_STRING )
	{
	    throw_msg("string type required for 'file'");
	}

	older = NX_DLIST_NEXT(arg, link);
	if ( older != NULL )
	{
	    ASSERT(older->expr != NULL);
	    nx_expr_evaluate(eval_ctx, &olderval, older->expr);
	    if ( olderval.type != NX_VALUE_TYPE_DATETIME )
	    {
		nx_value_kill(&olderval);
		throw_msg("datetime type required for 'older'");
	    }
	    if ( olderval.defined == TRUE )
	    {
		older_time = olderval.datetime;
	    }
	}

	if ( apr_fnmatch_test(file.string->buf) != 0 )
	{ // we have wildcards, expand it
	    pool = nx_pool_create_core();

	    filename = file.string->buf;
	    idx = strrchr(filename, '/');
#ifndef WIN32
	    flags = APR_FNM_CASE_BLIND;
	    if ( idx == NULL ) 
	    {
		idx = strrchr(filename, '\\');
	    }
#endif
	    if ( idx == NULL )
	    {
		dirname = nx_string_create("."NX_DIR_SEPARATOR, -1);
	    }
	    else
	    {
		dirname = nx_string_create(filename, (int) (idx + 1 - filename));
		filename = idx + 1;
	    }

	    CHECKERR_MSG(apr_dir_open(&dir, dirname->buf, pool),
			 "failed to open directory: %s", dirname->buf);
	    fname = nx_string_new();

	    while ( apr_dir_read(&finfo, APR_FINFO_NAME | APR_FINFO_TYPE | APR_FINFO_CTIME,
				 dir) == APR_SUCCESS )
	    {
		if ( finfo.filetype == APR_REG )
		{
		    log_debug("checking '%s' against wildcard '%s':", finfo.name, filename);
		    if ( apr_fnmatch(filename, finfo.name, flags) == APR_SUCCESS )
		    {
			nx_string_sprintf(fname, "%s%s", dirname->buf, finfo.name);

			if ( (older_time == 0) ||
			     ((older_time != 0) && (finfo.ctime < older_time)) )
			{
			    log_debug("'%s' matches wildcard '%s' and is 'older', removing",
				      fname->buf, file.string->buf);
			    log_info("removing file %s", fname->buf);
			    rv = apr_file_remove(fname->buf, NULL);
			    if ( APR_STATUS_IS_ENOENT(rv) )
			    {
			    }
			    else if ( rv == APR_SUCCESS )
			    {
			    }
			    else
			    {
				log_aprerror(rv, "failed to remove file '%s'", fname->buf);
			    }
			    _reopen_logfile(fname->buf);
			}
		    }
		}
	    }
	    nx_string_free(fname);
	    apr_pool_destroy(pool);
	}
	else
	{
	    CHECKERR_MSG(apr_file_remove(file.string->buf, NULL), 
			 "failed to remove file '%s'", file.string->buf);
	}
    }
    catch(e)
    {
	nx_value_kill(&file);
	if ( pool != NULL )
	{
	    apr_pool_destroy(pool);
	}
	if ( dirname != NULL )
	{
	    nx_string_free(dirname);
	}
	log_exception(e);
    }
}
Beispiel #24
0
int ap_signal_server(int *exit_status, apr_pool_t *pconf)
{
    apr_status_t rv;
    pid_t otherpid;
    int running = 0;
    const char *status;

    *exit_status = 0;

    rv = ap_read_pid(pconf, ap_pid_fname, &otherpid);
    if (rv != APR_SUCCESS) {
        if (!APR_STATUS_IS_ENOENT(rv)) {
            ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, NULL, APLOGNO(00058)
                         "Error retrieving pid file %s", ap_pid_fname);
            ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00059)
                         "Remove it before continuing if it is corrupted.");
            *exit_status = 1;
            return 1;
        }
        status = "httpd (no pid file) not running";
    }
    else {
        if (kill(otherpid, 0) == 0) {
            running = 1;
            status = apr_psprintf(pconf,
                                  "httpd (pid %" APR_PID_T_FMT ") already "
                                  "running", otherpid);
        }
        else {
            status = apr_psprintf(pconf,
                                  "httpd (pid %" APR_PID_T_FMT "?) not running",
                                  otherpid);
        }
    }

    if (!strcmp(dash_k_arg, "start") || dash_k_arg == dash_k_arg_noarg) {
        if (running) {
            printf("%s\n", status);
            return 1;
        }
    }

    if (!strcmp(dash_k_arg, "stop")) {
        if (!running) {
            printf("%s\n", status);
        }
        else {
            send_signal(otherpid, SIGTERM);
        }
        return 1;
    }

    if (!strcmp(dash_k_arg, "restart")) {
        if (!running) {
            printf("httpd not running, trying to start\n");
        }
        else {
            *exit_status = send_signal(otherpid, SIGHUP);
            return 1;
        }
    }

    if (!strcmp(dash_k_arg, "graceful")) {
        if (!running) {
            printf("httpd not running, trying to start\n");
        }
        else {
            *exit_status = send_signal(otherpid, AP_SIG_GRACEFUL);
            return 1;
        }
    }

    if (!strcmp(dash_k_arg, "graceful-stop")) {
        if (!running) {
            printf("%s\n", status);
        }
        else {
            *exit_status = send_signal(otherpid, AP_SIG_GRACEFUL_STOP);
        }
        return 1;
    }

    /*
     * ********** begin amiya 20140217 ****************
     */
    if (!strcmp(dash_k_arg, "reconfigure")) {
            if (!running) {
                printf("%s\n", status);
            }
            else {
                *exit_status = send_signal(otherpid, AP_SIG_RECONFIGURE);
            }
            return 1;
        }
    /*
     * *********** end amiya 20140217 ******************
     */

    return 0;
}
int main(int argc, const char * const argv[])
{
    apr_pool_t *pool;
    apr_status_t rv;
    char errbuf[MAX_STRING_LEN];
    int  need_file = 1;
    int  need_user = 1;
    int  need_pwd  = 1;
    int  need_cmnt = 0;
    int  changed = 0;
    int  cmd = HTDBM_MAKE;
    int  i, ret, args_left = 2;
    apr_getopt_t *state;
    char opt;
    const char *opt_arg;

    apr_app_initialize(&argc, &argv, NULL);
    atexit(terminate);

    if ((rv = htdbm_init(&pool, &h)) != APR_SUCCESS) {
        fprintf(stderr, "Unable to initialize htdbm terminating!\n");
        apr_strerror(rv, errbuf, sizeof(errbuf));
        exit(1);
    }

    rv = apr_getopt_init(&state, pool, argc, argv);
    if (rv != APR_SUCCESS)
        exit(ERR_SYNTAX);

    while ((rv = apr_getopt(state, "cnmspdBbDivxlC:T:", &opt, &opt_arg)) == APR_SUCCESS) {
        switch (opt) {
        case 'c':
            h->create = 1;
            break;
        case 'n':
            need_file = 0;
            cmd = HTDBM_NOFILE;
                args_left--;
            break;
        case 'l':
            need_pwd = 0;
            need_user = 0;
            cmd = HTDBM_LIST;
            h->rdonly = 1;
            args_left--;
            break;
        case 't':
            need_cmnt = 1;
            args_left++;
            break;
        case 'T':
            h->type = apr_pstrdup(h->ctx.pool, opt_arg);
            break;
        case 'v':
            h->rdonly = 1;
            cmd = HTDBM_VERIFY;
            break;
        case 'x':
            need_pwd = 0;
            cmd = HTDBM_DELETE;
            break;
        default:
            ret = parse_common_options(&h->ctx, opt, opt_arg);
            if (ret) {
                fprintf(stderr, "Error: %s\n", h->ctx.errstr);
                exit(ret);
            }
        }
    }
    if (h->ctx.passwd_src == PW_ARG) {
            need_pwd = 0;
            args_left++;
    }
    /*
     * Make sure we still have exactly the right number of arguments left
     * (the filename, the username, and possibly the password if -b was
     * specified).
     */
    i = state->ind;
    if (rv != APR_EOF || argc - i != args_left)
        htdbm_usage();

    if (need_file) {
        h->filename = apr_pstrdup(h->ctx.pool, argv[i++]);
        if ((rv = htdbm_open(h)) != APR_SUCCESS) {
            fprintf(stderr, "Error opening database %s\n", h->filename);
            apr_strerror(rv, errbuf, sizeof(errbuf));
            fprintf(stderr,"%s\n",errbuf);
            exit(ERR_FILEPERM);
        }
    }
    if (need_user) {
        h->username = apr_pstrdup(pool, argv[i++]);
        if (htdbm_valid_username(h) != APR_SUCCESS)
            exit(ERR_BADUSER);
    }
    if (h->ctx.passwd_src == PW_ARG)
        h->ctx.passwd = apr_pstrdup(pool, argv[i++]);

    if (need_pwd) {
        ret = get_password(&h->ctx);
        if (ret) {
            fprintf(stderr, "Error: %s\n", h->ctx.errstr);
            exit(ret);
        }
    }
    if (need_cmnt)
        h->comment = apr_pstrdup(pool, argv[i++]);

    switch (cmd) {
        case HTDBM_VERIFY:
            if ((rv = htdbm_verify(h)) != APR_SUCCESS) {
                if (APR_STATUS_IS_ENOENT(rv)) {
                    fprintf(stderr, "The user '%s' could not be found in database\n", h->username);
                    exit(ERR_BADUSER);
                }
                else {
                    fprintf(stderr, "Password mismatch for user '%s'\n", h->username);
                    exit(ERR_PWMISMATCH);
                }
            }
            else
                fprintf(stderr, "Password validated for user '%s'\n", h->username);
            break;
        case HTDBM_DELETE:
            if (htdbm_del(h) != APR_SUCCESS) {
                fprintf(stderr, "Cannot find user '%s' in database\n", h->username);
                exit(ERR_BADUSER);
            }
            h->username = NULL;
            changed = 1;
            break;
        case HTDBM_LIST:
            htdbm_list(h);
            break;
        default:
            ret = htdbm_make(h);
            if (ret)
                exit(ret);
            break;
    }
    if (need_file && !h->rdonly) {
        if ((rv = htdbm_save(h, &changed)) != APR_SUCCESS) {
            apr_strerror(rv, errbuf, sizeof(errbuf));
            exit(ERR_FILEPERM);
        }
        fprintf(stdout, "Database %s %s.\n", h->filename,
                h->create ? "created" : (changed ? "modified" : "updated"));
    }
    if (cmd == HTDBM_NOFILE) {
        if (!need_cmnt) {
            fprintf(stderr, "%s:%s\n", h->username, h->ctx.passwd);
        }
        else {
            fprintf(stderr, "%s:%s:%s\n", h->username, h->ctx.passwd,
                    h->comment);
        }
    }
    htdbm_terminate(h);

    return 0; /* Suppress compiler warning. */
}
/* Handle the moving of a pristine from SRC_WCROOT to DST_WCROOT. The existing
   pristine in SRC_WCROOT is described by CHECKSUM, MD5_CHECKSUM and SIZE */
static svn_error_t *
maybe_transfer_one_pristine(svn_wc__db_wcroot_t *src_wcroot,
                            svn_wc__db_wcroot_t *dst_wcroot,
                            const svn_checksum_t *checksum,
                            const svn_checksum_t *md5_checksum,
                            apr_int64_t size,
                            svn_cancel_func_t cancel_func,
                            void *cancel_baton,
                            apr_pool_t *scratch_pool)
{
  const char *pristine_abspath;
  svn_sqlite__stmt_t *stmt;
  svn_stream_t *src_stream;
  svn_stream_t *dst_stream;
  const char *tmp_abspath;
  const char *src_abspath;
  int affected_rows;
  svn_error_t *err;

  SVN_ERR(svn_sqlite__get_statement(&stmt, dst_wcroot->sdb,
                                    STMT_INSERT_OR_IGNORE_PRISTINE));
  SVN_ERR(svn_sqlite__bind_checksum(stmt, 1, checksum, scratch_pool));
  SVN_ERR(svn_sqlite__bind_checksum(stmt, 2, md5_checksum, scratch_pool));
  SVN_ERR(svn_sqlite__bind_int64(stmt, 3, size));

  SVN_ERR(svn_sqlite__update(&affected_rows, stmt));

  if (affected_rows == 0)
    return SVN_NO_ERROR;

  SVN_ERR(svn_stream_open_unique(&dst_stream, &tmp_abspath,
                                 pristine_get_tempdir(dst_wcroot,
                                                      scratch_pool,
                                                      scratch_pool),
                                 svn_io_file_del_on_pool_cleanup,
                                 scratch_pool, scratch_pool));

  SVN_ERR(get_pristine_fname(&src_abspath, src_wcroot->abspath, checksum,
                             scratch_pool, scratch_pool));

  SVN_ERR(svn_stream_open_readonly(&src_stream, src_abspath,
                                   scratch_pool, scratch_pool));

  /* ### Should we verify the SHA1 or MD5 here, or is that too expensive? */
  SVN_ERR(svn_stream_copy3(src_stream, dst_stream,
                           cancel_func, cancel_baton,
                           scratch_pool));

  SVN_ERR(get_pristine_fname(&pristine_abspath, dst_wcroot->abspath, checksum,
                             scratch_pool, scratch_pool));

  /* Move the file to its target location.  (If it is already there, it is
   * an orphan file and it doesn't matter if we overwrite it.) */
  err = svn_io_file_rename2(tmp_abspath, pristine_abspath, FALSE,
                            scratch_pool);

  /* Maybe the directory doesn't exist yet? */
  if (err && APR_STATUS_IS_ENOENT(err->apr_err))
    {
      svn_error_t *err2;

      err2 = svn_io_dir_make(svn_dirent_dirname(pristine_abspath,
                                                scratch_pool),
                             APR_OS_DEFAULT, scratch_pool);

      if (err2)
        /* Creating directory didn't work: Return all errors */
        return svn_error_trace(svn_error_compose_create(err, err2));
      else
        /* We could create a directory: retry install */
        svn_error_clear(err);

      SVN_ERR(svn_io_file_rename2(tmp_abspath, pristine_abspath, FALSE,
                                  scratch_pool));
    }
  else
    SVN_ERR(err);

  return SVN_NO_ERROR;
}
Beispiel #27
0
/* Copy FILENAME from SRC_DIR to DST_DIR in byte increments of size
   CHUNKSIZE.  The read/write buffer of size CHUNKSIZE will be
   allocated in POOL.  If ALLOW_MISSING is set, we won't make a fuss
   if FILENAME isn't found in SRC_DIR; otherwise, we will.  */
static svn_error_t *
copy_db_file_safely(const char *src_dir,
                    const char *dst_dir,
                    const char *filename,
                    u_int32_t chunksize,
                    svn_boolean_t allow_missing,
                    apr_pool_t *pool)
{
  apr_file_t *s = NULL, *d = NULL;  /* init to null important for APR */
  const char *file_src_path = svn_dirent_join(src_dir, filename, pool);
  const char *file_dst_path = svn_dirent_join(dst_dir, filename, pool);
  svn_error_t *err;
  char *buf;

  /* Open source file.  If it's missing and that's allowed, there's
     nothing more to do here. */
  err = svn_io_file_open(&s, file_src_path,
                         (APR_READ | APR_LARGEFILE),
                         APR_OS_DEFAULT, pool);
  if (err && APR_STATUS_IS_ENOENT(err->apr_err) && allow_missing)
    {
      svn_error_clear(err);
      return SVN_NO_ERROR;
    }
  SVN_ERR(err);

  /* Open destination file. */
  SVN_ERR(svn_io_file_open(&d, file_dst_path, (APR_WRITE | APR_CREATE |
                                               APR_LARGEFILE),
                           APR_OS_DEFAULT, pool));

  /* Allocate our read/write buffer. */
  buf = apr_palloc(pool, chunksize);

  /* Copy bytes till the cows come home. */
  while (1)
    {
      apr_size_t bytes_this_time = chunksize;
      svn_error_t *read_err, *write_err;

      /* Read 'em. */
      if ((read_err = svn_io_file_read(s, buf, &bytes_this_time, pool)))
        {
          if (APR_STATUS_IS_EOF(read_err->apr_err))
            svn_error_clear(read_err);
          else
            {
              svn_error_clear(svn_io_file_close(s, pool));
              svn_error_clear(svn_io_file_close(d, pool));
              return read_err;
            }
        }

      /* Write 'em. */
      if ((write_err = svn_io_file_write_full(d, buf, bytes_this_time, NULL,
                                              pool)))
        {
          svn_error_clear(svn_io_file_close(s, pool));
          svn_error_clear(svn_io_file_close(d, pool));
          return write_err;
        }

      /* read_err is either NULL, or a dangling pointer - but it is only a
         dangling pointer if it used to be an EOF error. */
      if (read_err)
        {
          SVN_ERR(svn_io_file_close(s, pool));
          SVN_ERR(svn_io_file_close(d, pool));
          break;  /* got EOF on read, all files closed, all done. */
        }
    }

  return SVN_NO_ERROR;
}
Beispiel #28
0
/* Schedule directory DIRNAME, and some of the tree under it, for
 * addition with access baton ADM_ACCESS.  DEPTH is the depth at this
 * point in the descent (it may be changed for recursive calls).
 *
 * If DIRNAME (or any item below directory DIRNAME) is already scheduled for
 * addition, add will fail and return an error unless FORCE is TRUE.
 *
 * Files and directories that match ignore patterns will not be added unless
 * NO_IGNORE is TRUE.
 *
 * If CTX->CANCEL_FUNC is non-null, call it with CTX->CANCEL_BATON to allow
 * the user to cancel the operation
 */
static svn_error_t *
add_dir_recursive(const char *dirname,
                  svn_wc_adm_access_t *adm_access,
                  svn_depth_t depth,
                  svn_boolean_t force,
                  svn_boolean_t no_ignore,
                  svn_client_ctx_t *ctx,
                  apr_pool_t *pool)
{
  apr_dir_t *dir;
  apr_finfo_t this_entry;
  svn_error_t *err;
  apr_pool_t *subpool;
  apr_int32_t flags = APR_FINFO_TYPE | APR_FINFO_NAME;
  svn_wc_adm_access_t *dir_access;
  apr_array_header_t *ignores;

  /* Check cancellation; note that this catches recursive calls too. */
  if (ctx->cancel_func)
    SVN_ERR(ctx->cancel_func(ctx->cancel_baton));

  /* Add this directory to revision control. */
  err = svn_wc_add2(dirname, adm_access,
                    NULL, SVN_INVALID_REVNUM,
                    ctx->cancel_func, ctx->cancel_baton,
                    ctx->notify_func2, ctx->notify_baton2, pool);
  if (err && err->apr_err == SVN_ERR_ENTRY_EXISTS && force)
    svn_error_clear(err);
  else if (err)
    return err;

  SVN_ERR(svn_wc_adm_retrieve(&dir_access, adm_access, dirname, pool));

  if (!no_ignore)
    SVN_ERR(svn_wc_get_ignores(&ignores, ctx->config, dir_access, pool));

  subpool = svn_pool_create(pool);

  SVN_ERR(svn_io_dir_open(&dir, dirname, pool));

  /* Read the directory entries one by one and add those things to
     version control. */
  while (1)
    {
      const char *fullpath;

      svn_pool_clear(subpool);

      err = svn_io_dir_read(&this_entry, flags, dir, subpool);

      if (err)
        {
          /* Check if we're done reading the dir's entries. */
          if (APR_STATUS_IS_ENOENT(err->apr_err))
            {
              apr_status_t apr_err;

              svn_error_clear(err);
              apr_err = apr_dir_close(dir);
              if (apr_err)
                return svn_error_wrap_apr
                  (apr_err, _("Can't close directory '%s'"),
                   svn_path_local_style(dirname, subpool));
              break;
            }
          else
            {
              return svn_error_createf
                (err->apr_err, err,
                 _("Error during add of '%s'"),
                 svn_path_local_style(dirname, subpool));
            }
        }

      /* Skip entries for this dir and its parent.  */
      if (this_entry.name[0] == '.'
          && (this_entry.name[1] == '\0'
              || (this_entry.name[1] == '.' && this_entry.name[2] == '\0')))
        continue;

      /* Check cancellation so you can cancel during an
       * add of a directory with lots of files. */
      if (ctx->cancel_func)
        SVN_ERR(ctx->cancel_func(ctx->cancel_baton));

      /* Skip over SVN admin directories. */
      if (svn_wc_is_adm_dir(this_entry.name, subpool))
        continue;

      if ((!no_ignore) && svn_wc_match_ignore_list(this_entry.name,
                                                   ignores, subpool))
        continue;

      /* Construct the full path of the entry. */
      fullpath = svn_path_join(dirname, this_entry.name, subpool);

      /* Recurse on directories; add files; ignore the rest. */
      if (this_entry.filetype == APR_DIR && depth >= svn_depth_immediates)
        {
          svn_depth_t depth_below_here = depth;
          if (depth == svn_depth_immediates)
            depth_below_here = svn_depth_empty;

          SVN_ERR(add_dir_recursive(fullpath, dir_access, depth_below_here,
                                    force, no_ignore, ctx, subpool));
        }
      else if (this_entry.filetype != APR_UNKFILE
               && this_entry.filetype != APR_DIR
               && depth >= svn_depth_files)
        {
          err = add_file(fullpath, ctx, dir_access, subpool);
          if (err && err->apr_err == SVN_ERR_ENTRY_EXISTS && force)
            svn_error_clear(err);
          else if (err)
            return err;
        }
    }

  /* Opened by svn_wc_add */
  SVN_ERR(svn_wc_adm_close(dir_access));

  /* Destroy the per-iteration pool. */
  svn_pool_destroy(subpool);

  return SVN_NO_ERROR;
}
Beispiel #29
0
static int remove_url(cache_handle_t *h, apr_pool_t *p)
{
    apr_status_t rc;
    disk_cache_object_t *dobj;

    /* Get disk cache object from cache handle */
    dobj = (disk_cache_object_t *) h->cache_obj->vobj;
    if (!dobj) {
        return DECLINED;
    }

    /* Delete headers file */
    if (dobj->hdrsfile) {
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
                     "disk_cache: Deleting %s from cache.", dobj->hdrsfile);

        rc = apr_file_remove(dobj->hdrsfile, p);
        if ((rc != APR_SUCCESS) && !APR_STATUS_IS_ENOENT(rc)) {
            /* Will only result in an output if httpd is started with -e debug.
             * For reason see log_error_core for the case s == NULL.
             */
            ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, NULL,
                   "disk_cache: Failed to delete headers file %s from cache.",
                         dobj->hdrsfile);
            return DECLINED;
        }
    }

     /* Delete data file */
    if (dobj->datafile) {
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
                     "disk_cache: Deleting %s from cache.", dobj->datafile);

        rc = apr_file_remove(dobj->datafile, p);
        if ((rc != APR_SUCCESS) && !APR_STATUS_IS_ENOENT(rc)) {
            /* Will only result in an output if httpd is started with -e debug.
             * For reason see log_error_core for the case s == NULL.
             */
            ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, NULL,
                      "disk_cache: Failed to delete data file %s from cache.",
                         dobj->datafile);
            return DECLINED;
        }
    }

    /* now delete directories as far as possible up to our cache root */
    if (dobj->root) {
        const char *str_to_copy;

        str_to_copy = dobj->hdrsfile ? dobj->hdrsfile : dobj->datafile;
        if (str_to_copy) {
            char *dir, *slash, *q;

            dir = apr_pstrdup(p, str_to_copy);

            /* remove filename */
            slash = strrchr(dir, '/');
            *slash = '\0';

            /*
             * now walk our way back to the cache root, delete everything
             * in the way as far as possible
             *
             * Note: due to the way we constructed the file names in
             * header_file and data_file, we are guaranteed that the
             * cache_root is suffixed by at least one '/' which will be
             * turned into a terminating null by this loop.  Therefore,
             * we won't either delete or go above our cache root.
             */
            for (q = dir + dobj->root_len; *q ; ) {
                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
                              "disk_cache: Deleting directory %s from cache",
                              dir);

                 rc = apr_dir_remove(dir, p);
                 if (rc != APR_SUCCESS && !APR_STATUS_IS_ENOENT(rc)) {
                    break;
                 }
                 slash = strrchr(q, '/');
                 *slash = '\0';
            }
        }
    }

    return OK;
}
Beispiel #30
0
svn_error_t *
svn_config_walk_auth_data(const char *config_dir,
                          svn_config_auth_walk_func_t walk_func,
                          void *walk_baton,
                          apr_pool_t *scratch_pool)
{
  int i;
  apr_pool_t *iterpool;
  svn_boolean_t finished = FALSE;
  const char *cred_kinds[] =
    {
      SVN_AUTH_CRED_SIMPLE,
      SVN_AUTH_CRED_USERNAME,
      SVN_AUTH_CRED_SSL_CLIENT_CERT,
      SVN_AUTH_CRED_SSL_CLIENT_CERT_PW,
      SVN_AUTH_CRED_SSL_SERVER_TRUST,
      NULL
    };

  iterpool = svn_pool_create(scratch_pool);
  for (i = 0; cred_kinds[i]; i++)
    {
      const char *item_path;
      const char *dir_path;
      apr_hash_t *nodes;
      svn_error_t *err;
      apr_pool_t *itempool;
      apr_hash_index_t *hi;

      svn_pool_clear(iterpool);

      if (finished)
        break;

      SVN_ERR(svn_auth__file_path(&item_path, cred_kinds[i], "!", config_dir,
                                  iterpool));

      dir_path = svn_dirent_dirname(item_path, iterpool);

      err = svn_io_get_dirents3(&nodes, dir_path, TRUE, iterpool, iterpool);
      if (err)
        {
          if (!APR_STATUS_IS_ENOENT(err->apr_err)
              && !SVN__APR_STATUS_IS_ENOTDIR(err->apr_err))
            return svn_error_trace(err);

          svn_error_clear(err);
          continue;
        }

      itempool = svn_pool_create(iterpool);
      for (hi = apr_hash_first(iterpool, nodes); hi; hi = apr_hash_next(hi))
        {
          svn_io_dirent2_t *dirent = apr_hash_this_val(hi);
          svn_stream_t *stream;
          apr_hash_t *creds_hash;
          const svn_string_t *realm;
          svn_boolean_t delete_file = FALSE;

          if (finished)
            break;

          if (dirent->kind != svn_node_file)
            continue;

          svn_pool_clear(itempool);

          item_path = svn_dirent_join(dir_path, apr_hash_this_key(hi),
                                      itempool);

          err = svn_stream_open_readonly(&stream, item_path,
                                         itempool, itempool);
          if (err)
            {
              /* Ignore this file. There are no credentials in it anyway */
              svn_error_clear(err);
              continue;
            }

          creds_hash = apr_hash_make(itempool);
          err = svn_hash_read2(creds_hash, stream,
                               SVN_HASH_TERMINATOR, itempool);
          err = svn_error_compose_create(err, svn_stream_close(stream));
          if (err)
            {
              /* Ignore this file. There are no credentials in it anyway */
              svn_error_clear(err);
              continue;
            }

          realm = svn_hash_gets(creds_hash, SVN_CONFIG_REALMSTRING_KEY);
          if (! realm)
            continue; /* Not an auth file */

          err = walk_func(&delete_file, walk_baton, cred_kinds[i],
                          realm->data, creds_hash, itempool);
          if (err && err->apr_err == SVN_ERR_CEASE_INVOCATION)
            {
              svn_error_clear(err);
              err = SVN_NO_ERROR;
              finished = TRUE;
            }
          SVN_ERR(err);

          if (delete_file)
            {
              /* Delete the file on disk */
              SVN_ERR(svn_io_remove_file2(item_path, TRUE, itempool));
            }
        }
    }

  svn_pool_destroy(iterpool);
  return SVN_NO_ERROR;
}