Inserito esempio di server echo basato su select.
[gapil.git] / sources / select_echod.c
1 /* select_echod.c
2  * 
3  * Copyright (C) 2003 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 select_echod 
22  * Elementary TCP server for echo service (port 7) using select
23  *
24  * Author: Simone Piccardi
25  * Dec. 2003
26  *
27  * Usage: echod -h give all info
28  *
29  * $Id: select_echod.c,v 1.2 2003/12/25 22:16:06 piccardi Exp $ 
30  *
31  ****************************************************************/
32 /* 
33  * Include needed headers
34  */
35 #include <sys/types.h>   /* predefined types */
36 #include <unistd.h>      /* include unix standard library */
37 #include <arpa/inet.h>   /* IP addresses conversion utiliites */
38 #include <sys/socket.h>  /* socket library */
39 #include <stdio.h>       /* include standard I/O library */
40 #include <time.h>
41 #include <syslog.h>      /* syslog system functions */
42 #include <signal.h>      /* signal functions */
43 #include <errno.h>       /* error code */
44 #include <string.h>      /* error strings */
45 #include <stdlib.h>
46
47 #include "macros.h"
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 PrintErr(char * error);
57 /* Program beginning */
58 int main(int argc, char *argv[])
59 {
60 /* 
61  * Variables definition  
62  */
63     int waiting = 0;
64     int compat = 0;
65     struct sockaddr_in s_addr, c_addr;
66     socklen_t len;
67     char buffer[MAXLINE];
68     char fd_open[FD_SETSIZE];
69     fd_set fset;
70     int list_fd, fd;
71     int max_fd, nread, nwrite;
72     int i, n;
73     /*
74      * Input section: decode parameters passed in the calling 
75      * Use getopt function
76      */
77     opterr = 0;  /* don't want writing to stderr */
78     while ( (i = getopt(argc, argv, "hdicw:")) != -1) {
79         switch (i) {
80         /* 
81          * Handling options 
82          */ 
83         case 'h':  
84             printf("Wrong -h option use\n");
85             usage();
86             return(0);
87             break;
88         case 'i':
89             demonize = 0;
90             break;
91         case 'c':
92             compat = 1;
93             break;
94         case 'd':
95             debugging = 1;
96             break;
97         case 'w':
98             waiting = strtol(optarg, NULL, 10);
99             break;
100         case '?':   /* unrecognized options */
101             printf("Unrecognized options -%c\n",optopt);
102             usage();
103         default:    /* should not reached */
104             usage();
105         }
106     }
107     /* ***********************************************************
108      * 
109      *           Options processing completed
110      *
111      *                Main code beginning
112      * 
113      * ***********************************************************/
114     /* Main code begin here */
115     if (compat) {                             /* install signal handler */
116         Signal(SIGCHLD, HandSigCHLD);         /* non restarting handler */
117     } else {
118         SignalRestart(SIGCHLD, HandSigCHLD);  /* restarting handler */
119     }
120     /* create socket */
121     if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
122         perror("Socket creation error");
123         exit(1);
124     }
125     /* initialize address */
126     memset((void *)&s_addr, 0, sizeof(s_addr));   /* clear server address */
127     s_addr.sin_family = AF_INET;                  /* address type is INET */
128     s_addr.sin_port = htons(7);                   /* echo port is 7 */
129     s_addr.sin_addr.s_addr = htonl(INADDR_ANY);   /* connect from anywhere */
130     /* bind socket */
131     if (bind(list_fd, (struct sockaddr *)&s_addr, sizeof(s_addr)) < 0) {
132         perror("bind error");
133         exit(1);
134     }
135     /* release privileges and go daemon */
136     if (setgid(65534) !=0) { /* first give away group privileges */
137         perror("cannot give away group privileges");
138         exit(1);
139     }
140     if (setuid(65534) !=0) { /* and only after user ... */
141         perror("cannot give away user privileges");
142         exit(1);
143     }
144     if (demonize) {          /* go daemon */
145         openlog(argv[0], 0, LOG_DAEMON); /* open logging */
146         if (daemon(0, 0) != 0) {
147             perror("cannot start as daemon");
148             exit(1);
149         }
150     }
151     /* main body */
152     if (listen(list_fd, BACKLOG) < 0 ) {
153         PrintErr("listen error");
154         exit(1);
155     }
156     if (waiting) sleep(waiting);
157     /* initialize all needed variables */
158     memset(fd_open, 0, FD_SETSIZE);   /* clear array of open files */
159     max_fd = list_fd;                 /* maximum now is listening socket */
160     fd_open[max_fd] = 1;
161     /* main loop, wait for connection and data inside a select */
162     while (1) {    
163         FD_ZERO(&fset);               /* clear fd_set */
164         for (i = list_fd; i <= max_fd; i++) { /* initialize fd_set */
165             if (fd_open[i] != 0) FD_SET(i, &fset); 
166         }
167         while ( ((n = select(max_fd + 1, &fset, NULL, NULL, NULL)) < 0) 
168                 && (errno == EINTR));         /* wait for data or connection */
169         if (n < 0) {                          /* on real error exit */
170             PrintErr("select error");
171             exit(1);
172         }
173         /* on activity */
174         debug("Trovati %d socket attivi\n", n);
175         if (FD_ISSET(list_fd, &fset)) {       /* if new connection */
176             n--;                              /* decrement active */
177             len = sizeof(c_addr);             /* and call accept */
178             if ((fd = accept(list_fd, (struct sockaddr *)&c_addr, &len)) < 0) {
179                 PrintErr("accept error");
180                 exit(1);
181             }
182             debug("Connessione su fd %d restano %d socket attivi\n", fd, n);
183             fd_open[fd] = 1;                  /* set new connection socket */
184             if (max_fd < fd) max_fd = fd;     /* if needed set new maximum */
185             debug("max_fd=%d\n", max_fd);
186         }
187         /* loop on open connections */
188         i = list_fd;                  /* first socket to look */
189         while (n != 0) {              /* loop until active */
190             i++;                      /* start after listening socket */
191             debug("restano %d socket, fd %d\n", n, fd);
192             if (fd_open[i] == 0) continue;   /* closed, go next */
193             if (FD_ISSET(i, &fset)) {        /* if active process it*/
194                 n--;                         /* decrease active */
195                 debug("dati su fd %d\n", i);
196                 nread = read(i, buffer, MAXLINE);     /* read operations */
197                 if (nread < 0) {
198                     PrintErr("Errore in lettura");
199                     exit(1);
200                 }
201                 if (nread == 0) {            /* if closed connection */
202                     debug("fd %d chiuso\n", i);
203                     close(i);                /* close file */
204                     fd_open[i] = 0;          /* mark as closed in table */
205                     if (max_fd == i) {       /* if was the maximum */
206                         while (fd_open[--i] == 0);    /* loop down */
207                         max_fd = i;          /* set new maximum */
208                         debug("nuovo max_fd %d\n", max_fd);
209                         break;               /* and go back to select */
210                     }
211                     continue;                /* continue loop on open */
212                 }
213                 nwrite = FullWrite(i, buffer, nread); /* write data */
214                 if (nwrite) {
215                     PrintErr("Errore in scrittura");
216                     exit(1);
217                 }
218             }
219         }
220     }
221     /* normal exit, never reached */
222     exit(0);
223 }
224 /*
225  * routine to print usage info and exit
226  */
227 void usage(void) {
228     printf("Elementary echo server\n");
229     printf("Usage:\n");
230     printf("  echod [-h] \n");
231     printf("  -h           print this help\n");
232     printf("  -d           write debug info\n");
233     printf("  -i           use interactively\n");
234     printf("  -c           disable BSD semantics\n");
235     printf("  -w N         wait N sec. before calling accept\n");
236     exit(1);
237 }
238 /*
239  * routine to print error on stout or syslog
240  */
241 void PrintErr(char * error) {
242     if (demonize) {                       /* daemon mode */
243         syslog(LOG_ERR, "%s: %m", error); /* log string and error message */
244     } else {
245         perror(error);
246     }
247     return;
248 }