aff36e09e832292a8074783fb3bc365bf5c8d069
[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 #include <libgen.h>
52
53 #include <guacamole/client.h>
54 #include <guacamole/error.h>
55
56 #include "client.h"
57 #include "log.h"
58
59 void guacd_handle_connection(int fd) {
60
61     guac_client* client;
62     guac_client_plugin* plugin;
63     guac_instruction* select;
64     guac_instruction* connect;
65
66     /* Open guac_socket */
67     guac_socket* socket = guac_socket_open(fd);
68
69     /* Get protocol from select instruction */
70     select = guac_protocol_expect_instruction(
71             socket, GUACD_USEC_TIMEOUT, "select");
72     if (select == NULL) {
73
74         /* Log error */
75         guacd_log_guac_error("Error reading \"select\"");
76
77         /* Free resources */
78         guac_socket_close(socket);
79         return;
80     }
81
82     /* Validate args to select */
83     if (select->argc != 1) {
84
85         /* Log error */
86         guacd_log_error("Bad number of arguments to \"select\" (%i)",
87                 select->argc);
88
89         /* Free resources */
90         guac_socket_close(socket);
91         return;
92     }
93
94     guacd_log_info("Protocol \"%s\" selected", select->argv[0]);
95
96     /* Get plugin from protocol in select */
97     plugin = guac_client_plugin_open(select->argv[0]);
98     guac_instruction_free(select);
99
100     if (plugin == NULL) {
101
102         /* Log error */
103         guacd_log_guac_error("Error loading client plugin");
104
105         /* Free resources */
106         guac_socket_close(socket);
107         return;
108     }
109
110     /* Send args response */
111     if (guac_protocol_send_args(socket, plugin->args)
112             || guac_socket_flush(socket)) {
113
114         /* Log error */
115         guacd_log_guac_error("Error sending \"args\"");
116
117         if (guac_client_plugin_close(plugin))
118             guacd_log_guac_error("Error closing client plugin");
119
120         guac_socket_close(socket);
121         return;
122     }
123
124     /* Get args from connect instruction */
125     connect = guac_protocol_expect_instruction(
126             socket, GUACD_USEC_TIMEOUT, "connect");
127     if (connect == NULL) {
128
129         /* Log error */
130         guacd_log_guac_error("Error reading \"connect\"");
131
132         if (guac_client_plugin_close(plugin))
133             guacd_log_guac_error("Error closing client plugin");
134
135         guac_socket_close(socket);
136         return;
137     }
138
139     /* Load and init client */
140     client = guac_client_plugin_get_client(plugin, socket,
141             connect->argc, connect->argv,
142             guacd_client_log_info, guacd_client_log_error);
143
144     guac_instruction_free(connect);
145
146     if (client == NULL) {
147
148         guacd_log_guac_error("Error instantiating client");
149
150         if (guac_client_plugin_close(plugin))
151             guacd_log_guac_error("Error closing client plugin");
152
153         guac_socket_close(socket);
154         return;
155     }
156
157     /* Start client threads */
158     guacd_log_info("Starting client");
159     if (guacd_client_start(client))
160         guacd_log_error("Client finished abnormally");
161     else
162         guacd_log_info("Client finished normally");
163
164     /* Clean up */
165     guac_client_free(client);
166     if (guac_client_plugin_close(plugin))
167         guacd_log_error("Error closing client plugin");
168
169     /* Close socket */
170     guac_socket_close(socket);
171
172     return;
173
174 }
175
176 int main(int argc, char* argv[]) {
177
178     /* Server */
179     int socket_fd;
180     struct addrinfo* addresses;
181     struct addrinfo* current_address;
182     char bound_address[1024];
183     char bound_port[64];
184     int opt_on = 1;
185
186     struct addrinfo hints = {
187         .ai_family   = AF_UNSPEC,
188         .ai_socktype = SOCK_STREAM,
189         .ai_protocol = IPPROTO_TCP
190     };
191
192     /* Client */
193     struct sockaddr_in client_addr;
194     socklen_t client_addr_len;
195     int connected_socket_fd;
196
197     /* Arguments */
198     char* listen_address = NULL; /* Default address of INADDR_ANY */
199     char* listen_port = "4822";  /* Default port */
200     char* pidfile = NULL;
201     int opt;
202
203     /* General */
204     int retval;
205
206     /* Daemon Process */
207     pid_t daemon_pid;
208
209     /* Parse arguments */
210     while ((opt = getopt(argc, argv, "l:b:p:")) != -1) {
211         if (opt == 'l') {
212             listen_port = strdup(optarg);
213         }
214         else if (opt == 'b') {
215             listen_address = strdup(optarg);
216         }
217         else if (opt == 'p') {
218             pidfile = strdup(optarg);
219         }
220         else {
221
222             fprintf(stderr, "USAGE: %s"
223                     " [-l LISTENPORT]"
224                     " [-b LISTENADDRESS]"
225                     " [-p PIDFILE]\n", argv[0]);
226
227             exit(EXIT_FAILURE);
228         }
229     }
230
231     /* Set up logging prefix */
232     strncpy(log_prefix, basename(argv[0]), sizeof(log_prefix));
233
234
235     /* Get addresses for binding */
236     if ((retval = getaddrinfo(listen_address, listen_port, &hints, &addresses))) {
237         guacd_log_error("Error parsing given address or port: %s",
238                 gai_strerror(retval));
239         exit(EXIT_FAILURE);
240     }
241
242     /* Get socket */
243     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
244     if (socket_fd < 0) {
245         guacd_log_error("Error opening socket: %s", strerror(errno));
246         exit(EXIT_FAILURE);
247     }
248
249     /* Allow socket reuse */
250     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
251         guacd_log_info("Unable to set socket options for reuse: %s", strerror(errno));
252     }
253
254     /* Attempt binding of each address until success */
255     current_address = addresses;
256     while (current_address != NULL) {
257
258         int retval;
259
260         /* Resolve hostname */
261         if ((retval = getnameinfo(current_address->ai_addr,
262                 current_address->ai_addrlen,
263                 bound_address, sizeof(bound_address),
264                 bound_port, sizeof(bound_port),
265                 NI_NUMERICHOST | NI_NUMERICSERV)))
266             guacd_log_error("Unable to resolve host: %s",
267                     gai_strerror(retval));
268
269         /* Attempt to bind socket to address */
270         if (bind(socket_fd,
271                     current_address->ai_addr,
272                     current_address->ai_addrlen) == 0) {
273
274             guacd_log_info("Successfully bound socket to "
275                     "host %s, port %s", bound_address, bound_port);
276
277             /* Done if successful bind */
278             break;
279
280         }
281
282         /* Otherwise log information regarding bind failure */
283         else
284             guacd_log_info("Unable to bind socket to "
285                     "host %s, port %s: %s",
286                     bound_address, bound_port, strerror(errno));
287
288         current_address = current_address->ai_next;
289
290     }
291
292     /* If unable to bind to anything, fail */
293     if (current_address == NULL) {
294         guacd_log_error("Unable to bind socket to any addresses.");
295         exit(EXIT_FAILURE);
296     }
297
298     /* Fork into background */
299     daemon_pid = fork();
300
301     /* If error, fail */
302     if (daemon_pid == -1) {
303         guacd_log_error("Error forking daemon process: %s", strerror(errno));
304         exit(EXIT_FAILURE);
305     }
306
307     /* If parent, write PID file and exit */
308     else if (daemon_pid != 0) {
309
310         if (pidfile != NULL) {
311
312             /* Attempt to open pidfile and write PID */
313             FILE* pidf = fopen(pidfile, "w");
314             if (pidf) {
315                 fprintf(pidf, "%d\n", daemon_pid);
316                 fclose(pidf);
317             }
318
319             /* Warn on failure */
320             else {
321                 guacd_log_error("Could not write PID file: %s", strerror(errno));
322                 exit(EXIT_FAILURE);
323             }
324
325         }
326
327         exit(EXIT_SUCCESS);
328     }
329
330     /* Open log */
331     openlog(NULL, LOG_PID, LOG_DAEMON);
332
333     /* Ignore SIGPIPE */
334     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
335         guacd_log_info("Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
336     }
337
338     /* Ignore SIGCHLD (force automatic removal of children) */
339     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
340         guacd_log_info("Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
341     }
342
343     /* Log listening status */
344     syslog(LOG_INFO,
345             "Listening on host %s, port %s", bound_address, bound_port);
346
347     /* Free addresses */
348     freeaddrinfo(addresses);
349
350     /* Daemon loop */
351     for (;;) {
352
353         pid_t child_pid;
354
355         /* Listen for connections */
356         if (listen(socket_fd, 5) < 0) {
357             guacd_log_error("Could not listen on socket: %s", strerror(errno));
358             return 3;
359         }
360
361         /* Accept connection */
362         client_addr_len = sizeof(client_addr);
363         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
364         if (connected_socket_fd < 0) {
365             guacd_log_error("Could not accept client connection: %s", strerror(errno));
366             return 3;
367         }
368
369         /* 
370          * Once connection is accepted, send child into background.
371          *
372          * Note that we prefer fork() over threads for connection-handling
373          * processes as they give each connection its own memory area, and
374          * isolate the main daemon and other connections from errors in any
375          * particular client plugin.
376          */
377
378         child_pid = fork();
379
380         /* If error, log */
381         if (child_pid == -1)
382             guacd_log_error("Error forking child process: %s", strerror(errno));
383
384         /* If child, start client, and exit when finished */
385         else if (child_pid == 0) {
386             guacd_handle_connection(connected_socket_fd);
387             close(connected_socket_fd);
388             return 0;
389         }
390
391         /* If parent, close reference to child's descriptor */
392         else if (close(connected_socket_fd) < 0) {
393             guacd_log_error("Error closing daemon reference to child descriptor: %s", strerror(errno));
394         }
395
396     }
397
398     /* Close socket */
399     if (close(socket_fd) < 0) {
400         guacd_log_error("Could not close socket: %s", strerror(errno));
401         return 3;
402     }
403
404     return 0;
405
406 }
407