a0ba7f81fe8e9c9f8eefd87988eb2646bd54a930
[guacd.git] / src / daemon.c
1
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
5  * The contents of this file are subject to the Mozilla Public License Version
6  * 1.1 (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  * http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the
13  * License.
14  *
15  * The Original Code is guacd.
16  *
17  * The Initial Developer of the Original Code is
18  * Michael Jumper.
19  * Portions created by the Initial Developer are Copyright (C) 2010
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 #include <unistd.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <sys/types.h>
44
45 #include <sys/socket.h>
46 #include <netdb.h>
47 #include <netinet/in.h>
48
49 #include <errno.h>
50 #include <syslog.h>
51
52 #include <guacamole/client.h>
53 #include <guacamole/error.h>
54
55 #include "client.h"
56 #include "log.h"
57
58 void guacd_handle_connection(int fd) {
59
60     guac_client* client;
61     guac_client_plugin* plugin;
62     guac_instruction* select;
63     guac_instruction* connect;
64
65     /* Open guac_socket */
66     guac_socket* socket = guac_socket_open(fd);
67
68     /* Get protocol from select instruction */
69     select = guac_protocol_expect_instruction(
70             socket, GUACD_USEC_TIMEOUT, "select");
71     if (select == NULL) {
72
73         /* Log error */
74         guacd_log_guac_error("Error reading \"select\"");
75
76         /* Free resources */
77         guac_socket_close(socket);
78         return;
79     }
80
81     /* Validate args to select */
82     if (select->argc != 1) {
83
84         /* Log error */
85         syslog(LOG_ERR, "Bad number of arguments to \"select\" (%i)",
86                 select->argc);
87
88         /* Free resources */
89         guac_socket_close(socket);
90         return;
91     }
92
93     syslog(LOG_INFO, "Protocol \"%s\" selected", select->argv[0]);
94
95     /* Get plugin from protocol in select */
96     plugin = guac_client_plugin_open(select->argv[0]);
97     guac_instruction_free(select);
98
99     if (plugin == NULL) {
100
101         /* Log error */
102         guacd_log_guac_error("Error loading client plugin");
103
104         /* Free resources */
105         guac_socket_close(socket);
106         return;
107     }
108
109     /* Send args response */
110     if (guac_protocol_send_args(socket, plugin->args)
111             || guac_socket_flush(socket)) {
112
113         /* Log error */
114         guacd_log_guac_error("Error sending \"args\"");
115
116         if (guac_client_plugin_close(plugin))
117             guacd_log_guac_error("Error closing client plugin");
118
119         guac_socket_close(socket);
120         return;
121     }
122
123     /* Get args from connect instruction */
124     connect = guac_protocol_expect_instruction(
125             socket, GUACD_USEC_TIMEOUT, "connect");
126     if (connect == NULL) {
127
128         /* Log error */
129         guacd_log_guac_error("Error reading \"connect\"");
130
131         if (guac_client_plugin_close(plugin))
132             guacd_log_guac_error("Error closing client plugin");
133
134         guac_socket_close(socket);
135         return;
136     }
137
138     /* Load and init client */
139     client = guac_client_plugin_get_client(plugin, socket,
140             connect->argc, connect->argv); 
141     guac_instruction_free(connect);
142
143     if (client == NULL) {
144
145         guacd_log_guac_error("Error instantiating client");
146
147         if (guac_client_plugin_close(plugin))
148             guacd_log_guac_error("Error closing client plugin");
149
150         guac_socket_close(socket);
151         return;
152     }
153
154     /* Set up logging in client */
155     client->log_info_handler  = guacd_log_info;
156     client->log_error_handler = guacd_log_error;
157
158     /* Start client threads */
159     syslog(LOG_INFO, "Starting client");
160     if (guacd_client_start(client))
161         syslog(LOG_ERR, "Client finished abnormally");
162     else
163         syslog(LOG_INFO, "Client finished normally");
164
165     /* Clean up */
166     guac_client_free(client);
167     if (guac_client_plugin_close(plugin))
168         syslog(LOG_ERR, "Error closing client plugin");
169
170     /* Close socket */
171     guac_socket_close(socket);
172
173     return;
174
175 }
176
177 int main(int argc, char* argv[]) {
178
179     /* Server */
180     int socket_fd;
181     struct addrinfo* addresses;
182     struct addrinfo* current_address;
183     char bound_address[1024];
184     char bound_port[64];
185     int opt_on = 1;
186
187     struct addrinfo hints = {
188         .ai_family   = AF_UNSPEC,
189         .ai_socktype = SOCK_STREAM,
190         .ai_protocol = IPPROTO_TCP
191     };
192
193     /* Client */
194     struct sockaddr_in client_addr;
195     socklen_t client_addr_len;
196     int connected_socket_fd;
197
198     /* Arguments */
199     char* listen_address = NULL; /* Default address of INADDR_ANY */
200     char* listen_port = "4822";  /* Default port */
201     char* pidfile = NULL;
202     int opt;
203
204     /* General */
205     int retval;
206
207     /* Daemon Process */
208     pid_t daemon_pid;
209
210     /* Parse arguments */
211     while ((opt = getopt(argc, argv, "l:b:p:")) != -1) {
212         if (opt == 'l') {
213             listen_port = strdup(optarg);
214         }
215         else if (opt == 'b') {
216             listen_address = strdup(optarg);
217         }
218         else if (opt == 'p') {
219             pidfile = strdup(optarg);
220         }
221         else {
222
223             fprintf(stderr, "USAGE: %s"
224                     " [-l LISTENPORT]"
225                     " [-b LISTENADDRESS]"
226                     " [-p PIDFILE]\n", argv[0]);
227
228             exit(EXIT_FAILURE);
229         }
230     }
231
232     /* Get addresses for binding */
233     if ((retval = getaddrinfo(listen_address, listen_port, &hints, &addresses))) {
234         fprintf(stderr, "Error parsing given address or port: %s\n",
235                 gai_strerror(retval));
236         exit(EXIT_FAILURE);
237     }
238
239     /* Get socket */
240     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
241     if (socket_fd < 0) {
242         fprintf(stderr, "Error opening socket: %s\n", strerror(errno));
243         exit(EXIT_FAILURE);
244     }
245
246     /* Allow socket reuse */
247     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
248         fprintf(stderr, "Warning: Unable to set socket options for reuse: %s\n", strerror(errno));
249     }
250
251     /* Attempt binding of each address until success */
252     current_address = addresses;
253     while (current_address != NULL) {
254
255         int retval;
256
257         /* Resolve hostname */
258         if ((retval = getnameinfo(current_address->ai_addr,
259                 current_address->ai_addrlen,
260                 bound_address, sizeof(bound_address),
261                 bound_port, sizeof(bound_port),
262                 NI_NUMERICHOST | NI_NUMERICSERV)))
263             fprintf(stderr, "Unable to resolve host: %s\n",
264                     gai_strerror(retval));
265
266         /* Attempt to bind socket to address */
267         if (bind(socket_fd,
268                     current_address->ai_addr,
269                     current_address->ai_addrlen) == 0) {
270
271             fprintf(stderr, "Successfully bound socket to "
272                     "host %s, port %s\n", bound_address, bound_port);
273
274             /* Done if successful bind */
275             break;
276
277         }
278
279         /* Otherwise log error */
280         else
281             fprintf(stderr, "Error binding socket to "
282                     "host %s, port %s: %s\n",
283                     bound_address, bound_port, strerror(errno));
284
285         current_address = current_address->ai_next;
286
287     }
288
289     /* If unable to bind to anything, fail */
290     if (current_address == NULL) {
291         fprintf(stderr, "Unable to bind socket to any addresses.\n");
292         exit(EXIT_FAILURE);
293     }
294
295     /* Fork into background */
296     daemon_pid = fork();
297
298     /* If error, fail */
299     if (daemon_pid == -1) {
300         fprintf(stderr, "Error forking daemon process: %s\n", strerror(errno));
301         exit(EXIT_FAILURE);
302     }
303
304     /* If parent, write PID file and exit */
305     else if (daemon_pid != 0) {
306
307         if (pidfile != NULL) {
308
309             /* Attempt to open pidfile and write PID */
310             FILE* pidf = fopen(pidfile, "w");
311             if (pidf) {
312                 fprintf(pidf, "%d\n", daemon_pid);
313                 fclose(pidf);
314             }
315
316             /* Warn on failure */
317             else {
318                 fprintf(stderr, "WARNING: Could not write PID file: %s\n", strerror(errno));
319                 exit(EXIT_FAILURE);
320             }
321
322         }
323
324         exit(EXIT_SUCCESS);
325     }
326
327     /* Open log */
328     openlog(NULL, LOG_PID, LOG_DAEMON);
329
330     /* Ignore SIGPIPE */
331     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
332         syslog(LOG_ERR, "Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
333     }
334
335     /* Ignore SIGCHLD (force automatic removal of children) */
336     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
337         syslog(LOG_ERR, "Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
338     }
339
340     /* Log listening status */
341     syslog(LOG_INFO,
342             "Listening on host %s, port %s", bound_address, bound_port);
343
344     /* Free addresses */
345     freeaddrinfo(addresses);
346
347     /* Daemon loop */
348     for (;;) {
349
350         pid_t child_pid;
351
352         /* Listen for connections */
353         if (listen(socket_fd, 5) < 0) {
354             syslog(LOG_ERR, "Could not listen on socket: %s", strerror(errno));
355             return 3;
356         }
357
358         /* Accept connection */
359         client_addr_len = sizeof(client_addr);
360         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
361         if (connected_socket_fd < 0) {
362             syslog(LOG_ERR, "Could not accept client connection: %s", strerror(errno));
363             return 3;
364         }
365
366         /* 
367          * Once connection is accepted, send child into background.
368          *
369          * Note that we prefer fork() over threads for connection-handling
370          * processes as they give each connection its own memory area, and
371          * isolate the main daemon and other connections from errors in any
372          * particular client plugin.
373          */
374
375         child_pid = fork();
376
377         /* If error, log */
378         if (child_pid == -1)
379             syslog(LOG_ERR, "Error forking child process: %s\n", strerror(errno));
380
381         /* If child, start client, and exit when finished */
382         else if (child_pid == 0) {
383             guacd_handle_connection(connected_socket_fd);
384             close(connected_socket_fd);
385             return 0;
386         }
387
388         /* If parent, close reference to child's descriptor */
389         else if (close(connected_socket_fd) < 0) {
390             syslog(LOG_ERR, "Error closing daemon reference to child descriptor: %s", strerror(errno));
391         }
392
393     }
394
395     /* Close socket */
396     if (close(socket_fd) < 0) {
397         syslog(LOG_ERR, "Could not close socket: %s", strerror(errno));
398         return 3;
399     }
400
401     return 0;
402
403 }
404