Null terminate string in buffer before feeding it to strtol()
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2005, 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 maxfd;
172   ssize_t rc;
173   ssize_t len;
174   ssize_t nread;
175   ssize_t bytes_written;
176   ssize_t bytes_read;
177   ssize_t port_strlen;
178   unsigned char buffer[256]; /* FIX: bigger buffer */
179   char data[256];
180   curl_socket_t sockfd;
181
182   timeout.tv_sec = 120;
183   timeout.tv_usec = 0;
184
185   FD_ZERO(&fds_read);
186   FD_ZERO(&fds_write);
187   FD_ZERO(&fds_err);
188
189   FD_SET(fileno(stdin), &fds_read);
190
191   switch(*mode) {
192   case PASSIVE_LISTEN:
193     /* server mode */
194     sockfd = listenfd;
195     /* there's always a socket to wait for */
196     FD_SET(sockfd, &fds_read);
197     maxfd = sockfd;
198     break;
199
200   case PASSIVE_CONNECT:
201     sockfd = *sockfdp;
202     if(-1 == sockfd) {
203       /* eeek, we are supposedly connected and then this cannot be -1 ! */
204       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
205       maxfd = 0; /* stdin */
206     }
207     else {
208       /* there's always a socket to wait for */
209       FD_SET(sockfd, &fds_read);
210       maxfd = sockfd;
211     }
212     break;
213
214   case ACTIVE:
215     sockfd = *sockfdp;
216
217     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
218     if(sockfd != CURL_SOCKET_BAD) {
219       FD_SET(sockfd, &fds_read);
220       maxfd = sockfd;
221     }
222     else {
223       logmsg("No socket to read on");
224       maxfd = 0;
225     }
226     break;
227
228   case ACTIVE_DISCONNECT:
229     logmsg("disconnected, no socket to read on");
230     maxfd = 0;
231     sockfd = CURL_SOCKET_BAD;
232     break;
233   }
234
235   do {
236     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
237   } while((rc == -1) && (ourerrno() == EINTR));
238
239   switch(rc) {
240   case -1:
241     return FALSE;
242
243   case 0: /* timeout! */
244     return TRUE;
245   }
246
247
248   if(FD_ISSET(fileno(stdin), &fds_read)) {
249     /* read from stdin, commands/data to be dealt with and possibly passed on
250        to the socket
251
252        protocol:
253
254        4 letter command + LF [mandatory]
255
256        4-digit hexadecimal data length + LF [if the command takes data]
257        data                       [the data being as long as set above]
258
259        Commands:
260
261        DATA - plain pass-thru data
262     */
263     nread = read(fileno(stdin), buffer, 5);
264     if(5 == nread) {
265
266       logmsg("Received %c%c%c%c (on stdin)",
267              buffer[0], buffer[1], buffer[2], buffer[3] );
268
269       if(!memcmp("PING", buffer, 4)) {
270         /* send reply on stdout, just proving we are alive */
271         write(fileno(stdout), "PONG\n", 5);
272       }
273
274       else if(!memcmp("PORT", buffer, 4)) {
275         /* question asking us what PORT number we are listening to.
276            Replies with PORT with "IPv[num]/[port]" */
277         sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, port);
278         port_strlen = (ssize_t)strlen((char *)buffer);
279         sprintf(data, "PORT\n%04x\n", port_strlen);
280         write(fileno(stdout), data, 10);
281         write(fileno(stdout), buffer, port_strlen);
282       }
283       else if(!memcmp("QUIT", buffer, 4)) {
284         /* just die */
285         logmsg("quits");
286         return FALSE;
287       }
288       else if(!memcmp("DATA", buffer, 4)) {
289         /* data IN => data OUT */
290
291         if(5 != read(fileno(stdin), buffer, 5))
292           return FALSE;
293         buffer[4] = '\0';
294
295         len = (ssize_t)strtol((char *)buffer, NULL, 16);
296         if(len != read(fileno(stdin), buffer, len))
297           return FALSE;
298
299         logmsg("> %d bytes data, server => client", len);
300         lograw(buffer, len);
301
302         if(*mode == PASSIVE_LISTEN) {
303           logmsg("*** We are disconnected!");
304           write(fileno(stdout), "DISC\n", 5);
305         }
306         else {
307           /* send away on the socket */
308           bytes_written = swrite(sockfd, buffer, len);
309           if(bytes_written != len) {
310             logmsg("Not all data was sent. Bytes to send: %d sent: %d", 
311                    len, bytes_written);
312           }
313         }
314       }
315       else if(!memcmp("DISC", buffer, 4)) {
316         /* disconnect! */
317         write(fileno(stdout), "DISC\n", 5);
318         if(sockfd != CURL_SOCKET_BAD) {
319           logmsg("====> Client forcibly disconnected");
320           sclose(sockfd);
321           *sockfdp = CURL_SOCKET_BAD;
322           if(*mode == PASSIVE_CONNECT)
323             *mode = PASSIVE_LISTEN;
324           else
325             *mode = ACTIVE_DISCONNECT;
326         }
327         else
328           logmsg("attempt to close already dead connection");
329         return TRUE;
330       }
331     }
332     else if(nread == -1){
333       logmsg("read %d from stdin, exiting", nread);
334       return FALSE;
335     }
336   }
337
338   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
339
340     if(*mode == PASSIVE_LISTEN) {
341       /* there's no stream set up yet, this is an indication that there's a
342          client connecting. */
343       sockfd = accept(sockfd, NULL, NULL);
344       if(-1 == sockfd)
345         logmsg("accept() failed\n");
346       else {
347         logmsg("====> Client connect");
348         write(fileno(stdout), "CNCT\n", 5);
349         *sockfdp = sockfd; /* store the new socket */
350         *mode = PASSIVE_CONNECT; /* we have connected */
351       }
352       return TRUE;
353     }
354
355     /* read from socket, pass on data to stdout */
356     bytes_read = sread(sockfd, buffer, sizeof(buffer));
357
358     if(bytes_read <= 0) {
359       logmsg("====> Client disconnect");
360       write(fileno(stdout), "DISC\n", 5);
361       sclose(sockfd);
362       *sockfdp = CURL_SOCKET_BAD;
363       if(*mode == PASSIVE_CONNECT)
364         *mode = PASSIVE_LISTEN;
365       else
366         *mode = ACTIVE_DISCONNECT;
367       return TRUE;
368     }
369
370     sprintf(data, "DATA\n%04x\n", bytes_read);
371     write(fileno(stdout), data, 10);
372     write(fileno(stdout), buffer, bytes_read);
373
374     logmsg("< %d bytes data, client => server", bytes_read);
375     lograw(buffer, bytes_read);
376   }
377
378   return TRUE;
379 }
380
381 static curl_socket_t sockdaemon(curl_socket_t sock,
382                                 unsigned short *port)
383 {
384   /* passive daemon style */
385   struct sockaddr_in me;
386 #ifdef ENABLE_IPV6
387   struct sockaddr_in6 me6;
388 #endif /* ENABLE_IPV6 */
389   int flag = 1;
390   int rc;
391
392   if (setsockopt
393       (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
394        sizeof(int)) < 0) {
395     perror("setsockopt(SO_REUSEADDR)");
396   }
397
398 #ifdef ENABLE_IPV6
399   if(!use_ipv6) {
400 #endif
401     me.sin_family = AF_INET;
402     me.sin_addr.s_addr = INADDR_ANY;
403     me.sin_port = htons(*port);
404     rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
405 #ifdef ENABLE_IPV6
406   }
407   else {
408     memset(&me6, 0, sizeof(struct sockaddr_in6));
409     me6.sin6_family = AF_INET6;
410     me6.sin6_addr = in6addr_any;
411     me6.sin6_port = htons(*port);
412     rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
413   }
414 #endif /* ENABLE_IPV6 */
415   if(rc < 0) {
416     perror("binding stream socket");
417     logmsg("Error binding socket");
418     return CURL_SOCKET_BAD;
419   }
420
421   if(!*port) {
422     /* The system picked a port number, now figure out which port we actually
423        got */
424     /* we succeeded to bind */
425     struct sockaddr_in add;
426     socklen_t socksize = sizeof(add);
427
428     if(getsockname(sock, (struct sockaddr *) &add,
429                    &socksize)<0) {
430       fprintf(stderr, "getsockname() failed");
431       return CURL_SOCKET_BAD;
432     }
433     *port = ntohs(add.sin_port);
434   }
435
436   /* start accepting connections */
437   listen(sock, 4);
438
439   return sock;
440 }
441
442 static curl_socket_t mksock(bool use_ipv6)
443 {
444   curl_socket_t sock;
445 #ifdef ENABLE_IPV6
446   if(!use_ipv6)
447 #else
448     (void)use_ipv6;
449 #endif
450   sock = socket(AF_INET, SOCK_STREAM, 0);
451 #ifdef ENABLE_IPV6
452   else
453     sock = socket(AF_INET6, SOCK_STREAM, 0);
454 #endif
455
456   if (sock < 0) {
457     perror("opening stream socket");
458     logmsg("Error opening socket");
459     return CURL_SOCKET_BAD;
460   }
461
462   return sock;
463 }
464
465
466 int main(int argc, char *argv[])
467 {
468   struct sockaddr_in me;
469 #ifdef ENABLE_IPV6
470   struct sockaddr_in6 me6;
471 #endif /* ENABLE_IPV6 */
472   curl_socket_t sock;
473   curl_socket_t msgsock;
474   FILE *pidfile;
475   char *pidname= (char *)".sockfilt.pid";
476   int rc;
477   int arg=1;
478   enum sockmode mode = PASSIVE_LISTEN; /* default */
479
480   while(argc>arg) {
481     if(!strcmp("--version", argv[arg])) {
482       printf("sockfilt IPv4%s\n",
483 #ifdef ENABLE_IPV6
484              "/IPv6"
485 #else
486              ""
487 #endif
488              );
489       return 0;
490     }
491     else if(!strcmp("--pidfile", argv[arg])) {
492       arg++;
493       if(argc>arg)
494         pidname = argv[arg++];
495     }
496     else if(!strcmp("--logfile", argv[arg])) {
497       arg++;
498       if(argc>arg)
499         serverlogfile = argv[arg++];
500     }
501     else if(!strcmp("--ipv6", argv[arg])) {
502 #ifdef ENABLE_IPV6
503       use_ipv6=TRUE;
504 #endif
505       arg++;
506     }
507     else if(!strcmp("--ipv4", argv[arg])) {
508       /* for completeness, we support this option as well */
509       use_ipv6=FALSE;
510       arg++;
511     }
512     else if(!strcmp("--port", argv[arg])) {
513       arg++;
514       if(argc>arg) {
515         port = (unsigned short)atoi(argv[arg]);
516         arg++;
517       }
518     }
519     else if(!strcmp("--connect", argv[arg])) {
520       /* Asked to actively connect to the specified local port instead of
521          doing a passive server-style listening. */
522       arg++;
523       if(argc>arg) {
524         connectport = (unsigned short)atoi(argv[arg]);
525         arg++;
526       }
527     }
528     else {
529       puts("Usage: sockfilt [option]\n"
530            " --version\n"
531            " --logfile [file]\n"
532            " --pidfile [file]\n"
533            " --ipv4\n"
534            " --ipv6\n"
535            " --port [port]");
536       return 0;
537     }
538   }
539
540 #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
541   win32_init();
542   atexit(win32_cleanup);
543 #else
544
545 #ifdef SIGPIPE
546 #ifdef HAVE_SIGNAL
547   signal(SIGPIPE, sigpipe_handler);
548 #endif
549 #ifdef HAVE_SIGINTERRUPT
550   siginterrupt(SIGPIPE, 1);
551 #endif
552 #endif
553 #endif
554
555
556   sock = mksock(use_ipv6);
557
558   if(connectport) {
559     /* Active mode, we should connect to the given port number */
560     mode = ACTIVE;
561 #ifdef ENABLE_IPV6
562     if(!use_ipv6) {
563 #endif
564       memset(&me, 0, sizeof(me));
565       me.sin_family = AF_INET;
566       me.sin_port = htons(connectport);
567       me.sin_addr.s_addr = INADDR_ANY;
568       Curl_inet_pton(AF_INET, "127.0.0.1", &me.sin_addr);
569
570       rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
571 #ifdef ENABLE_IPV6
572     }
573     else {
574       memset(&me6, 0, sizeof(me6));
575       me6.sin6_family = AF_INET6;
576       me6.sin6_port = htons(connectport);
577       Curl_inet_pton(AF_INET6, "::1", &me6.sin6_addr);
578
579       rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
580     }
581 #endif /* ENABLE_IPV6 */
582     if(rc) {
583       perror("connecting stream socket");
584       logmsg("Error connecting to port %d", port);
585       return 1;
586     }
587     logmsg("====> Client connect");
588     msgsock = sock; /* use this as stream */
589   }
590   else {
591     /* passive daemon style */
592     sock = sockdaemon(sock, &port);
593     if(CURL_SOCKET_BAD == sock)
594       return 1;
595     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
596   }
597
598   logmsg("Running IPv%d version",
599          (use_ipv6?6:4));
600
601   if(connectport)
602     logmsg("Connected to port %d", connectport);
603   else
604     logmsg("Listening on port %d", port);
605
606   pidfile = fopen(pidname, "w");
607   if(pidfile) {
608     int pid = (int)getpid();
609     fprintf(pidfile, "%d\n", pid);
610     fclose(pidfile);
611     logmsg("Wrote pid %d to %s", pid, pidname);
612   }
613   else
614     fprintf(stderr, "Couldn't write pid file\n");
615
616   while(juggle(&msgsock, sock, &mode));
617
618   sclose(sock);
619
620   return 0;
621 }
622