/*
 * Copyright (c) 2005 Sendmail, Inc. and its suppliers.
 *      All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: cdb_open_wr.c,v 1.4 2006/07/18 02:43:18 ca Exp $")
#include "sm/error.h"
#include "sm/heap.h"
#include "sm/assert.h"
#include "sm/str.h"
#include "sm/io.h"
#include "sm/cdb.h"
#include "cdb.h"

/*
**  CDB_OPEN_WR -- open a CDB file for writing
**
**	Parameters:
**		cdb_ctx -- CDB context
**		ta_id -- transaction id
**		pfp -- (pointer to) file pointer (output)
**		mode -- mode for open
**		instance -- instance of file (0: default, valid: 0-9)
**		io_vector -- I/O vector (can be NULL)
**		bufsize -- size of buffer (only for buffered file)
**		pcdb_id -- (pointer to) cdb id (output)
**
**	Returns:
**		usual sm_error code; ENOMEM, EINVAL
**
**	Last code review:
**	Last code change:
*/

sm_ret_T
cdb_open_wr(cdb_ctx_P cdb_ctx, sessta_id_T ta_id, sm_file_T **pfp, int mode, int instance, sm_stream_T *io_vector, size_t bufsize, cdb_id_P *pcdb_id)
{
	cdb_id_P cdb_id;
	sessta_id_P pta_id;

	SM_REQUIRE(cdb_ctx != NULL);

	if (instance < 0 || instance > 9)
		return sm_error_perm(SM_EM_CDB, EINVAL);
	if (instance > 0)
		SM_REQUIRE(pcdb_id != NULL);
	if (pcdb_id != NULL)
	{
		pta_id = sm_zalloc(sizeof(sessta_id_T));
		if (NULL == pta_id)
			return sm_error_perm(SM_EM_CDB, ENOMEM);
		strlcpy(pta_id, ta_id, sizeof(sessta_id_T));
	}
	else
		pta_id = ta_id;

	if (1 == instance)
		pta_id[0] = 'M';
	else if (instance > 0)
		pta_id[0] = (char) instance + '0';
	if (pcdb_id != NULL)
	{
		cdb_id = sm_cstr_crt((uchar *) pta_id, sizeof(sessta_id_T));
		if (NULL == cdb_id)
		{
			sm_free_size(pta_id, sizeof(sessta_id_T));
			return sm_error_perm(SM_EM_CDB, ENOMEM);
		}
		*pcdb_id = cdb_id;
	}

	if (io_vector != NULL)
	{
		if (bufsize > 0)
			return sm_io_open(&SmCDBStL, pta_id, mode, pfp,
				SM_IO_WHAT_CDB_HDL, cdb_ctx,
				SM_IO_WHAT_VECTORS, io_vector,
				SM_IO_WHAT_BSIZE, bufsize,
				SM_IO_WHAT_END);
		else
			return sm_io_open(&SmCDBStL, pta_id, mode, pfp,
				SM_IO_WHAT_CDB_HDL, cdb_ctx,
				SM_IO_WHAT_VECTORS, io_vector,
				SM_IO_WHAT_END);
	}
	else
		return sm_io_open(&SmCDBSt, pta_id, mode, pfp,
			SM_IO_WHAT_CDB_HDL, cdb_ctx, SM_IO_WHAT_END);
}


syntax highlighted by Code2HTML, v. 0.9.1