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>
47 #include <sys/socket.h>
49 #include <netinet/in.h>
55 #include <guacamole/client.h>
56 #include <guacamole/error.h>
62 #include <libxml2/libxml/parser.h>
63 #include <libxml2/libxml/tree.h>
64 #include <libxml2/libxml/xpath.h>
65 #include <libxml2/libxml/xpathInternals.h>
68 /* check the version. This calls xmlInitParser() */
69 /* braces to stop indent getting confused */
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;
83 xmlNodePtr myNode = NULL;
85 /* Create xpath evaluation context */
86 if (NULL == (xpathCtx = xmlXPathNewContext (pDoc)))
89 /* Evaluate xpath expression */
90 if (NULL == (xpathObj = xmlXPathEvalExpression (xpath_expr, xpathCtx))) {
91 xmlXPathFreeContext (xpathCtx);
95 nodeSet = xpathObj->nodesetval;
96 size = (nodeSet) ? nodeSet->nodeNr : 0;
98 myNode = nodeSet->nodeTab[0];
100 xmlXPathFreeObject (xpathObj);
101 xmlXPathFreeContext (xpathCtx);
105 char * xml_get_string (xmlDoc * pDoc, char *xpathexpr) {
106 xmlNodePtr config_node = NULL;
107 xmlChar *propval = NULL;
109 /* Find the node in question beneath the config node */
110 if (NULL == (config_node = xml_get_node (pDoc, xpathexpr)))
113 /* Find the property attached to that node; if it's not there, return 0 */
114 if (NULL == (propval = xmlNodeGetContent (config_node)))
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
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 */
126 void guacd_handle_connection(int fd) {
129 guac_client_plugin* plugin;
130 guac_instruction* select;
131 guac_instruction* connect;
133 /* Open guac_socket */
134 guac_socket* socket = guac_socket_open(fd);
136 /* Get protocol from select instruction */
137 select = guac_protocol_expect_instruction(
138 socket, GUACD_USEC_TIMEOUT, "select");
139 if (select == NULL) {
142 guacd_log_guac_error("Error reading \"select\"");
145 guac_socket_close(socket);
149 /* Validate args to select */
150 if (select->argc != 1) {
153 guacd_log_error("Bad number of arguments to \"select\" (%i)",
157 guac_socket_close(socket);
161 guacd_log_info("Protocol \"%s\" selected", select->argv[0]);
163 /* Get plugin from protocol in select */
164 plugin = guac_client_plugin_open(select->argv[0]);
165 guac_instruction_free(select);
167 if (plugin == NULL) {
170 guacd_log_guac_error("Error loading client plugin");
173 guac_socket_close(socket);
177 /* Send args response */
178 if (guac_protocol_send_args(socket, plugin->args)
179 || guac_socket_flush(socket)) {
182 guacd_log_guac_error("Error sending \"args\"");
184 if (guac_client_plugin_close(plugin))
185 guacd_log_guac_error("Error closing client plugin");
187 guac_socket_close(socket);
191 /* Get args from connect instruction */
192 connect = guac_protocol_expect_instruction(
193 socket, GUACD_USEC_TIMEOUT, "connect");
194 if (connect == NULL) {
197 guacd_log_guac_error("Error reading \"connect\"");
199 if (guac_client_plugin_close(plugin))
200 guacd_log_guac_error("Error closing client plugin");
202 guac_socket_close(socket);
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);
211 guac_instruction_free(connect);
213 if (client == NULL) {
215 guacd_log_guac_error("Error instantiating client");
217 if (guac_client_plugin_close(plugin))
218 guacd_log_guac_error("Error closing client plugin");
220 guac_socket_close(socket);
224 /* Start client threads */
225 guacd_log_info("Starting client");
226 if (guacd_client_start(client))
227 guacd_log_error("Client finished abnormally");
229 guacd_log_info("Client finished normally");
232 guac_client_free(client);
233 if (guac_client_plugin_close(plugin))
234 guacd_log_error("Error closing client plugin");
237 guac_socket_close(socket);
243 void guacd_handle_connection_xml(int fd, char* xmlconfig) {
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;
253 if (NULL == (socket = guac_socket_open(fd))) {
254 guacd_log_guac_error("Could not open socket");
258 if (NULL == (pDoc = xmlParseMemory (xmlconfig, strlen(xmlconfig)))) {
259 guacd_log_guac_error("Could not parse XML");
263 if (NULL == (protocol = xml_get_string(pDoc, "/params/protocol"))) {
264 guacd_log_guac_error("Could not parse XML");
268 guacd_log_info("Opening protocol '%s'", protocol);
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");
276 /* Now parse protocol strings */
278 const char * params = "/params/";
279 int lparams = strlen(params);
280 for (arg = plugin->args; *arg && **arg; arg++)
282 if (NULL == (protocol_argv = calloc(sizeof(char *), protocol_argc+1))) {
283 guacd_log_guac_error("Cannot allocate protocol arguments");
288 for (i=0; i<protocol_argc; i++) {
291 int l = strlen(plugin->args[i]);
292 char * argname = malloc(lparams+l+1);
294 guacd_log_guac_error("Error duplicating argument list");
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:'_';
302 char * value = xml_get_string(pDoc, argname);
305 guacd_log_info("Argument '%s' set to '%s'", plugin->args[i], value);
306 protocol_argv[i]=value;
309 guacd_log_info("Starting protocol %s, %d arguments", protocol, protocol_argc);
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");
319 /* Start client threads */
320 guacd_log_info("Starting client");
321 if (guacd_client_start(client))
322 guacd_log_error("Client finished abnormally");
324 guacd_log_info("Client finished normally");
329 guac_client_free(client);
331 if (plugin && guac_client_plugin_close(plugin))
332 guacd_log_error("Error closing client plugin");
336 for (parg = protocol_argv ; *parg; parg++)
345 guac_socket_close(socket);
350 int main(int argc, char* argv[]) {
354 struct addrinfo* addresses;
355 struct addrinfo* current_address;
356 char bound_address[1024];
360 struct addrinfo hints = {
361 .ai_family = AF_UNSPEC,
362 .ai_socktype = SOCK_STREAM,
363 .ai_protocol = IPPROTO_TCP
367 struct sockaddr_in client_addr;
368 socklen_t client_addr_len;
369 int connected_socket_fd;
372 char* listen_address = NULL; /* Default address of INADDR_ANY */
373 char* listen_port = "4822"; /* Default port */
374 char* pidfile = NULL;
377 char * xmlconfig = NULL;
387 /* Parse arguments */
388 while ((opt = getopt(argc, argv, "l:b:p:x:f")) != -1) {
390 listen_port = strdup(optarg);
392 else if (opt == 'b') {
393 listen_address = strdup(optarg);
395 else if (opt == 'f') {
398 else if (opt == 'p') {
399 pidfile = strdup(optarg);
401 else if (opt == 'x') {
402 xmlconfig = strdup (optarg);
406 fprintf(stderr, "USAGE: %s"
408 " [-b LISTENADDRESS]"
411 " [-x XMLCONFIG]\n", argv[0]);
417 /* Set up logging prefix */
418 strncpy(log_prefix, basename(argv[0]), sizeof(log_prefix));
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));
429 socket_fd = socket(AF_INET, SOCK_STREAM, 0);
431 guacd_log_error("Error opening socket: %s", strerror(errno));
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));
440 /* Attempt binding of each address until success */
441 current_address = addresses;
442 while (current_address != NULL) {
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));
455 /* Attempt to bind socket to address */
457 current_address->ai_addr,
458 current_address->ai_addrlen) == 0) {
460 guacd_log_info("Successfully bound socket to "
461 "host %s, port %s", bound_address, bound_port);
463 /* Done if successful bind */
468 /* Otherwise log information regarding bind failure */
470 guacd_log_info("Unable to bind socket to "
471 "host %s, port %s: %s",
472 bound_address, bound_port, strerror(errno));
474 current_address = current_address->ai_next;
478 /* If unable to bind to anything, fail */
479 if (current_address == NULL) {
480 guacd_log_error("Unable to bind socket to any addresses.");
486 /* Fork into background */
490 if (daemon_pid == -1) {
491 guacd_log_error("Error forking daemon process: %s", strerror(errno));
495 /* If parent, write PID file and exit */
496 else if (daemon_pid != 0) {
498 if (pidfile != NULL) {
500 /* Attempt to open pidfile and write PID */
501 FILE* pidf = fopen(pidfile, "w");
503 fprintf(pidf, "%d\n", daemon_pid);
507 /* Warn on failure */
509 guacd_log_error("Could not write PID file: %s", strerror(errno));
520 openlog(NULL, LOG_PID, LOG_DAEMON);
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.");
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.");
532 /* Log listening status */
534 "Listening on host %s, port %s", bound_address, bound_port);
537 freeaddrinfo(addresses);
544 /* Listen for connections */
545 if (listen(socket_fd, 5) < 0) {
546 guacd_log_error("Could not listen on socket: %s", strerror(errno));
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));
559 * Once connection is accepted, send child into background.
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.
567 child_pid = (foreground>1)?0:fork();
571 guacd_log_error("Error forking child process: %s", strerror(errno));
573 /* If child, start client, and exit when finished */
574 else if (child_pid == 0) {
576 guacd_handle_connection_xml(connected_socket_fd, xmlconfig);
578 guacd_handle_connection(connected_socket_fd);
579 close(connected_socket_fd);
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));
591 if (close(socket_fd) < 0) {
592 guacd_log_error("Could not close socket: %s", strerror(errno));