1 /* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
14 * The Original Code is guacd.
16 * The Initial Developer of the Original Code is
18 * Portions created by the Initial Developer are Copyright (C) 2010
19 * the Initial Developer. All Rights Reserved.
22 * David PHAM-VAN <d.pham-van@ulteo.com> Ulteo SAS - http://www.ulteo.com
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.
36 * ***** END LICENSE BLOCK ***** */
43 #include <sys/types.h>
48 #include <sys/socket.h>
50 #include <netinet/in.h>
56 #include <guacamole/client.h>
57 #include <guacamole/error.h>
63 #include <libxml2/libxml/parser.h>
64 #include <libxml2/libxml/tree.h>
65 #include <libxml2/libxml/xpath.h>
66 #include <libxml2/libxml/xpathInternals.h>
69 /* check the version. This calls xmlInitParser() */
70 /* braces to stop indent getting confused */
78 xmlNodePtr xml_get_node (xmlDoc * pDoc, const char *xpathexpr) {
79 xmlChar *xpath_expr = (xmlChar *) xpathexpr;
80 xmlXPathContextPtr xpathCtx = NULL;
81 xmlXPathObjectPtr xpathObj = NULL;
82 xmlNodeSetPtr nodeSet = NULL;
84 xmlNodePtr myNode = NULL;
86 /* Create xpath evaluation context */
87 if (NULL == (xpathCtx = xmlXPathNewContext (pDoc)))
90 /* Evaluate xpath expression */
91 if (NULL == (xpathObj = xmlXPathEvalExpression (xpath_expr, xpathCtx))) {
92 xmlXPathFreeContext (xpathCtx);
96 nodeSet = xpathObj->nodesetval;
97 size = (nodeSet) ? nodeSet->nodeNr : 0;
99 myNode = nodeSet->nodeTab[0];
101 xmlXPathFreeObject (xpathObj);
102 xmlXPathFreeContext (xpathCtx);
106 char * xml_get_string (xmlDoc * pDoc, char *xpathexpr) {
107 xmlNodePtr config_node = NULL;
108 xmlChar *propval = NULL;
110 /* Find the node in question beneath the config node */
111 if (NULL == (config_node = xml_get_node (pDoc, xpathexpr)))
114 /* Find the property attached to that node; if it's not there, return 0 */
115 if (NULL == (propval = xmlNodeGetContent (config_node)))
118 /* We would like to just return propval here, but that's an xmlChar * allocated by
119 * libxml, and thus the caller can't just free() it - it would need to be xmlFree()'d.
120 * so we'll fiddle around and generate our own copy allocated with libc
122 char *value = strdup ((char *) propval);
123 xmlFree (propval); /* as xmlGetProp makes a copy of the string */
124 return value; /* caller's responsibility to free() this */
127 void guacd_handle_connection(int fd) {
130 guac_client_plugin* plugin;
131 guac_instruction* select;
132 guac_instruction* connect;
134 /* Open guac_socket */
135 guac_socket* socket = guac_socket_open(fd);
137 /* Get protocol from select instruction */
138 select = guac_protocol_expect_instruction(
139 socket, GUACD_USEC_TIMEOUT, "select");
140 if (select == NULL) {
143 guacd_log_guac_error("Error reading \"select\"");
146 guac_socket_close(socket);
150 /* Validate args to select */
151 if (select->argc != 1) {
154 guacd_log_error("Bad number of arguments to \"select\" (%i)",
158 guac_socket_close(socket);
162 guacd_log_info("Protocol \"%s\" selected", select->argv[0]);
164 /* Get plugin from protocol in select */
165 plugin = guac_client_plugin_open(select->argv[0]);
166 guac_instruction_free(select);
168 if (plugin == NULL) {
171 guacd_log_guac_error("Error loading client plugin");
174 guac_socket_close(socket);
178 /* Send args response */
179 if (guac_protocol_send_args(socket, plugin->args)
180 || guac_socket_flush(socket)) {
183 guacd_log_guac_error("Error sending \"args\"");
185 if (guac_client_plugin_close(plugin))
186 guacd_log_guac_error("Error closing client plugin");
188 guac_socket_close(socket);
192 /* Get args from connect instruction */
193 connect = guac_protocol_expect_instruction(
194 socket, GUACD_USEC_TIMEOUT, "connect");
195 if (connect == NULL) {
198 guacd_log_guac_error("Error reading \"connect\"");
200 if (guac_client_plugin_close(plugin))
201 guacd_log_guac_error("Error closing client plugin");
203 guac_socket_close(socket);
207 /* Load and init client */
208 client = guac_client_plugin_get_client(plugin, socket,
209 connect->argc, connect->argv,
210 guacd_client_log_info, guacd_client_log_error);
212 guac_instruction_free(connect);
214 if (client == NULL) {
216 guacd_log_guac_error("Error instantiating client");
218 if (guac_client_plugin_close(plugin))
219 guacd_log_guac_error("Error closing client plugin");
221 guac_socket_close(socket);
225 /* Start client threads */
226 guacd_log_info("Starting client");
227 if (guacd_client_start(client))
228 guacd_log_error("Client finished abnormally");
230 guacd_log_info("Client finished normally");
233 guac_client_free(client);
234 if (guac_client_plugin_close(plugin))
235 guacd_log_error("Error closing client plugin");
238 guac_socket_close(socket);
244 void guacd_handle_connection_xml(int fd, char* xmlconfig) {
246 guac_client* client = NULL;
247 guac_client_plugin* plugin = NULL;
248 char ** protocol_argv = NULL;
249 int protocol_argc = 0;
250 xmlDoc * pDoc = NULL;
251 char * protocol = NULL;
252 guac_socket* socket = NULL;
254 if (NULL == (socket = guac_socket_open(fd))) {
255 guacd_log_guac_error("Could not open socket");
259 if (NULL == (pDoc = xmlParseMemory (xmlconfig, strlen(xmlconfig)))) {
260 guacd_log_guac_error("Could not parse XML");
264 if (NULL == (protocol = xml_get_string(pDoc, "/params/protocol"))) {
265 guacd_log_guac_error("Could not find protocol element in XML");
269 guacd_log_info("Opening protocol '%s'", protocol);
271 /* Get plugin from protocol in select */
272 if (NULL == (plugin = guac_client_plugin_open(protocol))) {
273 guacd_log_guac_error("Error loading client plugin");
277 /* Now parse protocol strings */
279 const char * params = "/params/";
280 int lparams = strlen(params);
281 for (arg = plugin->args; *arg && **arg; arg++)
283 if (NULL == (protocol_argv = calloc(sizeof(char *), protocol_argc+1))) {
284 guacd_log_guac_error("Cannot allocate protocol arguments");
289 for (i=0; i<protocol_argc; i++) {
292 int l = strlen(plugin->args[i]);
293 char * argname = malloc(lparams+l+1);
295 guacd_log_guac_error("Error duplicating argument list");
298 strncpy(argname, params, lparams);
299 /* replace non-alpha characters by '_' for XML */
300 for (p = plugin->args[i], q = argname+lparams; *p; p++, q++)
301 *q = isalnum(*p)?*p:'_';
303 char * value = xml_get_string(pDoc, argname);
306 guacd_log_info("Argument '%s' set to '%s'", plugin->args[i], value);
307 protocol_argv[i]=value;
310 guacd_log_info("Starting protocol %s, %d arguments", protocol, protocol_argc);
312 /* Load and init client */
313 if (NULL == (client = guac_client_plugin_get_client(plugin, socket,
314 protocol_argc, protocol_argv,
315 guacd_client_log_info, guacd_client_log_error))) {
316 guacd_log_guac_error("Error instantiating client");
320 /* Start client threads */
321 guacd_log_info("Starting client");
322 if (guacd_client_start(client))
323 guacd_log_error("Client finished abnormally");
325 guacd_log_info("Client finished normally");
330 guac_client_free(client);
332 if (plugin && guac_client_plugin_close(plugin))
333 guacd_log_error("Error closing client plugin");
337 for (parg = protocol_argv ; *parg; parg++)
346 guac_socket_close(socket);
352 const char *devnull = "/dev/null";
354 /* Fork once to ensure we aren't the process group leader */
357 fprintf (stderr, "Unable to fork\n");
361 /* Exit if we are the parent */
363 _exit (0); /* parent exits */
365 /* Start a new session */
368 /* Fork again so the session group leader exits */
371 fprintf (stderr, "Unable to fork\n");
375 /* Exit if we are the parent */
377 _exit (0); /* parent exits */
379 if (chdir ("/") <0) {
380 fprintf (stderr, "Unable to chdir /\n");
384 /* Now close all FDs and reopen the 3 stdxxx to /dev/null */
385 for (i = getdtablesize () - 1; i >= 0; i--)
388 i = open (devnull, O_RDWR);
390 fprintf (stderr, "Unable to open /dev/null\n");
393 i = open (devnull, O_RDONLY);
398 i = open (devnull, O_WRONLY);
403 i = open (devnull, O_WRONLY);
412 int main(int argc, char* argv[]) {
416 struct addrinfo* addresses;
417 struct addrinfo* current_address;
418 char bound_address[1024];
422 struct addrinfo hints = {
423 .ai_family = AF_UNSPEC,
424 .ai_socktype = SOCK_STREAM,
425 .ai_protocol = IPPROTO_TCP
429 struct sockaddr_in client_addr;
430 socklen_t client_addr_len;
431 int connected_socket_fd;
434 char* listen_address = NULL; /* Default address of INADDR_ANY */
435 char* listen_port = "4822"; /* Default port */
436 char* pidfile = NULL;
440 char * xmlconfig = NULL;
447 /* Parse arguments */
448 while ((opt = getopt(argc, argv, "l:b:p:x:s: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 == 's') {
462 suppliedfd = atoi(optarg);
465 else if (opt == 'x') {
466 xmlconfig = strdup (optarg);
470 fprintf(stderr, "USAGE: %s"
472 " [-b LISTENADDRESS]"
476 " [-x XMLCONFIG]\n", argv[0]);
482 /* Daemonize before we start opening sockets, as this closes FDs */
486 if (pidfile != NULL) {
487 /* Attempt to open pidfile and write PID */
488 FILE* pidf = fopen(pidfile, "w");
490 fprintf(pidf, "%d\n", getpid());
493 /* Warn on failure */
494 guacd_log_error("Could not write PID file: %s", strerror(errno));
499 /* Set up logging prefix */
500 strncpy(log_prefix, basename(argv[0]), sizeof(log_prefix));
502 /* Open log as early as we can */
503 openlog(NULL, LOG_PID, LOG_DAEMON);
506 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
507 guacd_log_info("Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
510 /* Ignore SIGCHLD (force automatic removal of children) */
511 if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
512 guacd_log_info("Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
515 /* Handle the case where we have a supplied fd */
516 if (suppliedfd != -1) {
518 guacd_handle_connection_xml(suppliedfd, xmlconfig);
520 guacd_handle_connection(suppliedfd);
524 /* Get addresses for binding */
525 if ((retval = getaddrinfo(listen_address, listen_port, &hints, &addresses))) {
526 guacd_log_error("Error parsing given address or port: %s",
527 gai_strerror(retval));
532 socket_fd = socket(AF_INET, SOCK_STREAM, 0);
534 guacd_log_error("Error opening socket: %s", strerror(errno));
538 /* Allow socket reuse */
539 if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
540 guacd_log_info("Unable to set socket options for reuse: %s", strerror(errno));
543 /* Attempt binding of each address until success */
544 current_address = addresses;
545 while (current_address != NULL) {
549 /* Resolve hostname */
550 if ((retval = getnameinfo(current_address->ai_addr,
551 current_address->ai_addrlen,
552 bound_address, sizeof(bound_address),
553 bound_port, sizeof(bound_port),
554 NI_NUMERICHOST | NI_NUMERICSERV)))
555 guacd_log_error("Unable to resolve host: %s",
556 gai_strerror(retval));
558 /* Attempt to bind socket to address */
560 current_address->ai_addr,
561 current_address->ai_addrlen) == 0) {
563 guacd_log_info("Successfully bound socket to "
564 "host %s, port %s", bound_address, bound_port);
566 /* Done if successful bind */
571 /* Otherwise log information regarding bind failure */
573 guacd_log_info("Unable to bind socket to "
574 "host %s, port %s: %s",
575 bound_address, bound_port, strerror(errno));
577 current_address = current_address->ai_next;
581 /* If unable to bind to anything, fail */
582 if (current_address == NULL) {
583 guacd_log_error("Unable to bind socket to any addresses.");
587 /* Log listening status */
589 "Listening on host %s, port %s", bound_address, bound_port);
592 freeaddrinfo(addresses);
599 /* Listen for connections */
600 if (listen(socket_fd, 5) < 0) {
601 guacd_log_error("Could not listen on socket: %s", strerror(errno));
605 /* Accept connection */
606 client_addr_len = sizeof(client_addr);
607 connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
608 if (connected_socket_fd < 0) {
609 guacd_log_error("Could not accept client connection: %s", strerror(errno));
614 * Once connection is accepted, send child into background.
616 * Note that we prefer fork() over threads for connection-handling
617 * processes as they give each connection its own memory area, and
618 * isolate the main daemon and other connections from errors in any
619 * particular client plugin.
622 child_pid = (foreground>1)?0:fork();
626 guacd_log_error("Error forking child process: %s", strerror(errno));
628 /* If child, start client, and exit when finished */
629 else if (child_pid == 0) {
631 guacd_handle_connection_xml(connected_socket_fd, xmlconfig);
633 guacd_handle_connection(connected_socket_fd);
634 close(connected_socket_fd);
638 /* If parent, close reference to child's descriptor */
639 else if (close(connected_socket_fd) < 0) {
640 guacd_log_error("Error closing daemon reference to child descriptor: %s", strerror(errno));
646 if (close(socket_fd) < 0) {
647 guacd_log_error("Could not close socket: %s", strerror(errno));