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