/*
 * Copyright (c) 2003, 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: strfchrquoted.c,v 1.5 2007/11/14 06:03:08 ca Exp $")
#include "sm/assert.h"
#include "sm/error.h"
#include "sm/ctype.h"
#include "sm/str.h"
#include "sm/str-int.h"

/*
**  SM_STR_FCHRQUOTED -- find first occurrence of a char in str,
**	observe quotes and escape chars
**
**	Parameters:
**		str -- string in which to find delim
**		delims -- list of delimiter (e.g., "+" or "-")
**		pidx -- index in string at which delim appears first
**			only valid for SM_SUCCESS
**
**	Returns:
**		usual error code
*/

sm_ret_T
sm_str_fchrquoted(sm_str_P str, const uchar *delims, uint *pidx)
{
	sm_ret_T ret;
	uchar ch;
	uint i, len;
	bool quoted;

	SM_IS_BUF(str);
	SM_REQUIRE(pidx != NULL);

	ret = sm_error_perm(SM_EM_STR, SM_E_NOTFOUND);
	if (NULL == delims || '\0' == *delims)
		return ret;

	/* how to allow for these? */
	SM_REQUIRE(*delims != (uchar) '"');
	SM_REQUIRE(*delims != (uchar) '\\');

	quoted = false;
	len = sm_str_getlen(str);

	/* search for delimiter, make sure it isn't quoted or escaped */
	for (i = 0; i < len; i++) {
		ch = sm_str_rd_elem(str, i);
		if (ch == '"') {
			quoted = !quoted;
			continue;
		}
		if (quoted)
			continue;
		if (strchr((const char *)delims, ch) != NULL) {
			*pidx = i;
			ret = SM_SUCCESS;
			break;
		}
		if (ch == '\\') {
			if (++i >= len)
				break;
		}
	}
	return ret;
}


syntax highlighted by Code2HTML, v. 0.9.1