Modifiche di ieri sera.
[gapil.git] / sources / TCP_countd.c
1 /* TCP_countd.c
2  * 
3  * Copyright (C) 2007 Simone Piccardi
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at
8  * your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /****************************************************************
20  *
21  * Program countd: Elementary TCP server for teaching purpose, count
22  * number of request to the server itself, use POSIX semaphores and
23  * shared memory
24  *
25  * Author: Simone Piccardi
26  * Feb. 2007
27  *
28  * Usage: countd -h give all info
29  *
30  ****************************************************************/
31 /* 
32  * Include needed headers
33  */
34 #include <sys/types.h>   /* predefined types */
35 #include <unistd.h>      /* include unix standard library */
36 #include <arpa/inet.h>   /* IP addresses conversion utiliites */
37 #include <sys/socket.h>  /* socket library */
38 #include <stdio.h>       /* include standard I/O library */
39 #include <time.h>
40 #include <sys/mman.h>
41 #include <semaphore.h>
42 #include <syslog.h>      /* syslog system functions */
43 #include <signal.h>      /* signal functions */
44 #include <errno.h>       /* error code */
45 #include <string.h>      /* error strings */
46 #include <stdlib.h>
47
48 #include "Gapil.h"
49
50 #define BACKLOG 10
51 #define MAXLINE 256
52 int demonize  = 1;  /* daemon use option: default is daemon */
53 int debugging = 0;  /* debug info printing option: default is no debug */
54 /* Subroutines declaration */
55 void usage(void);
56 void ServEcho(int sockfd);
57 void PrintErr(char * error);
58 /* Program beginning */
59 int main(int argc, char *argv[])
60 {
61 /* 
62  * Variables definition  
63  */
64     int list_fd, conn_fd;
65     int waiting = 0;
66     int keepalive = 0; 
67     int reuse = 0;
68     int compat = 0;
69     pid_t pid;
70     struct sockaddr_in cli_add;
71     socklen_t len;
72     char debug[MAXLINE], ipaddr[20];
73     /*
74      * Input section: decode parameters passed in the calling 
75      * Use getopt function
76      */
77     int i;
78     opterr = 0;  /* don't want writing to stderr */
79     while ( (i = getopt(argc, argv, "hkrdicw:")) != -1) {
80         switch (i) {
81         /* 
82          * Handling options 
83          */ 
84         case 'h':  
85             printf("Wrong -h option use\n");
86             usage();
87             return(0);
88             break;
89         case 'i':
90             demonize = 0;
91             break;
92         case 'k':
93             keepalive = 1;
94             break;
95         case 'r':
96             reuse = 1;
97             break;
98         case 'c':
99             compat = 1;
100             break;
101         case 'd':
102             debugging = 1;
103             break;
104         case 'w':
105             waiting = strtol(optarg, NULL, 10);
106             break;
107         case '?':   /* unrecognized options */
108             printf("Unrecognized options -%c\n",optopt);
109             usage();
110         default:    /* should not reached */
111             usage();
112         }
113     }
114     /* ***********************************************************
115      * 
116      *           Options processing completed
117      *
118      *                Main code beginning
119      * 
120      * ***********************************************************/
121     /* Main code begin here */
122     if (compat) {                             /* install signal handler */
123         Signal(SIGCHLD, HandSigCHLD);         /* non restarting handler */
124     } else {
125         SignalRestart(SIGCHLD, HandSigCHLD);  /* restarting handler */
126     }
127     /* create and bind socket */
128     if ( (list_fd = sockbindopt(argv[optind], "echo", 6, 
129                                 SOCK_STREAM, reuse)) < 0) {
130         return 1;
131     }   
132     /* release privileges and go daemon */
133     if (setgid(65534) !=0) { /* first give away group privileges */
134         perror("cannot give away group privileges");
135         exit(1);
136     }
137     if (setuid(65534) !=0) { /* and only after user ... */
138         perror("cannot give away user privileges");
139         exit(1);
140     }
141     if (demonize) {          /* go daemon */
142         openlog(argv[0], 0, LOG_DAEMON); /* open logging */
143         if (daemon(0, 0) != 0) {
144             perror("cannot start as daemon");
145             exit(1);
146         }
147     }
148     /* main body */
149     if (listen(list_fd, BACKLOG) < 0 ) {
150         PrintErr("listen error");
151         exit(1);
152     }
153     if (waiting) sleep(waiting);
154     /* handle echo to client */
155     while (1) {
156         /* accept connection */
157         len = sizeof(cli_add);
158         while (((conn_fd = accept(list_fd, (struct sockaddr *)&cli_add, &len)) 
159                 < 0) && (errno == EINTR)); 
160         if (conn_fd < 0) {
161             PrintErr("accept error");
162             exit(1);
163         }
164         if (debugging) {
165             inet_ntop(AF_INET, &cli_add.sin_addr, ipaddr, sizeof(ipaddr));
166             snprintf(debug, MAXLINE, "Accepted connection form %s\n", ipaddr);
167             if (demonize) {
168                 syslog(LOG_DEBUG, debug);
169             } else {
170                 printf("%s", debug);
171             }
172         }
173         /* fork to handle connection */
174         if ( (pid = fork()) < 0 ){
175             PrintErr("fork error");
176             exit(1);
177         }
178         if (pid == 0) {      /* child */
179             close(list_fd);          /* close listening socket */   
180             if (keepalive) {         /* enable keepalive ? */
181                 setsockopt(conn_fd, SOL_SOCKET, SO_KEEPALIVE, 
182                            &keepalive, sizeof(keepalive));
183             }
184             ServEcho(conn_fd);       /* handle echo */
185             if (debugging) {
186                 snprintf(debug, MAXLINE, "Closed connection %s\n", ipaddr);
187                 if (demonize) {
188                     syslog(LOG_DEBUG, debug);
189                 } else {
190                     printf("%s", debug);
191                 }
192             }
193             exit(0);
194         } else {             /* parent */
195             close(conn_fd);          /* close connected socket */
196         }
197     }
198     /* normal exit, never reached */
199     exit(0);
200 }
201 /*
202  * routine to print usage info and exit
203  */
204 void usage(void) {
205     printf("A counter server\n");
206     printf("Usage:\n");
207     printf("  countd [-h] \n");
208     printf("  -h           print this help\n");
209     printf("  -d           write debug info\n");
210     printf("  -k           enable SO_KEEPALIVE\n");
211     printf("  -r           enable SO_REUSEADDR\n");
212     printf("  -i           use interactively\n");
213     printf("  -c           disable BSD semantics\n");
214     printf("  -w N         wait N sec. before calling accept\n");
215     exit(1);
216 }
217 /*
218  * routine to handle echo for connection
219  */
220 void ServEcho(int sockfd) {
221     char buffer[MAXLINE];
222     int nread, nwrite;
223     char debug[MAXLINE+20];
224     /* main loop, reading 0 char means client close connection */
225     while ( (nread = read(sockfd, buffer, MAXLINE)) != 0) {
226         if (nread < 0) {
227             PrintErr("Errore in lettura");
228             return;
229         }
230         nwrite = FullWrite(sockfd, buffer, nread);
231         if (nwrite) {
232             PrintErr("Errore in scrittura");
233             return;
234         }
235         if (debugging) {
236             buffer[nread] = 0;
237             snprintf(debug, MAXLINE+20, "Letti %d byte, %s", nread, buffer);
238             if (demonize) {          /* daemon mode */
239                 syslog(LOG_DEBUG, debug);
240             } else {
241                 printf("%s", debug);
242             }
243         }
244     }
245     return;
246 }
247 /*
248  * routine to print error on stout or syslog
249  */
250 void PrintErr(char * error) {
251     if (demonize) {                       /* daemon mode */
252         syslog(LOG_ERR, "%s: %m", error); /* log string and error message */
253     } else {
254         perror(error);
255     }
256     return;
257 }
258
259
260 #define MAXLINE 80
261 #define BACKLOG 10
262 /* Program begin */
263 void usage(void);
264 int main(int argc, char *argv[])
265 {
266 /* 
267  * Variables definition  
268  */
269     int list_fd, conn_fd;
270     int i;
271     struct sockaddr_in serv_add;
272     char buffer[MAXLINE];
273     time_t timeval;
274     /*
275      * Input section: decode parameters passed in the calling 
276      * Use getopt function
277      */
278     opterr = 0;  /* don't want writing to stderr */
279     while ( (i = getopt(argc, argv, "h")) != -1) {
280         switch (i) {
281         /* 
282          * Handling options 
283          */ 
284         case 'h':  
285             printf("Wrong -h option use\n");
286             usage();
287             return(0);
288             break;
289         case '?':   /* unrecognized options */
290             printf("Unrecognized options -%c\n",optopt);
291             usage();
292         default:    /* should not reached */
293             usage();
294         }
295     }
296     /* ***********************************************************
297      * 
298      *           Options processing completed
299      *
300      *                Main code beginning
301      * 
302      * ***********************************************************/
303     /* create socket */
304     if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
305         perror("Socket creation error");
306         exit(-1);
307     }
308     /* initialize address */
309     memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
310     serv_add.sin_family = AF_INET;                  /* address type is INET */
311     serv_add.sin_port = htons(13);                  /* daytime port is 13 */
312     serv_add.sin_addr.s_addr = htonl(INADDR_ANY);   /* connect from anywhere */
313     /* bind socket */
314     if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
315         perror("bind error");
316         exit(-1);
317     }
318     /* listen on socket */
319     if (listen(list_fd, BACKLOG) < 0 ) {
320         perror("listen error");
321         exit(-1);
322     }
323     /* write daytime to client */
324     while (1) {
325         if ( (conn_fd = accept(list_fd, (struct sockaddr *) NULL, NULL)) <0 ) {
326             perror("accept error");
327             exit(-1);
328         }
329         timeval = time(NULL);
330         snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
331         if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
332             perror("write error");
333             exit(-1);
334         }
335         close(conn_fd);
336     }
337
338     /* normal exit */
339     exit(0);
340 }
341 /*
342  * routine to print usage info and exit
343  */
344 void usage(void) {
345     printf("Simple daytime server\n");
346     printf("Usage:\n");
347     printf("  daytimed [-h] \n");
348     printf("  -h           print this help\n");
349     exit(1);
350 }