1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
/*++
/* NAME
/* timed_connect 3
/* SUMMARY
/* connect operation with timeout
/* SYNOPSIS
/* #include <sys/socket.h>
/* #include <timed_connect.h>
/*
/* int timed_connect(fd, buf, buf_len, timeout)
/* int fd;
/* struct sockaddr *buf;
/* int buf_len;
/* int timeout;
/* DESCRIPTION
/* timed_connect() implement a BSD socket connect() operation that is
/* bounded in time.
/*
/* Arguments:
/* .IP fd
/* File descriptor in the range 0..FD_SETSIZE. This descriptor
/* must be set to non-blocking mode prior to calling timed_connect().
/* .IP buf
/* Socket address buffer pointer.
/* .IP buf_len
/* Size of socket address buffer.
/* .IP timeout
/* The deadline in seconds. This must be a number > 0.
/* DIAGNOSTICS
/* Panic: interface violations.
/* When the operation does not complete within the deadline, the
/* result value is -1, and errno is set to ETIMEDOUT.
/* All other returns are identical to those of a blocking connect(2)
/* operation.
/* WARNINGS
/* .ad
/* .fi
/* A common error is to call timed_connect() without enabling
/* non-blocking I/O on the socket. In that case, the \fItimeout\fR
/* parameter takes no effect.
/* LICENSE
/* .ad
/* .fi
/* The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/* Wietse Venema
/* IBM T.J. Watson Research
/* P.O. Box 704
/* Yorktown Heights, NY 10598, USA
/*--*/
/* System library. */
#include <sys_defs.h>
#include <sys/socket.h>
#include <errno.h>
/* Utility library. */
#include "msg.h"
#include "iostuff.h"
#include "sane_connect.h"
#include "timed_connect.h"
/* timed_connect - connect with deadline */
int timed_connect(int sock, struct sockaddr *sa, int len, int timeout)
{
int error;
SOCKOPT_SIZE error_len;
/*
* Sanity check. Just like with timed_wait(), the timeout must be a
* positive number.
*/
if (timeout <= 0)
msg_panic("timed_connect: bad timeout: %d", timeout);
/*
* Start the connection, and handle all possible results.
*/
if (sane_connect(sock, sa, len) == 0)
return (0);
if (errno != EINPROGRESS)
return (-1);
/*
* A connection is in progress. Wait for a limited amount of time for
* something to happen. If nothing happens, report an error.
*/
if (write_wait(sock, timeout) < 0)
return (-1);
/*
* Something happened. Some Solaris 2 versions have getsockopt() itself
* return the error, instead of returning it via the parameter list.
*/
error = 0;
error_len = sizeof(error);
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *) &error, &error_len) < 0)
return (-1);
if (error) {
errno = error;
return (-1);
}
/*
* No problems.
*/
return (0);
}
|