2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
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/
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
15 * The Original Code is guacd.
17 * The Initial Developer of the Original Code is
19 * Portions created by the Initial Developer are Copyright (C) 2010
20 * the Initial Developer. All Rights Reserved.
23 * David PHAM-VAN <d.pham-van@ulteo.com> Ulteo SAS - http://www.ulteo.com
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.
37 * ***** END LICENSE BLOCK ***** */
44 #include <sys/types.h>
49 #include <sys/socket.h>
51 #include <netinet/in.h>
57 #include <guacamole/client.h>
58 #include <guacamole/error.h>
64 #include <libxml2/libxml/parser.h>
65 #include <libxml2/libxml/tree.h>
66 #include <libxml2/libxml/xpath.h>
67 #include <libxml2/libxml/xpathInternals.h>
70 /* check the version. This calls xmlInitParser() */
71 /* braces to stop indent getting confused */
79 xmlNodePtr xml_get_node (xmlDoc * pDoc, const char *xpathexpr) {
80 xmlChar *xpath_expr = (xmlChar *) xpathexpr;
81 xmlXPathContextPtr xpathCtx = NULL;
82 xmlXPathObjectPtr xpathObj = NULL;
83 xmlNodeSetPtr nodeSet = NULL;
85 xmlNodePtr myNode = NULL;
87 /* Create xpath evaluation context */
88 if (NULL == (xpathCtx = xmlXPathNewContext (pDoc)))
91 /* Evaluate xpath expression */
92 if (NULL == (xpathObj = xmlXPathEvalExpression (xpath_expr, xpathCtx))) {
93 xmlXPathFreeContext (xpathCtx);
97 nodeSet = xpathObj->nodesetval;
98 size = (nodeSet) ? nodeSet->nodeNr : 0;
100 myNode = nodeSet->nodeTab[0];
102 xmlXPathFreeObject (xpathObj);
103 xmlXPathFreeContext (xpathCtx);
107 char * xml_get_string (xmlDoc * pDoc, char *xpathexpr) {
108 xmlNodePtr config_node = NULL;
109 xmlChar *propval = NULL;
111 /* Find the node in question beneath the config node */
112 if (NULL == (config_node = xml_get_node (pDoc, xpathexpr)))
115 /* Find the property attached to that node; if it's not there, return 0 */
116 if (NULL == (propval = xmlNodeGetContent (config_node)))
119 /* We would like to just return propval here, but that's an xmlChar * allocated by
120 * libxml, and thus the caller can't just free() it - it would need to be xmlFree()'d.
121 * so we'll fiddle around and generate our own copy allocated with libc
123 char *value = strdup ((char *) propval);
124 xmlFree (propval); /* as xmlGetProp makes a copy of the string */
125 return value; /* caller's responsibility to free() this */
128 void guacd_handle_connection(int fd) {
131 guac_client_plugin* plugin;
132 guac_instruction* select;
133 guac_instruction* connect;
135 /* Open guac_socket */
136 guac_socket* socket = guac_socket_open(fd);
138 /* Get protocol from select instruction */
139 select = guac_protocol_expect_instruction(
140 socket, GUACD_USEC_TIMEOUT, "select");
141 if (select == NULL) {
144 guacd_log_guac_error("Error reading \"select\"");
147 guac_socket_close(socket);
151 /* Validate args to select */
152 if (select->argc != 1) {
155 guacd_log_error("Bad number of arguments to \"select\" (%i)",
159 guac_socket_close(socket);
163 guacd_log_info("Protocol \"%s\" selected", select->argv[0]);
165 /* Get plugin from protocol in select */
166 plugin = guac_client_plugin_open(select->argv[0]);
167 guac_instruction_free(select);
169 if (plugin == NULL) {
172 guacd_log_guac_error("Error loading client plugin");
175 guac_socket_close(socket);
179 /* Send args response */
180 if (guac_protocol_send_args(socket, plugin->args)
181 || guac_socket_flush(socket)) {
184 guacd_log_guac_error("Error sending \"args\"");
186 if (guac_client_plugin_close(plugin))
187 guacd_log_guac_error("Error closing client plugin");
189 guac_socket_close(socket);
193 /* Get args from connect instruction */
194 connect = guac_protocol_expect_instruction(
195 socket, GUACD_USEC_TIMEOUT, "connect");
196 if (connect == NULL) {
199 guacd_log_guac_error("Error reading \"connect\"");
201 if (guac_client_plugin_close(plugin))
202 guacd_log_guac_error("Error closing client plugin");
204 guac_socket_close(socket);
208 /* Load and init client */
209 client = guac_client_plugin_get_client(plugin, socket,
210 connect->argc, connect->argv,
211 guacd_client_log_info, guacd_client_log_error);
213 guac_instruction_free(connect);
215 if (client == NULL) {
217 guacd_log_guac_error("Error instantiating client");
219 if (guac_client_plugin_close(plugin))
220 guacd_log_guac_error("Error closing client plugin");
222 guac_socket_close(socket);
226 /* Start client threads */
227 guacd_log_info("Starting client");
228 if (guacd_client_start(client))
229 guacd_log_error("Client finished abnormally");
231 guacd_log_info("Client finished normally");
234 guac_client_free(client);
235 if (guac_client_plugin_close(plugin))
236 guacd_log_error("Error closing client plugin");
239 guac_socket_close(socket);
245 void guacd_handle_connection_xml(int fd, char* xmlconfig) {
247 guac_client* client = NULL;
248 guac_client_plugin* plugin = NULL;
249 char ** protocol_argv = NULL;
250 int protocol_argc = 0;
251 xmlDoc * pDoc = NULL;
252 char * protocol = NULL;
253 guac_socket* socket = NULL;
255 if (NULL == (socket = guac_socket_open(fd))) {
256 guacd_log_guac_error("Could not open socket");
260 if (NULL == (pDoc = xmlParseMemory (xmlconfig, strlen(xmlconfig)))) {
261 guacd_log_guac_error("Could not parse XML");
265 if (NULL == (protocol = xml_get_string(pDoc, "/params/protocol"))) {
266 guacd_log_guac_error("Could not parse XML");
270 guacd_log_info("Opening protocol '%s'", protocol);
272 /* Get plugin from protocol in select */
273 if (NULL == (plugin = guac_client_plugin_open(protocol))) {
274 guacd_log_guac_error("Error loading client plugin");
278 /* Now parse protocol strings */
280 const char * params = "/params/";
281 int lparams = strlen(params);
282 for (arg = plugin->args; *arg && **arg; arg++)
284 if (NULL == (protocol_argv = calloc(sizeof(char *), protocol_argc+1))) {
285 guacd_log_guac_error("Cannot allocate protocol arguments");
290 for (i=0; i<protocol_argc; i++) {
293 int l = strlen(plugin->args[i]);
294 char * argname = malloc(lparams+l+1);
296 guacd_log_guac_error("Error duplicating argument list");
299 strncpy(argname, params, lparams);
300 /* replace non-alpha characters by '_' for XML */
301 for (p = plugin->args[i], q = argname+lparams; *p; p++, q++)
302 *q = isalnum(*p)?*p:'_';
304 char * value = xml_get_string(pDoc, argname);
307 guacd_log_info("Argument '%s' set to '%s'", plugin->args[i], value);
308 protocol_argv[i]=value;
311 guacd_log_info("Starting protocol %s, %d arguments", protocol, protocol_argc);
313 /* Load and init client */
314 if (NULL == (client = guac_client_plugin_get_client(plugin, socket,
315 protocol_argc, protocol_argv,
316 guacd_client_log_info, guacd_client_log_error))) {
317 guacd_log_guac_error("Error instantiating client");
321 /* Start client threads */
322 guacd_log_info("Starting client");
323 if (guacd_client_start(client))
324 guacd_log_error("Client finished abnormally");
326 guacd_log_info("Client finished normally");
331 guac_client_free(client);
333 if (plugin && guac_client_plugin_close(plugin))
334 guacd_log_error("Error closing client plugin");
338 for (parg = protocol_argv ; *parg; parg++)
347 guac_socket_close(socket);
353 const char *devnull = "/dev/null";
355 /* Fork once to ensure we aren't the process group leader */
358 fprintf (stderr, "Unable to fork\n");
362 /* Exit if we are the parent */
364 _exit (0); /* parent exits */
366 /* Start a new session */
369 /* Fork again so the session group leader exits */
372 fprintf (stderr, "Unable to fork\n");
376 /* Exit if we are the parent */
378 _exit (0); /* parent exits */
380 if (chdir ("/") <0) {
381 fprintf (stderr, "Unable to chdir /\n");
385 /* Now close all FDs and reopen the 3 stdxxx to /dev/null */
386 for (i = getdtablesize () - 1; i >= 0; i--)
389 i = open (devnull, O_RDWR);
391 fprintf (stderr, "Unable to open /dev/null\n");
394 i = open (devnull, O_RDONLY);
399 i = open (devnull, O_WRONLY);
404 i = open (devnull, O_WRONLY);
413 int main(int argc, char* argv[]) {
417 struct addrinfo* addresses;
418 struct addrinfo* current_address;
419 char bound_address[1024];
423 struct addrinfo hints = {
424 .ai_family = AF_UNSPEC,
425 .ai_socktype = SOCK_STREAM,
426 .ai_protocol = IPPROTO_TCP
430 struct sockaddr_in client_addr;
431 socklen_t client_addr_len;
432 int connected_socket_fd;
435 char* listen_address = NULL; /* Default address of INADDR_ANY */
436 char* listen_port = "4822"; /* Default port */
437 char* pidfile = NULL;
440 char * xmlconfig = NULL;
447 /* Parse arguments */
448 while ((opt = getopt(argc, argv, "l:b:p:x:f")) != -1) {
450 listen_port = strdup(optarg);
452 else if (opt == 'b') {
453 listen_address = strdup(optarg);
455 else if (opt == 'f') {
458 else if (opt == 'p') {
459 pidfile = strdup(optarg);
461 else if (opt == 'x') {
462 xmlconfig = strdup (optarg);
466 fprintf(stderr, "USAGE: %s"
468 " [-b LISTENADDRESS]"
471 " [-x XMLCONFIG]\n", argv[0]);
477 /* Daemonize before we start opening sockets, as this closes FDs */
481 if (pidfile != NULL) {
482 /* Attempt to open pidfile and write PID */
483 FILE* pidf = fopen(pidfile, "w");
485 fprintf(pidf, "%d\n", getpid());
488 /* Warn on failure */
489 guacd_log_error("Could not write PID file: %s", strerror(errno));
494 /* Set up logging prefix */
495 strncpy(log_prefix, basename(argv[0]), sizeof(log_prefix));
497 /* Open log as early as we can */
498 openlog(NULL, LOG_PID, LOG_DAEMON);
500 /* Get addresses for binding */
501 if ((retval = getaddrinfo(listen_address, listen_port, &hints, &addresses))) {
502 guacd_log_error("Error parsing given address or port: %s",
503 gai_strerror(retval));
508 socket_fd = socket(AF_INET, SOCK_STREAM, 0);
510 guacd_log_error("Error opening socket: %s", strerror(errno));
514 /* Allow socket reuse */
515 if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
516 guacd_log_info("Unable to set socket options for reuse: %s", strerror(errno));
519 /* Attempt binding of each address until success */
520 current_address = addresses;
521 while (current_address != NULL) {
525 /* Resolve hostname */
526 if ((retval = getnameinfo(current_address->ai_addr,
527 current_address->ai_addrlen,
528 bound_address, sizeof(bound_address),
529 bound_port, sizeof(bound_port),
530 NI_NUMERICHOST | NI_NUMERICSERV)))
531 guacd_log_error("Unable to resolve host: %s",
532 gai_strerror(retval));
534 /* Attempt to bind socket to address */
536 current_address->ai_addr,
537 current_address->ai_addrlen) == 0) {
539 guacd_log_info("Successfully bound socket to "
540 "host %s, port %s", bound_address, bound_port);
542 /* Done if successful bind */
547 /* Otherwise log information regarding bind failure */
549 guacd_log_info("Unable to bind socket to "
550 "host %s, port %s: %s",
551 bound_address, bound_port, strerror(errno));
553 current_address = current_address->ai_next;
557 /* If unable to bind to anything, fail */
558 if (current_address == NULL) {
559 guacd_log_error("Unable to bind socket to any addresses.");
564 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
565 guacd_log_info("Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
568 /* Ignore SIGCHLD (force automatic removal of children) */
569 if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
570 guacd_log_info("Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
573 /* Log listening status */
575 "Listening on host %s, port %s", bound_address, bound_port);
578 freeaddrinfo(addresses);
585 /* Listen for connections */
586 if (listen(socket_fd, 5) < 0) {
587 guacd_log_error("Could not listen on socket: %s", strerror(errno));
591 /* Accept connection */
592 client_addr_len = sizeof(client_addr);
593 connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
594 if (connected_socket_fd < 0) {
595 guacd_log_error("Could not accept client connection: %s", strerror(errno));
600 * Once connection is accepted, send child into background.
602 * Note that we prefer fork() over threads for connection-handling
603 * processes as they give each connection its own memory area, and
604 * isolate the main daemon and other connections from errors in any
605 * particular client plugin.
608 child_pid = (foreground>1)?0:fork();
612 guacd_log_error("Error forking child process: %s", strerror(errno));
614 /* If child, start client, and exit when finished */
615 else if (child_pid == 0) {
617 guacd_handle_connection_xml(connected_socket_fd, xmlconfig);
619 guacd_handle_connection(connected_socket_fd);
620 close(connected_socket_fd);
624 /* If parent, close reference to child's descriptor */
625 else if (close(connected_socket_fd) < 0) {
626 guacd_log_error("Error closing daemon reference to child descriptor: %s", strerror(errno));
632 if (close(socket_fd) < 0) {
633 guacd_log_error("Could not close socket: %s", strerror(errno));