1 /* This file is part of Mailfromd.
2    Copyright (C) 2005-2021 Sergey Poznyakoff
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16 
17 #ifdef HAVE_CONFIG_H
18 # include <config.h>
19 #endif
20 #include <stdlib.h>
21 #include "libmf.h"
22 
23 #include <mailutils/mailutils.h>
24 
25 void
init_timeout_ctl(struct timeout_ctl * tctl,time_t timeout)26 init_timeout_ctl(struct timeout_ctl *tctl, time_t timeout)
27 {
28 	tctl->start = time(NULL);
29 	tctl->timeout = timeout;
30 }
31 
32 int
mf_stream_wait(mu_stream_t stream,int flags,struct timeout_ctl * tctl)33 mf_stream_wait(mu_stream_t stream, int flags, struct timeout_ctl *tctl)
34 {
35 	int rc;
36 	int oflags = flags;
37 	struct timeval tv;
38 
39 	while (tctl->timeout) {
40 		tv.tv_sec = tctl->timeout;
41 		tv.tv_usec = 0;
42 		rc = mu_stream_wait(stream, &oflags, &tv);
43 
44 		/* Correct the timeout */
45 		UPDATE_TTW(*tctl);
46 
47 		switch (rc) {
48 		case 0:
49 			if (flags & oflags)
50 				return 0;
51 			/* FALLTHROUGH */
52 		case EAGAIN:
53 		case EINPROGRESS:
54 			continue;
55 
56 		default:
57 			return rc;
58 		}
59 	}
60 
61 	return ETIMEDOUT;
62 }
63 
64