Additional logging, moderate cleanup.
[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 <netinet/in.h>
47
48 #include <errno.h>
49 #include <syslog.h>
50
51 #include <guacamole/client.h>
52 #include <guacamole/error.h>
53
54 #include "client.h"
55
56 typedef struct client_thread_data {
57
58     int fd;
59
60 } client_thread_data;
61
62
63 void* start_client_thread(void* data) {
64
65     guac_client* client;
66     guac_client_plugin* plugin;
67     guac_instruction* select;
68     guac_instruction* connect;
69
70     /* Get thread data */
71     client_thread_data* thread_data = (client_thread_data*) data;
72
73     /* Open guac_socket */
74     guac_socket* socket = guac_socket_open(thread_data->fd);
75
76     /* Get protocol from select instruction */
77     select = guac_protocol_expect_instruction(
78             socket, GUAC_USEC_TIMEOUT, "select");
79     if (select == NULL) {
80
81         /* Log error */
82         syslog(LOG_ERR, "Error reading \"select\": %s",
83                 guac_status_string(guac_error));
84
85         /* Free resources */
86         guac_socket_close(socket);
87         free(data);
88         return NULL;
89     }
90
91     /* Validate args to select */
92     if (select->argc != 1) {
93
94         /* Log error */
95         syslog(LOG_ERR, "Bad number of arguments to \"select\" (%i)",
96                 select->argc);
97
98         /* Free resources */
99         guac_socket_close(socket);
100         free(data);
101         return NULL;
102     }
103
104     syslog(LOG_INFO, "Protocol \"%s\" selected", select->argv[0]);
105
106     /* Get plugin from protocol in select */
107     plugin = guac_client_plugin_open(select->argv[0]);
108     guac_instruction_free(select);
109
110     if (plugin == NULL) {
111
112         /* Log error */
113         syslog(LOG_ERR, "Error loading client plugin: %s",
114                 guac_status_string(guac_error));
115
116         /* Free resources */
117         guac_socket_close(socket);
118         free(data);
119         return NULL;
120     }
121
122     /* Send args response */
123     if (guac_protocol_send_args(socket, plugin->args)
124             || guac_socket_flush(socket)) {
125
126         /* Log error */
127         syslog(LOG_ERR, "Error sending \"args\": %s",
128                 guac_status_string(guac_error));
129
130         if (guac_client_plugin_close(plugin))
131             syslog(LOG_ERR, "Error closing client plugin");
132
133         guac_socket_close(socket);
134         free(data);
135         return NULL;
136     }
137
138     /* Get args from connect instruction */
139     connect = guac_protocol_expect_instruction(
140             socket, GUAC_USEC_TIMEOUT, "connect");
141     if (connect == NULL) {
142
143         /* Log error */
144         syslog(LOG_ERR, "Error reading \"connect\": %s",
145                 guac_status_string(guac_error));
146
147         if (guac_client_plugin_close(plugin))
148             syslog(LOG_ERR, "Error closing client plugin");
149
150         guac_socket_close(socket);
151         free(data);
152         return NULL;
153     }
154
155     /* Load and init client */
156     client = guac_client_plugin_get_client(plugin, socket,
157             connect->argc, connect->argv); 
158     guac_instruction_free(connect);
159
160     if (client == NULL) {
161
162         syslog(LOG_ERR, "Error instantiating client: %s",
163                 guac_status_string(guac_error));
164
165         if (guac_client_plugin_close(plugin))
166             syslog(LOG_ERR, "Error closing client plugin");
167
168         guac_socket_close(socket);
169         free(data);
170         return NULL;
171     }
172
173     /* Start client threads */
174     syslog(LOG_INFO, "Starting client");
175     if (guac_start_client(client))
176         syslog(LOG_ERR, "Client finished abnormally");
177     else
178         syslog(LOG_INFO, "Client finished normally");
179
180     /* Clean up */
181     guac_client_free(client);
182     if (guac_client_plugin_close(plugin))
183         syslog(LOG_ERR, "Error closing client plugin");
184
185     /* Close socket */
186     guac_socket_close(socket);
187     close(thread_data->fd);
188
189     free(data);
190     return NULL;
191
192 }
193
194 int main(int argc, char* argv[]) {
195
196     /* Server */
197     int socket_fd;
198     struct sockaddr_in server_addr;
199     int opt_on = 1;
200
201     /* Client */
202     struct sockaddr_in client_addr;
203     socklen_t client_addr_len;
204     int connected_socket_fd;
205
206     /* Arguments */
207     int listen_port = 4822; /* Default port */
208     int opt;
209
210     char* pidfile = NULL;
211
212     /* Daemon Process */
213     pid_t daemon_pid;
214
215     /* Parse arguments */
216     while ((opt = getopt(argc, argv, "l:p:")) != -1) {
217         if (opt == 'l') {
218             listen_port = atoi(optarg);
219             if (listen_port <= 0) {
220                 fprintf(stderr, "Invalid port: %s\n", optarg);
221                 exit(EXIT_FAILURE);
222             }
223         }
224         else if (opt == 'p') {
225             pidfile = strdup(optarg);
226         }
227         else {
228             fprintf(stderr, "USAGE: %s [-l LISTENPORT] [-p PIDFILE]\n", argv[0]);
229             exit(EXIT_FAILURE);
230         }
231     }
232
233     /* Get binding address */
234     memset(&server_addr, 0, sizeof(server_addr)); /* Zero struct */
235     server_addr.sin_family = AF_INET;
236     server_addr.sin_addr.s_addr = INADDR_ANY;
237     server_addr.sin_port = htons(listen_port);
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     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
247         fprintf(stderr, "Warning: Unable to set socket options for reuse: %s\n", strerror(errno));
248     }
249
250     /* Bind socket to address */
251     if (bind(socket_fd, (struct sockaddr*) &server_addr,
252                 sizeof(server_addr)) < 0) {
253         fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
254         exit(EXIT_FAILURE);
255     } 
256
257     /* Fork into background */
258 #ifdef HAVE_FORK
259     daemon_pid = fork();
260
261     /* If error, fail */
262     if (daemon_pid == -1) {
263         fprintf(stderr, "Error forking daemon process: %s\n", strerror(errno));
264         exit(EXIT_FAILURE);
265     }
266
267     /* If parent, write PID file and exit */
268     else if (daemon_pid != 0) {
269
270         if (pidfile != NULL) {
271
272             /* Attempt to open pidfile and write PID */
273             FILE* pidf = fopen(pidfile, "w");
274             if (pidf) {
275                 fprintf(pidf, "%d\n", daemon_pid);
276                 fclose(pidf);
277             }
278
279             /* Warn on failure */
280             else {
281                 fprintf(stderr, "WARNING: Could not write PID file: %s\n", strerror(errno));
282                 exit(EXIT_FAILURE);
283             }
284
285         }
286
287         exit(EXIT_SUCCESS);
288     }
289 #else
290     daemon_pid = getpid();
291     syslog(LOG_INFO, "fork() not defined at compile time.");
292     syslog(LOG_INFO, "guacd running in foreground only.");
293 #endif
294
295     /* Otherwise, this is the daemon */
296     syslog(LOG_INFO, "Listening on port %i", listen_port);
297
298     /* Ignore SIGPIPE */
299     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
300         syslog(LOG_ERR, "Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
301     }
302
303     /* Ignore SIGCHLD (force automatic removal of children) */
304     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
305         syslog(LOG_ERR, "Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
306     }
307
308     /* Daemon loop */
309     for (;;) {
310
311 #ifdef HAVE_FORK
312         pid_t child_pid;
313 #else
314         guac_thread_t thread;
315 #endif
316         client_thread_data* data;
317
318         /* Listen for connections */
319         if (listen(socket_fd, 5) < 0) {
320             syslog(LOG_ERR, "Could not listen on socket: %s", strerror(errno));
321             return 3;
322         }
323
324         /* Accept connection */
325         client_addr_len = sizeof(client_addr);
326         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
327         if (connected_socket_fd < 0) {
328             syslog(LOG_ERR, "Could not accept client connection: %s", strerror(errno));
329             return 3;
330         }
331
332         data = malloc(sizeof(client_thread_data));
333         data->fd = connected_socket_fd;
334
335         /* 
336          * Once connection is accepted, send child into background, whether through
337          * fork() or through creating a thread. If thead support is not present on
338          * the platform, guacd will still work, but will only be able to handle one
339          * connection at a time.
340          */
341
342 #ifdef HAVE_FORK
343
344         /*** FORK ***/
345
346         /*
347          * Note that we prefer fork() over threads for connection-handling
348          * processes as they give each connection its own memory area, and
349          * isolate the main daemon and other connections from errors in any
350          * particular client plugin.
351          */
352
353         child_pid = fork();
354
355         /* If error, log */
356         if (child_pid == -1)
357             syslog(LOG_ERR, "Error forking child process: %s\n", strerror(errno));
358
359         /* If child, start client, and exit when finished */
360         else if (child_pid == 0) {
361             start_client_thread(data);
362             return 0;
363         }
364
365         /* If parent, close reference to child's descriptor */
366         else if (close(connected_socket_fd) < 0) {
367             syslog(LOG_ERR, "Error closing daemon reference to child descriptor: %s", strerror(errno));
368         }
369
370 #else
371
372         if (guac_thread_create(&thread, start_client_thread, (void*) data))
373             syslog(LOG_ERR, "Could not create client thread: %s", strerror(errno));
374
375 #endif
376
377     }
378
379     /* Close socket */
380     if (close(socket_fd) < 0) {
381         syslog(LOG_ERR, "Could not close socket: %s", strerror(errno));
382         return 3;
383     }
384
385     return 0;
386
387 }
388