Remove unneeded server name information in ssl status.
[cascardo/rnetproxy.git] / tcp_server.c
1 /*
2  * Copyright (C) 2008-2009  Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  *
17  */
18
19 #include <sys/socket.h>
20 #include <sys/types.h>
21 #include <netinet/in.h>
22 #include <netdb.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 static int
28 tcp_server (struct addrinfo *ai)
29 {
30   int fd;
31   fd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
32   if (fd < 0)
33     return -1;
34   if (bind (fd, ai->ai_addr, ai->ai_addrlen) < 0)
35     {
36       close (fd);
37       return -1;
38     }
39   if (listen (fd, 5) < 0)
40     {
41       close (fd);
42       return -1;
43     }
44   return fd;
45 }
46
47 static int
48 tcp_server_list (struct addrinfo *ai)
49 {
50   int fd = -1;
51   for (; ai; ai = ai->ai_next)
52     {
53       fd = tcp_server (ai);
54       if (fd >= 0)
55         {
56           return fd;
57         }
58     }
59   return fd;
60 }
61
62 int
63 hc_tcp_server (char *service)
64 {
65   struct addrinfo hint;
66   struct addrinfo *ai = NULL;
67   int fd;
68   hint.ai_family = AF_UNSPEC;
69   hint.ai_socktype = SOCK_STREAM;
70   hint.ai_protocol = 0;
71   hint.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_V4MAPPED;
72   if (getaddrinfo (NULL, service, &hint, &ai) < 0)
73     return -1;
74   fd = tcp_server_list (ai);
75   freeaddrinfo (ai);
76   return fd;
77 }
78
79 #ifdef TEST
80 int
81 main (int argc, char **argv)
82 {
83   char *service;
84   int fd;
85   service = (argc >= 2) ? argv[1] : "110";
86   fd = hc_tcp_server (service);
87   if (fd > 0)
88     close (fd);
89   return 0;
90 }
91 #endif