1 | #include "server.h" |
---|
2 | |
---|
3 | int main (int argc, char ** argv) |
---|
4 | { |
---|
5 | struct in_addr remote_addr, |
---|
6 | local_addr; |
---|
7 | unsigned short remote_port, |
---|
8 | local_port; |
---|
9 | int listen_fd; |
---|
10 | |
---|
11 | ParseArgs (argc, argv, &remote_addr, &remote_port, &local_addr, &local_port); |
---|
12 | |
---|
13 | Initialise (); |
---|
14 | |
---|
15 | // Create server socket before becoming a daemon so |
---|
16 | // there is still a chance to print an error message. |
---|
17 | listen_fd = CreateServerSocket (local_addr, local_port); |
---|
18 | if ( listen_fd < 0 ) |
---|
19 | pbomb ("Unable to create server socket"); |
---|
20 | |
---|
21 | Daemonise (); |
---|
22 | |
---|
23 | MainLoop (listen_fd, remote_addr, remote_port); // never returns |
---|
24 | |
---|
25 | exit (EXIT_SUCCESS); |
---|
26 | } |
---|
27 | |
---|
28 | // ParseArgs() |
---|
29 | // Parse the command line arguments to extract the remote |
---|
30 | // and local adresses and port numbers, ra, rp, la & lp. |
---|
31 | // Exit the program gracefully upon error. |
---|
32 | void ParseArgs (int argc, char ** argv, struct in_addr * ra, unsigned short * rp, struct in_addr * la, unsigned short * lp) |
---|
33 | { |
---|
34 | // argv[0] = program name |
---|
35 | // argv[1] = remote_addr |
---|
36 | // argv[2] = remote_port |
---|
37 | // argv[3] = local_addr (optional) |
---|
38 | // argv[4] = local_port (optional) |
---|
39 | |
---|
40 | char * p = strrchr (argv[0], '/'); |
---|
41 | |
---|
42 | strncpy (g_program_name, (p == NULL) ? argv[0] : p + 1, sizeof (g_program_name) - 1); |
---|
43 | |
---|
44 | if ( (argc < 3) || (argc > 5) ) |
---|
45 | { |
---|
46 | fprintf (stderr, "usage: %s remote_addr remote_port [local_addr] [local_port]\n", argv[0]); |
---|
47 | exit (EXIT_FAILURE); |
---|
48 | } |
---|
49 | |
---|
50 | if ( NameToAddr (argv[1], ra) ) |
---|
51 | hbomb ("Unable to resolve \"%s\" to an ip address", argv[1]); |
---|
52 | |
---|
53 | if ( NameToPort (argv[2], rp, "tcp") ) |
---|
54 | quit ("Unable to resolve \"%s\" to a port number", argv[2]); |
---|
55 | |
---|
56 | if ( argc < 4 ) |
---|
57 | la->s_addr = htonl (INADDR_ANY); |
---|
58 | else |
---|
59 | if ( NameToAddr (argv[3], la) ) |
---|
60 | hbomb ("Unable to resolve \"%s\" to an ip address", argv[3]); |
---|
61 | |
---|
62 | if ( argc < 5 ) |
---|
63 | memcpy (lp, rp, sizeof (*lp)); |
---|
64 | else |
---|
65 | if ( NameToPort (argv[4], lp, "tcp") ) |
---|
66 | quit ("Unable to resolve \"%s\" to a port number", argv[4]); |
---|
67 | } |
---|
68 | |
---|
69 | // Initialise() |
---|
70 | // Setup syslog, signal handlers, and other intialisation. |
---|
71 | void Initialise (void) |
---|
72 | { |
---|
73 | openlog (g_program_name, LOG_PID, LOG_USER); |
---|
74 | syslog (LOG_INFO, "%s started", g_program_name); |
---|
75 | |
---|
76 | chdir ("/"); // Change working directory to the root. |
---|
77 | |
---|
78 | umask (0); // Clear our file mode creation mask |
---|
79 | |
---|
80 | set_signal_handler (SIGCHLD, sig_child); |
---|
81 | |
---|
82 | signal (SIGPIPE, SIG_IGN); |
---|
83 | } |
---|
84 | |
---|
85 | // sig_child() |
---|
86 | // Handles SIGCHLD from exiting child processes. |
---|
87 | void sig_child (int signo) |
---|
88 | { |
---|
89 | pid_t pid; |
---|
90 | |
---|
91 | (void) signo; // suppress compiler warning |
---|
92 | |
---|
93 | for ( ; ; ) |
---|
94 | { |
---|
95 | pid = waitpid (WAIT_ANY, NULL, WNOHANG); |
---|
96 | |
---|
97 | if ( pid > 0 ) |
---|
98 | syslog (LOG_INFO, "Caught SIGCHLD from pid %d", pid); |
---|
99 | else |
---|
100 | break; |
---|
101 | } |
---|
102 | |
---|
103 | if ( (pid < 0) && (errno != ECHILD) ) |
---|
104 | syslog (LOG_ERR, "waitpid(): %m"), exit (EXIT_FAILURE); |
---|
105 | |
---|
106 | return; |
---|
107 | } |
---|
108 | |
---|
109 | // CreateServerSocket() |
---|
110 | // Create a socket, bind it to the specified address |
---|
111 | // and port, and set it to listen for client connections. |
---|
112 | // Returns < 0 on failure to bind, bombs on error otherwise, |
---|
113 | // returns the fd of the new socket on success. |
---|
114 | int CreateServerSocket (struct in_addr addr, unsigned short port) |
---|
115 | { |
---|
116 | int err, |
---|
117 | fd; |
---|
118 | const int on = 1; |
---|
119 | struct sockaddr_in sa; |
---|
120 | |
---|
121 | // Create a socket and get its descriptor. |
---|
122 | fd = socket (AF_INET, SOCK_STREAM, 0); |
---|
123 | if ( fd < 0 ) |
---|
124 | syslog (LOG_ERR, "socket(): %m"), exit (EXIT_FAILURE); |
---|
125 | |
---|
126 | // Set SO_REUSEADDR socket option |
---|
127 | if ( setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0 ) |
---|
128 | syslog (LOG_ERR, "setsockopt(fd%d, SO_REUSEADDR): %m", fd); |
---|
129 | |
---|
130 | // Load a sa structure with the specified address and port |
---|
131 | sa.sin_family = AF_INET; |
---|
132 | sa.sin_port = htons (port); |
---|
133 | sa.sin_addr = addr; |
---|
134 | memset (sa.sin_zero, 0, sizeof (sa.sin_zero)); |
---|
135 | |
---|
136 | // Bind our socket to the address and port specified |
---|
137 | err = bind (fd, (struct sockaddr *) &sa, sizeof (sa)); |
---|
138 | if ( err < 0 ) |
---|
139 | { |
---|
140 | syslog (LOG_ERR, "bind(): %m"); |
---|
141 | return err; |
---|
142 | } |
---|
143 | |
---|
144 | // Tell socket to listen and queue up to 5 incoming connections. |
---|
145 | if ( listen (fd, 5) < 0 ) |
---|
146 | syslog (LOG_ERR, "listen(): %m"), exit (EXIT_FAILURE); |
---|
147 | |
---|
148 | return fd; |
---|
149 | } |
---|
150 | |
---|
151 | // Daemonise() |
---|
152 | // Put the program in the background, set PPID=1, create a |
---|
153 | // new session and process group, without a controlling tty. |
---|
154 | void Daemonise (void) |
---|
155 | { |
---|
156 | pid_t pid; |
---|
157 | |
---|
158 | // Close stdin, stdout & stderr |
---|
159 | // TODO: |
---|
160 | // open /dev/null and dup the fd to stdin, stdout & stderr |
---|
161 | // close(STDIN_FILENO); |
---|
162 | // close(STDOUT_FILENO); |
---|
163 | // close(STDERR_FILENO); |
---|
164 | |
---|
165 | syslog (LOG_INFO, "%s daemonising", g_program_name); |
---|
166 | |
---|
167 | // Fork the process to put it in the background. |
---|
168 | |
---|
169 | pid = fork (); |
---|
170 | if ( pid == -1 ) |
---|
171 | syslog (LOG_ERR, "fork(): %m"), exit (EXIT_FAILURE); |
---|
172 | |
---|
173 | // parent terminates here, so shell thinks the command is done. |
---|
174 | if ( pid ) |
---|
175 | exit (0); |
---|
176 | |
---|
177 | syslog (LOG_INFO, "%s in background", g_program_name); |
---|
178 | |
---|
179 | // 1st child continues to run in the background with PPID=1 |
---|
180 | |
---|
181 | // Become leader of a new session and a new process group, |
---|
182 | // with no controlling tty. |
---|
183 | setsid (); |
---|
184 | |
---|
185 | // Fork again to guarantee the process will |
---|
186 | // not be able to aquire a controlling tty. |
---|
187 | |
---|
188 | // signal (SIGHUP, SIG_IGN); |
---|
189 | // required according to Stevens' UNP2 p333 |
---|
190 | |
---|
191 | pid = fork (); |
---|
192 | if (pid == -1) |
---|
193 | syslog (LOG_ERR, "fork(): %m"), exit (EXIT_FAILURE); |
---|
194 | |
---|
195 | if ( pid ) // 1st child terminates |
---|
196 | exit (0); |
---|
197 | |
---|
198 | // 2nd child continues, no longer a session or group leader |
---|
199 | |
---|
200 | syslog (LOG_INFO, "%s daemonised", g_program_name); |
---|
201 | } |
---|
202 | |
---|
203 | // MainLoop() |
---|
204 | // Classic concurrent server model. |
---|
205 | // Wait for a client to connect, fork a child process |
---|
206 | // to do the business with the client, parent process |
---|
207 | // continues to wait for the next connection. |
---|
208 | // This function does not return. |
---|
209 | void MainLoop (int listen_fd, struct in_addr rem_addr, unsigned short rem_port) |
---|
210 | { |
---|
211 | int server_fd, |
---|
212 | client_fd; |
---|
213 | pid_t child_pid; |
---|
214 | |
---|
215 | for ( ; ; ) |
---|
216 | { |
---|
217 | client_fd = AcceptClientConnection (listen_fd); |
---|
218 | |
---|
219 | child_pid = fork (); |
---|
220 | |
---|
221 | if ( child_pid == -1 ) |
---|
222 | syslog (LOG_ERR, "fork(): %m"), exit (EXIT_FAILURE); |
---|
223 | |
---|
224 | if ( child_pid ) // parent |
---|
225 | { |
---|
226 | close (client_fd); |
---|
227 | |
---|
228 | syslog (LOG_INFO, "Forked child pid %d to deal with client", child_pid); |
---|
229 | |
---|
230 | continue; |
---|
231 | } |
---|
232 | else // child |
---|
233 | { |
---|
234 | close (listen_fd); |
---|
235 | |
---|
236 | server_fd = ConnectToServer (rem_addr, rem_port); |
---|
237 | |
---|
238 | Proxy (server_fd, client_fd); |
---|
239 | |
---|
240 | syslog (LOG_INFO, "exiting"); |
---|
241 | _exit (0); |
---|
242 | } |
---|
243 | } |
---|
244 | } |
---|
245 | |
---|
246 | // Proxy() |
---|
247 | // Copies data between server_fd and client_fd in both directions |
---|
248 | // until one or other peer closes their connection. |
---|
249 | void Proxy (int server_fd, int client_fd) |
---|
250 | { |
---|
251 | pid_t helper_pid; |
---|
252 | |
---|
253 | syslog (LOG_INFO, "Proxy(fd%d, fd%d)", server_fd, client_fd); |
---|
254 | |
---|
255 | signal (SIGCHLD, SIG_IGN); |
---|
256 | |
---|
257 | helper_pid = fork (); |
---|
258 | if ( helper_pid == -1 ) |
---|
259 | syslog (LOG_ERR, "fork(): %m"), exit (EXIT_FAILURE); |
---|
260 | |
---|
261 | if ( helper_pid ) // parent |
---|
262 | { |
---|
263 | syslog (LOG_INFO, "Forked child pid %d to help with proxying", helper_pid); |
---|
264 | |
---|
265 | Cat (server_fd, client_fd); |
---|
266 | |
---|
267 | shutdown (client_fd, 1); |
---|
268 | close (server_fd); |
---|
269 | close (client_fd); |
---|
270 | |
---|
271 | wait (0); // wait for helper to exit |
---|
272 | } |
---|
273 | else // child (helper) |
---|
274 | { |
---|
275 | Cat (client_fd, server_fd); |
---|
276 | |
---|
277 | shutdown (server_fd, 1); |
---|
278 | |
---|
279 | syslog (LOG_INFO, "exiting"); |
---|
280 | exit (0); // helper exits here |
---|
281 | } |
---|
282 | } |
---|
283 | |
---|
284 | // AcceptClientConnection() |
---|
285 | // waits for a tcp connect to the socket listen_fd, which |
---|
286 | // must already be bound and set to listen on a local port. |
---|
287 | // Bombs on error, returns the fd of the new socket on success. |
---|
288 | int AcceptClientConnection (int listen_fd) |
---|
289 | { |
---|
290 | int newfd; |
---|
291 | struct sockaddr_in sa; |
---|
292 | socklen_t socklen; |
---|
293 | |
---|
294 | syslog (LOG_INFO, "AcceptClientConnection(fd%d)", listen_fd); |
---|
295 | |
---|
296 | // Accept the connection and create a new socket for it. |
---|
297 | socklen = sizeof (sa); |
---|
298 | memset (&sa, 0, socklen); |
---|
299 | do |
---|
300 | { |
---|
301 | newfd = accept (listen_fd, (struct sockaddr *) &sa, &socklen); |
---|
302 | } |
---|
303 | while ( (newfd < 0) && (errno == EINTR) ); |
---|
304 | |
---|
305 | syslog (LOG_INFO, "Accepted client connection on new socket fd%d", newfd); |
---|
306 | |
---|
307 | if ( newfd < 0 ) |
---|
308 | syslog (LOG_ERR, "accept(): %m"), exit (EXIT_FAILURE); |
---|
309 | |
---|
310 | if ( socklen != sizeof (sa) ) |
---|
311 | syslog (LOG_ERR, "accept() screwed up!"), exit (EXIT_FAILURE); |
---|
312 | |
---|
313 | return (newfd); |
---|
314 | } |
---|
315 | |
---|
316 | // ConnectToServer() |
---|
317 | // attempts a tcp connect to the server specified |
---|
318 | // by addr and port. Bombs on failure to connect, |
---|
319 | // returns the fd of the new socket on success. |
---|
320 | int ConnectToServer (struct in_addr addr, unsigned short port) |
---|
321 | { |
---|
322 | // TODO: have a timeout for connect() - see Unix socket FAQ 6.2 |
---|
323 | |
---|
324 | int fd, err; |
---|
325 | struct sockaddr_in sa; |
---|
326 | |
---|
327 | // Create a socket and get its descriptor. |
---|
328 | fd = socket (AF_INET, SOCK_STREAM, 0); |
---|
329 | |
---|
330 | if ( fd < 0 ) |
---|
331 | syslog (LOG_ERR, "socket(): %m"), exit (EXIT_FAILURE); |
---|
332 | |
---|
333 | sa.sin_family = AF_INET; |
---|
334 | sa.sin_port = htons (port); |
---|
335 | sa.sin_addr = addr; |
---|
336 | memset (sa.sin_zero, 0, sizeof (sa.sin_zero)); |
---|
337 | |
---|
338 | err = connect (fd, (struct sockaddr *) &sa, sizeof (sa)); |
---|
339 | if (err < 0) |
---|
340 | { |
---|
341 | syslog (LOG_ERR, "Unable to connect socket fd%d to server: %m", fd); |
---|
342 | exit (EXIT_FAILURE); |
---|
343 | } |
---|
344 | |
---|
345 | syslog (LOG_INFO, "Connected socket fd%d to server", fd); |
---|
346 | |
---|
347 | return fd; |
---|
348 | } |
---|
349 | |
---|
350 | // Cat() |
---|
351 | // read data from in_fd and write it to out_fd until |
---|
352 | // the connection is closed by one of the peers. |
---|
353 | // Data is copied using a dynamically allocated buffer. |
---|
354 | void Cat (int in_fd, int out_fd) |
---|
355 | { |
---|
356 | unsigned char * const buf = malloc (BUF_SIZE); |
---|
357 | int bytes_rcvd, |
---|
358 | bytes_sent = 0, |
---|
359 | i; |
---|
360 | |
---|
361 | syslog (LOG_INFO, "Cat(fd%d, fd%d)", in_fd, out_fd); |
---|
362 | |
---|
363 | if ( buf == NULL ) |
---|
364 | syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); |
---|
365 | |
---|
366 | do |
---|
367 | { |
---|
368 | bytes_rcvd = recv (in_fd, buf, BUF_SIZE, 0); |
---|
369 | |
---|
370 | for ( i = 0; i < bytes_rcvd; i += bytes_sent ) |
---|
371 | { |
---|
372 | bytes_sent = send (out_fd, buf + i, bytes_rcvd - i, 0); |
---|
373 | |
---|
374 | if ( bytes_sent < 0 ) |
---|
375 | break; |
---|
376 | } |
---|
377 | } |
---|
378 | while ( (bytes_rcvd > 0) && (bytes_sent > 0) ); |
---|
379 | |
---|
380 | if ( (bytes_rcvd < 0) && (errno != ECONNRESET) ) |
---|
381 | syslog (LOG_ERR, "recv(): %m"), exit (EXIT_FAILURE); |
---|
382 | |
---|
383 | if ( (bytes_sent < 0) && (errno != EPIPE) ) |
---|
384 | syslog (LOG_ERR, "send(): %m"), exit (EXIT_FAILURE); |
---|
385 | |
---|
386 | free (buf); |
---|
387 | } |
---|
388 | |
---|
389 | // NameToAddress() |
---|
390 | // Convert name to an ip address. |
---|
391 | // Returns 0 on success, -1 on failure. |
---|
392 | int NameToAddr (const char * name, struct in_addr * p_inaddr) |
---|
393 | { |
---|
394 | struct hostent * he; |
---|
395 | |
---|
396 | // First, attempt to convert from string ip format |
---|
397 | // TODO: use inet_aton() instead |
---|
398 | p_inaddr->s_addr = inet_addr (name); |
---|
399 | if ( p_inaddr->s_addr != -1U ) // Success |
---|
400 | return 0; |
---|
401 | |
---|
402 | // Next, attempt to read from /etc/hosts or do a DNS lookup |
---|
403 | he = gethostbyname (name); |
---|
404 | if ( he != NULL ) // Success |
---|
405 | { |
---|
406 | memcpy (p_inaddr, he->h_addr, sizeof (struct in_addr)); |
---|
407 | return 0; |
---|
408 | } |
---|
409 | |
---|
410 | return -1; // Failed to resolve name to an ip address |
---|
411 | } |
---|
412 | |
---|
413 | // NameToPort() |
---|
414 | // Convert name to a port number. Name can either be a port name |
---|
415 | // (in which case proto must also be set to either "tcp" or "udp") |
---|
416 | // or name can be the ascii representation of the port number. |
---|
417 | // Returns 0 on success, -1 on failure. |
---|
418 | int NameToPort (const char * name, unsigned short * port, const char * proto) |
---|
419 | { |
---|
420 | unsigned long lport; |
---|
421 | char * errpos; |
---|
422 | struct servent * se; |
---|
423 | |
---|
424 | // First, attempt to convert string to integer |
---|
425 | lport = strtoul (name, &errpos, 0); |
---|
426 | if ( (*errpos == 0) && (lport <= 65535) ) // Success |
---|
427 | { |
---|
428 | *port = lport; |
---|
429 | return 0; |
---|
430 | } |
---|
431 | |
---|
432 | // Next, attempt to read the string from /etc/services |
---|
433 | se = getservbyname (name, proto); |
---|
434 | if ( se != NULL) // Success |
---|
435 | { |
---|
436 | *port = ntohs (se->s_port); |
---|
437 | return 0; |
---|
438 | } |
---|
439 | |
---|
440 | return -1; // Failed to resolve port name to a number |
---|
441 | } |
---|
442 | |
---|
443 | // quit() |
---|
444 | // Print an error message to stderr |
---|
445 | // and syslog, then exit the program. |
---|
446 | void quit (const char * fmt, ...) // quit with msg |
---|
447 | { |
---|
448 | va_list ap; |
---|
449 | |
---|
450 | fflush (stdout); |
---|
451 | |
---|
452 | fprintf (stderr, "%s: ", g_program_name); |
---|
453 | |
---|
454 | va_start (ap, fmt); |
---|
455 | vfprintf (stderr, fmt, ap); |
---|
456 | va_end (ap); |
---|
457 | |
---|
458 | fputc ('\n', stderr); |
---|
459 | |
---|
460 | syslog (LOG_ERR, "I quit!"); |
---|
461 | |
---|
462 | exit (EXIT_FAILURE); |
---|
463 | } |
---|
464 | |
---|
465 | // pbomb() |
---|
466 | // Print an error message to stderr |
---|
467 | // and syslog, then exit the program. |
---|
468 | // pbomb() additionally include the |
---|
469 | // string representation of errno. |
---|
470 | void pbomb (const char * fmt, ...) // bomb with perror |
---|
471 | { |
---|
472 | va_list ap; |
---|
473 | int errno_save = errno; |
---|
474 | char buf[100]; |
---|
475 | |
---|
476 | fflush (stdout); |
---|
477 | |
---|
478 | fprintf (stderr, "%s: ", g_program_name); |
---|
479 | |
---|
480 | va_start (ap, fmt); |
---|
481 | vsnprintf (buf, sizeof (buf), fmt, ap); |
---|
482 | va_end (ap); |
---|
483 | |
---|
484 | errno = errno_save; |
---|
485 | perror (buf); |
---|
486 | |
---|
487 | syslog (LOG_ERR, "Bang!: %s: %m", buf); |
---|
488 | |
---|
489 | exit (EXIT_FAILURE); |
---|
490 | } |
---|
491 | |
---|
492 | // hbomb() |
---|
493 | // Print an error message to stderr |
---|
494 | // and syslog, then exit the program. |
---|
495 | // hbomb() additionally include the |
---|
496 | // string representation of h_errno. |
---|
497 | void hbomb (const char * fmt, ...) // bomb with herror |
---|
498 | { |
---|
499 | va_list ap; |
---|
500 | int h_errno_save = h_errno; |
---|
501 | char buf[100]; |
---|
502 | |
---|
503 | fflush (stdout); |
---|
504 | |
---|
505 | fprintf (stderr, "%s: ", g_program_name); |
---|
506 | |
---|
507 | va_start (ap, fmt); |
---|
508 | vsnprintf (buf, sizeof (buf), fmt, ap); |
---|
509 | va_end (ap); |
---|
510 | |
---|
511 | h_errno = h_errno_save; |
---|
512 | herror (buf); |
---|
513 | |
---|
514 | syslog (LOG_ERR, "Bang!: %s: %s", buf, hstrerror (h_errno)); |
---|
515 | |
---|
516 | exit (EXIT_FAILURE); |
---|
517 | } |
---|
518 | |
---|
519 | // set_signal_handler() |
---|
520 | // Sets a signal handler function. |
---|
521 | // Similar to signal() but this method |
---|
522 | // is more portable between platforms. |
---|
523 | void set_signal_handler (int signum, signal_handler_t sa_handler_func) |
---|
524 | { |
---|
525 | struct sigaction act; |
---|
526 | |
---|
527 | act.sa_handler = sa_handler_func; |
---|
528 | sigemptyset (&(act.sa_mask)); |
---|
529 | act.sa_flags = 0; |
---|
530 | |
---|
531 | if ( sigaction (signum, &act, NULL) < 0 ) |
---|
532 | { |
---|
533 | syslog (LOG_ERR, "Error setting handler for signal %d: %m", signum); |
---|
534 | exit (EXIT_FAILURE); |
---|
535 | } |
---|
536 | } |
---|