hal.c revision b86d567b
1/*
2 * Copyright © 2007 Daniel Stone
3 * Copyright © 2007 Red Hat, Inc.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *
24 * Author: Daniel Stone <daniel@fooishbar.org>
25 */
26
27#ifdef HAVE_DIX_CONFIG_H
28#include <dix-config.h>
29#endif
30
31#include <dbus/dbus.h>
32#include <hal/libhal.h>
33#include <string.h>
34#include <sys/select.h>
35
36#include "input.h"
37#include "inputstr.h"
38#include "hotplug.h"
39#include "config-backends.h"
40#include "os.h"
41
42
43#define LIBHAL_PROP_KEY "input.x11_options."
44#define LIBHAL_XKB_PROP_KEY "input.xkb."
45
46
47struct config_hal_info {
48    DBusConnection *system_bus;
49    LibHalContext *hal_ctx;
50};
51
52/* Used for special handling of xkb options. */
53struct xkb_options {
54    char* layout;
55    char* model;
56    char* rules;
57    char* variant;
58    char* options;
59};
60
61
62static void
63remove_device(DeviceIntPtr dev)
64{
65    /* this only gets called for devices that have already been added */
66    LogMessage(X_INFO, "config/hal: removing device %s\n", dev->name);
67
68    /* Call PIE here so we don't try to dereference a device that's
69     * already been removed. */
70    OsBlockSignals();
71    ProcessInputEvents();
72    DeleteInputDeviceRequest(dev);
73    OsReleaseSignals();
74}
75
76static void
77device_removed(LibHalContext *ctx, const char *udi)
78{
79    DeviceIntPtr dev, next;
80    char *value;
81
82    value = xalloc(strlen(udi) + 5); /* "hal:" + NULL */
83    if (!value)
84        return;
85    sprintf(value, "hal:%s", udi);
86
87    for (dev = inputInfo.devices; dev; dev = next) {
88	next = dev->next;
89        if (dev->config_info && strcmp(dev->config_info, value) == 0)
90            remove_device(dev);
91    }
92    for (dev = inputInfo.off_devices; dev; dev = next) {
93	next = dev->next;
94        if (dev->config_info && strcmp(dev->config_info, value) == 0)
95            remove_device(dev);
96    }
97
98    xfree(value);
99}
100
101static void
102add_option(InputOption **options, const char *key, const char *value)
103{
104    if (!value || *value == '\0')
105        return;
106
107    for (; *options; options = &(*options)->next)
108        ;
109    *options = xcalloc(sizeof(**options), 1);
110    if (!*options) /* Yeesh. */
111        return;
112    (*options)->key = xstrdup(key);
113    (*options)->value = xstrdup(value);
114    (*options)->next = NULL;
115}
116
117static char *
118get_prop_string(LibHalContext *hal_ctx, const char *udi, const char *name)
119{
120    char *prop, *ret;
121
122    prop = libhal_device_get_property_string(hal_ctx, udi, name, NULL);
123    LogMessageVerb(X_INFO, 10, "config/hal: getting %s on %s returned %s\n", name, udi, prop ? prop : "(null)");
124    if (prop) {
125        ret = xstrdup(prop);
126        libhal_free_string(prop);
127    }
128    else {
129        return NULL;
130    }
131
132    return ret;
133}
134
135static char *
136get_prop_string_array(LibHalContext *hal_ctx, const char *udi, const char *prop)
137{
138    char **props, *ret, *str;
139    int i, len = 0;
140
141    props = libhal_device_get_property_strlist(hal_ctx, udi, prop, NULL);
142    if (props) {
143        for (i = 0; props[i]; i++)
144            len += strlen(props[i]);
145
146        ret = xcalloc(sizeof(char), len + i); /* i - 1 commas, 1 NULL */
147        if (!ret) {
148            libhal_free_string_array(props);
149            return NULL;
150        }
151
152        str = ret;
153        for (i = 0; props[i]; i++) {
154            strcpy(str, props[i]);
155            str += strlen(props[i]);
156            *str++ = ',';
157        }
158        *(str-1) = '\0';
159
160        libhal_free_string_array(props);
161    }
162    else {
163        return NULL;
164    }
165
166    return ret;
167}
168
169static BOOL
170device_is_duplicate(char *config_info)
171{
172    DeviceIntPtr dev;
173
174    for (dev = inputInfo.devices; dev; dev = dev->next)
175    {
176        if (dev->config_info && (strcmp(dev->config_info, config_info) == 0))
177            return TRUE;
178    }
179
180    for (dev = inputInfo.off_devices; dev; dev = dev->next)
181    {
182        if (dev->config_info && (strcmp(dev->config_info, config_info) == 0))
183            return TRUE;
184    }
185
186    return FALSE;
187}
188
189static void
190device_added(LibHalContext *hal_ctx, const char *udi)
191{
192    char *path = NULL, *driver = NULL, *name = NULL, *config_info = NULL;
193    InputOption *options = NULL, *tmpo = NULL;
194    DeviceIntPtr dev = NULL;
195    DBusError error;
196    struct xkb_options xkb_opts = {0};
197    int rc;
198
199    LibHalPropertySet *set = NULL;
200	LibHalPropertySetIterator set_iter;
201    char *psi_key = NULL, *tmp_val;
202
203
204    dbus_error_init(&error);
205
206    driver = get_prop_string(hal_ctx, udi, "input.x11_driver");
207    if (!driver){
208        /* verbose, don't tell the user unless they _want_ to see it */
209        LogMessageVerb(X_INFO,7,"config/hal: no driver specified for device %s\n", udi);
210        goto unwind;
211    }
212
213    path = get_prop_string(hal_ctx, udi, "input.device");
214    if (!path) {
215        LogMessage(X_WARNING,"config/hal: no driver or path specified for %s\n", udi);
216        goto unwind;
217    }
218
219    name = get_prop_string(hal_ctx, udi, "info.product");
220    if (!name)
221        name = xstrdup("(unnamed)");
222
223    options = xcalloc(sizeof(*options), 1);
224    if (!options){
225        LogMessage(X_ERROR, "config/hal: couldn't allocate space for input options!\n");
226        goto unwind;
227    }
228
229    options->key = xstrdup("_source");
230    options->value = xstrdup("server/hal");
231    if (!options->key || !options->value) {
232        LogMessage(X_ERROR, "config/hal: couldn't allocate first key/value pair\n");
233        goto unwind;
234    }
235
236    /* most drivers use device.. not path. evdev uses both however, but the
237     * path version isn't documented apparently. support both for now. */
238    add_option(&options, "path", path);
239    add_option(&options, "device", path);
240
241    add_option(&options, "driver", driver);
242    add_option(&options, "name", name);
243
244    config_info = xalloc(strlen(udi) + 5); /* "hal:" and NULL */
245    if (!config_info) {
246        LogMessage(X_ERROR, "config/hal: couldn't allocate name\n");
247        goto unwind;
248    }
249    sprintf(config_info, "hal:%s", udi);
250
251    /* Check for duplicate devices */
252    if (device_is_duplicate(config_info))
253    {
254        LogMessage(X_WARNING, "config/hal: device %s already added. Ignoring.\n", name);
255        goto unwind;
256    }
257
258    /* ok, grab options from hal.. iterate through all properties
259    * and lets see if any of them are options that we can add */
260    set = libhal_device_get_all_properties(hal_ctx, udi, &error);
261
262    if (!set) {
263        LogMessage(X_ERROR, "config/hal: couldn't get property list for %s: %s (%s)\n",
264               udi, error.name, error.message);
265        goto unwind;
266    }
267
268    libhal_psi_init(&set_iter,set);
269    while (libhal_psi_has_more(&set_iter)) {
270        /* we are looking for supported keys.. extract and add to options */
271        psi_key = libhal_psi_get_key(&set_iter);
272
273        if (psi_key){
274
275            /* normal options first (input.x11_options.<propname>) */
276            if (!strncasecmp(psi_key, LIBHAL_PROP_KEY, sizeof(LIBHAL_PROP_KEY)-1)){
277                char* tmp;
278
279                /* only support strings for all values */
280                tmp_val = get_prop_string(hal_ctx, udi, psi_key);
281
282                if (tmp_val){
283
284                    /* xkb needs special handling. HAL specs include
285                     * input.xkb.xyz options, but the x11-input.fdi specifies
286                     * input.x11_options.Xkbxyz options. By default, we use
287                     * the former, unless the specific X11 ones are specified.
288                     * Since we can't predict the order in which the keys
289                     * arrive, we need to store them.
290                     */
291                    if ((tmp = strcasestr(psi_key, "xkb")) && strlen(tmp) >= 4)
292                    {
293                        if (!strcasecmp(&tmp[3], "layout"))
294                        {
295                            if (xkb_opts.layout)
296                                xfree(xkb_opts.layout);
297                            xkb_opts.layout = strdup(tmp_val);
298                        } else if (!strcasecmp(&tmp[3], "model"))
299                        {
300                            if (xkb_opts.model)
301                                xfree(xkb_opts.model);
302                            xkb_opts.model = strdup(tmp_val);
303                        } else if (!strcasecmp(&tmp[3], "rules"))
304                        {
305                            if (xkb_opts.rules)
306                                xfree(xkb_opts.rules);
307                            xkb_opts.rules = strdup(tmp_val);
308                        } else if (!strcasecmp(&tmp[3], "variant"))
309                        {
310                            if (xkb_opts.variant)
311                                xfree(xkb_opts.variant);
312                            xkb_opts.variant = strdup(tmp_val);
313                        } else if (!strcasecmp(&tmp[3], "options"))
314                        {
315                            if (xkb_opts.options)
316                                xfree(xkb_opts.options);
317                            xkb_opts.options = strdup(tmp_val);
318                        }
319                    } else
320                    {
321                        /* all others */
322                        add_option(&options, psi_key + sizeof(LIBHAL_PROP_KEY)-1, tmp_val);
323                        xfree(tmp_val);
324                    }
325                } else
326                {
327                    /* server 1.4 had xkb_options as strlist. */
328                    if ((tmp = strcasestr(psi_key, "xkb")) &&
329                        (strlen(tmp) >= 4) &&
330                        (!strcasecmp(&tmp[3], "options")) &&
331                        (tmp_val = get_prop_string_array(hal_ctx, udi, psi_key)))
332                    {
333                        if (xkb_opts.options)
334                            xfree(xkb_opts.options);
335                        xkb_opts.options = strdup(tmp_val);
336                    }
337                }
338            } else if (!strncasecmp(psi_key, LIBHAL_XKB_PROP_KEY, sizeof(LIBHAL_XKB_PROP_KEY)-1)){
339                char* tmp;
340
341                /* only support strings for all values */
342                tmp_val = get_prop_string(hal_ctx, udi, psi_key);
343
344                if (tmp_val && strlen(psi_key) >= sizeof(LIBHAL_XKB_PROP_KEY)) {
345
346                    tmp = &psi_key[sizeof(LIBHAL_XKB_PROP_KEY) - 1];
347
348                    if (!strcasecmp(tmp, "layout"))
349                    {
350                        if (!xkb_opts.layout)
351                            xkb_opts.layout = strdup(tmp_val);
352                    } else if (!strcasecmp(tmp, "rules"))
353                    {
354                        if (!xkb_opts.rules)
355                            xkb_opts.rules = strdup(tmp_val);
356                    } else if (!strcasecmp(tmp, "variant"))
357                    {
358                        if (!xkb_opts.variant)
359                            xkb_opts.variant = strdup(tmp_val);
360                    } else if (!strcasecmp(tmp, "model"))
361                    {
362                        if (!xkb_opts.model)
363                            xkb_opts.model = strdup(tmp_val);
364                    } else if (!strcasecmp(tmp, "options"))
365                    {
366                        if (!xkb_opts.options)
367                            xkb_opts.options = strdup(tmp_val);
368                    }
369                    xfree(tmp_val);
370                } else
371                {
372                    /* server 1.4 had xkb options as strlist */
373                    tmp_val = get_prop_string_array(hal_ctx, udi, psi_key);
374                    if (tmp_val && strlen(psi_key) >= sizeof(LIBHAL_XKB_PROP_KEY))
375                    {
376                        tmp = &psi_key[sizeof(LIBHAL_XKB_PROP_KEY) - 1];
377                        if (!strcasecmp(tmp, ".options") && (!xkb_opts.options))
378                            xkb_opts.options = strdup(tmp_val);
379                    }
380                }
381            }
382        }
383
384        /* psi_key doesn't need to be freed */
385        libhal_psi_next(&set_iter);
386    }
387
388
389    /* Now add xkb options */
390    if (xkb_opts.layout)
391        add_option(&options, "xkb_layout", xkb_opts.layout);
392    if (xkb_opts.rules)
393        add_option(&options, "xkb_rules", xkb_opts.rules);
394    if (xkb_opts.variant)
395        add_option(&options, "xkb_variant", xkb_opts.variant);
396    if (xkb_opts.model)
397        add_option(&options, "xkb_model", xkb_opts.model);
398    if (xkb_opts.options)
399        add_option(&options, "xkb_options", xkb_opts.options);
400
401    /* this isn't an error, but how else do you output something that the user can see? */
402    LogMessage(X_INFO, "config/hal: Adding input device %s\n", name);
403    if ((rc = NewInputDeviceRequest(options, &dev)) != Success) {
404        LogMessage(X_ERROR, "config/hal: NewInputDeviceRequest failed (%d)\n", rc);
405        dev = NULL;
406        goto unwind;
407    }
408
409    for (; dev; dev = dev->next){
410        if (dev->config_info)
411            xfree(dev->config_info);
412        dev->config_info = xstrdup(config_info);
413    }
414
415unwind:
416    if (set)
417        libhal_free_property_set(set);
418    if (path)
419        xfree(path);
420    if (driver)
421        xfree(driver);
422    if (name)
423        xfree(name);
424    if (config_info)
425        xfree(config_info);
426    while (!dev && (tmpo = options)) {
427        options = tmpo->next;
428        xfree(tmpo->key);
429        xfree(tmpo->value);
430        xfree(tmpo);
431    }
432
433    if (xkb_opts.layout)
434        xfree(xkb_opts.layout);
435    if (xkb_opts.rules)
436        xfree(xkb_opts.rules);
437    if (xkb_opts.model)
438        xfree(xkb_opts.model);
439    if (xkb_opts.variant)
440        xfree(xkb_opts.variant);
441    if (xkb_opts.options)
442        xfree(xkb_opts.options);
443
444    dbus_error_free(&error);
445
446    return;
447}
448
449static void
450disconnect_hook(void *data)
451{
452    DBusError error;
453    struct config_hal_info *info = data;
454
455    if (info->hal_ctx) {
456        if (dbus_connection_get_is_connected(info->system_bus)) {
457            dbus_error_init(&error);
458            if (!libhal_ctx_shutdown(info->hal_ctx, &error))
459                LogMessage(X_WARNING, "config/hal: disconnect_hook couldn't shut down context: %s (%s)\n",
460                        error.name, error.message);
461            dbus_error_free(&error);
462        }
463        libhal_ctx_free(info->hal_ctx);
464    }
465
466    info->hal_ctx = NULL;
467    info->system_bus = NULL;
468}
469
470static BOOL
471connect_and_register(DBusConnection *connection, struct config_hal_info *info)
472{
473    DBusError error;
474    char **devices;
475    int num_devices, i;
476
477    if (info->hal_ctx)
478        return TRUE; /* already registered, pretend we did something */
479
480    info->system_bus = connection;
481
482    dbus_error_init(&error);
483
484    info->hal_ctx = libhal_ctx_new();
485    if (!info->hal_ctx) {
486        LogMessage(X_ERROR, "config/hal: couldn't create HAL context\n");
487        goto out_err;
488    }
489
490    if (!libhal_ctx_set_dbus_connection(info->hal_ctx, info->system_bus)) {
491        LogMessage(X_ERROR, "config/hal: couldn't associate HAL context with bus\n");
492        goto out_ctx;
493    }
494    if (!libhal_ctx_init(info->hal_ctx, &error)) {
495        LogMessage(X_ERROR, "config/hal: couldn't initialise context: %s (%s)\n",
496		   error.name ? error.name : "unknown error",
497		   error.message ? error.message : "null");
498        goto out_ctx;
499    }
500    if (!libhal_device_property_watch_all(info->hal_ctx, &error)) {
501        LogMessage(X_ERROR, "config/hal: couldn't watch all properties: %s (%s)\n",
502		   error.name ? error.name : "unknown error",
503		   error.message ? error.message : "null");
504        goto out_ctx;
505    }
506    libhal_ctx_set_device_added(info->hal_ctx, device_added);
507    libhal_ctx_set_device_removed(info->hal_ctx, device_removed);
508
509    devices = libhal_find_device_by_capability(info->hal_ctx, "input",
510                                               &num_devices, &error);
511    /* FIXME: Get default devices if error is set. */
512    if (dbus_error_is_set(&error)) {
513        LogMessage(X_ERROR, "config/hal: couldn't find input device: %s (%s)\n",
514		   error.name ? error.name : "unknown error",
515		   error.message ? error.message : "null");
516        goto out_ctx;
517    }
518    for (i = 0; i < num_devices; i++)
519        device_added(info->hal_ctx, devices[i]);
520    libhal_free_string_array(devices);
521
522    dbus_error_free(&error);
523
524    return TRUE;
525
526out_ctx:
527    dbus_error_free(&error);
528
529    if (info->hal_ctx) {
530        if (!libhal_ctx_shutdown(info->hal_ctx, &error)) {
531            LogMessage(X_WARNING, "config/hal: couldn't shut down context: %s (%s)\n",
532		       error.name ? error.name : "unknown error",
533		       error.message ? error.message : "null");
534            dbus_error_free(&error);
535        }
536        libhal_ctx_free(info->hal_ctx);
537    }
538
539out_err:
540    dbus_error_free(&error);
541
542    info->hal_ctx = NULL;
543    info->system_bus = NULL;
544
545    return FALSE;
546}
547
548
549/**
550 * Handle NewOwnerChanged signals to deal with HAL startup at X server runtime.
551 *
552 * NewOwnerChanged is send once when HAL shuts down, and once again when it
553 * comes back up. Message has three arguments, first is the name
554 * (org.freedesktop.Hal), the second one is the old owner, third one is new
555 * owner.
556 */
557static DBusHandlerResult
558ownerchanged_handler(DBusConnection *connection, DBusMessage *message, void *data)
559{
560    int ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
561
562    if (dbus_message_is_signal(message,
563                               "org.freedesktop.DBus",
564                               "NameOwnerChanged")) {
565        DBusError error;
566        char *name, *old_owner, *new_owner;
567
568        dbus_error_init(&error);
569        dbus_message_get_args(message, &error,
570                              DBUS_TYPE_STRING, &name,
571                              DBUS_TYPE_STRING, &old_owner,
572                              DBUS_TYPE_STRING, &new_owner,
573                              DBUS_TYPE_INVALID);
574
575        if (dbus_error_is_set(&error)) {
576            ErrorF("[config/hal] failed to get NameOwnerChanged args: %s (%s)\n",
577                   error.name, error.message);
578        } else if (name && strcmp(name, "org.freedesktop.Hal") == 0) {
579
580            if (!old_owner || !strlen(old_owner)) {
581                DebugF("[config/hal] HAL startup detected.\n");
582                if (connect_and_register(connection, (struct config_hal_info*)data))
583                    dbus_connection_unregister_object_path(connection,
584                                                     "/org/freedesktop/DBus");
585                else
586                    ErrorF("[config/hal] Failed to connect to HAL bus.\n");
587            }
588
589            ret = DBUS_HANDLER_RESULT_HANDLED;
590        }
591        dbus_error_free(&error);
592    }
593
594    return ret;
595}
596
597/**
598 * Register a handler for the NameOwnerChanged signal.
599 */
600static BOOL
601listen_for_startup(DBusConnection *connection, void *data)
602{
603    DBusObjectPathVTable vtable = { .message_function = ownerchanged_handler, };
604    DBusError error;
605    const char MATCH_RULE[] = "sender='org.freedesktop.DBus',"
606                              "interface='org.freedesktop.DBus',"
607                              "type='signal',"
608                              "path='/org/freedesktop/DBus',"
609                              "member='NameOwnerChanged'";
610    int rc = FALSE;
611
612    dbus_error_init(&error);
613    dbus_bus_add_match(connection, MATCH_RULE, &error);
614    if (!dbus_error_is_set(&error)) {
615        if (dbus_connection_register_object_path(connection,
616                                                  "/org/freedesktop/DBus",
617                                                  &vtable,
618                                                  data))
619            rc = TRUE;
620        else
621            ErrorF("[config/hal] cannot register object path.\n");
622    } else {
623        ErrorF("[config/hal] couldn't add match rule: %s (%s)\n", error.name,
624                error.message);
625        ErrorF("[config/hal] cannot detect a HAL startup.\n");
626    }
627
628    dbus_error_free(&error);
629
630    return rc;
631}
632
633static void
634connect_hook(DBusConnection *connection, void *data)
635{
636    struct config_hal_info *info = data;
637
638    if (listen_for_startup(connection, data) &&
639        connect_and_register(connection, info))
640        dbus_connection_unregister_object_path(connection,
641                                               "/org/freedesktop/DBus");
642
643    return;
644}
645
646static struct config_hal_info hal_info;
647static struct config_dbus_core_hook hook = {
648    .connect = connect_hook,
649    .disconnect = disconnect_hook,
650    .data = &hal_info,
651};
652
653int
654config_hal_init(void)
655{
656    memset(&hal_info, 0, sizeof(hal_info));
657    hal_info.system_bus = NULL;
658    hal_info.hal_ctx = NULL;
659
660    if (!config_dbus_core_add_hook(&hook)) {
661        LogMessage(X_ERROR, "config/hal: failed to add D-Bus hook\n");
662        return 0;
663    }
664
665    /* verbose message */
666    LogMessageVerb(X_INFO,7,"config/hal: initialized");
667
668    return 1;
669}
670
671void
672config_hal_fini(void)
673{
674    config_dbus_core_remove_hook(&hook);
675}
676