added a size > buffer size check to make it easier to track this in the
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 /* Purpose
25  *
26  * 1. Accept a TCP connection on a custom port (ipv4 or ipv6), or connect
27  *    to a given (localhost) port.
28  *
29  * 2. Get commands on STDIN. Pass data on to the TCP stream.
30  *    Get data from TCP stream and pass on to STDOUT.
31  *
32  * This program is made to perform all the socket/stream/connection stuff for
33  * the test suite's (perl) FTP server. Previously the perl code did all of
34  * this by its own, but I decided to let this program do the socket layer
35  * because of several things:
36  *
37  * o We want the perl code to work with rather old perl installations, thus
38  *   we cannot use recent perl modules or features.
39  *
40  * o We want IPv6 support for systems that provide it, and doing optional IPv6
41  *   support in perl seems if not impossible so at least awkward.
42  *
43  * o We want FTP-SSL support, which means that a connection that starts with
44  *   plain sockets needs to be able to "go SSL" in the midst. This would also
45  *   require some nasty perl stuff I'd rather avoid.
46  *
47  * (Source originally based on sws.c)
48  */
49 #include "setup.h" /* portability help from the lib directory */
50
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <stdarg.h>
55 #include <signal.h>
56 #include <time.h>
57 #include <ctype.h>
58 #include <sys/time.h>
59 #include <sys/types.h>
60
61 #ifdef HAVE_UNISTD_H
62 #include <unistd.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 #include <netinet/in.h>
69 #endif
70 #ifdef _XOPEN_SOURCE_EXTENDED
71 /* This define is "almost" required to build on HPUX 11 */
72 #include <arpa/inet.h>
73 #endif
74 #ifdef HAVE_NETDB_H
75 #include <netdb.h>
76 #endif
77
78 #define ENABLE_CURLX_PRINTF
79 /* make the curlx header define all printf() functions to use the curlx_*
80    versions instead */
81 #include "curlx.h" /* from the private lib dir */
82 #include "getpart.h"
83 #include "inet_pton.h"
84 #include "util.h"
85
86 /* include memdebug.h last */
87 #include "memdebug.h"
88
89 #define DEFAULT_PORT 8999
90
91 #ifndef DEFAULT_LOGFILE
92 #define DEFAULT_LOGFILE "log/sockfilt.log"
93 #endif
94
95 #ifdef SIGPIPE
96 static volatile int sigpipe;  /* Why? It's not used */
97 #endif
98
99 const char *serverlogfile = (char *)DEFAULT_LOGFILE;
100
101 static void lograw(unsigned char *buffer, ssize_t len)
102 {
103   char data[120];
104   ssize_t i;
105   unsigned char *ptr = buffer;
106   char *optr = data;
107   ssize_t width=0;
108
109   for(i=0; i<len; i++) {
110     switch(ptr[i]) {
111     case '\n':
112       sprintf(optr, "\\n");
113       width += 2;
114       optr += 2;
115       break;
116     case '\r':
117       sprintf(optr, "\\r");
118       width += 2;
119       optr += 2;
120       break;
121     default:
122       sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
123       width++;
124       optr++;
125       break;
126     }
127
128     if(width>60) {
129       logmsg("'%s'", data);
130       width = 0;
131       optr = data;
132     }
133   }
134   if(width)
135     logmsg("'%s'", data);
136 }
137
138 #ifdef SIGPIPE
139 static void sigpipe_handler(int sig)
140 {
141   (void)sig; /* prevent warning */
142   sigpipe = 1;
143 }
144 #endif
145
146 char use_ipv6=FALSE;
147 unsigned short port = DEFAULT_PORT;
148 unsigned short connectport = 0; /* if non-zero, we activate this mode */
149
150 enum sockmode {
151   PASSIVE_LISTEN,    /* as a server waiting for connections */
152   PASSIVE_CONNECT,   /* as a server, connected to a client */
153   ACTIVE,            /* as a client, connected to a server */
154   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
155 };
156
157 /*
158   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
159
160   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
161   accept()
162 */
163 static int juggle(curl_socket_t *sockfdp,
164                   curl_socket_t listenfd,
165                   enum sockmode *mode)
166 {
167   struct timeval timeout;
168   fd_set fds_read;
169   fd_set fds_write;
170   fd_set fds_err;
171   curl_socket_t sockfd;
172   curl_socket_t maxfd;
173   ssize_t rc;
174   ssize_t nread_stdin;
175   ssize_t nread_socket;
176   ssize_t bytes_written;
177   ssize_t buffer_len;
178
179  /* 'buffer' is this excessively large only to be able to support things like
180     test 1003 which tests exceedingly large server response lines */
181   unsigned char buffer[17010];
182   char data[16];
183
184   timeout.tv_sec = 120;
185   timeout.tv_usec = 0;
186
187   FD_ZERO(&fds_read);
188   FD_ZERO(&fds_write);
189   FD_ZERO(&fds_err);
190
191   FD_SET(fileno(stdin), &fds_read);
192
193   switch(*mode) {
194
195   case PASSIVE_LISTEN:
196
197     /* server mode */
198     sockfd = listenfd;
199     /* there's always a socket to wait for */
200     FD_SET(sockfd, &fds_read);
201     maxfd = sockfd;
202     break;
203
204   case PASSIVE_CONNECT:
205
206     sockfd = *sockfdp;
207     if(CURL_SOCKET_BAD == sockfd) {
208       /* eeek, we are supposedly connected and then this cannot be -1 ! */
209       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
210       maxfd = 0; /* stdin */
211     }
212     else {
213       /* there's always a socket to wait for */
214       FD_SET(sockfd, &fds_read);
215       maxfd = sockfd;
216     }
217     break;
218
219   case ACTIVE:
220
221     sockfd = *sockfdp;
222     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
223     if(CURL_SOCKET_BAD != sockfd) {
224       FD_SET(sockfd, &fds_read);
225       maxfd = sockfd;
226     }
227     else {
228       logmsg("No socket to read on");
229       maxfd = 0;
230     }
231     break;
232
233   case ACTIVE_DISCONNECT:
234
235     logmsg("disconnected, no socket to read on");
236     maxfd = 0;
237     sockfd = CURL_SOCKET_BAD;
238     break;
239
240   } /* switch(*mode) */
241
242   do {
243     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
244   } while((rc == -1) && (SOCKERRNO == EINTR));
245
246   switch(rc) {
247   case -1:
248     return FALSE;
249
250   case 0: /* timeout! */
251     return TRUE;
252   }
253
254
255   if(FD_ISSET(fileno(stdin), &fds_read)) {
256     /* read from stdin, commands/data to be dealt with and possibly passed on
257        to the socket
258
259        protocol:
260
261        4 letter command + LF [mandatory]
262
263        4-digit hexadecimal data length + LF [if the command takes data]
264        data                       [the data being as long as set above]
265
266        Commands:
267
268        DATA - plain pass-thru data
269     */
270     nread_stdin = read(fileno(stdin), buffer, 5);
271     if(5 == nread_stdin) {
272
273       logmsg("Received %c%c%c%c (on stdin)",
274              buffer[0], buffer[1], buffer[2], buffer[3] );
275
276       if(!memcmp("PING", buffer, 4)) {
277         /* send reply on stdout, just proving we are alive */
278         write(fileno(stdout), "PONG\n", 5);
279       }
280
281       else if(!memcmp("PORT", buffer, 4)) {
282         /* Question asking us what PORT number we are listening to.
283            Replies to PORT with "IPv[num]/[port]" */
284         sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
285         buffer_len = (ssize_t)strlen((char *)buffer);
286         snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
287         write(fileno(stdout), data, 10);
288         write(fileno(stdout), buffer, buffer_len);
289       }
290       else if(!memcmp("QUIT", buffer, 4)) {
291         /* just die */
292         logmsg("quits");
293         return FALSE;
294       }
295       else if(!memcmp("DATA", buffer, 4)) {
296         /* data IN => data OUT */
297
298         if(5 != read(fileno(stdin), buffer, 5))
299           return FALSE;
300         buffer[5] = '\0';
301
302         buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
303         if (buffer_len > (ssize_t)sizeof(buffer)) {
304           logmsg("Buffer size %d too small for data size %d", 
305                    (int)sizeof(buffer), buffer_len);
306           return FALSE;
307         }
308         logmsg("> %d bytes data, server => client", buffer_len);
309
310         if(buffer_len > (ssize_t)sizeof(buffer)) {
311           logmsg("ERROR: %d bytes of data does not fit within the %d "
312                  "bytes buffer", buffer_len, sizeof(buffer));
313           return FALSE;
314         }
315
316         /*
317          * To properly support huge data chunks, we need to repeat the call
318          * to read() until we're done or it fails.
319          */
320         nread_stdin = 0;
321         do {
322           /* get data in the buffer at the correct position */
323           ssize_t rc = read(fileno(stdin), &buffer[nread_stdin],
324                             buffer_len - nread_stdin);
325           logmsg("read %d bytes", rc);
326           if(rc <= 0)
327             return FALSE;
328           nread_stdin += rc;
329         } while (nread_stdin < buffer_len);
330
331         lograw(buffer, buffer_len);
332
333         if(*mode == PASSIVE_LISTEN) {
334           logmsg("*** We are disconnected!");
335           write(fileno(stdout), "DISC\n", 5);
336         }
337         else {
338           /* send away on the socket */
339           bytes_written = swrite(sockfd, buffer, buffer_len);
340           if(bytes_written != buffer_len) {
341             logmsg("Not all data was sent. Bytes to send: %d sent: %d", 
342                    buffer_len, bytes_written);
343           }
344         }
345       }
346       else if(!memcmp("DISC", buffer, 4)) {
347         /* disconnect! */
348         write(fileno(stdout), "DISC\n", 5);
349         if(sockfd != CURL_SOCKET_BAD) {
350           logmsg("====> Client forcibly disconnected");
351           sclose(sockfd);
352           *sockfdp = CURL_SOCKET_BAD;
353           if(*mode == PASSIVE_CONNECT)
354             *mode = PASSIVE_LISTEN;
355           else
356             *mode = ACTIVE_DISCONNECT;
357         }
358         else
359           logmsg("attempt to close already dead connection");
360         return TRUE;
361       }
362     }
363     else if(-1 == nread_stdin) {
364       logmsg("read %d from stdin, exiting", nread_stdin);
365       return FALSE;
366     }
367   }
368
369
370   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
371
372     if(*mode == PASSIVE_LISTEN) {
373       /* there's no stream set up yet, this is an indication that there's a
374          client connecting. */
375       sockfd = accept(sockfd, NULL, NULL);
376       if(CURL_SOCKET_BAD == sockfd)
377         logmsg("accept() failed");
378       else {
379         logmsg("====> Client connect");
380         write(fileno(stdout), "CNCT\n", 5);
381         *sockfdp = sockfd; /* store the new socket */
382         *mode = PASSIVE_CONNECT; /* we have connected */
383       }
384       return TRUE;
385     }
386
387     /* read from socket, pass on data to stdout */
388     nread_socket = sread(sockfd, buffer, sizeof(buffer));
389
390     if(nread_socket <= 0) {
391       logmsg("====> Client disconnect");
392       write(fileno(stdout), "DISC\n", 5);
393       sclose(sockfd);
394       *sockfdp = CURL_SOCKET_BAD;
395       if(*mode == PASSIVE_CONNECT)
396         *mode = PASSIVE_LISTEN;
397       else
398         *mode = ACTIVE_DISCONNECT;
399       return TRUE;
400     }
401
402     snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
403     write(fileno(stdout), data, 10);
404     write(fileno(stdout), buffer, nread_socket);
405
406     logmsg("< %d bytes data, client => server", nread_socket);
407     lograw(buffer, nread_socket);
408   }
409
410   return TRUE;
411 }
412
413 static curl_socket_t sockdaemon(curl_socket_t sock,
414                                 unsigned short *port)
415 {
416   /* passive daemon style */
417   struct sockaddr_in me;
418 #ifdef ENABLE_IPV6
419   struct sockaddr_in6 me6;
420 #endif /* ENABLE_IPV6 */
421   int flag = 1;
422   int rc;
423   int maxretr = 12;
424   int delay= 10;
425
426   rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
427        (void *)&flag, sizeof(flag));
428   while ((rc < 0) && maxretr) {
429     maxretr--;
430     go_sleep(delay);
431     delay *= 2; /* double the sleep for next attempt */
432     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
433          (void *)&flag, sizeof(flag));
434   }
435   if (rc < 0) {
436     perror("setsockopt(SO_REUSEADDR)");
437   }
438
439 #ifdef ENABLE_IPV6
440   if(!use_ipv6) {
441 #endif
442     me.sin_family = AF_INET;
443     me.sin_addr.s_addr = INADDR_ANY;
444     me.sin_port = htons(*port);
445     rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
446 #ifdef ENABLE_IPV6
447   }
448   else {
449     memset(&me6, 0, sizeof(struct sockaddr_in6));
450     me6.sin6_family = AF_INET6;
451     me6.sin6_addr = in6addr_any;
452     me6.sin6_port = htons(*port);
453     rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
454   }
455 #endif /* ENABLE_IPV6 */
456   if(rc < 0) {
457     perror("binding stream socket");
458     logmsg("Error binding socket");
459     return CURL_SOCKET_BAD;
460   }
461
462   if(!*port) {
463     /* The system picked a port number, now figure out which port we actually
464        got */
465     /* we succeeded to bind */
466     struct sockaddr_in add;
467     socklen_t socksize = sizeof(add);
468
469     if(getsockname(sock, (struct sockaddr *) &add,
470                    &socksize)<0) {
471       logmsg("getsockname() failed with error: %d", SOCKERRNO);
472       return CURL_SOCKET_BAD;
473     }
474     *port = ntohs(add.sin_port);
475   }
476
477   /* start accepting connections */
478   rc = listen(sock, 4);
479   if(0 != rc) {
480     logmsg("listen() failed with error: %d", SOCKERRNO);
481     sclose(sock);
482     return CURL_SOCKET_BAD;
483   }
484
485   return sock;
486 }
487
488 static curl_socket_t mksock(bool use_ipv6)
489 {
490   curl_socket_t sock;
491 #ifdef ENABLE_IPV6
492   if(!use_ipv6)
493 #else
494     (void)use_ipv6;
495 #endif
496   sock = socket(AF_INET, SOCK_STREAM, 0);
497 #ifdef ENABLE_IPV6
498   else
499     sock = socket(AF_INET6, SOCK_STREAM, 0);
500 #endif
501
502   if (CURL_SOCKET_BAD == sock) {
503     perror("opening stream socket");
504     logmsg("Error opening socket");
505   }
506
507   return sock;
508 }
509
510
511 int main(int argc, char *argv[])
512 {
513   struct sockaddr_in me;
514 #ifdef ENABLE_IPV6
515   struct sockaddr_in6 me6;
516 #endif /* ENABLE_IPV6 */
517   curl_socket_t sock;
518   curl_socket_t msgsock;
519   FILE *pidfile;
520   char *pidname= (char *)".sockfilt.pid";
521   int rc;
522   int error;
523   int arg=1;
524   enum sockmode mode = PASSIVE_LISTEN; /* default */
525
526   while(argc>arg) {
527     if(!strcmp("--version", argv[arg])) {
528       printf("sockfilt IPv4%s\n",
529 #ifdef ENABLE_IPV6
530              "/IPv6"
531 #else
532              ""
533 #endif
534              );
535       return 0;
536     }
537     else if(!strcmp("--pidfile", argv[arg])) {
538       arg++;
539       if(argc>arg)
540         pidname = argv[arg++];
541     }
542     else if(!strcmp("--logfile", argv[arg])) {
543       arg++;
544       if(argc>arg)
545         serverlogfile = argv[arg++];
546     }
547     else if(!strcmp("--ipv6", argv[arg])) {
548 #ifdef ENABLE_IPV6
549       use_ipv6=TRUE;
550 #endif
551       arg++;
552     }
553     else if(!strcmp("--ipv4", argv[arg])) {
554       /* for completeness, we support this option as well */
555       use_ipv6=FALSE;
556       arg++;
557     }
558     else if(!strcmp("--port", argv[arg])) {
559       arg++;
560       if(argc>arg) {
561         port = (unsigned short)atoi(argv[arg]);
562         arg++;
563       }
564     }
565     else if(!strcmp("--connect", argv[arg])) {
566       /* Asked to actively connect to the specified local port instead of
567          doing a passive server-style listening. */
568       arg++;
569       if(argc>arg) {
570         connectport = (unsigned short)atoi(argv[arg]);
571         arg++;
572       }
573     }
574     else {
575       puts("Usage: sockfilt [option]\n"
576            " --version\n"
577            " --logfile [file]\n"
578            " --pidfile [file]\n"
579            " --ipv4\n"
580            " --ipv6\n"
581            " --port [port]");
582       return 0;
583     }
584   }
585
586 #ifdef WIN32
587   win32_init();
588   atexit(win32_cleanup);
589 #else
590
591 #ifdef SIGPIPE
592 #ifdef HAVE_SIGNAL
593   signal(SIGPIPE, sigpipe_handler);
594 #endif
595 #ifdef HAVE_SIGINTERRUPT
596   siginterrupt(SIGPIPE, 1);
597 #endif
598 #endif
599 #endif
600
601
602   sock = mksock(use_ipv6);
603   if (CURL_SOCKET_BAD == sock) {
604     logmsg("Error opening socket: %d", SOCKERRNO);
605     return 1;
606   }
607
608   if(connectport) {
609     /* Active mode, we should connect to the given port number */
610     mode = ACTIVE;
611 #ifdef ENABLE_IPV6
612     if(!use_ipv6) {
613 #endif
614       memset(&me, 0, sizeof(me));
615       me.sin_family = AF_INET;
616       me.sin_port = htons(connectport);
617       me.sin_addr.s_addr = INADDR_ANY;
618       Curl_inet_pton(AF_INET, "127.0.0.1", &me.sin_addr);
619
620       rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
621 #ifdef ENABLE_IPV6
622     }
623     else {
624       memset(&me6, 0, sizeof(me6));
625       me6.sin6_family = AF_INET6;
626       me6.sin6_port = htons(connectport);
627       Curl_inet_pton(AF_INET6, "::1", &me6.sin6_addr);
628
629       rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
630     }
631 #endif /* ENABLE_IPV6 */
632     if(rc) {
633       perror("connecting stream socket");
634       logmsg("Error connecting to port %d", port);
635       sclose(sock);
636       return 1;
637     }
638     logmsg("====> Client connect");
639     msgsock = sock; /* use this as stream */
640   }
641   else {
642     /* passive daemon style */
643     sock = sockdaemon(sock, &port);
644     if(CURL_SOCKET_BAD == sock)
645       return 1;
646     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
647   }
648
649   logmsg("Running IPv%d version",
650          (use_ipv6?6:4));
651
652   if(connectport)
653     logmsg("Connected to port %d", connectport);
654   else
655     logmsg("Listening on port %d", port);
656
657   pidfile = fopen(pidname, "w");
658   if(pidfile) {
659     int pid = (int)getpid();
660     fprintf(pidfile, "%d\n", pid);
661     fclose(pidfile);
662     logmsg("Wrote pid %d to %s", pid, pidname);
663   }
664   else {
665     error = ERRNO;
666     logmsg("fopen() failed with error: %d %s\n", error, strerror(error));
667     logmsg("Error opening file: %s\n", pidname);
668     logmsg("Couldn't write pid file\n");
669     sclose(sock);
670     return 1;
671   }
672
673   while(juggle(&msgsock, sock, &mode));
674
675   sclose(sock);
676
677   return 0;
678 }
679