Small fixes to get really working control sockets on Windows.
[tinc] / src / control.c
1 /*
2     control.c -- Control socket handling.
3     Copyright (C) 2007 Guus Sliepen <guus@tinc-vpn.org>
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
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21 #include "conf.h"
22 #include "control.h"
23 #include "control_common.h"
24 #include "graph.h"
25 #include "logger.h"
26 #include "utils.h"
27 #include "xalloc.h"
28
29 static int control_socket = -1;
30 static struct event control_event;
31 static splay_tree_t *control_socket_tree;
32 extern char *controlsocketname;
33
34 static void handle_control_data(struct bufferevent *event, void *data) {
35         tinc_ctl_request_t req;
36         tinc_ctl_request_t res;
37         struct evbuffer *res_data = NULL;
38         void *req_data;
39
40         if(EVBUFFER_LENGTH(event->input) < sizeof req)
41                 return;
42
43         /* Copy the structure to ensure alignment */
44         memcpy(&req, EVBUFFER_DATA(event->input), sizeof req);
45
46         if(EVBUFFER_LENGTH(event->input) < req.length)
47                 return;
48         req_data = EVBUFFER_DATA(event->input) + sizeof req;
49
50         if(req.length < sizeof req)
51                 goto failure;
52
53         memset(&res, 0, sizeof res);
54         res.type = req.type;
55         res.id = req.id;
56
57         res_data = evbuffer_new();
58         if(res_data == NULL) {
59                 res.res_errno = ENOMEM;
60                 goto respond;
61         }
62
63         if(req.type == REQ_STOP) {
64                 logger(LOG_NOTICE, "Got '%s' command", "stop");
65                 event_loopexit(NULL);
66                 goto respond;
67         }
68
69         if(req.type == REQ_DUMP_NODES) {
70                 logger(LOG_NOTICE, "Got '%s' command", "dump nodes");
71                 res.res_errno = dump_nodes(res_data);
72                 goto respond;
73         }
74
75         if(req.type == REQ_DUMP_EDGES) {
76                 logger(LOG_NOTICE, "Got '%s' command", "dump edges");
77                 res.res_errno = dump_edges(res_data);
78                 goto respond;
79         }
80
81         if(req.type == REQ_DUMP_SUBNETS) {
82                 logger(LOG_NOTICE, "Got '%s' command", "dump subnets");
83                 res.res_errno = dump_subnets(res_data);
84                 goto respond;
85         }
86
87         if(req.type == REQ_DUMP_CONNECTIONS) {
88                 logger(LOG_NOTICE, "Got '%s' command", "dump connections");
89                 res.res_errno = dump_connections(res_data);
90                 goto respond;
91         }
92
93         if(req.type == REQ_DUMP_GRAPH) {
94                 logger(LOG_NOTICE, "Got '%s' command", "dump graph");
95                 res.res_errno = dump_graph(res_data);
96                 goto respond;
97         }
98
99         if(req.type == REQ_PURGE) {
100                 logger(LOG_NOTICE, "Got '%s' command", "purge");
101                 purge();
102                 goto respond;
103         }
104
105         if(req.type == REQ_SET_DEBUG) {
106                 debug_t new_debug_level;
107
108                 logger(LOG_NOTICE, "Got '%s' command", "debug");
109                 if(req.length != sizeof req + sizeof debug_level)
110                         res.res_errno = EINVAL;
111                 else {
112                         memcpy(&new_debug_level, req_data, sizeof new_debug_level);
113                         logger(LOG_NOTICE, "Changing debug level from %d to %d",
114                                    debug_level, new_debug_level);
115                         if(evbuffer_add_printf(res_data,
116                                                                    "Changing debug level from %d to %d\n",
117                                                                    debug_level, new_debug_level) == -1)
118                                 res.res_errno = errno;
119                         debug_level = new_debug_level;
120                 }
121                 goto respond;
122         }
123
124         if(req.type == REQ_RETRY) {
125                 logger(LOG_NOTICE, "Got '%s' command", "retry");
126                 retry();
127                 goto respond;
128         }
129
130         if(req.type == REQ_RELOAD) {
131                 logger(LOG_NOTICE, "Got '%s' command", "reload");
132                 res.res_errno = reload_configuration();
133                 goto respond;
134         }
135
136         logger(LOG_DEBUG, "Malformed control command received");
137         res.res_errno = EINVAL;
138
139 respond:
140         res.length = (sizeof res)
141                                  + ((res_data == NULL) ? 0 : EVBUFFER_LENGTH(res_data));
142         evbuffer_drain(event->input, req.length);
143         if(bufferevent_write(event, &res, sizeof res) == -1)
144                 goto failure;
145         if(res_data != NULL) {
146                 if(bufferevent_write_buffer(event, res_data) == -1)
147                         goto failure;
148                 evbuffer_free(res_data);
149         }
150         return;
151
152 failure:
153         logger(LOG_INFO, "Closing control socket on error");
154         evbuffer_free(res_data);
155         close(event->ev_read.ev_fd);
156         splay_delete(control_socket_tree, event);
157 }
158
159 static void handle_control_error(struct bufferevent *event, short what, void *data) {
160         if(what & EVBUFFER_EOF)
161                 logger(LOG_DEBUG, "Control socket connection closed by peer");
162         else
163                 logger(LOG_DEBUG, "Error while reading from control socket: %s", strerror(errno));
164
165         close(event->ev_read.ev_fd);
166         splay_delete(control_socket_tree, event);
167 }
168
169 static void handle_new_control_socket(int fd, short events, void *data) {
170         int newfd;
171         struct bufferevent *ev;
172         tinc_ctl_greeting_t greeting;
173
174         newfd = accept(fd, NULL, NULL);
175
176         if(newfd < 0) {
177                 logger(LOG_ERR, "Accepting a new connection failed: %s", strerror(errno));
178                 event_del(&control_event);
179                 return;
180         }
181
182         ev = bufferevent_new(newfd, handle_control_data, NULL, handle_control_error, NULL);
183         if(!ev) {
184                 logger(LOG_ERR, "Could not create bufferevent for new control connection: %s", strerror(errno));
185                 close(newfd);
186                 return;
187         }
188
189         memset(&greeting, 0, sizeof greeting);
190         greeting.version = TINC_CTL_VERSION_CURRENT;
191         greeting.pid = getpid();
192         if(bufferevent_write(ev, &greeting, sizeof greeting) == -1) {
193                 logger(LOG_ERR,
194                            "Cannot send greeting for new control connection: %s",
195                            strerror(errno));
196                 bufferevent_free(ev);
197                 close(newfd);
198                 return;
199         }
200
201         bufferevent_enable(ev, EV_READ);
202         splay_insert(control_socket_tree, ev);
203
204         logger(LOG_DEBUG, "Control socket connection accepted");
205 }
206
207 static int control_compare(const struct event *a, const struct event *b) {
208         return a < b ? -1 : a > b ? 1 : 0;
209 }
210
211 bool init_control() {
212         int result;
213
214 #ifdef HAVE_MINGW
215         struct sockaddr_in addr;
216         memset(&addr, 0, sizeof addr);
217         addr.sin_family = AF_INET;
218         addr.sin_addr.s_addr = htonl(0x7f000001);
219         addr.sin_port = htons(55555);
220         int option = 1;
221
222         control_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
223         if(control_socket < 0) {
224                 logger(LOG_ERR, "Creating control socket failed: %s", sockstrerror(sockerrno));
225                 goto bail;
226         }
227
228         setsockopt(control_socket, SOL_SOCKET, SO_REUSEADDR, &option, sizeof option);
229 #else
230         struct sockaddr_un addr;
231         char *lastslash;
232
233         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
234                 logger(LOG_ERR, "Control socket filename too long!");
235                 goto bail;
236         }
237
238         memset(&addr, 0, sizeof addr);
239         addr.sun_family = AF_UNIX;
240         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
241
242         control_socket = socket(PF_UNIX, SOCK_STREAM, 0);
243
244         if(control_socket < 0) {
245                 logger(LOG_ERR, "Creating UNIX socket failed: %s", strerror(errno));
246                 goto bail;
247         }
248
249         /*
250          * Restrict connections to our control socket by ensuring the parent
251          * directory can be traversed only by root. Note this is not totally
252          * race-free unless all ancestors are writable only by trusted users,
253          * which we don't verify.
254          */
255
256         struct stat statbuf;
257         lastslash = strrchr(controlsocketname, '/');
258         if(lastslash != NULL) {
259                 *lastslash = 0; /* temporarily change controlsocketname to be dir */
260                 if(mkdir(controlsocketname, 0700) < 0 && errno != EEXIST) {
261                         logger(LOG_ERR, "Unable to create control socket directory %s: %s", controlsocketname, strerror(errno));
262                         *lastslash = '/';
263                         goto bail;
264                 }
265
266                 result = stat(controlsocketname, &statbuf);
267                 *lastslash = '/';
268         } else
269                 result = stat(".", &statbuf);
270
271         if(result < 0) {
272                 logger(LOG_ERR, "Examining control socket directory failed: %s", strerror(errno));
273                 goto bail;
274         }
275
276         if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
277                 logger(LOG_ERR, "Control socket directory ownership/permissions insecure.");
278                 goto bail;
279         }
280 #endif
281
282         result = bind(control_socket, (struct sockaddr *)&addr, sizeof addr);
283
284         if(result < 0 && sockinuse(sockerrno)) {
285 #ifndef HAVE_MINGW
286                 result = connect(control_socket, (struct sockaddr *)&addr, sizeof addr);
287                 if(result < 0) {
288                         logger(LOG_WARNING, "Removing old control socket.");
289                         unlink(controlsocketname);
290                         result = bind(control_socket, (struct sockaddr *)&addr, sizeof addr);
291                 } else
292 #endif
293                 {
294                         if(netname)
295                                 logger(LOG_ERR, "Another tincd is already running for net `%s'.", netname);
296                         else
297                                 logger(LOG_ERR, "Another tincd is already running.");
298                         goto bail;
299                 }
300         }
301
302         if(result < 0) {
303                 logger(LOG_ERR, "Can't bind to %s: %s", controlsocketname, strerror(errno));
304                 goto bail;
305         }
306
307         if(listen(control_socket, 3) < 0) {
308                 logger(LOG_ERR, "Can't listen on %s: %s", controlsocketname, strerror(errno));
309                 goto bail;
310         }
311
312         control_socket_tree = splay_alloc_tree((splay_compare_t)control_compare, (splay_action_t)bufferevent_free);
313
314         event_set(&control_event, control_socket, EV_READ | EV_PERSIST, handle_new_control_socket, NULL);
315         event_add(&control_event, NULL);
316         return true;
317
318 bail:
319         if(control_socket != -1) {
320                 closesocket(control_socket);
321                 control_socket = -1;
322         }
323         return false;
324 }
325
326 void exit_control() {
327         event_del(&control_event);
328         closesocket(control_socket);
329         unlink(controlsocketname);
330 }