File: sockrun.c

package info (click to toggle)
libhsync 0.5.7-1.2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,060 kB
  • ctags: 543
  • sloc: sh: 7,944; ansic: 5,413; makefile: 154
file content (421 lines) | stat: -rw-r--r-- 10,273 bytes parent folder | download
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
/*=				       	-*- c-file-style: "bsd" -*-
 * rproxy -- dynamic caching and delta update in HTTP
 * $Id: sockrun.c,v 1.7 2000/08/06 12:50:36 mbp Exp $
 *
 * Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>
 *
 * This program 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.1 of the License, 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * sockrun.c -- Run a program with input and output filtered through
 * sockets.
 *
 * In a perfectly functional program this will prove nothing.
 * However, in one which has bugs to do with packetization causing
 * short reads and writes, this might shake out some bugs.
 *
 * This program is called with the arguments for a subsidiary command
 * (leaving aside some options.)  On execution, it forks into three parts:
 *
 *    stdin --INPUT--> COMMAND --OUTPUT--> stdout
 *
 * The program creates two localhost sockets.  The middle part execs
 * the specified command.  The two outer parts copy to and from
 * stdout.  When eof or SIGPIPE is reached on any file, that part
 * terminates: they do not necessarily all finish together.  The main
 * program waits for them all to complete, and exits successfully only
 * if all the parts exited successfully.
 *
 * On Linux you can change the loopback MTU to fiddle with this.
 * However quite often more than one packet will slip through before
 * the call returns.
 */

/*
 * TODO: Let the input and output parts proceed more slowly, or with
 * randomly limited lengths, so that it's more likely fragmentation
 * will be seen in the middle.  In particular, let people set a
 * maximum size for data copied in and out, and also a time in ms to
 * sleep between reads and writes.
 *
 * TODO: Should we display an error message on broken pipes, or not?
 * If we do, then a program which terminates without reading all of
 * its input will cause an error -- but this is perhaps good behaviour
 * anyhow.
 *
 * TODO: Another version of this which takes *two* commands and runs
 * them with a socket joining stdout of the first to stdin of the
 * second.  This might be good for testing encoding and decoding
 * working together.  The syntax is probably something like this:
 *
 *   sockrun2 hsnad \| hsdecode
 *
 * Perhaps we want to just support that as a generalization within
 * this single sockrun program?
 */


#include "includes.h"

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

#include <netinet/in.h>
#include <netinet/tcp.h>

#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>

static int no_nagle = 0;
static pid_t            in_pid, cmd_pid, out_pid;
static int              out_svr_sock, in_svr_sock;
static int              cmd_argc;
static char           **cmd_argv;
int                     out_port, in_port;


static void
show_usage(void)
{
    printf("Usage: sockcli COMMAND [ARG ...]\n"
           "Connect to a local TCP port and copy data in and out\n"
           "  -N    don't Nagle me; send packets immediately\n"
           "  -D    turn on trace, if enabled in library\n");
}


static int
open_client_socket(int *psock, int port)
{
    struct sockaddr_in addr;
    int             sock;

    /* Create a socket */
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        _hs_error("create socket failed: %s", strerror(errno));
	return -1;
    }

    hs_bzero((char *) &addr, sizeof addr);
#ifdef HAVE_SOCK_SIN_LEN
    addr.sin_len = sizeof(addr);
#endif
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(0x7f000001);

    if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &no_nagle,
                   sizeof no_nagle) < 0) {
        _hs_error("error setting TCP_NODELAY=%d: %s",
                  no_nagle, strerror(errno));
    }

    if (connect(sock, (struct sockaddr *) &addr, sizeof addr) < 0) {
        _hs_error("connect socket to localhost:%d failed: %s",
                  port, strerror(errno));
	return (-1);
    }

    _hs_trace("got socket %d on port %d", sock, ntohs(addr.sin_port));
    *psock = sock;

    return 1;
}


static int
bind_any_socket(int *psock, int *pport)
{
    struct sockaddr_in addr;
    int             sock;
#ifdef HAVE_SOCKLEN_T
    socklen_t           len;
#else
    size_t len;
#endif

    /* Create a socket */
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        _hs_error("create socket failed: %s", strerror(errno));
	return -1;
    }

    /* Get an address.  Any address is fine. */
    hs_bzero((char *) &addr, sizeof addr);
#ifdef HAVE_SOCK_SIN_LEN
    addr.sin_len = sizeof(addr);
#endif
    addr.sin_port = 0;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(sock, (struct sockaddr *) &addr, sizeof addr) < 0) {
        _hs_error("bind socket failed: %s", strerror(errno));
	return (-1);
    }

    /* where are we? */
    len = sizeof addr;
    if (getsockname(sock, (struct sockaddr *) &addr, &len) < 0) {
        _hs_error("getsockname failed: %s", strerror(errno));
        return -1;
    }

    _hs_trace("got socket on port %d", ntohs(addr.sin_port));

    *pport = ntohs(addr.sin_port);
    *psock = sock;

    if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &no_nagle,
                   sizeof no_nagle) < 0) {
        _hs_error("error setting TCP_NODELAY=%d: %s",
                  no_nagle, strerror(errno));
    }

    /* Listen for connections. */
    if (listen(sock, 10) < 0) {
        _hs_error("listen failed: %s", strerror(errno));
        return -1;
    }

    return 1;
}



static int
out_main(void)
{
    int         out_sock;

    int ret;
    _hs_trace("output process waiting for connection");
    if ((out_sock = accept(out_svr_sock, NULL, 0)) < 0) {
        _hs_error("can't accept connection to output: %s",
                  strerror(errno));
        return 1;
    }
    close(out_svr_sock);

    ret = _hs_file_copy_all(out_sock, STDOUT_FILENO);
    if (close(out_sock) < 0) {
        _hs_error("close write socket: %s", strerror(errno));
        return -1;
    }

    return 0;
}


static int
in_main(void)
{
    int         in_sock;
    int ret;

    if (open_client_socket(&in_sock, in_port) < 0) {
        return 1;
    }

    ret = _hs_file_copy_all(STDIN_FILENO, in_sock);
    close(in_sock);

    return 0;
}

static int
fork_run(pid_t *new_pid, int (*fn)(void))
{
    pid_t               pid;

    pid = fork();
    if (pid < 0) {
        _hs_error("error forking child: %s", strerror(errno));
        return -1;
    } else if (pid == 0) {
        exit(fn());
    } else {
        _hs_trace("forked child %d", (int) pid);
        *new_pid = pid;
        return pid;
    }
}


static int
start_output(void)
{
    if (bind_any_socket(&out_svr_sock, &out_port ) < 0)
        return -1;

    if (fork_run(&out_pid, out_main) < 0)
        return -1;

    close(out_svr_sock);        /* in parent */

    return 0;
}


static int
cmd_main(void)
{
    int         cmd_out_sock, cmd_in_sock;

    if (open_client_socket(&cmd_out_sock, out_port) < 0) {
        return 1;
    }

    _hs_trace("command process waiting for connection");
    if ((cmd_in_sock = accept(in_svr_sock, NULL, 0)) < 0) {
        _hs_error("can't accept connection to command: %s",
                  strerror(errno));
        return 1;
    }
    close(in_svr_sock);

    if (dup2(cmd_out_sock, STDOUT_FILENO) < 0) {
        _hs_error("can't redirect command output to socket: %s",
                  strerror(errno));
        return 1;
    }
    if (dup2(cmd_in_sock, STDIN_FILENO) < 0) {
        _hs_error("can't redirect command input from socket: %s",
                  strerror(errno));
        return 1;
    }

    if (execvp(cmd_argv[0], cmd_argv) < 0) {
        _hs_error("can't start %s: %s",
                  cmd_argv[0], strerror(errno));
        return 1;
    }

    return 0;                   /* should be unreachable */
}


static int
start_command(void)
{
    if (bind_any_socket(&in_svr_sock, &in_port) < 0)
        return -1;

    if (fork_run(&cmd_pid, cmd_main) < 0)
        return -1;

    close(in_svr_sock);         /* in parent */
    return 0;
}


static int
start_input(void)
{
    if (fork_run(&in_pid, in_main) < 0)
        return -1;
    return 0;
}


static int
reap_child(int pid)
{
    int status;

    if (waitpid(pid, &status, 0) < 0) {
        _hs_error("wait error: %s", strerror(errno));
        return -1;
    }

    if (status) {
        _hs_error("child %d exited with status %#x",
                  pid, status);
        return -1;
    } else {
        _hs_trace("child %d exited with status %#x",
                  pid, status);
        return 0;
    }
}



int
main(int argc, char **argv)
{
    int                 c;

    /* may turn it on later */
    while ((c = getopt(argc, argv, "DN")) != -1) {
	switch (c) {
	case '?':
	case ':':
	    return -1;
    	case 'D':
	    if (!hs_supports_trace()) {
		_hs_error("library does not support trace");
	    }
	    hs_trace_set_level(LOG_DEBUG);
	    break;
        case 'N':
            no_nagle = 1;
            break;
        default:
            abort();
	}
    }

    signal(SIGPIPE, SIG_IGN);

    if (optind >= argc) {
        show_usage();
        return 1;
    }

    cmd_argc = argc - optind;
    cmd_argv = argv + optind;

    if (start_output() < 0) {
        return 1;
    }

    if (start_command() < 0) {
        kill(out_pid, SIGHUP);
        return 1;
    }

    if (start_input() < 0) {
        kill(out_pid, SIGHUP);
        kill(cmd_pid, SIGHUP);
        return 1;
    }

    reap_child(out_pid);
    reap_child(cmd_pid);
    reap_child(in_pid);

    return 0;
}