File: vanessa_socket_client.c

package info (click to toggle)
vanessa-socket 0.0.13-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,728 kB
  • sloc: sh: 11,325; ansic: 1,659; makefile: 69
file content (432 lines) | stat: -rw-r--r-- 12,403 bytes parent folder | download | duplicates (5)
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**********************************************************************
 * vanessa_socket_client.c                                November 1999
 * Simon Horman                                      horms@verge.net.au
 *
 * Open a tcp socket to a server (we are the client)
 *
 * vanessa_socket
 * Library to simplify handling of TCP sockets
 * Copyright (C) 1999-2008  Simon Horman <horms@verge.net.au>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 * 
 * This library 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
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307 USA
 *
 **********************************************************************/

#include "vanessa_socket.h"


/**********************************************************************
 * vanessa_socket_client_open_sockaddr_in
 * Open a socket connection as a client
 * pre: to: sockaddr structure specifying address and port to connect 
 *          to.
 *      flag: If VANESSA_SOCKET_NO_LOOKUP then no host and port lookups
 *            will be performed
 * post: socket is opened
 * return: open socket
 *         -1 on error
 **********************************************************************/

int vanessa_socket_client_open_sockaddr_in(struct sockaddr_in to,
					   const vanessa_socket_flag_t
					   flag)
{
	int s;
	struct sockaddr_in from;

	/* Connect to foreign 'to' server */
	s = vanessa_socket_client_open_src_sockaddr_in(from, to, 
			flag | VANESSA_SOCKET_NO_FROM);
	if (s < 0) {
		VANESSA_LOGGER_DEBUG
		    ("vanessa_socket_client_open_src_sockaddr_in");
		return (-1);
	}

	return (s);
}



/**********************************************************************
 * vanessa_socket_client_open
 * Open a socket connection as a client
 * pre: host: hostname or ipaddress to open socket to
 *      port: name or number to open
 *      flag: If VANESSA_SOCKET_NO_LOOKUP then no host and port lookups
 *            will be performed
 * post: socket is opened
 * return: open socket
 *         -1 on error
 **********************************************************************/

int vanessa_socket_client_open(const char *host,
			       const char *port,
			       const vanessa_socket_flag_t flag)
{
	int s;

	s = vanessa_socket_client_src_open(NULL, NULL, host, port, 
			flag | VANESSA_SOCKET_NO_FROM);
	if (s < 0) {
		VANESSA_LOGGER_DEBUG("vanessa_socket_client_src_open");
		return (-1);
	}

	return (s);
}


/**********************************************************************
 * vanessa_socket_client_open_src_sockaddr_in
 * Open a socket connection as a client
 * pre: from: sockaddr structure specifying address and port to connect
 *            from. 
 *            If from.sin_addr.s_addr==INADDR_ANY then the operating 
 *            system will select an appropriate source address.
 *            If from.sin_port==INPORT_ANY then the operating system 
 *            will select an appropriate source address.
 *      to: sockaddr structure specifying address and port to connect 
 *          to.
 *      flag: Logical or of VANESSA_SOCKET_NO_LOOKUP and 
 *            VANESSA_SOCKET_NO_FROM
 *            If flag&VANESSA_SOCKET_NO_LOOKUP then no host and port 
 *            lookups will be performed 
 *            If flag&VANESSA_SOCKET_NO_FROM then the from parameter 
 *            will not be used and the operating system will select a 
 *            source address and port
 *            If flag&VANESSA_SOCKET_TCP_KEEPALIVE then turn on
 *            TCP-Keepalive
 * post: socket is opened
 * return: open socket
 *         -1 on error
 **********************************************************************/

int vanessa_socket_client_open_src_sockaddr_in(struct sockaddr_in from,
					       struct sockaddr_in to,
					       const vanessa_socket_flag_t
					       flag)
{
	int out;
	int g;

	/* Create socket */
	memset((struct sockaddr *) &from, 0, sizeof(from));
	if ((out = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		VANESSA_LOGGER_DEBUG_ERRNO("socket");
		return (-1);
	}

	/* Turn on TCP-Keepalive */
	if (flag & VANESSA_SOCKET_TCP_KEEPALIVE) {
		g = 1;
		setsockopt(out, SOL_SOCKET, SO_KEEPALIVE, (void *) &g, sizeof g);
	}

	/* Bind 'from' to socket */
	if (!(flag & VANESSA_SOCKET_NO_FROM) ||
	    from.sin_addr.s_addr != INADDR_ANY ||
	    from.sin_port != INPORT_ANY) {
		if (bind
		    (out, (struct sockaddr *) &from,
		     sizeof(struct sockaddr_in)) < 0) {
			VANESSA_LOGGER_DEBUG_ERRNO("bind");
			return (-1);
		}
	}

	/* Connect to foreign 'to' server */
	if (connect(out, (struct sockaddr *) &to, sizeof(to)) < 0) {
		VANESSA_LOGGER_DEBUG_ERRNO("connect");
		return (-1);
	}

	return (out);
}



/**********************************************************************
 * vanessa_socket_client_src_open
 * Open a socket connection as a client
 * pre: src_host: hostname or ipaddress to open socket from
 *                If NULL then the operating system will select
 *                an appropriate source address.
 *      src_port: name or number to open
 *                If NULL then the operating system will select
 *                an appropriate source port.
 *      dst_host: hostname or ipaddress to open socket to
 *      dst_port: name or number to open
 *      flag: Logical or of VANESSA_SOCKET_NO_LOOKUP and 
 *            VANESSA_SOCKET_NO_FROM
 *            If flag&VANESSA_SOCKET_NO_LOOKUP then no host and port 
 *            lookups will be performed 
 *            If flag&VANESSA_SOCKET_NO_FROM then the from parameter 
 *            will not be used and the operating system will select a 
 *            source address and port
 *            If flag&VANESSA_SOCKET_TCP_KEEPALIVE then turn on
 *            TCP-Keepalive
 * post: socket is opened
 * return: open socket
 *         -1 on error
 **********************************************************************/

int vanessa_socket_client_src_open(const char *src_host,
				   const char *src_port,
				   const char *dst_host,
				   const char *dst_port,
				   const vanessa_socket_flag_t flag)
{
	int s, err;
	struct addrinfo hints, *dst_ai, *src_ai;
	struct addrinfo *dst_res = NULL, *src_res = NULL;
	int g;

	src_res = NULL;
	/* Get sockaddr list for source address */
	if ((src_host || src_port) && !(flag & VANESSA_SOCKET_NO_FROM)) {
		bzero(&hints, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		err = getaddrinfo(src_host, src_port, &hints, &src_res);
		if (err) {
			src_res = NULL;
			if (err == EAI_SYSTEM)
				VANESSA_LOGGER_DEBUG_UNSAFE("getaddrinfo src: "
							    "\"%s\" \"%s\": %s",
							    src_host, src_port,
							    strerror(errno));
			else
				VANESSA_LOGGER_DEBUG_UNSAFE("getaddrinfo src: "
							    "\"%s\" \"%s\": %s",
							    src_host, src_port,
							    gai_strerror(err));
			goto err;
		}
	}

	/* Get sockaddr list for destination address */
	bzero(&hints, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	err = getaddrinfo(dst_host, dst_port, &hints, &dst_res);
	if (err) {
		dst_res = NULL;
		if (err == EAI_SYSTEM)
			VANESSA_LOGGER_DEBUG_UNSAFE("getaddrinfo dst: "
						    "\"%s\" \"%s\": %s",
						    dst_host, dst_port,
						    strerror(errno));
		else
			VANESSA_LOGGER_DEBUG_UNSAFE("getaddrinfo dst: "
						    "\"%s\" \"%s\": %s",
						    dst_host, dst_port,
						    gai_strerror(err));
		goto err;
	}

	/* Try all combinations of destination and source until we get a
	 * connection.
	 */
	dst_ai = dst_res;
	do {
		/* Create socket */
		if ( (s = socket(dst_res->ai_family, dst_res->ai_socktype,
				 dst_res->ai_protocol)) < 0) {
			VANESSA_LOGGER_DEBUG_ERRNO("socket");
			continue;
		}

		/* Turn on TCP-Keepalive */
		if (flag & VANESSA_SOCKET_TCP_KEEPALIVE) {
			g = 1;
			setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &g,
				   sizeof g);
		}

		src_ai = src_res;
		/* Run through this loop at least once even if there is no 
		 * explicit source address.
		 */
		do {
			if (src_ai) {
				/* Bind source address to socket */
				if (bind(s, src_ai->ai_addr,
					 src_ai->ai_addrlen) < 0 ) {
					VANESSA_LOGGER_DEBUG_ERRNO("bind");
					continue;
				}
			}
			/* Connect to destination server */
			if (connect(s, dst_res->ai_addr,
				    dst_res->ai_addrlen) == 0)
				goto out;
			VANESSA_LOGGER_DEBUG_ERRNO("connect");
		} while (src_ai && (src_ai = src_ai->ai_next));

		if (close(s)) {
			VANESSA_LOGGER_DEBUG_ERRNO("close");
			goto err;
		}
	} while (dst_ai && (dst_ai = dst_ai->ai_next));

	VANESSA_LOGGER_DEBUG("vanessa_socket_client_src_open");
err:
	s = -1;
out:
	if (dst_res)
		freeaddrinfo(dst_res);
	if (src_res)
		freeaddrinfo(src_res);
	return s;
}


#ifdef THIS_CODE_IS_EXPERIMENTAL
/* Code below this line is Experimental */

int vanessa_socket_client_open_src_sockaddr_inv
    (struct sockaddr_in from, struct sockaddr_in *to, int tocount,
     const vanessa_socket_flag_t flag) {
	int s, i, hifd = 0, remaining = 0, ret = -1;
	fd_set connections;
	long opt = 1;
	struct timeval tv;

	FD_ZERO(&connections);
	tv.tv_sec = 120;
	tv.tv_usec = 0;

	for (i = 0; i < tocount; i++) {
		if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
			VANESSA_LOGGER_DEBUG_ERRNO("socket");
			goto out;
		}
		if (!(flag & VANESSA_SOCKET_NO_FROM)) {
			if (setsockopt
			    (s, SOL_SOCKET, SO_REUSEADDR, &opt,
			     sizeof(opt)))
				VANESSA_LOGGER_DEBUG_ERRNO
				    ("setsockopt(SO_REUSEADDR)");
			if (bind
			    (s, (struct sockaddr *) &from,
			     sizeof(from)) < 0) {
				VANESSA_LOGGER_DEBUG_ERRNO("bind");
				goto out;
			}
		}
		if (fcntl(s, F_SETFL, O_NDELAY))
			VANESSA_LOGGER_DEBUG_ERRNO("fcntl(O_NDELAY)");
		if (connect(s, (struct sockaddr *) (to + i), sizeof(*to)) <
		    0 && errno != EINPROGRESS) {
			VANESSA_LOGGER_DEBUG_ERRNO("connect");
			goto out;
		}
		FD_SET(s, &connections);
		if (s > hifd)
			hifd = s;
		remaining++;
	}

	while (tv.tv_sec > 0 || tv.tv_usec > 0) {
		struct timeval now, then, timeout;
		int j;
		fd_set rfds, wfds;

		memcpy(&timeout, &tv, sizeof(tv));
		FD_ZERO(&rfds);
		FD_ZERO(&wfds);
		for (i = 0; i <= hifd; i++)
			if (FD_ISSET(i, &connections)) {
				FD_SET(i, &rfds);
				FD_SET(i, &wfds);
			}
		gettimeofday(&now, NULL);
		i = select(hifd + 1, &rfds, &wfds, NULL, &timeout);
		if (i < 0) {
			VANESSA_LOGGER_DEBUG_ERRNO("select");
			goto out;
		}
		if (!i)
			goto out;
		gettimeofday(&then, NULL);
		timeradd(&tv, &now, &tv);
		timersub(&tv, &then, &tv);
		for (j = 0; j <= hifd; j++) {
			int serr, serrlen;

			serrlen = sizeof(serr);
			if (FD_ISSET(j, &wfds) || FD_ISSET(j, &rfds)) {
				if (!getsockopt
				    (j, SOL_SOCKET, SO_ERROR, &serr,
				     &serrlen) && !serr) {
					ret = j;
					goto out;
				}
				close(j);
				FD_CLR(j, &connections);
			}
		}
	}

      out:
	for (i = 0; i <= hifd; i++) {
		if (i == ret)
			continue;
		if (FD_ISSET(i, &connections))
			close(i);
	}
	if (ret >= 0)
		if (fcntl(ret, F_SETFL, O_NDELAY))
			VANESSA_LOGGER_DEBUG_ERRNO("fcntl(O_NDELAY)");
	return ret;
}


int vanessa_socket_host_port_sockaddr_inv(const char *host,
					  const char *port,
					  struct sockaddr_in **addr,
					  int *addrcount,
					  const vanessa_socket_flag_t flag)
{
	int portno;
	int i, count = 0;
	struct hostent *hp;

	memset((struct sockaddr *) addr, 0, sizeof(addr));

	if ((hp = gethostbyname(host)) == NULL) {
		VANESSA_LOGGER_DEBUG_HERRNO("gethostbyname");
		return (-1);
	}
	while (hp->h_addr_list[++count]);
	*addr = malloc(sizeof(**addr) * count);

	if ((portno = vanessa_socket_port_portno(port, flag)) < 0) {
		VANESSA_LOGGER_DEBUG("vanessa_socket_port_portno");
		return (-1);
	}
	for (i = 0; i < count; i++) {
		(*addr)[i].sin_family = AF_INET;
		(*addr)[i].sin_port = (unsigned short int) portno;
		memcpy(&(*addr)[i].sin_addr.s_addr, hp->h_addr_list[i],
		       hp->h_length);
	}
	*addrcount = count;
	return 0;
}

#endif				/* THIS_CODE_IS_EXPERIMENTAL */