signals.c 79.4 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 3
/* signals.c  Bus signal connection implementation
 *
4
 * Copyright (C) 2003, 2005  Red Hat, Inc.
5
 *
6
 * Licensed under the Academic Free License version 2.1
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21 22
 *
 */
23 24

#include <config.h>
25 26 27

#include <string.h>

28 29 30
#include "signals.h"
#include "services.h"
#include "utils.h"
31
#include <dbus/dbus-marshal-validate.h>
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

struct BusMatchRule
{
  int refcount;       /**< reference count */

  DBusConnection *matches_go_to; /**< Owner of the rule */

  unsigned int flags; /**< BusMatchFlags */

  int   message_type;
  char *interface;
  char *member;
  char *sender;
  char *destination;
  char *path;
47

48
  unsigned int *arg_lens;
49 50
  char **args;
  int args_len;
51 52
};

53
#define BUS_MATCH_ARG_NAMESPACE   0x4000000u
54 55
#define BUS_MATCH_ARG_IS_PATH  0x8000000u

56 57
#define BUS_MATCH_ARG_FLAGS (BUS_MATCH_ARG_NAMESPACE | BUS_MATCH_ARG_IS_PATH)

58 59 60 61 62 63 64 65 66 67 68 69
BusMatchRule*
bus_match_rule_new (DBusConnection *matches_go_to)
{
  BusMatchRule *rule;

  rule = dbus_new0 (BusMatchRule, 1);
  if (rule == NULL)
    return NULL;

  rule->refcount = 1;
  rule->matches_go_to = matches_go_to;

70
#ifndef DBUS_ENABLE_EMBEDDED_TESTS
71 72 73
  _dbus_assert (rule->matches_go_to != NULL);
#endif
  
74 75 76
  return rule;
}

77
BusMatchRule *
78 79 80 81 82
bus_match_rule_ref (BusMatchRule *rule)
{
  _dbus_assert (rule->refcount > 0);

  rule->refcount += 1;
83 84

  return rule;
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
}

void
bus_match_rule_unref (BusMatchRule *rule)
{
  _dbus_assert (rule->refcount > 0);

  rule->refcount -= 1;
  if (rule->refcount == 0)
    {
      dbus_free (rule->interface);
      dbus_free (rule->member);
      dbus_free (rule->sender);
      dbus_free (rule->destination);
      dbus_free (rule->path);
100
      dbus_free (rule->arg_lens);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

      /* can't use dbus_free_string_array() since there
       * are embedded NULL
       */
      if (rule->args)
        {
          int i;

          i = 0;
          while (i < rule->args_len)
            {
              if (rule->args[i])
                dbus_free (rule->args[i]);
              ++i;
            }

          dbus_free (rule->args);
        }
      
120 121 122 123
      dbus_free (rule);
    }
}

124
#if defined(DBUS_ENABLE_VERBOSE_MODE) || defined(DBUS_ENABLE_STATS)
125 126 127 128 129 130 131 132 133 134
static dbus_bool_t
append_key_and_escaped_value (DBusString *str, const char *token, const char *value)
{
  const char *p = value;

  if (!_dbus_string_append_printf (str, "%s='", token))
    return FALSE;

  while (*p != '\0')
    {
135
      const char *next = strchr (p, '\'');
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

      if (next)
        {
          if (!_dbus_string_append_printf (str, "%.*s", (int) (next - p), p))
            return FALSE;
          /* Horrible escape sequence: single quote cannot be escaped inside
           * a single quoted string. So we close the single quote, escape the
           * single quote, and reopen a single quote.
           */
          if (!_dbus_string_append_printf (str, "'\\''"))
            return FALSE;
          p = next + 1;
        }
      else
        {
          if (!_dbus_string_append_printf (str, "%s", p))
            return FALSE;
          break;
        }
    }

  if (!_dbus_string_append_byte (str, '\''))
    return FALSE;

  return TRUE;
}

163
/* returns NULL if no memory */
164 165 166 167 168 169 170 171
static char*
match_rule_to_string (BusMatchRule *rule)
{
  DBusString str;
  char *ret;
  
  if (!_dbus_string_init (&str))
    {
172
      return NULL;
173 174 175 176
    }
  
  if (rule->flags & BUS_MATCH_MESSAGE_TYPE)
    {
177
      if (!append_key_and_escaped_value (&str, "type",
178 179
            dbus_message_type_to_string (rule->message_type)))
        goto nomem;
180 181 182 183 184 185 186 187 188 189
    }

  if (rule->flags & BUS_MATCH_INTERFACE)
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }
      
190
      if (!append_key_and_escaped_value (&str, "interface", rule->interface))
191 192 193 194 195 196 197 198 199 200 201
        goto nomem;
    }

  if (rule->flags & BUS_MATCH_MEMBER)
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }
      
202
      if (!append_key_and_escaped_value (&str, "member", rule->member))
203 204 205 206 207 208 209 210 211 212 213
        goto nomem;
    }

  if (rule->flags & BUS_MATCH_PATH)
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }
      
214
      if (!append_key_and_escaped_value (&str, "path", rule->path))
215 216 217
        goto nomem;
    }

218
  if (rule->flags & BUS_MATCH_PATH_NAMESPACE)
219 220 221 222 223 224 225
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }

226
      if (!append_key_and_escaped_value (&str, "path_namespace", rule->path))
227 228 229
        goto nomem;
    }

230 231 232 233 234 235 236 237
  if (rule->flags & BUS_MATCH_SENDER)
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }
      
238
      if (!append_key_and_escaped_value (&str, "sender", rule->sender))
239 240 241 242 243 244 245 246 247 248 249
        goto nomem;
    }

  if (rule->flags & BUS_MATCH_DESTINATION)
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }
      
250
      if (!append_key_and_escaped_value (&str, "destination", rule->destination))
251 252
        goto nomem;
    }
253

254 255 256 257 258 259 260 261
  if (rule->flags & BUS_MATCH_CLIENT_IS_EAVESDROPPING)
    {
      if (_dbus_string_get_length (&str) > 0)
        {
          if (!_dbus_string_append (&str, ","))
            goto nomem;
        }

262
      if (!append_key_and_escaped_value (&str, "eavesdrop",
263 264 265 266 267
            (rule->flags & BUS_MATCH_CLIENT_IS_EAVESDROPPING) ?
            "true" : "false"))
        goto nomem;
    }

268 269 270 271 272 273 274 275 276 277 278
  if (rule->flags & BUS_MATCH_ARGS)
    {
      int i;
      
      _dbus_assert (rule->args != NULL);

      i = 0;
      while (i < rule->args_len)
        {
          if (rule->args[i] != NULL)
            {
279
              dbus_bool_t is_path, is_namespace;
280

281 282 283 284 285
              if (_dbus_string_get_length (&str) > 0)
                {
                  if (!_dbus_string_append (&str, ","))
                    goto nomem;
                }
286 287

              is_path = (rule->arg_lens[i] & BUS_MATCH_ARG_IS_PATH) != 0;
288
              is_namespace = (rule->arg_lens[i] & BUS_MATCH_ARG_NAMESPACE) != 0;
289 290
              
              if (!_dbus_string_append_printf (&str,
291
                                               "arg%d%s",
292 293
                                               i,
                                               is_path ? "path" :
294 295 296
                                               is_namespace ? "namespace" : ""))
                goto nomem;
              if (!append_key_and_escaped_value (&str, "", rule->args[i]))
297 298 299 300 301 302
                goto nomem;
            }
          
          ++i;
        }
    }
303 304 305 306 307 308 309 310 311
  
  if (!_dbus_string_steal_data (&str, &ret))
    goto nomem;

  _dbus_string_free (&str);
  return ret;
  
 nomem:
  _dbus_string_free (&str);
312
  return NULL;
313
}
314
#endif /* defined(DBUS_ENABLE_VERBOSE_MODE) || defined(DBUS_ENABLE_STATS) */
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

dbus_bool_t
bus_match_rule_set_message_type (BusMatchRule *rule,
                                 int           type)
{
  rule->flags |= BUS_MATCH_MESSAGE_TYPE;

  rule->message_type = type;

  return TRUE;
}

dbus_bool_t
bus_match_rule_set_interface (BusMatchRule *rule,
                              const char   *interface)
{
  char *new;

  _dbus_assert (interface != NULL);

  new = _dbus_strdup (interface);
  if (new == NULL)
    return FALSE;

  rule->flags |= BUS_MATCH_INTERFACE;
  dbus_free (rule->interface);
  rule->interface = new;

  return TRUE;
}

dbus_bool_t
bus_match_rule_set_member (BusMatchRule *rule,
                           const char   *member)
{
  char *new;

  _dbus_assert (member != NULL);

  new = _dbus_strdup (member);
  if (new == NULL)
    return FALSE;

  rule->flags |= BUS_MATCH_MEMBER;
  dbus_free (rule->member);
  rule->member = new;

  return TRUE;
}

dbus_bool_t
bus_match_rule_set_sender (BusMatchRule *rule,
                           const char   *sender)
{
  char *new;

  _dbus_assert (sender != NULL);

  new = _dbus_strdup (sender);
  if (new == NULL)
    return FALSE;

  rule->flags |= BUS_MATCH_SENDER;
  dbus_free (rule->sender);
  rule->sender = new;

  return TRUE;
}

dbus_bool_t
bus_match_rule_set_destination (BusMatchRule *rule,
                                const char   *destination)
{
  char *new;

  _dbus_assert (destination != NULL);

  new = _dbus_strdup (destination);
  if (new == NULL)
    return FALSE;

  rule->flags |= BUS_MATCH_DESTINATION;
  dbus_free (rule->destination);
  rule->destination = new;

  return TRUE;
}

403 404 405 406 407 408 409 410 411 412
void
bus_match_rule_set_client_is_eavesdropping (BusMatchRule *rule,
                                            dbus_bool_t is_eavesdropping)
{
  if (is_eavesdropping)
    rule->flags |= BUS_MATCH_CLIENT_IS_EAVESDROPPING;
  else
    rule->flags &= ~(BUS_MATCH_CLIENT_IS_EAVESDROPPING);
}

413 414 415 416 417 418 419 420 421
dbus_bool_t
bus_match_rule_get_client_is_eavesdropping (BusMatchRule *rule)
{
  if (rule->flags & BUS_MATCH_CLIENT_IS_EAVESDROPPING)
    return TRUE;
  else
    return FALSE;
}

422 423
dbus_bool_t
bus_match_rule_set_path (BusMatchRule *rule,
424 425
                         const char   *path,
                         dbus_bool_t   is_namespace)
426 427 428 429 430 431 432 433 434
{
  char *new;

  _dbus_assert (path != NULL);

  new = _dbus_strdup (path);
  if (new == NULL)
    return FALSE;

435
  rule->flags &= ~(BUS_MATCH_PATH|BUS_MATCH_PATH_NAMESPACE);
436

437 438 439 440
  if (is_namespace)
    rule->flags |= BUS_MATCH_PATH_NAMESPACE;
  else
    rule->flags |= BUS_MATCH_PATH;
441

442 443
  dbus_free (rule->path);
  rule->path = new;
444 445 446 447

  return TRUE;
}

448
dbus_bool_t
449 450 451
bus_match_rule_set_arg (BusMatchRule     *rule,
                        int                arg,
                        const DBusString *value,
452 453
                        dbus_bool_t       is_path,
                        dbus_bool_t       is_namespace)
454
{
455
  int length;
456 457 458 459 460 461 462 463 464
  char *new;

  _dbus_assert (value != NULL);

  /* args_len is the number of args not including null termination
   * in the char**
   */
  if (arg >= rule->args_len)
    {
465
      unsigned int *new_arg_lens;
466 467 468 469 470 471 472 473
      char **new_args;
      int new_args_len;
      int i;

      new_args_len = arg + 1;

      /* add another + 1 here for null termination */
      new_args = dbus_realloc (rule->args,
474
                               sizeof (char *) * (new_args_len + 1));
475
      if (new_args == NULL)
476
        return FALSE;
477 478 479 480 481 482 483 484 485 486

      /* NULL the new slots */
      i = rule->args_len;
      while (i <= new_args_len) /* <= for null termination */
        {
          new_args[i] = NULL;
          ++i;
        }
      
      rule->args = new_args;
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503

      /* and now add to the lengths */
      new_arg_lens = dbus_realloc (rule->arg_lens,
                                   sizeof (int) * (new_args_len + 1));

      if (new_arg_lens == NULL)
        return FALSE;

      /* zero the new slots */
      i = rule->args_len;
      while (i <= new_args_len) /* <= for null termination */
        {
          new_arg_lens[i] = 0;
          ++i;
        }

      rule->arg_lens = new_arg_lens;
504 505 506
      rule->args_len = new_args_len;
    }

507 508 509 510
  length = _dbus_string_get_length (value);
  if (!_dbus_string_copy_data (value, &new))
    return FALSE;

511 512 513
  rule->flags |= BUS_MATCH_ARGS;

  dbus_free (rule->args[arg]);
514
  rule->arg_lens[arg] = length;
515 516
  rule->args[arg] = new;

517 518 519
  if (is_path)
    rule->arg_lens[arg] |= BUS_MATCH_ARG_IS_PATH;

520 521 522
  if (is_namespace)
    rule->arg_lens[arg] |= BUS_MATCH_ARG_NAMESPACE;

523 524
  /* NULL termination didn't get busted */
  _dbus_assert (rule->args[rule->args_len] == NULL);
525
  _dbus_assert (rule->arg_lens[rule->args_len] == 0);
526 527 528 529

  return TRUE;
}

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
#define ISWHITE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))

static dbus_bool_t
find_key (const DBusString *str,
          int               start,
          DBusString       *key,
          int              *value_pos,
          DBusError        *error)
{
  const char *p;
  const char *s;
  const char *key_start;
  const char *key_end;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
  s = _dbus_string_get_const_data (str);

  p = s + start;

  while (*p && ISWHITE (*p))
    ++p;

  key_start = p;

  while (*p && *p != '=' && !ISWHITE (*p))
    ++p;

  key_end = p;

  while (*p && ISWHITE (*p))
    ++p;
  
  if (key_start == key_end)
    {
      /* Empty match rules or trailing whitespace are OK */
      *value_pos = p - s;
      return TRUE;
    }

  if (*p != '=')
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                      "Match rule has a key with no subsequent '=' character");
      return FALSE;
    }
  ++p;
  
  if (!_dbus_string_append_len (key, key_start, key_end - key_start))
    {
      BUS_SET_OOM (error);
      return FALSE;
    }

  *value_pos = p - s;
  
  return TRUE;
}

static dbus_bool_t
find_value (const DBusString *str,
            int               start,
            const char       *key,
            DBusString       *value,
            int              *value_end,
            DBusError        *error)
{
  const char *p;
  const char *s;
  char quote_char;
  int orig_len;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
  orig_len = _dbus_string_get_length (value);
  
  s = _dbus_string_get_const_data (str);

  p = s + start;

  quote_char = '\0';

  while (*p)
    {
      if (quote_char == '\0')
        {
          switch (*p)
            {
            case '\0':
              goto done;

            case '\'':
              quote_char = '\'';
              goto next;
              
            case ',':
              ++p;
              goto done;

            case '\\':
              quote_char = '\\';
              goto next;
              
            default:
              if (!_dbus_string_append_byte (value, *p))
                {
                  BUS_SET_OOM (error);
                  goto failed;
                }
            }
        }
      else if (quote_char == '\\')
        {
          /* \ only counts as an escape if escaping a quote mark */
          if (*p != '\'')
            {
              if (!_dbus_string_append_byte (value, '\\'))
                {
                  BUS_SET_OOM (error);
                  goto failed;
                }
            }

          if (!_dbus_string_append_byte (value, *p))
            {
              BUS_SET_OOM (error);
              goto failed;
            }
          
          quote_char = '\0';
        }
      else
        {
          _dbus_assert (quote_char == '\'');

          if (*p == '\'')
            {
              quote_char = '\0';
            }
          else
            {
              if (!_dbus_string_append_byte (value, *p))
                {
                  BUS_SET_OOM (error);
                  goto failed;
                }
            }
        }

    next:
      ++p;
    }

 done:

  if (quote_char == '\\')
    {
      if (!_dbus_string_append_byte (value, '\\'))
        {
          BUS_SET_OOM (error);
          goto failed;
        }
    }
  else if (quote_char == '\'')
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                      "Unbalanced quotation marks in match rule");
      goto failed;
    }
  else
    _dbus_assert (quote_char == '\0');

  /* Zero-length values are allowed */
  
  *value_end = p - s;
  
  return TRUE;

 failed:
  _DBUS_ASSERT_ERROR_IS_SET (error);
  _dbus_string_set_length (value, orig_len);
  return FALSE;
}

/* duplicates aren't allowed so the real legitimate max is only 6 or
 * so. Leaving extra so we don't have to bother to update it.
716 717
 * FIXME this is sort of busted now with arg matching, but we let
 * you match on up to 10 args for now
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
 */
#define MAX_RULE_TOKENS 16

/* this is slightly too high level to be termed a "token"
 * but let's not be pedantic.
 */
typedef struct
{
  char *key;
  char *value;
} RuleToken;

static dbus_bool_t
tokenize_rule (const DBusString *rule_text,
               RuleToken         tokens[MAX_RULE_TOKENS],
               DBusError        *error) 
{
  int i;
  int pos;
  DBusString key;
  DBusString value;
  dbus_bool_t retval;

  retval = FALSE;
  
  if (!_dbus_string_init (&key))
    {
      BUS_SET_OOM (error);
      return FALSE;
    }

  if (!_dbus_string_init (&value))
    {
      _dbus_string_free (&key);
      BUS_SET_OOM (error);
      return FALSE;
    }

  i = 0;
  pos = 0;
  while (i < MAX_RULE_TOKENS &&
         pos < _dbus_string_get_length (rule_text))
    {
      _dbus_assert (tokens[i].key == NULL);
      _dbus_assert (tokens[i].value == NULL);

      if (!find_key (rule_text, pos, &key, &pos, error))
        goto out;

      if (_dbus_string_get_length (&key) == 0)
        goto next;
      
      if (!_dbus_string_steal_data (&key, &tokens[i].key))
        {
          BUS_SET_OOM (error);
          goto out;
        }

      if (!find_value (rule_text, pos, tokens[i].key, &value, &pos, error))
        goto out;

      if (!_dbus_string_steal_data (&value, &tokens[i].value))
        {
          BUS_SET_OOM (error);
          goto out;
        }

    next:
      ++i;
    }

  retval = TRUE;
  
 out:
  if (!retval)
    {
      i = 0;
      while (tokens[i].key || tokens[i].value)
        {
          dbus_free (tokens[i].key);
          dbus_free (tokens[i].value);
          tokens[i].key = NULL;
          tokens[i].value = NULL;
          ++i;
        }
    }
  
  _dbus_string_free (&key);
  _dbus_string_free (&value);
  
  return retval;
}

811 812 813 814 815 816
static dbus_bool_t
bus_match_rule_parse_arg_match (BusMatchRule     *rule,
                                const char       *key,
                                const DBusString *value,
                                DBusError        *error)
{
817 818
  dbus_bool_t is_path = FALSE;
  dbus_bool_t is_namespace = FALSE;
819 820
  DBusString key_str;
  unsigned long arg;
821
  int length;
822 823 824 825 826 827 828 829 830 831 832
  int end;

  /* For now, arg0='foo' always implies that 'foo' is a
   * DBUS_TYPE_STRING. Someday we could add an arg0type='int32' thing
   * if we wanted, which would specify another type, in which case
   * arg0='5' would have the 5 parsed as an int rather than string.
   */
  
  /* First we need to parse arg0 = 0, arg27 = 27 */

  _dbus_string_init_const (&key_str, key);
833
  length = _dbus_string_get_length (&key_str);
834 835 836 837 838 839 840 841

  if (_dbus_string_get_length (&key_str) < 4)
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                      "Key '%s' in match rule starts with 'arg' but lacks an arg number. Should be 'arg0' or 'arg7' for example.\n", key);
      goto failed;
    }

842
  if (!_dbus_string_parse_uint (&key_str, 3, &arg, &end))
843 844 845 846 847 848
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                      "Key '%s' in match rule starts with 'arg' but could not parse arg number. Should be 'arg0' or 'arg7' for example.\n", key);
      goto failed;
    }

849
  if (end != length)
850
    {
851 852
      int len1 = strlen ("path");
      if ((end + len1) == length &&
853 854 855 856 857 858
          _dbus_string_ends_with_c_str (&key_str, "path"))
        {
          is_path = TRUE;
        }
      else if (_dbus_string_equal_c_str (&key_str, "arg0namespace"))
        {
859
          int value_len = _dbus_string_get_length (value);
860

861
          is_namespace = TRUE;
862 863 864 865

          if (!_dbus_validate_bus_namespace (value, 0, value_len))
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
866
                  "arg0namespace='%s' is not a valid prefix of a bus name",
867 868 869
                  _dbus_string_get_const_data (value));
              goto failed;
            }
870 871 872 873 874 875 876
        }
      else
        {
          dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
              "Key '%s' in match rule contains junk after argument number (%u). Only 'arg%upath' (for example) or 'arg0namespace' are valid", key, arg, arg);
          goto failed;
        }
877 878
    }

879 880 881 882 883 884 885 886 887 888 889 890 891
  /* If we didn't check this we could allocate a huge amount of RAM */
  if (arg > DBUS_MAXIMUM_MATCH_RULE_ARG_NUMBER)
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                      "Key '%s' in match rule has arg number %lu but the maximum is %d.\n", key, (unsigned long) arg, DBUS_MAXIMUM_MATCH_RULE_ARG_NUMBER);
      goto failed;
    }
  
  if ((rule->flags & BUS_MATCH_ARGS) &&
      rule->args_len > (int) arg &&
      rule->args[arg] != NULL)
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
892
                      "Argument %d matched more than once in match rule\n", key);
893 894 895
      goto failed;
    }
  
896
  if (!bus_match_rule_set_arg (rule, arg, value, is_path, is_namespace))
897 898 899 900 901 902 903 904 905 906 907 908
    {
      BUS_SET_OOM (error);
      goto failed;
    }

  return TRUE;

 failed:
  _DBUS_ASSERT_ERROR_IS_SET (error);
  return FALSE;
}

909 910 911 912 913
/*
 * The format is comma-separated with strings quoted with single quotes
 * as for the shell (to escape a literal single quote, use '\'').
 *
 * type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='Foo',
914
 * path='/bar/foo',destination=':452345.34'
915 916 917 918 919 920 921 922
 *
 */
BusMatchRule*
bus_match_rule_parse (DBusConnection   *matches_go_to,
                      const DBusString *rule_text,
                      DBusError        *error)
{
  BusMatchRule *rule;
923 924 925 926
  RuleToken tokens[MAX_RULE_TOKENS+1]; /* NULL termination + 1 */
  int i;
  
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
927 928 929 930 931 932 933 934 935

  if (_dbus_string_get_length (rule_text) > DBUS_MAXIMUM_MATCH_RULE_LENGTH)
    {
      dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
                      "Match rule text is %d bytes, maximum is %d",
                      _dbus_string_get_length (rule_text),
                      DBUS_MAXIMUM_MATCH_RULE_LENGTH);
      return NULL;
    }
936 937 938
  
  memset (tokens, '\0', sizeof (tokens));
  
939 940
  rule = bus_match_rule_new (matches_go_to);
  if (rule == NULL)
941 942 943 944
    {
      BUS_SET_OOM (error);
      goto failed;
    }
945
  
946 947
  if (!tokenize_rule (rule_text, tokens, error))
    goto failed;
948
  
949 950 951
  i = 0;
  while (tokens[i].key != NULL)
    {
952 953
      DBusString tmp_str;
      int len;
954 955 956
      const char *key = tokens[i].key;
      const char *value = tokens[i].value;
      
957 958 959
      _dbus_string_init_const (&tmp_str, value);
      len = _dbus_string_get_length (&tmp_str);

960 961 962 963 964 965 966 967 968 969 970 971 972
      if (strcmp (key, "type") == 0)
        {
          int t;

          if (rule->flags & BUS_MATCH_MESSAGE_TYPE)
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Key %s specified twice in match rule\n", key);
              goto failed;
            }
          
          t = dbus_message_type_from_string (value);
          
973 974 975 976 977 978 979
          if (t == DBUS_MESSAGE_TYPE_INVALID)
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Invalid message type (%s) in match rule\n", value);
              goto failed;
            }

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
          if (!bus_match_rule_set_message_type (rule, t))
            {
              BUS_SET_OOM (error);
              goto failed;
            }
        }
      else if (strcmp (key, "sender") == 0)
        {
          if (rule->flags & BUS_MATCH_SENDER)
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Key %s specified twice in match rule\n", key);
              goto failed;
            }

995
          if (!_dbus_validate_bus_name (&tmp_str, 0, len))
996 997
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
998
                              "Sender name '%s' is invalid\n", value);
999 1000 1001
              goto failed;
            }

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
          if (!bus_match_rule_set_sender (rule, value))
            {
              BUS_SET_OOM (error);
              goto failed;
            }
        }
      else if (strcmp (key, "interface") == 0)
        {
          if (rule->flags & BUS_MATCH_INTERFACE)
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Key %s specified twice in match rule\n", key);
              goto failed;
            }

1017
          if (!_dbus_validate_interface (&tmp_str, 0, len))
1018 1019 1020 1021 1022 1023
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Interface name '%s' is invalid\n", value);
              goto failed;
            }

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
          if (!bus_match_rule_set_interface (rule, value))
            {
              BUS_SET_OOM (error);
              goto failed;
            }
        }
      else if (strcmp (key, "member") == 0)
        {
          if (rule->flags & BUS_MATCH_MEMBER)
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Key %s specified twice in match rule\n", key);
              goto failed;
            }

1039
          if (!_dbus_validate_member (&tmp_str, 0, len))
1040 1041 1042 1043 1044 1045
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Member name '%s' is invalid\n", value);
              goto failed;
            }

1046 1047 1048 1049 1050 1051
          if (!bus_match_rule_set_member (rule, value))
            {
              BUS_SET_OOM (error);
              goto failed;
            }
        }
1052 1053
      else if (strcmp (key, "path") == 0 ||
          strcmp (key, "path_namespace") == 0)
1054
        {
1055 1056 1057
          dbus_bool_t is_namespace = (strcmp (key, "path_namespace") == 0);

          if (rule->flags & (BUS_MATCH_PATH | BUS_MATCH_PATH_NAMESPACE))
1058 1059
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
1060
                              "path or path_namespace specified twice in match rule\n");
1061 1062 1063
              goto failed;
            }

1064
          if (!_dbus_validate_path (&tmp_str, 0, len))
1065 1066 1067 1068 1069 1070
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Path '%s' is invalid\n", value);
              goto failed;
            }

1071
          if (!bus_match_rule_set_path (rule, value, is_namespace))
1072 1073 1074 1075 1076
            {
              BUS_SET_OOM (error);
              goto failed;
            }
        }
1077 1078 1079 1080 1081 1082 1083 1084 1085
      else if (strcmp (key, "destination") == 0)
        {
          if (rule->flags & BUS_MATCH_DESTINATION)
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "Key %s specified twice in match rule\n", key);
              goto failed;
            }

1086
          if (!_dbus_validate_bus_name (&tmp_str, 0, len))
1087 1088
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
1089
                              "Destination name '%s' is invalid\n", value);
1090 1091 1092
              goto failed;
            }

1093 1094 1095 1096 1097 1098
          if (!bus_match_rule_set_destination (rule, value))
            {
              BUS_SET_OOM (error);
              goto failed;
            }
        }
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
      else if (strcmp (key, "eavesdrop") == 0)
        {
          /* do not detect "eavesdrop" being used more than once in rule:
           * 1) it's not possible, it's only in the flags
           * 2) it might be used twice to disable eavesdropping when it's
           * automatically added (eg dbus-monitor/bustle) */

          /* we accept only "true|false" as possible values */
          if ((strcmp (value, "true") == 0))
            {
              bus_match_rule_set_client_is_eavesdropping (rule, TRUE);
            }
          else if (strcmp (value, "false") == 0)
            {
              bus_match_rule_set_client_is_eavesdropping (rule, FALSE);
            }
          else
            {
              dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                              "eavesdrop='%s' is invalid, "
                              "it should be 'true' or 'false'\n",
                              value);
              goto failed;
            }
        }
1124 1125 1126 1127 1128
      else if (strncmp (key, "arg", 3) == 0)
        {
          if (!bus_match_rule_parse_arg_match (rule, key, &tmp_str, error))
            goto failed;
        }
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
      else
        {
          dbus_set_error (error, DBUS_ERROR_MATCH_RULE_INVALID,
                          "Unknown key \"%s\" in match rule",
                          key);
          goto failed;
        }

      ++i;
    }
  

  goto out;
1142
  
1143 1144
 failed:
  _DBUS_ASSERT_ERROR_IS_SET (error);
1145
  if (rule)
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    {
      bus_match_rule_unref (rule);
      rule = NULL;
    }

 out:
  
  i = 0;
  while (tokens[i].key || tokens[i].value)
    {
      _dbus_assert (i < MAX_RULE_TOKENS);
      dbus_free (tokens[i].key);
      dbus_free (tokens[i].value);
      ++i;
    }
  
  return rule;
1163 1164
}

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
typedef struct RulePool RulePool;
struct RulePool
{
  /* Maps non-NULL interface names to non-NULL (DBusList **)s */
  DBusHashTable *rules_by_iface;

  /* List of BusMatchRules which don't specify an interface */
  DBusList *rules_without_iface;
};

1175 1176 1177 1178
struct BusMatchmaker
{
  int refcount;

1179
  /* Pools of rules, grouped by the type of message they match. 0
1180 1181 1182
   * (DBUS_MESSAGE_TYPE_INVALID) represents rules that do not specify a message
   * type.
   */
1183
  RulePool rules_by_type[DBUS_NUM_MESSAGE_TYPES];
1184 1185
};

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
#ifdef DBUS_ENABLE_STATS
dbus_bool_t
bus_match_rule_dump (BusMatchmaker *matchmaker,
                     DBusConnection *conn_filter,
                     DBusMessageIter *arr_iter)
{
  int i;

  for (i = 0 ; i < DBUS_NUM_MESSAGE_TYPES ; i++)
    {
      DBusHashIter iter;
      DBusList **list;
      DBusList *link;

      _dbus_hash_iter_init (matchmaker->rules_by_type[i].rules_by_iface, &iter);
      while (_dbus_hash_iter_next (&iter))
        {
          list =  _dbus_hash_iter_get_value (&iter);
          for (link = _dbus_list_get_first_link (list);
               link != NULL;
               link = _dbus_list_get_next_link (list, link))
            {
              BusMatchRule *rule = link->data;

              if (rule->matches_go_to == conn_filter)
                {
                  char *s = match_rule_to_string (rule);

                  if (s == NULL)
                    return FALSE;

                  if (!dbus_message_iter_append_basic (arr_iter, DBUS_TYPE_STRING, &s))
                    {
                      dbus_free (s);
                      return FALSE;
                    }
                  dbus_free (s);
                }
            }
        }
      list = &matchmaker->rules_by_type[i].rules_without_iface;
      for (link = _dbus_list_get_first_link (list);
           link != NULL;
           link = _dbus_list_get_next_link (list, link))
        {
          BusMatchRule *rule = link->data;

          if (rule->matches_go_to == conn_filter)
            {
              char *s = match_rule_to_string (rule);

              if (s == NULL)
                return FALSE;

              if (!dbus_message_iter_append_basic (arr_iter, DBUS_TYPE_STRING, &s))
                {
                  dbus_free (s);
                  return FALSE;
                }
              dbus_free (s);
            }
        }
    }

  return TRUE;
}
#endif

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
static void
rule_list_free (DBusList **rules)
{
  while (*rules != NULL)
    {
      BusMatchRule *rule;

      rule = (*rules)->data;
      bus_match_rule_unref (rule);
      _dbus_list_remove_link (rules, *rules);
    }
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
static void
rule_list_ptr_free (DBusList **list)
{
  /* We have to cope with NULL because the hash table frees the "existing"
   * value (which is NULL) when creating a new table entry...
   */
  if (list != NULL)
    {
      rule_list_free (list);
      dbus_free (list);
    }
}

1280 1281 1282 1283
BusMatchmaker*
bus_matchmaker_new (void)
{
  BusMatchmaker *matchmaker;
1284
  int i;
1285 1286 1287 1288 1289 1290

  matchmaker = dbus_new0 (BusMatchmaker, 1);
  if (matchmaker == NULL)
    return NULL;

  matchmaker->refcount = 1;
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

  for (i = DBUS_MESSAGE_TYPE_INVALID; i < DBUS_NUM_MESSAGE_TYPES; i++)
    {
      RulePool *p = matchmaker->rules_by_type + i;

      p->rules_by_iface = _dbus_hash_table_new (DBUS_HASH_STRING,
          dbus_free, (DBusFreeFunction) rule_list_ptr_free);

      if (p->rules_by_iface == NULL)
        goto nomem;
    }

1303
  return matchmaker;
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

 nomem:
  for (i = DBUS_MESSAGE_TYPE_INVALID; i < DBUS_NUM_MESSAGE_TYPES; i++)
    {
      RulePool *p = matchmaker->rules_by_type + i;

      if (p->rules_by_iface == NULL)
        break;
      else
        _dbus_hash_table_unref (p->rules_by_iface);
    }
1315
  dbus_free (matchmaker);
1316 1317

  return NULL;
1318 1319
}

1320 1321
static DBusList **
bus_matchmaker_get_rules (BusMatchmaker *matchmaker,
1322 1323 1324
                          int            message_type,
                          const char    *interface,
                          dbus_bool_t    create)
1325
{
1326 1327
  RulePool *p;

1328 1329 1330
  _dbus_assert (message_type >= 0);
  _dbus_assert (message_type < DBUS_NUM_MESSAGE_TYPES);

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  _dbus_verbose ("Looking up rules for message_type %d, interface %s\n",
                 message_type,
                 interface != NULL ? interface : "<null>");

  p = matchmaker->rules_by_type + message_type;

  if (interface == NULL)
    {
      return &p->rules_without_iface;
    }
  else
    {
      DBusList **list;

      list = _dbus_hash_table_lookup_string (p->rules_by_iface, interface);

      if (list == NULL && create)
        {
          char *dupped_interface;

          list = dbus_new0 (DBusList *, 1);
          if (list == NULL)
            return NULL;

          dupped_interface = _dbus_strdup (interface);
          if (dupped_interface == NULL)
            {
              dbus_free (list);
              return NULL;
            }

          _dbus_verbose ("Adding list for type %d, iface %s\n", message_type,
                         interface);

          if (!_dbus_hash_table_insert_string (p->rules_by_iface,
                                               dupped_interface, list))
            {
              dbus_free (list);
              dbus_free (dupped_interface);
              return NULL;
            }
        }

      return list;
    }
}

static void
bus_matchmaker_gc_rules (BusMatchmaker *matchmaker,
                         int            message_type,
                         const char    *interface,
                         DBusList     **rules)
{
  RulePool *p;

  if (interface == NULL)
    return;

  if (*rules != NULL)
    return;

  _dbus_verbose ("GCing HT entry for message_type %u, interface %s\n",
                 message_type, interface);

  p = matchmaker->rules_by_type + message_type;

  _dbus_assert (_dbus_hash_table_lookup_string (p->rules_by_iface, interface)
      == rules);

  _dbus_hash_table_remove_string (p->rules_by_iface, interface);
1401 1402
}

1403
BusMatchmaker *
1404 1405 1406 1407 1408
bus_matchmaker_ref (BusMatchmaker *matchmaker)
{
  _dbus_assert (matchmaker->refcount > 0);

  matchmaker->refcount += 1;
1409 1410

  return matchmaker;
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
}

void
bus_matchmaker_unref (BusMatchmaker *matchmaker)
{
  _dbus_assert (matchmaker->refcount > 0);

  matchmaker->refcount -= 1;
  if (matchmaker->refcount == 0)
    {
1421 1422 1423
      int i;

      for (i = DBUS_MESSAGE_TYPE_INVALID; i < DBUS_NUM_MESSAGE_TYPES; i++)
1424 1425 1426 1427 1428 1429
        {
          RulePool *p = matchmaker->rules_by_type + i;

          _dbus_hash_table_unref (p->rules_by_iface);
          rule_list_free (&p->rules_without_iface);
        }
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

      dbus_free (matchmaker);
    }
}

/* The rule can't be modified after it's added. */
dbus_bool_t
bus_matchmaker_add_rule (BusMatchmaker   *matchmaker,
                         BusMatchRule    *rule)
{
1440 1441
  DBusList **rules;

1442 1443
  _dbus_assert (bus_connection_is_active (rule->matches_go_to));

1444 1445 1446 1447 1448 1449 1450 1451 1452
  _dbus_verbose ("Adding rule with message_type %d, interface %s\n",
                 rule->message_type,
                 rule->interface != NULL ? rule->interface : "<null>");

  rules = bus_matchmaker_get_rules (matchmaker, rule->message_type,
                                    rule->interface, TRUE);

  if (rules == NULL)
    return FALSE;
1453 1454

  if (!_dbus_list_append (rules, rule))
1455 1456 1457 1458
    return FALSE;

  if (!bus_connection_add_match_rule (rule->matches_go_to, rule))
    {
1459
      _dbus_list_remove_last (rules, rule);
1460 1461
      bus_matchmaker_gc_rules (matchmaker, rule->message_type,
                               rule->interface, rules);
1462 1463
      return FALSE;
    }
1464

1465 1466 1467 1468 1469 1470 1471
  bus_match_rule_ref (rule);

#ifdef DBUS_ENABLE_VERBOSE_MODE
  {
    char *s = match_rule_to_string (rule);

    _dbus_verbose ("Added match rule %s to connection %p\n",
1472
                   s ? s : "nomem", rule->matches_go_to);
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
    dbus_free (s);
  }
#endif
  
  return TRUE;
}

static dbus_bool_t
match_rule_equal (BusMatchRule *a,
                  BusMatchRule *b)
{
  if (a->flags != b->flags)
    return FALSE;

1487 1488 1489
  if (a->matches_go_to != b->matches_go_to)
    return FALSE;

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
  if ((a->flags & BUS_MATCH_MESSAGE_TYPE) &&
      a->message_type != b->message_type)
    return FALSE;

  if ((a->flags & BUS_MATCH_MEMBER) &&
      strcmp (a->member, b->member) != 0)
    return FALSE;

  if ((a->flags & BUS_MATCH_PATH) &&
      strcmp (a->path, b->path) != 0)
    return FALSE;
1501

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
  if ((a->flags & BUS_MATCH_INTERFACE) &&
      strcmp (a->interface, b->interface) != 0)
    return FALSE;

  if ((a->flags & BUS_MATCH_SENDER) &&
      strcmp (a->sender, b->sender) != 0)
    return FALSE;

  if ((a->flags & BUS_MATCH_DESTINATION) &&
      strcmp (a->destination, b->destination) != 0)
    return FALSE;

1514 1515 1516
  /* we already compared the value of flags, and
   * BUS_MATCH_CLIENT_IS_EAVESDROPPING does not have another struct member */

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
  if (a->flags & BUS_MATCH_ARGS)
    {
      int i;
      
      if (a->args_len != b->args_len)
        return FALSE;
      
      i = 0;
      while (i < a->args_len)
        {
1527 1528
          int length;

1529 1530 1531
          if ((a->args[i] != NULL) != (b->args[i] != NULL))
            return FALSE;

1532 1533 1534
          if (a->arg_lens[i] != b->arg_lens[i])
            return FALSE;

1535
          length = a->arg_lens[i] & ~BUS_MATCH_ARG_FLAGS;
1536

1537 1538 1539
          if (a->args[i] != NULL)
            {
              _dbus_assert (b->args[i] != NULL);
1540
              if (memcmp (a->args[i], b->args[i], length) != 0)
1541 1542 1543 1544 1545 1546 1547
                return FALSE;
            }
          
          ++i;
        }
    }
  
1548 1549 1550 1551
  return TRUE;
}

static void
1552
bus_matchmaker_remove_rule_link (DBusList       **rules,
1553 1554 1555 1556 1557
                                 DBusList        *link)
{
  BusMatchRule *rule = link->data;
  
  bus_connection_remove_match_rule (rule->matches_go_to, rule);
1558
  _dbus_list_remove_link (rules, link);
1559 1560 1561 1562 1563 1564

#ifdef DBUS_ENABLE_VERBOSE_MODE
  {
    char *s = match_rule_to_string (rule);

    _dbus_verbose ("Removed match rule %s for connection %p\n",
1565
                   s ? s : "nomem", rule->matches_go_to);
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    dbus_free (s);
  }
#endif
  
  bus_match_rule_unref (rule);  
}

void
bus_matchmaker_remove_rule (BusMatchmaker   *matchmaker,
                            BusMatchRule    *rule)
{
1577 1578
  DBusList **rules;

1579 1580 1581 1582
  _dbus_verbose ("Removing rule with message_type %d, interface %s\n",
                 rule->message_type,
                 rule->interface != NULL ? rule->interface : "<null>");

1583
  bus_connection_remove_match_rule (rule->matches_go_to, rule);
1584

1585 1586 1587 1588 1589 1590 1591 1592
  rules = bus_matchmaker_get_rules (matchmaker, rule->message_type,
                                    rule->interface, FALSE);

  /* We should only be asked to remove a rule by identity right after it was
   * added, so there should be a list for it.
   */
  _dbus_assert (rules != NULL);

1593
  _dbus_list_remove (rules, rule);
1594 1595
  bus_matchmaker_gc_rules (matchmaker, rule->message_type, rule->interface,
      rules);
1596 1597 1598 1599 1600 1601

#ifdef DBUS_ENABLE_VERBOSE_MODE
  {
    char *s = match_rule_to_string (rule);

    _dbus_verbose ("Removed match rule %s for connection %p\n",
1602
                   s ? s : "nomem", rule->matches_go_to);
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    dbus_free (s);
  }
#endif
  
  bus_match_rule_unref (rule);
}

/* Remove a single rule which is equal to the given rule by value */
dbus_bool_t
bus_matchmaker_remove_rule_by_value (BusMatchmaker   *matchmaker,
                                     BusMatchRule    *value,
                                     DBusError       *error)
{
1616
  DBusList **rules;
1617
  DBusList *link = NULL;
1618

1619 1620 1621
  _dbus_verbose ("Removing rule by value with message_type %d, interface %s\n",
                 value->message_type,
                 value->interface != NULL ? value->interface : "<null>");
1622

1623 1624 1625 1626
  rules = bus_matchmaker_get_rules (matchmaker, value->message_type,
      value->interface, FALSE);

  if (rules != NULL)
1627
    {
1628 1629 1630 1631 1632 1633 1634 1635
      /* we traverse backward because bus_connection_remove_match_rule()
       * removes the most-recently-added rule
       */
      link = _dbus_list_get_last_link (rules);
      while (link != NULL)
        {
          BusMatchRule *rule;
          DBusList *prev;
1636

1637 1638
          rule = link->data;
          prev = _dbus_list_get_prev_link (rules, link);
1639

1640 1641 1642 1643 1644
          if (match_rule_equal (rule, value))
            {
              bus_matchmaker_remove_rule_link (rules, link);
              break;
            }
1645

1646 1647
          link = prev;
        }
1648 1649 1650 1651 1652 1653 1654 1655 1656
    }

  if (link == NULL)
    {
      dbus_set_error (error, DBUS_ERROR_MATCH_RULE_NOT_FOUND,
                      "The given match rule wasn't found and can't be removed");
      return FALSE;
    }

1657 1658 1659
  bus_matchmaker_gc_rules (matchmaker, value->message_type, value->interface,
      rules);

1660 1661 1662
  return TRUE;
}

1663 1664
static void
rule_list_remove_by_connection (DBusList       **rules,
1665
                                DBusConnection  *connection)
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
{
  DBusList *link;

  link = _dbus_list_get_first_link (rules);
  while (link != NULL)
    {
      BusMatchRule *rule;
      DBusList *next;

      rule = link->data;
      next = _dbus_list_get_next_link (rules, link);

1678
      if (rule->matches_go_to == connection)
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
        {
          bus_matchmaker_remove_rule_link (rules, link);
        }
      else if (((rule->flags & BUS_MATCH_SENDER) && *rule->sender == ':') ||
               ((rule->flags & BUS_MATCH_DESTINATION) && *rule->destination == ':'))
        {
          /* The rule matches to/from a base service, see if it's the
           * one being disconnected, since we know this service name
           * will never be recycled.
           */
          const char *name;

1691
          name = bus_connection_get_name (connection);
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
          _dbus_assert (name != NULL); /* because we're an active connection */

          if (((rule->flags & BUS_MATCH_SENDER) &&
               strcmp (rule->sender, name) == 0) ||
              ((rule->flags & BUS_MATCH_DESTINATION) &&
               strcmp (rule->destination, name) == 0))
            {
              bus_matchmaker_remove_rule_link (rules, link);
            }
        }

      link = next;
    }
}

1707 1708
void
bus_matchmaker_disconnected (BusMatchmaker   *matchmaker,
1709
                             DBusConnection  *connection)
1710
{
1711
  int i;
1712 1713 1714 1715 1716 1717 1718 1719

  /* FIXME
   *
   * This scans all match rules on the bus. We could avoid that
   * for the rules belonging to the connection, since we keep
   * a list of those; but for the rules that just refer to
   * the connection we'd need to do something more elaborate.
   */
1720

1721
  _dbus_assert (bus_connection_is_active (connection));
1722

1723
  _dbus_verbose ("Removing all rules for connection %p\n", connection);
1724

1725
  for (i = DBUS_MESSAGE_TYPE_INVALID; i < DBUS_NUM_MESSAGE_TYPES; i++)
1726
    {
1727 1728 1729
      RulePool *p = matchmaker->rules_by_type + i;
      DBusHashIter iter;

1730
      rule_list_remove_by_connection (&p->rules_without_iface, connection);
1731 1732 1733 1734 1735

      _dbus_hash_iter_init (p->rules_by_iface, &iter);
      while (_dbus_hash_iter_next (&iter))
        {
          DBusList **items = _dbus_hash_iter_get_value (&iter);
1736

1737
          rule_list_remove_by_connection (items, connection);
1738 1739 1740 1741

          if (*items == NULL)
            _dbus_hash_iter_remove_entry (&iter);
        }
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
    }
}

static dbus_bool_t
connection_is_primary_owner (DBusConnection *connection,
                             const char     *service_name)
{
  BusService *service;
  DBusString str;
  BusRegistry *registry;

1753 1754
  _dbus_assert (connection != NULL);
  
1755 1756 1757 1758 1759 1760 1761 1762
  registry = bus_connection_get_registry (connection);

  _dbus_string_init_const (&str, service_name);
  service = bus_registry_lookup (registry, &str);

  if (service == NULL)
    return FALSE; /* Service doesn't exist so connection can't own it. */

1763
  return bus_service_get_primary_owners_connection (service) == connection;
1764 1765
}

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
static dbus_bool_t
str_has_prefix (const char *str, const char *prefix)
{
  size_t prefix_len;
  prefix_len = strlen (prefix);
  if (strncmp (str, prefix, prefix_len) == 0)
    return TRUE;
  else
    return FALSE;
}

1777 1778 1779 1780
static dbus_bool_t
match_rule_matches (BusMatchRule    *rule,
                    DBusConnection  *sender,
                    DBusConnection  *addressed_recipient,
1781 1782
                    DBusMessage     *message,
                    BusMatchFlags    already_matched)
1783
{
1784
  dbus_bool_t wants_to_eavesdrop = FALSE;
1785 1786
  int flags;

1787 1788 1789 1790
  /* All features of the match rule are AND'd together,
   * so FALSE if any of them don't match.
   */

1791 1792 1793 1794
  /* sender/addressed_recipient of #NULL may mean bus driver,
   * or for addressed_recipient may mean a message with no
   * specific recipient (i.e. a signal)
   */
1795 1796 1797 1798

  /* Don't bother re-matching features we've already checked implicitly. */
  flags = rule->flags & (~already_matched);

1799 1800 1801
  if (flags & BUS_MATCH_CLIENT_IS_EAVESDROPPING)
    wants_to_eavesdrop = TRUE;

1802
  if (flags & BUS_MATCH_MESSAGE_TYPE)
1803 1804 1805 1806 1807 1808 1809
    {
      _dbus_assert (rule->message_type != DBUS_MESSAGE_TYPE_INVALID);

      if (rule->message_type != dbus_message_get_type (message))
        return FALSE;
    }

1810
  if (flags & BUS_MATCH_INTERFACE)
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    {
      const char *iface;

      _dbus_assert (rule->interface != NULL);

      iface = dbus_message_get_interface (message);
      if (iface == NULL)
        return FALSE;

      if (strcmp (iface, rule->interface) != 0)
        return FALSE;
    }

1824
  if (flags & BUS_MATCH_MEMBER)
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    {
      const char *member;

      _dbus_assert (rule->member != NULL);

      member = dbus_message_get_member (message);
      if (member == NULL)
        return FALSE;

      if (strcmp (member, rule->member) != 0)
        return FALSE;
    }

1838
  if (flags & BUS_MATCH_SENDER)
1839 1840 1841
    {
      _dbus_assert (rule->sender != NULL);

1842 1843 1844
      if (sender == NULL)
        {
          if (strcmp (rule->sender,
1845
                      DBUS_SERVICE_DBUS) != 0)
1846 1847 1848 1849 1850 1851 1852
            return FALSE;
        }
      else
        {
          if (!connection_is_primary_owner (sender, rule->sender))
            return FALSE;
        }
1853 1854
    }

1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
  /* Note: this part is relevant for eavesdropper rules:
   * Two cases:
   * 1) rule has a destination to be matched
   *   (flag BUS_MATCH_DESTINATION present). Rule will match if:
   *   - rule->destination matches the addressed_recipient
   *   AND
   *   - wants_to_eavesdrop=TRUE
   *
   *   Note: (the case in which addressed_recipient is the actual rule owner
   *   is handled elsewere in dispatch.c:bus_dispatch_matches().
   *
   * 2) rule has no destination. Rule will match if:
   *    - message has no specified destination (ie broadcasts)
   *      (Note: this will rule out unicast method calls and unicast signals,
   *      fixing FDO#269748)
   *    OR
   *    - wants_to_eavesdrop=TRUE (destination-catch-all situation)
   */
1873
  if (flags & BUS_MATCH_DESTINATION)
1874 1875 1876 1877 1878 1879 1880
    {
      const char *destination;

      _dbus_assert (rule->destination != NULL);

      destination = dbus_message_get_destination (message);
      if (destination == NULL)
1881 1882 1883 1884 1885 1886
        /* broadcast, but this rule specified a destination: no match */
        return FALSE;

      /* rule owner does not intend to eavesdrop: we'll deliver only msgs
       * directed to it, NOT MATCHING */
      if (!wants_to_eavesdrop)
1887 1888
        return FALSE;

1889
      if (addressed_recipient == NULL)
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
        {
          /* If the message is going to be delivered to the dbus-daemon
           * itself, its destination will be "org.freedesktop.DBus",
           * which we again match against the rule (see bus_dispatch()
           * in bus/dispatch.c, which checks for o.fd.DBus first).
           *
           * If we are monitoring and we don't know who is going to receive
           * the message (for instance because they haven't been activated yet),
           * assume they will own the requested destination name and no other,
           * and match the rule's destination against that.
           */
          if (strcmp (rule->destination, destination) != 0)
1902 1903 1904 1905 1906 1907 1908
            return FALSE;
        }
      else
        {
          if (!connection_is_primary_owner (addressed_recipient, rule->destination))
            return FALSE;
        }
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
    } else { /* no destination in rule */
        dbus_bool_t msg_is_broadcast;

        _dbus_assert (rule->destination == NULL);

        msg_is_broadcast = (dbus_message_get_destination (message) == NULL);

        if (!wants_to_eavesdrop && !msg_is_broadcast)
          return FALSE;

        /* if we are here rule owner intends to eavesdrop
         * OR
         * message is being broadcasted */
1922 1923
    }

1924
  if (flags & BUS_MATCH_PATH)
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
    {
      const char *path;

      _dbus_assert (rule->path != NULL);

      path = dbus_message_get_path (message);
      if (path == NULL)
        return FALSE;

      if (strcmp (path, rule->path) != 0)
        return FALSE;
    }

1938
  if (flags & BUS_MATCH_PATH_NAMESPACE)
1939 1940
    {
      const char *path;
1941
      int len;
1942

1943
      _dbus_assert (rule->path != NULL);
1944 1945 1946 1947 1948

      path = dbus_message_get_path (message);
      if (path == NULL)
        return FALSE;

1949
      if (!str_has_prefix (path, rule->path))
1950
        return FALSE;
1951

1952
      len = strlen (rule->path);
1953 1954 1955

      /* Check that the actual argument is within the expected
       * namespace, rather than just starting with that string,
1956 1957
       * by checking that the matched prefix is followed by a '/'
       * or the end of the path.
1958 1959 1960
       *
       * Special case: the only valid path of length 1, "/",
       * matches everything.
1961
       */
1962
      if (len > 1 && path[len] != '\0' && path[len] != '/')
1963
        return FALSE;
1964 1965
    }

1966
  if (flags & BUS_MATCH_ARGS)
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
    {
      int i;
      DBusMessageIter iter;
      
      _dbus_assert (rule->args != NULL);

      dbus_message_iter_init (message, &iter);
      
      i = 0;
      while (i < rule->args_len)
        {
          int current_type;
          const char *expected_arg;
1980
          int expected_length;
1981
          dbus_bool_t is_path, is_namespace;
1982 1983

          expected_arg = rule->args[i];