3e247bea9f279b2b695b5f31bc47b289bb3ab5af
[platform/upstream/dbus.git] / bus / kdbus-d.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* kdbus-d.c  kdbus related daemon functions
3  *
4  * Copyright (C) 2013  Samsung Electronics
5  *
6  * Licensed under the Academic Free License version 2.1
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version and under the terms of the GNU
12  * Lesser General Public License as published by the
13  * Free Software Foundation; either version 2.1 of the License, or (at
14  * your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
24  *
25  */
26
27 #include <dbus/dbus-connection-internal.h>
28 #include "kdbus-d.h"
29 #define KDBUS_FOR_SBB
30 #include <dbus/kdbus.h>
31 #include <dbus/dbus-bus.h>
32 #include "dispatch.h"
33 #include <dbus/kdbus-common.h>
34 #include <dbus/dbus-transport.h>
35 #include <dbus/dbus-transport-kdbus.h>
36 #include "connection.h"
37 #include "activation.h"
38 #include "services.h"
39 #include <dbus/dbus-connection.h>
40
41 #include <utils.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <fcntl.h>
45 #include <unistd.h>
46 #include <errno.h>
47
48 /*
49  * Converts string with unique name into __u64 id number. If the name is not unique, sets error.
50  */
51 __u64 sender_name_to_id(const char* name, DBusError* error)
52 {
53         __u64 sender_id = 0;
54
55         if(!strncmp(name, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
56                 sender_id = strtoull(&name[3], NULL, 10);
57         else
58                 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Could not convert sender of the message into kdbus unique id");
59
60         return sender_id;
61 }
62
63 /**
64  * Seeks key in rule string, and duplicates value of the key into pValue.
65  * Because of the duplication, pValue must be freed after use.
66  *
67  * @param rule rule to look through
68  * @param key key to look for
69  * @param pValue pointer to value of the key found
70  * @return length of the value string, 0 means not found
71  */
72 static int parse_match_key(const char *rule, const char* key, char** pValue)
73 {
74   const char* pBegin;
75   const char* pValueEnd;
76   int value_length = 0;
77
78   pBegin = strstr(rule, key);
79   if(pBegin)
80   {
81     pBegin += strlen(key);
82     pValueEnd = strchr(pBegin, '\'');
83     if(pValueEnd)
84     {
85       value_length = pValueEnd - pBegin;
86       *pValue = strndup(pBegin, value_length);
87       if(*pValue)
88         _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue);
89     }
90   }
91   return value_length;
92 }
93
94 /**
95  * Adds a match rule to match broadcast messages going through the message bus.
96  * Do no affect messages addressed directly.
97  *
98  * The "rule" argument is the string form of a match rule.
99  *
100  * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism.
101  * Current mapping:
102  * interface match key mapped to bloom
103  * sender match key mapped to src_name
104  *
105  * @param transport transport
106  * @param id id of connection for which the rule is to be added
107  * @param rule textual form of match rule
108   */
109 dbus_bool_t add_match_kdbus (DBusTransport* transport, __u64 id, const char *rule)
110 {
111   struct kdbus_cmd_match* pCmd_match;
112   struct kdbus_item *pItem;
113   __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
114   uint64_t size;
115   int name_size;
116   char* pName = NULL;
117   char* pInterface = NULL;
118   dbus_bool_t ret_value = FALSE;
119   int fd;
120   __u64 bloom_size;
121
122   if(!_dbus_transport_get_socket_fd(transport, &fd))
123     return FALSE;
124
125   bloom_size = dbus_transport_get_bloom_size(transport);
126
127   /*parsing rule and calculating size of command*/
128   size = sizeof(struct kdbus_cmd_match);
129   if(parse_match_key(rule, "interface='", &pInterface))       /*actual size is not important for interface because bloom size is defined by bus*/
130     size += KDBUS_PART_HEADER_SIZE + bloom_size;
131   name_size = parse_match_key(rule, "sender='", &pName);
132   if(name_size)
133   {
134     if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
135     {
136       src_id = strtoull(&pName[3], NULL, 10);
137       free(pName);
138       pName = NULL;
139     }
140     else
141       size += KDBUS_ITEM_SIZE(name_size + 1);  //well known name
142   }
143
144   pCmd_match = alloca(size);
145   if(pCmd_match == NULL)
146     goto out;
147
148   pCmd_match->id = id;
149   pCmd_match->cookie = id;
150   pCmd_match->size = size;
151   pCmd_match->src_id = src_id;
152
153   pItem = pCmd_match->items;
154   if(pName)
155   {
156     pItem->type = KDBUS_MATCH_SRC_NAME;
157     pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
158     memcpy(pItem->str, pName, strlen(pName) + 1);
159     pItem = KDBUS_PART_NEXT(pItem);
160   }
161   if(pInterface)
162   {
163     pItem->type = KDBUS_MATCH_BLOOM;
164     pItem->size = KDBUS_PART_HEADER_SIZE + bloom_size;
165     strncpy(pItem->data, pInterface, bloom_size);
166   }
167
168   if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
169     _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
170   else
171   {
172     _dbus_verbose("Added match bus rule %s for id:%llu\n", rule, (unsigned long long)id);
173     ret_value = TRUE;
174   }
175
176 out:
177   if(pName)
178     free(pName);
179   if(pInterface)
180     free(pInterface);
181   return ret_value;
182 }
183
184 /**
185  * Opposing to dbus, in kdbus removes all match rules with given
186  * cookie, which in this implementation is equal to uniqe id.
187  *
188  * @param transport transport
189  * @param id connection id for which rules are to be removed
190  */
191 dbus_bool_t remove_match_kdbus (DBusTransport* transport, __u64 id)
192 {
193   struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
194   int fd;
195
196   if(!_dbus_transport_get_socket_fd(transport, &fd))
197     return FALSE;
198
199   cmd.cookie = id;
200   cmd.id = id;
201   cmd.size = sizeof(struct kdbus_cmd_match);
202
203   if(ioctl(fd, KDBUS_CMD_MATCH_REMOVE, &cmd))
204   {
205     _dbus_verbose("Failed removing match rule for id: %llu; error: %d, %m\n", (unsigned long long)id, errno);
206     return FALSE;
207   }
208   else
209   {
210     _dbus_verbose("Match rule removed correctly.\n");
211     return TRUE;
212   }
213 }
214
215 /**
216  * Performs kdbus query of id of the given name
217  *
218  * @param name name to query for
219  * @param transport transport
220  * @param pInfo nameInfo structure address to store info about the name
221  * @return 0 on success, -errno if failed
222  */
223 int kdbus_NameQuery(const char* name, DBusTransport* transport, struct nameInfo* pInfo)
224 {
225   struct kdbus_cmd_name_info *msg;
226   struct kdbus_item *item;
227   uint64_t size;
228   int ret;
229   uint64_t item_size;
230   int fd;
231
232   pInfo->sec_label_len = 0;
233   pInfo->sec_label = NULL;
234
235   if(!_dbus_transport_get_socket_fd(transport, &fd))
236     return -EPERM;
237
238   item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
239   item_size = (item_size < 56) ? 56 : item_size;  //at least 56 bytes are needed by kernel to place info about name, otherwise error
240   size = sizeof(struct kdbus_cmd_name_info) + item_size;
241
242   msg = malloc(size);
243   if (!msg)
244   {
245     _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
246     return -errno;
247   }
248
249   memset(msg, 0, size);
250   msg->size = size;
251     if((name[0] == ':') && (name[1] == '1') && (name[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
252       msg->id = strtoull(&name[3], NULL, 10);
253     else
254       msg->id = 0;
255
256   item = msg->items;
257   item->type = KDBUS_NAME_INFO_ITEM_NAME;
258   item->size = item_size;
259   memcpy(item->str, name, strlen(name) + 1);
260
261   again:
262   ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg);
263   if (ret < 0)
264   {
265     if(errno == EINTR)
266       goto again;
267     if(errno == EAGAIN)
268         goto again;
269     else if(ret == -ENOBUFS)
270     {
271       msg = realloc(msg, msg->size);  //prepare memory
272       if(msg != NULL)
273         goto again;
274     }
275     pInfo->uniqueId = 0;
276     ret = -errno;
277   }
278   else
279   {
280     pInfo->uniqueId = msg->id;
281     pInfo->userId = msg->creds.uid;
282     pInfo->processId = msg->creds.pid;
283     item = msg->items;
284     while((uint8_t *)(item) < (uint8_t *)(msg) + msg->size)
285     {
286       if(item->type == KDBUS_NAME_INFO_ITEM_SECLABEL)
287       {
288           pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1;
289         if(pInfo->sec_label_len != 0)
290         {
291           pInfo->sec_label = malloc(pInfo->sec_label_len);
292           if(pInfo->sec_label == NULL)
293             ret = -1;
294           else
295             memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len);
296         }
297         break;
298       }
299       item = KDBUS_PART_NEXT(item);
300     }
301   }
302
303   free(msg);
304   return ret;
305 }
306
307 /*
308  * Creates kdbus bus of given type.
309  */
310 char* make_kdbus_bus(DBusBusType type, const char* address, DBusError *error)
311 {
312     struct {
313         struct kdbus_cmd_bus_make head;
314         uint64_t n_size;
315         uint64_t n_type;
316         char name[64];
317     } __attribute__ ((__aligned__(8))) bus_make;
318
319     int fdc, ret;
320     char *bus;
321     char *addr_value;
322
323     _dbus_verbose("Opening /dev/kdbus/control\n");
324     fdc = open("/dev/kdbus/control", O_RDWR|O_CLOEXEC);
325     if (fdc < 0)
326     {
327         _dbus_verbose("--- error %d (%m)\n", fdc);
328         dbus_set_error(error, DBUS_ERROR_FAILED, "Opening /dev/kdbus/control failed: %d (%m)", fdc);
329         return NULL;
330     }
331
332     addr_value = strchr(address, ':') + 1;
333
334     memset(&bus_make, 0, sizeof(bus_make));
335     bus_make.head.bloom_size = 64;
336     bus_make.head.flags = KDBUS_MAKE_ACCESS_WORLD;
337     if(!strcmp(addr_value, "sbb"))
338       bus_make.head.flags |= KDBUS_MAKE_SBB_OFFSET;
339
340     if(type == DBUS_BUS_SYSTEM)
341         snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus-%s", getuid(), "system");
342     else if(type == DBUS_BUS_SESSION)
343         snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus", getuid());
344     else
345         snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus-%u", getuid(), getpid());
346
347     bus_make.n_type = KDBUS_MAKE_NAME;
348     bus_make.n_size = KDBUS_PART_HEADER_SIZE + strlen(bus_make.name) + 1;
349     bus_make.head.size = sizeof(struct kdbus_cmd_bus_make) + bus_make.n_size;
350
351     _dbus_verbose("Creating bus '%s'\n", bus_make.name);
352     ret = ioctl(fdc, KDBUS_CMD_BUS_MAKE, &bus_make);
353     if (ret)
354     {
355         _dbus_verbose("--- error %d (%m)\n", ret);
356         dbus_set_error(error, DBUS_ERROR_FAILED, "Creating bus '%s' failed: %d (%m)", bus_make.name, fdc);
357         return NULL;
358     }
359
360     if (asprintf(&bus, "kdbus:path=/dev/kdbus/%s/bus", bus_make.name) < 0)
361     {
362         BUS_SET_OOM (error);
363         return NULL;
364     }
365
366     _dbus_verbose("Return value '%s'\n", bus);
367         return bus;
368 }
369
370 /*
371  * Minimal server init needed by context to go further.
372  */
373 DBusServer* empty_server_init(char* address)
374 {
375         return dbus_server_init_mini(address);
376 }
377
378 static dbus_bool_t add_matches_for_kdbus_broadcasts(DBusConnection* connection)
379 {
380   struct kdbus_cmd_match* pCmd_match;
381   struct kdbus_item *pItem;
382   uint64_t size;
383   int fd;
384   DBusTransport *transport;
385   const char* unique_name;
386
387   transport = dbus_connection_get_transport(connection);
388
389   if(!_dbus_transport_get_socket_fd(transport, &fd))
390     {
391       errno = EPERM;
392       return FALSE;
393     }
394
395   size = sizeof(struct kdbus_cmd_match);
396   size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2;  /*3 name related items plus 2 id related items*/
397
398   pCmd_match = alloca(size);
399   if(pCmd_match == NULL)
400     {
401       errno = ENOMEM;
402       return FALSE;
403     }
404
405   unique_name = dbus_bus_get_unique_name(connection);
406
407   pCmd_match->id = strtoull(&unique_name[3], NULL, 10);
408   pCmd_match->cookie = 1;
409   pCmd_match->size = size;
410
411   pItem = pCmd_match->items;
412   pCmd_match->src_id = 0;
413   pItem->type = KDBUS_MATCH_NAME_CHANGE;
414   pItem->size = KDBUS_PART_HEADER_SIZE + 1;
415   pItem = KDBUS_PART_NEXT(pItem);
416   pItem->type = KDBUS_MATCH_NAME_ADD;
417   pItem->size = KDBUS_PART_HEADER_SIZE + 1;
418   pItem = KDBUS_PART_NEXT(pItem);
419   pItem->type = KDBUS_MATCH_NAME_REMOVE;
420   pItem->size = KDBUS_PART_HEADER_SIZE + 1;
421   pItem = KDBUS_PART_NEXT(pItem);
422   pItem->type = KDBUS_MATCH_ID_ADD;
423   pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
424   pItem = KDBUS_PART_NEXT(pItem);
425   pItem->type = KDBUS_MATCH_ID_REMOVE;
426   pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
427
428   if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
429     {
430       _dbus_verbose("Failed adding match rule for daemon, error: %d, %m\n", errno);
431       return FALSE;
432     }
433
434   _dbus_verbose("Added match rule for daemon correctly.\n");
435   return TRUE;
436 }
437
438 /*
439  * Connects daemon to bus created by him and adds matches for "system" broadcasts.
440  * Do not requests org.freedesktop.DBus name, because it's to early
441  * (some structures of BusContext are not ready yet).
442  */
443 DBusConnection* daemon_as_client(DBusBusType type, char* address, DBusError *error)
444 {
445   DBusConnection* connection;
446
447   dbus_bus_set_bus_connection_address(type, address);
448
449   connection = dbus_bus_get_private(type, error);  /*todo possibly could be optimised by using lower functions*/
450   if(connection == NULL)
451     return NULL;
452
453   if(!add_matches_for_kdbus_broadcasts(connection))
454     {
455       dbus_set_error (error, _dbus_error_from_errno (errno), "Could not add match for daemon, %s", _dbus_strerror_from_errno ());
456       goto failed;
457     }
458
459   if(dbus_error_is_set(error))
460     {
461       failed:
462       _dbus_connection_close_possibly_shared (connection);
463       dbus_connection_unref (connection);
464       connection = NULL;
465     }
466   else
467     _dbus_verbose ("Daemon connected as kdbus client.\n");
468
469   return connection;
470 }
471
472 /*
473  * Asks bus for org.freedesktop.DBus well-known name.
474  */
475 dbus_bool_t register_daemon_name(DBusConnection* connection)
476 {
477     DBusString daemon_name;
478     dbus_bool_t retval = FALSE;
479     BusTransaction *transaction;
480
481     _dbus_string_init_const(&daemon_name, DBUS_SERVICE_DBUS);
482     if(!register_kdbus_policy(DBUS_SERVICE_DBUS, dbus_connection_get_transport(connection), geteuid()))
483       return FALSE;
484
485     if(kdbus_request_name(connection, &daemon_name, 0, 0) != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
486        return FALSE;
487
488     transaction = bus_transaction_new (bus_connection_get_context(connection));
489     if (transaction == NULL)
490     {
491         kdbus_release_name(connection, &daemon_name, 0);
492         goto out;
493     }
494
495     if(!bus_registry_ensure (bus_connection_get_registry (connection), &daemon_name, connection, 0, transaction, NULL))
496     {
497         kdbus_release_name(connection, &daemon_name, 0);
498         goto out;
499     }
500
501     retval = TRUE;
502
503 out:
504         bus_transaction_cancel_and_free(transaction);
505     return retval;
506 }
507
508 dbus_uint32_t kdbus_request_name(DBusConnection* connection, const DBusString *service_name, dbus_uint32_t flags, __u64 sender_id)
509 {
510         int fd;
511
512         _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
513
514         return request_kdbus_name(fd, _dbus_string_get_const_data(service_name), flags, sender_id);
515 }
516
517 dbus_uint32_t kdbus_release_name(DBusConnection* connection, const DBusString *service_name, __u64 sender_id)
518 {
519         int fd;
520
521         _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
522
523         return release_kdbus_name(fd, _dbus_string_get_const_data(service_name), sender_id);
524 }
525
526 /*
527  * Asks kdbus for well-known names registered on the bus
528  */
529 dbus_bool_t kdbus_list_services (DBusConnection* connection, char ***listp, int *array_len)
530 {
531         int fd;
532         struct kdbus_cmd_names* pCmd;
533         __u64 cmd_size;
534         dbus_bool_t ret_val = FALSE;
535         char** list;
536         int list_len = 0;
537         int i = 0;
538         int j;
539
540         cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1);
541         pCmd = malloc(cmd_size);
542         if(pCmd == NULL)
543                 goto out;
544         pCmd->size = cmd_size;
545
546         _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
547
548 again:
549         cmd_size = 0;
550         if(ioctl(fd, KDBUS_CMD_NAME_LIST, pCmd))
551         {
552                 if(errno == EINTR)
553                         goto again;
554                 if(errno == ENOBUFS)                    //buffer to small to put all names into it
555                         cmd_size = pCmd->size;          //here kernel tells how much memory it needs
556                 else
557                 {
558                         _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
559                         goto out;
560                 }
561         }
562         if(cmd_size)  //kernel needs more memory
563         {
564                 pCmd = realloc(pCmd, cmd_size);  //prepare memory
565                 if(pCmd == NULL)
566                         return FALSE;
567                 goto again;                                             //and try again
568         }
569         else
570         {
571                 struct kdbus_cmd_name* pCmd_name;
572
573                 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
574                         list_len++;
575
576                 list = malloc(sizeof(char*) * (list_len + 1));
577                 if(list == NULL)
578                         goto out;
579
580                 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
581                 {
582                         list[i] = strdup(pCmd_name->name);
583                         if(list[i] == NULL)
584                         {
585                                 for(j=0; j<i; j++)
586                                         free(list[j]);
587                                 free(list);
588                                 goto out;
589                         }
590                         _dbus_verbose ("Name %d: %s\n", i, list[i]);
591                         ++i;
592                 }
593                 list[i] = NULL;
594         }
595
596         *array_len = list_len;
597         *listp = list;
598         ret_val = TRUE;
599
600 out:
601         if(pCmd)
602                 free(pCmd);
603         return ret_val;
604 }
605
606 /*
607  * Asks kdbus for list of connections being in the queue to own
608  * given well-known name. The list includes the owner of the name on the
609  * first position.
610  */
611 dbus_bool_t kdbus_list_queued (DBusConnection *connection, DBusList  **return_list,
612                                const char *name, DBusError  *error)
613 {
614   int fd;
615   struct kdbus_cmd_names* pCmd;
616   __u64 cmd_size;
617   dbus_bool_t ret_val = FALSE;
618   int name_length;
619
620   _dbus_assert (*return_list == NULL);
621
622   name_length = strlen(name) + 1;
623   cmd_size = sizeof(struct kdbus_cmd_names) + sizeof(struct kdbus_cmd_name) + name_length;
624   pCmd = malloc(cmd_size);
625   if(pCmd == NULL)
626     goto out;
627   pCmd->size = cmd_size;
628   pCmd->names[0].id = 0;
629   pCmd->names[0].size =  sizeof(struct kdbus_cmd_name) + name_length;
630   memcpy(pCmd->names[0].name, name, name_length);
631   _dbus_verbose ("Asking for queued owners of %s\n", pCmd->names[0].name);
632
633   _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
634
635   again:
636   cmd_size = 0;
637   if(ioctl(fd, KDBUS_CMD_NAME_LIST_QUEUED, pCmd))
638     {
639       if(errno == EINTR)
640         goto again;
641       if(errno == ENOBUFS)      //buffer to small to put all names into it
642         cmd_size = pCmd->size;    //here kernel tells how much memory it needs
643       else if(errno == ENOENT)
644         {
645           dbus_set_error (error, DBUS_ERROR_NAME_HAS_NO_OWNER,
646                       "Could not get owners of name '%s': no such name", name);
647           free(pCmd);
648           return FALSE;
649         }
650       else
651         {
652           _dbus_verbose("kdbus error asking for queued owners list: err %d (%m)\n",errno);
653           goto out;
654         }
655     }
656   if(cmd_size)  //kernel needs more memory
657     {
658       pCmd = realloc(pCmd, cmd_size);  //prepare memory
659       if(pCmd == NULL)
660         return FALSE;
661       goto again;           //and try again
662     }
663   else
664     {
665       struct kdbus_cmd_name* pCmd_name;
666
667       for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
668         {
669           char *uname = NULL;
670
671           _dbus_verbose ("Got queued owner id: %llu\n", (unsigned long long)pCmd_name->id);
672           uname = malloc(snprintf(uname, 0, ":1.%llu0", (unsigned long long)pCmd_name->id));
673           if(uname == NULL)
674             goto out;
675           sprintf(uname, ":1.%llu", (unsigned long long int)pCmd_name->id);
676           if (!_dbus_list_append (return_list, uname))
677             goto out;
678         }
679     }
680
681   ret_val = TRUE;
682
683   out:
684   if(pCmd)
685     free(pCmd);
686   if(ret_val == FALSE)
687     {
688       DBusList *link;
689
690       dbus_set_error (error, _dbus_error_from_errno (errno),
691           "Failed to list queued owners of \"%s\": %s",
692           name, _dbus_strerror (errno));
693
694       link = _dbus_list_get_first_link (return_list);
695       while (link != NULL)
696         {
697           DBusList *next = _dbus_list_get_next_link (return_list, link);
698
699           if(link->data != NULL)
700             free(link->data);
701
702           _dbus_list_free_link (link);
703           link = next;
704         }
705     }
706
707   return ret_val;
708 }
709
710 /*
711  *  Register match rule in kdbus on behalf of sender of the message
712  */
713 dbus_bool_t kdbus_add_match_rule (DBusConnection* connection, DBusMessage* message, const char* text, DBusError* error)
714 {
715         __u64 sender_id;
716
717         sender_id = sender_name_to_id(dbus_message_get_sender(message), error);
718         if(dbus_error_is_set(error))
719                 return FALSE;
720
721         if(!add_match_kdbus (dbus_connection_get_transport(connection), sender_id, text))
722         {
723               dbus_set_error (error, _dbus_error_from_errno (errno), "Could not add match for id:%d, %s",
724                               sender_id, _dbus_strerror_from_errno ());
725               return FALSE;
726         }
727
728         return TRUE;
729 }
730
731 /*
732  *  Removes match rule in kdbus on behalf of sender of the message
733  */
734 dbus_bool_t kdbus_remove_match (DBusConnection* connection, DBusMessage* message, DBusError* error)
735 {
736         __u64 sender_id;
737
738         sender_id = sender_name_to_id(dbus_message_get_sender(message), error);
739         if(dbus_error_is_set(error))
740                 return FALSE;
741
742         if(!remove_match_kdbus (dbus_connection_get_transport(connection), sender_id))
743         {
744               dbus_set_error (error, _dbus_error_from_errno (errno), "Could not remove match rules for id:%d", sender_id);
745               return FALSE;
746         }
747
748         return TRUE;
749 }
750
751 int kdbus_get_name_owner(DBusConnection* connection, const char* name, char* owner)
752 {
753   int ret;
754   struct nameInfo info;
755
756   ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
757   if(ret == 0) //unique id of the name
758   {
759     sprintf(owner, ":1.%llu", (unsigned long long int)info.uniqueId);
760     _dbus_verbose("Unique name discovered:%s\n", owner);
761   }
762   else if(ret != -ENOENT)
763     _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
764
765   return ret;
766 }
767
768 /*
769  *  Asks kdbus for uid of the owner of the name given in the message
770  */
771 dbus_bool_t kdbus_get_unix_user(DBusConnection* connection, const char* name, unsigned long* uid, DBusError* error)
772 {
773   struct nameInfo info;
774   int inter_ret;
775   dbus_bool_t ret = FALSE;
776
777   inter_ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
778   if(inter_ret == 0) //name found
779   {
780     _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId);
781     *uid = info.userId;
782     return TRUE;
783   }
784   else if(inter_ret == -ENOENT)  //name has no owner
785     {
786       _dbus_verbose ("Name %s has no owner.\n", name);
787       dbus_set_error (error, DBUS_ERROR_FAILED, "Could not get UID of name '%s': no such name", name);
788     }
789
790   else
791   {
792     _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno);
793     dbus_set_error (error, DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name);
794   }
795
796   return ret;
797 }
798
799 /*
800  *  Asks kdbus for pid of the owner of the name given in the message
801  */
802 dbus_bool_t kdbus_get_connection_unix_process_id(DBusConnection* connection, const char* name, unsigned long* pid, DBusError* error)
803 {
804         struct nameInfo info;
805         int inter_ret;
806         dbus_bool_t ret = FALSE;
807
808         inter_ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
809         if(inter_ret == 0) //name found
810         {
811                 _dbus_verbose("Process id:%llu\n", (unsigned long long) info.processId);
812                 *pid = info.processId;
813                 return TRUE;
814         }
815         else if(inter_ret == -ENOENT)  //name has no owner
816                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not get PID of name '%s': no such name", name);
817         else
818         {
819                 _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno);
820                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not determine PID for '%s'", name);
821         }
822
823         return ret;
824 }
825
826 /*
827  *  Asks kdbus for selinux_security_context of the owner of the name given in the message
828  */
829 dbus_bool_t kdbus_get_connection_unix_selinux_security_context(DBusConnection* connection, DBusMessage* message, DBusMessage* reply, DBusError* error)
830 {
831         char* name = NULL;
832         struct nameInfo info;
833         int inter_ret;
834         dbus_bool_t ret = FALSE;
835
836         dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
837         inter_ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
838         if(inter_ret == -ENOENT)  //name has no owner
839                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not get security context of name '%s': no such name", name);
840         else if(inter_ret < 0)
841         {
842                 _dbus_verbose("kdbus error determining security context: err %d (%m)\n", errno);
843                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not determine security context for '%s'", name);
844         }
845         else
846         {
847                 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
848                 {
849                       _DBUS_SET_OOM (error);
850                       return FALSE;
851                 }
852                 ret = TRUE;
853         }
854
855         return ret;
856 }
857
858 /**
859  * Gets the UNIX user ID of the connection from kdbus, if known. Returns #TRUE if
860  * the uid is filled in.  Always returns #FALSE on non-UNIX platforms
861  * for now., though in theory someone could hook Windows to NIS or
862  * something.  Always returns #FALSE prior to authenticating the
863  * connection.
864  *
865  * The UID of is only read by bus daemon from kdbus. You can not
866  * call this function from client side of the connection.
867  *
868  * You can ask the bus to tell you the UID of another connection though
869  * if you like; this is done with dbus_bus_get_unix_user().
870  *
871  * @param connection the connection
872  * @param uid return location for the user ID
873  * @returns #TRUE if uid is filled in with a valid user ID
874  */
875 dbus_bool_t
876 dbus_connection_get_unix_user (DBusConnection *connection,
877                                unsigned long  *uid)
878 {
879   _dbus_return_val_if_fail (connection != NULL, FALSE);
880   _dbus_return_val_if_fail (uid != NULL, FALSE);
881
882   if(bus_context_is_kdbus(bus_connection_get_context (connection)))
883     return kdbus_get_unix_user(connection, bus_connection_get_name(connection), uid, NULL);
884
885   return dbus_connection_get_unix_user_dbus(connection, uid);
886 }
887
888 /**
889  * Gets the process ID of the connection if any.
890  * Returns #TRUE if the pid is filled in.
891  *
892  * @param connection the connection
893  * @param pid return location for the process ID
894  * @returns #TRUE if uid is filled in with a valid process ID
895  */
896 dbus_bool_t
897 dbus_connection_get_unix_process_id (DBusConnection *connection,
898              unsigned long  *pid)
899 {
900   _dbus_return_val_if_fail (connection != NULL, FALSE);
901   _dbus_return_val_if_fail (pid != NULL, FALSE);
902
903   if(bus_context_is_kdbus(bus_connection_get_context (connection)))
904     return kdbus_get_connection_unix_process_id(connection, bus_connection_get_name(connection), pid, NULL);
905
906   return dbus_connection_get_unix_process_id_dbus(connection, pid);
907 }
908
909 /*
910  * Create connection structure for given name. It is needed to control starters - activatable services
911  * and for ListQueued method (as long as kdbus is not supporting it). This connections don't have it's own
912  * fd so it is set up on the basis of daemon's transport. Functionality of such connection is limited.
913  */
914 DBusConnection* create_phantom_connection(DBusConnection* connection, const char* name, DBusError* error)
915 {
916     DBusConnection *phantom_connection;
917     DBusString Sname;
918
919     _dbus_string_init_const(&Sname, name);
920
921     phantom_connection = _dbus_connection_new_for_used_transport (dbus_connection_get_transport(connection));
922     if(phantom_connection == NULL)
923         return FALSE;
924     if(!bus_connections_setup_connection(bus_connection_get_connections(connection), phantom_connection))
925     {
926         dbus_connection_unref_phantom(phantom_connection);
927         phantom_connection = NULL;
928         dbus_set_error (error, DBUS_ERROR_FAILED , "Name \"%s\" could not be acquired", name);
929         goto out;
930     }
931     if(!bus_connection_complete(phantom_connection, &Sname, error))
932     {
933         bus_connection_disconnected(phantom_connection);
934         phantom_connection = NULL;
935         goto out;
936     }
937
938     _dbus_verbose ("Created phantom connection for %s\n", bus_connection_get_name(phantom_connection));
939
940 out:
941     return phantom_connection;
942 }
943
944 /*
945  * Registers activatable services as kdbus starters.
946  */
947 dbus_bool_t register_kdbus_starters(DBusConnection* connection)
948 {
949     int i,j, len;
950     char **services;
951     dbus_bool_t retval = FALSE;
952     int fd;
953     BusTransaction *transaction;
954     DBusString name;
955     DBusTransport* transport;
956     unsigned long int euid;
957
958     transaction = bus_transaction_new (bus_connection_get_context(connection));
959     if (transaction == NULL)
960         return FALSE;
961
962     if (!bus_activation_list_services (bus_connection_get_activation (connection), &services, &len))
963         return FALSE;
964
965     transport = dbus_connection_get_transport(connection);
966     euid = geteuid();
967
968     if(!_dbus_transport_get_socket_fd (transport, &fd))
969       return FALSE;
970
971     _dbus_string_init(&name);
972
973     for(i=0; i<len; i++)
974     {
975         if(!register_kdbus_policy(services[i], transport, euid))
976           goto out;
977
978         if (request_kdbus_name(fd, services[i], (DBUS_NAME_FLAG_ALLOW_REPLACEMENT | KDBUS_NAME_STARTER) , 0) < 0)
979             goto out;
980
981         if(!_dbus_string_append(&name, services[i]))
982                 goto out;
983         if(!bus_registry_ensure (bus_connection_get_registry (connection), &name, connection,
984                         (DBUS_NAME_FLAG_ALLOW_REPLACEMENT | KDBUS_NAME_STARTER), transaction, NULL))
985                 goto out;
986         if(!_dbus_string_set_length(&name, 0))
987                 goto out;
988     }
989     retval = TRUE;
990
991 out:
992     if(retval == FALSE)
993     {
994         for(j=0; j<i; j++)
995             release_kdbus_name(fd, services[j], 0);
996     }
997     dbus_free_string_array (services);
998     _dbus_string_free(&name);
999     bus_transaction_cancel_and_free(transaction);
1000     return retval;
1001 }
1002
1003 /*
1004  * Updates kdbus starters (activatable services) after configuration was reloaded.
1005  * It releases all previous starters and registers all new.
1006  */
1007 dbus_bool_t update_kdbus_starters(DBusConnection* connection)
1008 {
1009     dbus_bool_t retval = FALSE;
1010     DBusList **services_old;
1011     DBusList *link;
1012     BusService *service = NULL;
1013     BusTransaction *transaction;
1014     int fd;
1015
1016     transaction = bus_transaction_new (bus_connection_get_context(connection));
1017     if (transaction == NULL)
1018         return FALSE;
1019
1020     if(!_dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd))
1021         goto out;
1022
1023     services_old = bus_connection_get_services_owned(connection);
1024     link = _dbus_list_get_first_link(services_old);
1025     link = _dbus_list_get_next_link (services_old, link); //skip org.freedesktop.DBus which is not starter
1026
1027     while (link != NULL)
1028     {
1029         int ret;
1030
1031         service = (BusService*) link->data;
1032         if(service == NULL)
1033             goto out;
1034
1035         ret = release_kdbus_name(fd, bus_service_get_name(service), 0);
1036
1037         if (ret == DBUS_RELEASE_NAME_REPLY_RELEASED)
1038         {
1039             if(!bus_service_remove_owner(service, connection, transaction, NULL))
1040                 _dbus_verbose ("Unable to remove\n");
1041         }
1042         else if(ret < 0)
1043             goto out;
1044
1045         link = _dbus_list_get_next_link (services_old, link);
1046     }
1047
1048     if(!register_kdbus_starters(connection))
1049     {
1050         _dbus_verbose ("Registering kdbus starters for dbus activatable names failed!\n");
1051         goto out;
1052     }
1053     retval = TRUE;
1054
1055 out:
1056         bus_transaction_cancel_and_free(transaction);
1057     return retval;
1058 }
1059
1060 /*
1061  * Analyzes system broadcasts about id and name changes.
1062  * Basing on this it sends NameAcquired and NameLost signals and clear phantom connections.
1063  */
1064 void handleNameOwnerChanged(DBusMessage *msg, BusTransaction *transaction, DBusConnection *connection)
1065 {
1066     const char *name, *old, *new;
1067
1068     if(!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &old, DBUS_TYPE_STRING, &new, DBUS_TYPE_INVALID))
1069     {
1070         _dbus_verbose ("Couldn't get args of NameOwnerChanged signal.\n");//, error.message);
1071         return;
1072     }
1073
1074     _dbus_verbose ("Got NameOwnerChanged signal:\nName: %s\nOld: %s\nNew: %s\n", name, old, new);
1075
1076     if(!strncmp(name, ":1.", 3))/*if it starts from :1. it is unique name - this might be IdRemoved info*/
1077     {
1078         if(!strcmp(name, old))  //yes it is - someone has disconnected
1079         {
1080             DBusConnection* conn;
1081
1082             conn = bus_connections_find_conn_by_name(bus_connection_get_connections(connection), name);
1083             if(conn)
1084                 bus_connection_disconnected(conn);
1085         }
1086     }
1087     else //it is well-known name
1088     {
1089         if((*old != 0) && (strcmp(old, bus_connection_get_name(connection))))
1090         {
1091             DBusMessage *message;
1092
1093             if(bus_connections_find_conn_by_name(bus_connection_get_connections(connection), old) == NULL)
1094                 goto next;
1095
1096             _dbus_verbose ("Owner '%s' lost name '%s'. Sending NameLost.\n", old, name);
1097
1098             message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameLost");
1099             if (message == NULL)
1100                 goto next;
1101
1102             if (!dbus_message_set_destination (message, old) || !dbus_message_append_args (message,
1103                                                                  DBUS_TYPE_STRING, &name,
1104                                                                  DBUS_TYPE_INVALID))
1105             {
1106                 dbus_message_unref (message);
1107                 goto next;
1108             }
1109
1110             bus_transaction_send_from_driver (transaction, connection, message);
1111             dbus_message_unref (message);
1112         }
1113     next:
1114         if((*new != 0) && (strcmp(new, bus_connection_get_name(connection))))
1115         {
1116             DBusMessage *message;
1117
1118             _dbus_verbose ("Owner '%s' acquired name '%s'. Sending NameAcquired.\n", new, name);
1119
1120             message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameAcquired");
1121             if (message == NULL)
1122                 return;
1123
1124             if (!dbus_message_set_destination (message, new) || !dbus_message_append_args (message,
1125                                                                  DBUS_TYPE_STRING, &name,
1126                                                                  DBUS_TYPE_INVALID))
1127             {
1128                 dbus_message_unref (message);
1129                 return;
1130             }
1131
1132             bus_transaction_send_from_driver (transaction, connection, message);
1133             dbus_message_unref (message);
1134         }
1135     }
1136
1137     if(bus_transaction_send(transaction, connection, msg))
1138       _dbus_verbose ("NameOwnerChanged sent\n");
1139     else
1140       _dbus_verbose ("Sending NameOwnerChanged failed\n");
1141 }