b1b64832693e59656d38ae21177770227e678839
[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.1 2003/12/25 17:31:09 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 "Gapil.h"
48
49 #define BACKLOG 10
50 #define MAXLINE 256
51 int demonize  = 1;  /* daemon use option: default is daemon */
52 int debugging = 0;  /* debug info printing option: default is no debug */
53 /* Subroutines declaration */
54 void usage(void);
55 void PrintErr(char * error);
56 /* Program beginning */
57 int main(int argc, char *argv[])
58 {
59 /* 
60  * Variables definition  
61  */
62     int waiting = 0;
63     int compat = 0;
64     struct sockaddr_in serv_add, cli_add;
65     socklen_t len;
66     char buffer[MAXLINE];
67     char fd_open[FD_SETSIZE];
68     fd_set fset;
69     int list_fd, fd;
70     int max_fd, nread, nwrite;
71     int i, n;
72     /*
73      * Input section: decode parameters passed in the calling 
74      * Use getopt function
75      */
76     opterr = 0;  /* don't want writing to stderr */
77     while ( (i = getopt(argc, argv, "hdicw:")) != -1) {
78         switch (i) {
79         /* 
80          * Handling options 
81          */ 
82         case 'h':  
83             printf("Wrong -h option use\n");
84             usage();
85             return(0);
86             break;
87         case 'i':
88             demonize = 0;
89             break;
90         case 'c':
91             compat = 1;
92             break;
93         case 'd':
94             debugging = 1;
95             break;
96         case 'w':
97             waiting = strtol(optarg, NULL, 10);
98             break;
99         case '?':   /* unrecognized options */
100             printf("Unrecognized options -%c\n",optopt);
101             usage();
102         default:    /* should not reached */
103             usage();
104         }
105     }
106     /* ***********************************************************
107      * 
108      *           Options processing completed
109      *
110      *                Main code beginning
111      * 
112      * ***********************************************************/
113     /* Main code begin here */
114     if (compat) {                             /* install signal handler */
115         Signal(SIGCHLD, HandSigCHLD);         /* non restarting handler */
116     } else {
117         SignalRestart(SIGCHLD, HandSigCHLD);  /* restarting handler */
118     }
119     /* create socket */
120     if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
121         perror("Socket creation error");
122         exit(1);
123     }
124     /* initialize address */
125     memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
126     serv_add.sin_family = AF_INET;                  /* address type is INET */
127     serv_add.sin_port = htons(7);                   /* echo port is 7 */
128     serv_add.sin_addr.s_addr = htonl(INADDR_ANY);   /* connect from anywhere */
129     /* bind socket */
130     if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
131         perror("bind error");
132         exit(1);
133     }
134     /* release privileges and go daemon */
135     if (setgid(65534) !=0) { /* first give away group privileges */
136         perror("cannot give away group privileges");
137         exit(1);
138     }
139     if (setuid(65534) !=0) { /* and only after user ... */
140         perror("cannot give away user privileges");
141         exit(1);
142     }
143     if (demonize) {          /* go daemon */
144         openlog(argv[0], 0, LOG_DAEMON); /* open logging */
145         if (daemon(0, 0) != 0) {
146             perror("cannot start as daemon");
147             exit(1);
148         }
149     }
150     /* main body */
151     if (listen(list_fd, BACKLOG) < 0 ) {
152         PrintErr("listen error");
153         exit(1);
154     }
155     if (waiting) sleep(waiting);
156     /* initialize all needed variables */
157     memset(fd_open, 0, FD_SETSIZE);   /* clear array of open files */
158     max_fd = list_fd;                 /* set maximum fd to look */
159     fd_open[max_fd] = 1;
160     /* main loop, wait for connection and data inside a select */
161     while (1) {    
162         FD_ZERO(&fset);               /* clear fd_set */
163         for (i = list_fd; i <= max_fd; i++) {
164             if (fd_open[i]) FD_SET(i, &fset); /* initialize open sockets */
165         }
166         while ( ((n = select(max_fd + 1, &fset, NULL, NULL, NULL)) < 0) 
167                 && (errno == EINTR));
168         /* there are data */
169         if (n < 0) {
170             PrintErr("select error");
171             exit(1);
172         }       
173         if (FD_ISSET(list_fd, &fset)) { /* if data on listening socket */
174             len = sizeof(cli_add);
175             fd = accept(list_fd, (struct sockaddr *)&cli_add, &len); 
176             if (fd < 0) {
177                 PrintErr("accept error");
178                 exit(1);
179             }
180             fd_open[fd] = 1;
181             if (max_fd < fd) max_fd = fd;
182             FD_SET(fd, &fset);
183             n--;
184         }
185         for (i = list_fd + 1; i <= max_fd; i++) {
186             if (fd_open[i] == 0) continue;
187             if (FD_ISSET(i, &fset)) {
188                 n--;
189                 nread = read(fd, buffer, MAXLINE);
190                 if (nread < 0) {
191                     PrintErr("Errore in lettura");
192                     exit(1);
193                 }
194                 if (nread == 0) {
195                     fd_open[i] = 0;
196                     if (max_fd == i) {
197                         while (fd_open[i] == 0) {
198                             i--;
199                         }
200                         max_fd = i;
201                         break;
202                     }
203                     continue;
204                 }
205                 nwrite = FullWrite(fd, buffer, nread);
206                 if (nwrite) {
207                     PrintErr("Errore in scrittura");
208                     exit(1);
209                 }
210             }
211         }
212         if (n != 0) {
213             PrintErr("Errore nella gestione dei file descriptor");
214         }
215     }
216     /* normal exit, never reached */
217     exit(0);
218 }
219 /*
220  * routine to print usage info and exit
221  */
222 void usage(void) {
223     printf("Elementary echo server\n");
224     printf("Usage:\n");
225     printf("  echod [-h] \n");
226     printf("  -h           print this help\n");
227     printf("  -d           write debug info\n");
228     printf("  -i           use interactively\n");
229     printf("  -c           disable BSD semantics\n");
230     printf("  -w N         wait N sec. before calling accept\n");
231     exit(1);
232 }
233 /*
234  * routine to print error on stout or syslog
235  */
236 void PrintErr(char * error) {
237     if (demonize) {                       /* daemon mode */
238         syslog(LOG_ERR, "%s: %m", error); /* log string and error message */
239     } else {
240         perror(error);
241     }
242     return;
243 }