/* This file is part of Mailfromd.
   Copyright (C) 2005-2025 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include "libmf.h"

#include <mailutils/mailutils.h>

void
init_timeout_ctl(struct timeout_ctl *tctl, time_t timeout)
{
	tctl->start = time(NULL);
	tctl->timeout = timeout;
}

int
mf_stream_wait(mu_stream_t stream, int flags, struct timeout_ctl *tctl)
{
	int rc;
	int oflags = flags;
	struct timeval tv;
	
	while (tctl->timeout) {
		tv.tv_sec = tctl->timeout;
		tv.tv_usec = 0;
		rc = mu_stream_wait(stream, &oflags, &tv);

		/* Correct the timeout */
		UPDATE_TTW(*tctl);
		
		switch (rc) {
		case 0:
			if (flags & oflags)
				return 0;
			/* FALLTHROUGH */
		case EAGAIN:
		case EINPROGRESS:
			continue;

		default:
			return rc;
		}
	}
			
	return ETIMEDOUT;
}

