/*
 * Copyright (c) 2002, 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: blockmode.c,v 1.5 2006/07/14 14:42:25 ca Exp $")
#include "sm/error.h"
#include "sm/assert.h"
#include "sm/fcntl.h"
#include "sm/io.h"

/*
**  SM_FD_NONBLOCK -- set blocking mode for a file (associated fd)
**
**	Parameters:
**		fd -- file descriptor
**
**	Results:
**		usual sm_error code
*/

sm_ret_T
sm_fd_nonblock(int fd, bool on)
{
	int fl;

	if (!is_valid_fd(fd))
		return sm_error_perm(SM_EM_IO, EBADF);

	errno = 0;
	fl = fcntl(fd, F_GETFL, 0);
	if (fl == -1)
		return sm_error_perm(SM_EM_IO, errno);

	/* XXX do we want to check whether the mode is already active? */
	fl = fcntl(fd, F_SETFL, on ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK));
	if (fl == -1)
		return sm_error_perm(SM_EM_IO, errno);
	return SM_SUCCESS;
}

/*
**  SM_FP_NONBLOCK -- set blocking mode for a file (associated fd)
**
**	Parameters:
**		fp -- file pointer
**
**	Results:
**		usual sm_error code
*/

sm_ret_T
sm_fp_nonblock(sm_file_T *fp, bool on)
{
	int fd;
	sm_ret_T res;

	SM_IS_FP(fp);
	fd = f_fd(*fp);
	if (!is_valid_fd(fd))
		return sm_error_perm(SM_EM_IO, EBADF);

	res = sm_fd_nonblock(fd, on);
	if (sm_is_success(res))
	{
		if (on)
			sm_io_clrblocking(fp);
		else
			sm_io_setblocking(fp);
	}
	return res;
}


syntax highlighted by Code2HTML, v. 0.9.1