Add provision for XML parameters on the command line avoiding negotiation with client
[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  * David PHAM-VAN <d.pham-van@ulteo.com> Ulteo SAS - http://www.ulteo.com
24  *
25  * Alternatively, the contents of this file may be used under the terms of
26  * either the GNU General Public License Version 2 or later (the "GPL"), or
27  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28  * in which case the provisions of the GPL or the LGPL are applicable instead
29  * of those above. If you wish to allow use of your version of this file only
30  * under the terms of either the GPL or the LGPL, and not to allow others to
31  * use your version of this file under the terms of the MPL, indicate your
32  * decision by deleting the provisions above and replace them with the notice
33  * and other provisions required by the GPL or the LGPL. If you do not delete
34  * the provisions above, a recipient may use your version of this file under
35  * the terms of any one of the MPL, the GPL or the LGPL.
36  *
37  * ***** END LICENSE BLOCK ***** */
38
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <signal.h>
44 #include <sys/types.h>
45 #include <ctype.h>
46
47 #include <sys/socket.h>
48 #include <netdb.h>
49 #include <netinet/in.h>
50
51 #include <errno.h>
52 #include <syslog.h>
53 #include <libgen.h>
54
55 #include <guacamole/client.h>
56 #include <guacamole/error.h>
57
58 #include "client.h"
59 #include "log.h"
60
61 /* XML */
62 #include <libxml2/libxml/parser.h>
63 #include <libxml2/libxml/tree.h>
64 #include <libxml2/libxml/xpath.h>
65 #include <libxml2/libxml/xpathInternals.h>
66
67 void xml_init () {
68     /* check the version. This calls xmlInitParser() */
69     /* braces to stop indent getting confused */
70     {LIBXML_TEST_VERSION}
71 }
72
73 void xml_deinit () {
74     xmlCleanupParser ();
75 }
76
77 xmlNodePtr xml_get_node (xmlDoc * pDoc, const char *xpathexpr) {
78     xmlChar *xpath_expr = (xmlChar *) xpathexpr;
79     xmlXPathContextPtr xpathCtx = NULL;
80     xmlXPathObjectPtr xpathObj = NULL;
81     xmlNodeSetPtr nodeSet = NULL;
82     int size;
83     xmlNodePtr myNode = NULL;
84
85     /* Create xpath evaluation context */
86     if (NULL == (xpathCtx = xmlXPathNewContext (pDoc)))
87         return NULL;
88         
89     /* Evaluate xpath expression */
90     if (NULL == (xpathObj = xmlXPathEvalExpression (xpath_expr, xpathCtx))) {
91         xmlXPathFreeContext (xpathCtx);
92         return NULL;
93     }
94
95     nodeSet = xpathObj->nodesetval;
96     size = (nodeSet) ? nodeSet->nodeNr : 0;
97     if (size == 1)
98         myNode = nodeSet->nodeTab[0];
99
100     xmlXPathFreeObject (xpathObj);
101     xmlXPathFreeContext (xpathCtx);
102     return myNode;
103 }
104
105 char * xml_get_string (xmlDoc * pDoc, char *xpathexpr) {
106     xmlNodePtr config_node = NULL;
107     xmlChar *propval = NULL;
108     
109     /* Find the node in question beneath the config node */
110     if (NULL == (config_node = xml_get_node (pDoc, xpathexpr)))
111         return NULL;
112     
113     /* Find the property attached to that node; if it's not there, return 0 */
114     if (NULL == (propval = xmlNodeGetContent (config_node)))
115         return NULL;
116
117     /* We would like to just return propval here, but that's an xmlChar * allocated by                                                                                                                    
118      * libxml, and thus the caller can't just free() it - it would need to be xmlFree()'d.                                                                                                                
119      * so we'll fiddle around and generate our own copy allocated with libc                                                                                                                               
120      */
121     char *value = strdup ((char *) propval);
122     xmlFree (propval);            /* as xmlGetProp makes a copy of the string */
123     return value;                 /* caller's responsibility to free() this */
124 }
125
126 void guacd_handle_connection(int fd) {
127
128     guac_client* client;
129     guac_client_plugin* plugin;
130     guac_instruction* select;
131     guac_instruction* connect;
132
133     /* Open guac_socket */
134     guac_socket* socket = guac_socket_open(fd);
135
136     /* Get protocol from select instruction */
137     select = guac_protocol_expect_instruction(
138             socket, GUACD_USEC_TIMEOUT, "select");
139     if (select == NULL) {
140
141         /* Log error */
142         guacd_log_guac_error("Error reading \"select\"");
143
144         /* Free resources */
145         guac_socket_close(socket);
146         return;
147     }
148
149     /* Validate args to select */
150     if (select->argc != 1) {
151
152         /* Log error */
153         guacd_log_error("Bad number of arguments to \"select\" (%i)",
154                 select->argc);
155
156         /* Free resources */
157         guac_socket_close(socket);
158         return;
159     }
160
161     guacd_log_info("Protocol \"%s\" selected", select->argv[0]);
162
163     /* Get plugin from protocol in select */
164     plugin = guac_client_plugin_open(select->argv[0]);
165     guac_instruction_free(select);
166
167     if (plugin == NULL) {
168
169         /* Log error */
170         guacd_log_guac_error("Error loading client plugin");
171
172         /* Free resources */
173         guac_socket_close(socket);
174         return;
175     }
176
177     /* Send args response */
178     if (guac_protocol_send_args(socket, plugin->args)
179             || guac_socket_flush(socket)) {
180
181         /* Log error */
182         guacd_log_guac_error("Error sending \"args\"");
183
184         if (guac_client_plugin_close(plugin))
185             guacd_log_guac_error("Error closing client plugin");
186
187         guac_socket_close(socket);
188         return;
189     }
190
191     /* Get args from connect instruction */
192     connect = guac_protocol_expect_instruction(
193             socket, GUACD_USEC_TIMEOUT, "connect");
194     if (connect == NULL) {
195
196         /* Log error */
197         guacd_log_guac_error("Error reading \"connect\"");
198
199         if (guac_client_plugin_close(plugin))
200             guacd_log_guac_error("Error closing client plugin");
201
202         guac_socket_close(socket);
203         return;
204     }
205
206     /* Load and init client */
207     client = guac_client_plugin_get_client(plugin, socket,
208             connect->argc, connect->argv,
209             guacd_client_log_info, guacd_client_log_error);
210
211     guac_instruction_free(connect);
212
213     if (client == NULL) {
214
215         guacd_log_guac_error("Error instantiating client");
216
217         if (guac_client_plugin_close(plugin))
218             guacd_log_guac_error("Error closing client plugin");
219
220         guac_socket_close(socket);
221         return;
222     }
223
224     /* Start client threads */
225     guacd_log_info("Starting client");
226     if (guacd_client_start(client))
227         guacd_log_error("Client finished abnormally");
228     else
229         guacd_log_info("Client finished normally");
230
231     /* Clean up */
232     guac_client_free(client);
233     if (guac_client_plugin_close(plugin))
234         guacd_log_error("Error closing client plugin");
235
236     /* Close socket */
237     guac_socket_close(socket);
238
239     return;
240
241 }
242
243 void guacd_handle_connection_xml(int fd, char* xmlconfig) {
244
245     guac_client* client = NULL;
246     guac_client_plugin* plugin = NULL;
247     char ** protocol_argv = NULL;
248     int protocol_argc = 0;
249     xmlDoc * pDoc = NULL;
250     char * protocol = NULL;
251     guac_socket* socket = NULL;
252
253     if (NULL == (socket = guac_socket_open(fd))) {
254         guacd_log_guac_error("Could not open socket");
255         goto error;
256     }
257
258     if (NULL == (pDoc = xmlParseMemory (xmlconfig, strlen(xmlconfig)))) {
259         guacd_log_guac_error("Could not parse XML");
260         goto error;
261     }
262
263     if (NULL == (protocol = xml_get_string(pDoc, "/params/protocol"))) {
264         guacd_log_guac_error("Could not parse XML");
265         goto error;
266     }
267
268     guacd_log_info("Opening protocol '%s'", protocol);
269
270     /* Get plugin from protocol in select */
271     if (NULL == (plugin = guac_client_plugin_open(protocol))) {
272         guacd_log_guac_error("Error loading client plugin");
273         goto error;
274     }
275
276     /* Now parse protocol strings */
277     const char ** arg;
278     const char * params = "/params/";
279     int lparams = strlen(params);
280     for (arg = plugin->args; *arg && **arg; arg++)
281         protocol_argc++;
282     if (NULL == (protocol_argv = calloc(sizeof(char *), protocol_argc+1))) {
283         guacd_log_guac_error("Cannot allocate protocol arguments");
284         goto error;
285     }
286
287     int i;
288     for (i=0; i<protocol_argc; i++) {
289         const char * p;
290         char * q;
291         int l = strlen(plugin->args[i]);
292         char * argname = malloc(lparams+l+1);
293         if (!argname) {
294             guacd_log_guac_error("Error duplicating argument list");
295             goto error;
296         }
297         strncpy(argname, params, lparams);
298         /* replace non-alpha characters by '_' for XML */
299         for (p = plugin->args[i], q = argname+lparams; *p; p++, q++)
300             *q = isalnum(*p)?*p:'_';
301         *q='\0';
302         char * value = xml_get_string(pDoc, argname);
303         if (!value)
304             value = strdup("");
305         guacd_log_info("Argument '%s' set to '%s'", plugin->args[i], value);
306         protocol_argv[i]=value;
307     }
308
309     guacd_log_info("Starting protocol %s, %d arguments", protocol, protocol_argc);
310
311     /* Load and init client */
312     if (NULL == (client = guac_client_plugin_get_client(plugin, socket,
313                                                         protocol_argc, protocol_argv,
314                                                         guacd_client_log_info, guacd_client_log_error))) {
315         guacd_log_guac_error("Error instantiating client");
316         goto error;
317     }
318
319     /* Start client threads */
320     guacd_log_info("Starting client");
321     if (guacd_client_start(client))
322         guacd_log_error("Client finished abnormally");
323     else
324         guacd_log_info("Client finished normally");
325
326   error:
327     /* Clean up */
328     if (client)
329         guac_client_free(client);
330
331     if (plugin && guac_client_plugin_close(plugin))
332         guacd_log_error("Error closing client plugin");
333
334     if (protocol_argv) {
335         char **parg;
336         for (parg = protocol_argv ; *parg; parg++)
337             free(*parg);
338         free(protocol_argv);
339     }
340     if (pDoc)
341         xmlFreeDoc(pDoc);
342     if (protocol)
343         free (protocol);
344     if (socket)
345         guac_socket_close(socket);
346
347     return;
348 }
349
350 int main(int argc, char* argv[]) {
351
352     /* Server */
353     int socket_fd;
354     struct addrinfo* addresses;
355     struct addrinfo* current_address;
356     char bound_address[1024];
357     char bound_port[64];
358     int opt_on = 1;
359
360     struct addrinfo hints = {
361         .ai_family   = AF_UNSPEC,
362         .ai_socktype = SOCK_STREAM,
363         .ai_protocol = IPPROTO_TCP
364     };
365
366     /* Client */
367     struct sockaddr_in client_addr;
368     socklen_t client_addr_len;
369     int connected_socket_fd;
370
371     /* Arguments */
372     char* listen_address = NULL; /* Default address of INADDR_ANY */
373     char* listen_port = "4822";  /* Default port */
374     char* pidfile = NULL;
375     int opt;
376     int foreground = 0;
377     char * xmlconfig = NULL;
378
379     /* General */
380     int retval;
381
382     /* Daemon Process */
383     pid_t daemon_pid;
384
385     xml_init();
386
387     /* Parse arguments */
388     while ((opt = getopt(argc, argv, "l:b:p:x:f")) != -1) {
389         if (opt == 'l') {
390             listen_port = strdup(optarg);
391         }
392         else if (opt == 'b') {
393             listen_address = strdup(optarg);
394         }
395         else if (opt == 'f') {
396             foreground++;
397         }
398         else if (opt == 'p') {
399             pidfile = strdup(optarg);
400         }
401         else if (opt == 'x') {
402             xmlconfig = strdup (optarg);
403         }
404         else {
405
406             fprintf(stderr, "USAGE: %s"
407                     " [-l LISTENPORT]"
408                     " [-b LISTENADDRESS]"
409                     " [-p PIDFILE]"
410                     " [-f]"
411                     " [-x XMLCONFIG]\n", argv[0]);
412
413             exit(EXIT_FAILURE);
414         }
415     }
416
417     /* Set up logging prefix */
418     strncpy(log_prefix, basename(argv[0]), sizeof(log_prefix));
419
420
421     /* Get addresses for binding */
422     if ((retval = getaddrinfo(listen_address, listen_port, &hints, &addresses))) {
423         guacd_log_error("Error parsing given address or port: %s",
424                 gai_strerror(retval));
425         exit(EXIT_FAILURE);
426     }
427
428     /* Get socket */
429     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
430     if (socket_fd < 0) {
431         guacd_log_error("Error opening socket: %s", strerror(errno));
432         exit(EXIT_FAILURE);
433     }
434
435     /* Allow socket reuse */
436     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
437         guacd_log_info("Unable to set socket options for reuse: %s", strerror(errno));
438     }
439
440     /* Attempt binding of each address until success */
441     current_address = addresses;
442     while (current_address != NULL) {
443
444         int retval;
445
446         /* Resolve hostname */
447         if ((retval = getnameinfo(current_address->ai_addr,
448                 current_address->ai_addrlen,
449                 bound_address, sizeof(bound_address),
450                 bound_port, sizeof(bound_port),
451                 NI_NUMERICHOST | NI_NUMERICSERV)))
452             guacd_log_error("Unable to resolve host: %s",
453                     gai_strerror(retval));
454
455         /* Attempt to bind socket to address */
456         if (bind(socket_fd,
457                     current_address->ai_addr,
458                     current_address->ai_addrlen) == 0) {
459
460             guacd_log_info("Successfully bound socket to "
461                     "host %s, port %s", bound_address, bound_port);
462
463             /* Done if successful bind */
464             break;
465
466         }
467
468         /* Otherwise log information regarding bind failure */
469         else
470             guacd_log_info("Unable to bind socket to "
471                     "host %s, port %s: %s",
472                     bound_address, bound_port, strerror(errno));
473
474         current_address = current_address->ai_next;
475
476     }
477
478     /* If unable to bind to anything, fail */
479     if (current_address == NULL) {
480         guacd_log_error("Unable to bind socket to any addresses.");
481         exit(EXIT_FAILURE);
482     }
483
484     if (!foreground) {
485
486         /* Fork into background */
487         daemon_pid = fork();
488
489         /* If error, fail */
490         if (daemon_pid == -1) {
491             guacd_log_error("Error forking daemon process: %s", strerror(errno));
492             exit(EXIT_FAILURE);
493         }
494
495         /* If parent, write PID file and exit */
496         else if (daemon_pid != 0) {
497
498             if (pidfile != NULL) {
499
500                 /* Attempt to open pidfile and write PID */
501                 FILE* pidf = fopen(pidfile, "w");
502                 if (pidf) {
503                     fprintf(pidf, "%d\n", daemon_pid);
504                     fclose(pidf);
505                 }
506
507                 /* Warn on failure */
508                 else {
509                     guacd_log_error("Could not write PID file: %s", strerror(errno));
510                     exit(EXIT_FAILURE);
511                 }
512
513             }
514
515             exit(EXIT_SUCCESS);
516         }
517     }
518
519     /* Open log */
520     openlog(NULL, LOG_PID, LOG_DAEMON);
521
522     /* Ignore SIGPIPE */
523     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
524         guacd_log_info("Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
525     }
526
527     /* Ignore SIGCHLD (force automatic removal of children) */
528     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
529         guacd_log_info("Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
530     }
531
532     /* Log listening status */
533     syslog(LOG_INFO,
534             "Listening on host %s, port %s", bound_address, bound_port);
535
536     /* Free addresses */
537     freeaddrinfo(addresses);
538
539     /* Daemon loop */
540     for (;;) {
541
542         pid_t child_pid;
543
544         /* Listen for connections */
545         if (listen(socket_fd, 5) < 0) {
546             guacd_log_error("Could not listen on socket: %s", strerror(errno));
547             return 3;
548         }
549
550         /* Accept connection */
551         client_addr_len = sizeof(client_addr);
552         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
553         if (connected_socket_fd < 0) {
554             guacd_log_error("Could not accept client connection: %s", strerror(errno));
555             return 3;
556         }
557
558         /* 
559          * Once connection is accepted, send child into background.
560          *
561          * Note that we prefer fork() over threads for connection-handling
562          * processes as they give each connection its own memory area, and
563          * isolate the main daemon and other connections from errors in any
564          * particular client plugin.
565          */
566
567         child_pid = (foreground>1)?0:fork();
568
569         /* If error, log */
570         if (child_pid == -1)
571             guacd_log_error("Error forking child process: %s", strerror(errno));
572
573         /* If child, start client, and exit when finished */
574         else if (child_pid == 0) {
575             if (xmlconfig)
576                 guacd_handle_connection_xml(connected_socket_fd, xmlconfig);
577             else
578                 guacd_handle_connection(connected_socket_fd);
579             close(connected_socket_fd);
580             return 0;
581         }
582
583         /* If parent, close reference to child's descriptor */
584         else if (close(connected_socket_fd) < 0) {
585             guacd_log_error("Error closing daemon reference to child descriptor: %s", strerror(errno));
586         }
587
588     }
589
590     /* Close socket */
591     if (close(socket_fd) < 0) {
592         guacd_log_error("Could not close socket: %s", strerror(errno));
593         return 3;
594     }
595
596     xml_deinit();
597     return 0;
598
599 }
600