Kdbus upstream merge in progress
[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_PART_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_conn_info *cmd;
226   int ret;
227   int fd;
228   uint64_t size;
229   __u64 id = 0;
230
231   pInfo->sec_label_len = 0;
232   pInfo->sec_label = NULL;
233
234   if(!_dbus_transport_get_socket_fd(transport, &fd))
235     return -EPERM;
236
237   size = sizeof(struct kdbus_cmd_conn_info);
238   if((name[0] == ':') && (name[1] == '1') && (name[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
239      id = strtoull(&name[3], NULL, 10);
240   if(id == 0)
241     size += strlen(name) + 1;
242
243   cmd = malloc(size);
244   if (!cmd)
245   {
246     _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
247     return -errno;
248   }
249
250   cmd->size = size;
251   cmd->id = id;
252   if(id == 0)
253     memcpy(cmd->name, name, strlen(name) + 1);
254
255   again:
256   ret = ioctl(fd, KDBUS_CMD_CONN_INFO, cmd);
257   if (ret < 0)
258   {
259     if(errno == EINTR)
260       goto again;
261     pInfo->uniqueId = 0;
262   }
263   else
264   {
265     struct kdbus_conn_info *info;
266     struct kdbus_item *item;
267
268     info = (struct kdbus_conn_info *)((char*)dbus_transport_get_pool_pointer(transport) + cmd->offset);
269     pInfo->uniqueId = info->id;
270
271     item = info->items;
272     while((uint8_t *)(item) < (uint8_t *)(info) + info->size)
273     {
274       if(item->type == KDBUS_ITEM_CREDS)
275         {
276           pInfo->userId = item->creds.uid;
277           pInfo->processId = item->creds.uid;
278         }
279
280       if(item->type == KDBUS_ITEM_SECLABEL)
281         {
282           pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1;
283           if(pInfo->sec_label_len != 0)
284             {
285               pInfo->sec_label = malloc(pInfo->sec_label_len);
286               if(pInfo->sec_label == NULL)
287                 ret = -1;
288               else
289                 memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len);
290             }
291         }
292
293       item = KDBUS_PART_NEXT(item);
294     }
295
296     again2:
297     if (ioctl(fd, KDBUS_CMD_FREE, &cmd->offset) < 0)
298     {
299       if(errno == EINTR)
300         goto again2;
301       _dbus_verbose("kdbus error freeing pool: %d (%m)\n", errno);
302       return -1;
303     }
304   }
305
306   free(cmd);
307   return ret;
308 }
309
310 /*
311  * Creates kdbus bus of given type.
312  */
313 char* make_kdbus_bus(DBusBusType type, const char* address, DBusError *error)
314 {
315     struct {
316         struct kdbus_cmd_bus_make head;
317         uint64_t n_size;
318         uint64_t n_type;
319         char name[64];
320     } __attribute__ ((__aligned__(8))) bus_make;
321
322     int fdc, ret;
323     char *bus;
324     char *addr_value;
325
326     _dbus_verbose("Opening /dev/kdbus/control\n");
327     fdc = open("/dev/kdbus/control", O_RDWR|O_CLOEXEC);
328     if (fdc < 0)
329     {
330         _dbus_verbose("--- error %d (%m)\n", fdc);
331         dbus_set_error(error, DBUS_ERROR_FAILED, "Opening /dev/kdbus/control failed: %d (%m)", fdc);
332         return NULL;
333     }
334
335     addr_value = strchr(address, ':') + 1;
336
337     memset(&bus_make, 0, sizeof(bus_make));
338     bus_make.head.bloom_size = 64;
339 #ifdef POLICY_TO_KDBUS
340     bus_make.head.flags = KDBUS_MAKE_ACCESS_WORLD;
341 #else
342     bus_make.head.flags = KDBUS_MAKE_POLICY_OPEN;
343 #endif
344     if(*addr_value)
345       {
346         if(!strcmp(addr_value, "sbb"))
347           bus_make.head.flags |= KDBUS_MAKE_SBB_OFFSET;
348         else
349           {
350             dbus_set_error_const(error, DBUS_ERROR_BAD_ADDRESS, "Invalid address parameter.");
351             return NULL;
352           }
353       }
354
355     if(type == DBUS_BUS_SYSTEM)
356         snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus-%s", getuid(), "system");
357     else if(type == DBUS_BUS_SESSION)
358         snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus", getuid());
359     else
360         snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus-%u", getuid(), getpid());
361
362     bus_make.n_type = KDBUS_MAKE_NAME;
363     bus_make.n_size = KDBUS_PART_HEADER_SIZE + strlen(bus_make.name) + 1;
364     bus_make.head.size = sizeof(struct kdbus_cmd_bus_make) + bus_make.n_size;
365
366     _dbus_verbose("Creating bus '%s'\n", bus_make.name);
367     ret = ioctl(fdc, KDBUS_CMD_BUS_MAKE, &bus_make);
368     if (ret)
369     {
370         _dbus_verbose("--- error %d (%m)\n", ret);
371         dbus_set_error(error, DBUS_ERROR_FAILED, "Creating bus '%s' failed: %d (%m)", bus_make.name, fdc);
372         return NULL;
373     }
374
375     if (asprintf(&bus, "kdbus:path=/dev/kdbus/%s/bus", bus_make.name) < 0)
376     {
377         BUS_SET_OOM (error);
378         return NULL;
379     }
380
381     _dbus_verbose("Return value '%s'\n", bus);
382         return bus;
383 }
384
385 /*
386  * Minimal server init needed by context to go further.
387  */
388 DBusServer* empty_server_init(char* address)
389 {
390         return dbus_server_init_mini(address);
391 }
392
393 static dbus_bool_t add_matches_for_kdbus_broadcasts(DBusConnection* connection)
394 {
395   struct kdbus_cmd_match* pCmd_match;
396   struct kdbus_item *pItem;
397   uint64_t size;
398   int fd;
399   DBusTransport *transport;
400   const char* unique_name;
401
402   transport = dbus_connection_get_transport(connection);
403
404   if(!_dbus_transport_get_socket_fd(transport, &fd))
405     {
406       errno = EPERM;
407       return FALSE;
408     }
409
410   size = sizeof(struct kdbus_cmd_match);
411   size += KDBUS_PART_SIZE(1)*3 + KDBUS_PART_SIZE(sizeof(__u64))*2;  /*3 name related items plus 2 id related items*/
412
413   pCmd_match = alloca(size);
414   if(pCmd_match == NULL)
415     {
416       errno = ENOMEM;
417       return FALSE;
418     }
419
420   unique_name = dbus_bus_get_unique_name(connection);
421
422   pCmd_match->id = strtoull(&unique_name[3], NULL, 10);
423   pCmd_match->cookie = 1;
424   pCmd_match->size = size;
425
426   pItem = pCmd_match->items;
427   pCmd_match->src_id = 0;
428   pItem->type = KDBUS_MATCH_NAME_CHANGE;
429   pItem->size = KDBUS_PART_HEADER_SIZE + 1;
430   pItem = KDBUS_PART_NEXT(pItem);
431   pItem->type = KDBUS_MATCH_NAME_ADD;
432   pItem->size = KDBUS_PART_HEADER_SIZE + 1;
433   pItem = KDBUS_PART_NEXT(pItem);
434   pItem->type = KDBUS_MATCH_NAME_REMOVE;
435   pItem->size = KDBUS_PART_HEADER_SIZE + 1;
436   pItem = KDBUS_PART_NEXT(pItem);
437   pItem->type = KDBUS_MATCH_ID_ADD;
438   pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
439   pItem = KDBUS_PART_NEXT(pItem);
440   pItem->type = KDBUS_MATCH_ID_REMOVE;
441   pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
442
443   if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
444     {
445       _dbus_verbose("Failed adding match rule for daemon, error: %d, %m\n", errno);
446       return FALSE;
447     }
448
449   _dbus_verbose("Added match rule for daemon correctly.\n");
450   return TRUE;
451 }
452
453 /*
454  * Connects daemon to bus created by him and adds matches for "system" broadcasts.
455  * Do not requests org.freedesktop.DBus name, because it's to early
456  * (some structures of BusContext are not ready yet).
457  */
458 DBusConnection* daemon_as_client(DBusBusType type, char* address, DBusError *error)
459 {
460   DBusConnection* connection;
461
462   dbus_bus_set_bus_connection_address(type, address);
463
464   connection = dbus_bus_get_private(type, error);  /*todo possibly could be optimised by using lower functions*/
465   if(connection == NULL)
466     return NULL;
467
468   if(!add_matches_for_kdbus_broadcasts(connection))
469     {
470       dbus_set_error (error, _dbus_error_from_errno (errno), "Could not add match for daemon, %s", _dbus_strerror_from_errno ());
471       goto failed;
472     }
473
474   if(dbus_error_is_set(error))
475     {
476       failed:
477       _dbus_connection_close_possibly_shared (connection);
478       dbus_connection_unref (connection);
479       connection = NULL;
480     }
481   else
482     _dbus_verbose ("Daemon connected as kdbus client.\n");
483
484   return connection;
485 }
486
487 /*
488  * Asks bus for org.freedesktop.DBus well-known name.
489  */
490 dbus_bool_t register_daemon_name(DBusConnection* connection)
491 {
492     DBusString daemon_name;
493     dbus_bool_t retval = FALSE;
494     BusTransaction *transaction;
495
496     _dbus_string_init_const(&daemon_name, DBUS_SERVICE_DBUS);
497 #ifdef POLICY_TO_KDBUS
498     if(!register_kdbus_policy(DBUS_SERVICE_DBUS, dbus_connection_get_transport(connection), geteuid()))
499       return FALSE;
500 #endif
501
502     if(kdbus_request_name(connection, &daemon_name, 0, 0) != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
503        return FALSE;
504
505     transaction = bus_transaction_new (bus_connection_get_context(connection));
506     if (transaction == NULL)
507     {
508         kdbus_release_name(connection, &daemon_name, 0);
509         goto out;
510     }
511
512     if(!bus_registry_ensure (bus_connection_get_registry (connection), &daemon_name, connection, 0, transaction, NULL))
513     {
514         kdbus_release_name(connection, &daemon_name, 0);
515         goto out;
516     }
517
518     retval = TRUE;
519
520 out:
521         bus_transaction_cancel_and_free(transaction);
522     return retval;
523 }
524
525 dbus_uint32_t kdbus_request_name(DBusConnection* connection, const DBusString *service_name, dbus_uint32_t flags, __u64 sender_id)
526 {
527         int fd;
528
529         _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
530
531         return request_kdbus_name(fd, _dbus_string_get_const_data(service_name), flags, sender_id);
532 }
533
534 dbus_uint32_t kdbus_release_name(DBusConnection* connection, const DBusString *service_name, __u64 sender_id)
535 {
536         int fd;
537
538         _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
539
540         return release_kdbus_name(fd, _dbus_string_get_const_data(service_name), sender_id);
541 }
542
543 /*
544  * Asks kdbus for well-known names registered on the bus
545  */
546 dbus_bool_t kdbus_list_services (DBusConnection* connection, char ***listp, int *array_len)
547 {
548         int fd;
549         struct kdbus_cmd_name_list __attribute__ ((__aligned__(8))) cmd;
550         struct kdbus_name_list *name_list;
551         struct kdbus_cmd_name *name;
552         DBusTransport *transport;
553         dbus_bool_t ret_val = FALSE;
554         char** list;
555         int list_len = 0;
556         int i = 0;
557         int j;
558
559         transport = dbus_connection_get_transport(connection);
560
561         if(!_dbus_transport_get_socket_fd(transport, &fd))
562           return FALSE;
563
564   cmd.flags = KDBUS_NAME_LIST_NAMES; //TODO add handling | KDBUS_NAME_LIST_UNIQUE;
565
566 again:
567         if(ioctl(fd, KDBUS_CMD_NAME_LIST, &cmd))
568         {
569                 if(errno == EINTR)
570                         goto again;
571                 else
572                 {
573                         _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
574                         goto out;
575                 }
576         }
577
578         name_list = (struct kdbus_name_list *)((char*)dbus_transport_get_pool_pointer(transport) + cmd.offset);
579
580   for (name = name_list->names; (uint8_t *)(name) < (uint8_t *)(name_list) + name_list->size; name = KDBUS_PART_NEXT(name))
581     list_len++;
582
583   _dbus_verbose ("Name list size: %llu\n", name_list->size);
584   _dbus_verbose ("List len: %d\n", list_len);
585
586   list = malloc(sizeof(char*) * (list_len + 1));
587   if(list == NULL)
588     goto out;
589
590   for (name = name_list->names; (uint8_t *)(name) < (uint8_t *)(name_list) + name_list->size; name = KDBUS_PART_NEXT(name))
591   {
592     list[i] = strdup(name->name);
593     if(list[i] == NULL)
594     {
595       for(j=0; j<i; j++)
596         free(list[j]);
597       free(list);
598       goto out;
599     }
600     _dbus_verbose ("Name %d: %s\n", i, list[i]);
601     ++i;
602   }
603
604   again2:
605   if (ioctl(fd, KDBUS_CMD_FREE, &cmd.offset) < 0)
606   {
607     if(errno == EINTR)
608       goto again2;
609     _dbus_verbose("kdbus error freeing pool: %d (%m)\n", errno);
610     return -1;
611   }
612
613   list[i] = NULL;
614         *array_len = list_len;
615         *listp = list;
616         ret_val = TRUE;
617
618 out:
619         return ret_val;
620 }
621
622 /*
623  * Asks kdbus for list of connections being in the queue to own
624  * given well-known name. The list includes the owner of the name on the
625  * first position.
626  */
627 dbus_bool_t kdbus_list_queued (DBusConnection *connection, DBusList  **return_list,
628                                const char *name, DBusError  *error)
629 {   //todo implement using new CMD_NAME_LIST
630 /*  int fd;
631   dbus_bool_t ret_val = FALSE;
632   int name_length;
633   struct kdbus_cmd_names* pCmd;
634   __u64 cmd_size;
635
636
637   _dbus_assert (*return_list == NULL);
638
639   name_length = strlen(name) + 1;
640
641   cmd_size = sizeof(struct kdbus_cmd_names) + sizeof(struct kdbus_cmd_name) + name_length;
642   pCmd = malloc(cmd_size);
643   if(pCmd == NULL)
644     goto out;
645   pCmd->size = cmd_size;
646   pCmd->names[0].id = 0;
647   pCmd->names[0].size =  sizeof(struct kdbus_cmd_name) + name_length;
648   memcpy(pCmd->names[0].name, name, name_length);
649
650   _dbus_verbose ("Asking for queued owners of %s\n", pCmd->names[0].name);
651
652   _dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd);
653
654   again:
655   cmd_size = 0;
656   if(ioctl(fd, KDBUS_CMD_NAME_LIST, pCmd))
657     {
658       if(errno == EINTR)
659         goto again;
660       if(errno == ENOBUFS)      //buffer to small to put all names into it
661         cmd_size = pCmd->size;    //here kernel tells how much memory it needs
662       else if(errno == ENOENT)
663         {
664           dbus_set_error (error, DBUS_ERROR_NAME_HAS_NO_OWNER,
665                       "Could not get owners of name '%s': no such name", name);
666           free(pCmd);
667           return FALSE;
668         }
669       else
670         {
671           _dbus_verbose("kdbus error asking for queued owners list: err %d (%m)\n",errno);
672           goto out;
673         }
674     }
675   if(cmd_size)  //kernel needs more memory
676     {
677       pCmd = realloc(pCmd, cmd_size);  //prepare memory
678       if(pCmd == NULL)
679         return FALSE;
680       goto again;           //and try again
681     }
682   else
683     {
684       struct kdbus_cmd_name* pCmd_name;
685
686       for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
687         {
688           char *uname = NULL;
689
690           _dbus_verbose ("Got queued owner id: %llu\n", (unsigned long long)pCmd_name->id);
691           uname = malloc(snprintf(uname, 0, ":1.%llu0", (unsigned long long)pCmd_name->id));
692           if(uname == NULL)
693             goto out;
694           sprintf(uname, ":1.%llu", (unsigned long long int)pCmd_name->id);
695           if (!_dbus_list_append (return_list, uname))
696             goto out;
697         }
698     }
699
700   ret_val = TRUE;
701
702   out:
703   if(pCmd)
704     free(pCmd);
705   if(ret_val == FALSE)
706     {
707       DBusList *link;
708
709       dbus_set_error (error, _dbus_error_from_errno (errno),
710           "Failed to list queued owners of \"%s\": %s",
711           name, _dbus_strerror (errno));
712
713       link = _dbus_list_get_first_link (return_list);
714       while (link != NULL)
715         {
716           DBusList *next = _dbus_list_get_next_link (return_list, link);
717
718           if(link->data != NULL)
719             free(link->data);
720
721           _dbus_list_free_link (link);
722           link = next;
723         }
724     }
725
726   return ret_val;*/
727   dbus_set_error (error, _dbus_error_from_errno (errno),
728       "Failed to list queued owners of \"%s\": %s",
729       name, "Function not implemented yet");
730   return FALSE;
731 }
732
733 /*
734  *  Register match rule in kdbus on behalf of sender of the message
735  */
736 dbus_bool_t kdbus_add_match_rule (DBusConnection* connection, DBusMessage* message, const char* text, DBusError* error)
737 {
738         __u64 sender_id;
739
740         sender_id = sender_name_to_id(dbus_message_get_sender(message), error);
741         if(dbus_error_is_set(error))
742                 return FALSE;
743
744         if(!add_match_kdbus (dbus_connection_get_transport(connection), sender_id, text))
745         {
746               dbus_set_error (error, _dbus_error_from_errno (errno), "Could not add match for id:%d, %s",
747                               sender_id, _dbus_strerror_from_errno ());
748               return FALSE;
749         }
750
751         return TRUE;
752 }
753
754 /*
755  *  Removes match rule in kdbus on behalf of sender of the message
756  */
757 dbus_bool_t kdbus_remove_match (DBusConnection* connection, DBusMessage* message, DBusError* error)
758 {
759         __u64 sender_id;
760
761         sender_id = sender_name_to_id(dbus_message_get_sender(message), error);
762         if(dbus_error_is_set(error))
763                 return FALSE;
764
765         if(!remove_match_kdbus (dbus_connection_get_transport(connection), sender_id))
766         {
767               dbus_set_error (error, _dbus_error_from_errno (errno), "Could not remove match rules for id:%d", sender_id);
768               return FALSE;
769         }
770
771         return TRUE;
772 }
773
774 int kdbus_get_name_owner(DBusConnection* connection, const char* name, char* owner)
775 {
776   int ret;
777   struct nameInfo info;
778
779   ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
780   if(ret == 0) //unique id of the name
781   {
782     sprintf(owner, ":1.%llu", (unsigned long long int)info.uniqueId);
783     _dbus_verbose("Unique name discovered:%s\n", owner);
784   }
785   else if((ret != -ENOENT) && (ret != -ENXIO))
786     _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
787
788   return ret;
789 }
790
791 /*
792  *  Asks kdbus for uid of the owner of the name given in the message
793  */
794 dbus_bool_t kdbus_get_unix_user(DBusConnection* connection, const char* name, unsigned long* uid, DBusError* error)
795 {
796   struct nameInfo info;
797   int inter_ret;
798   dbus_bool_t ret = FALSE;
799
800   inter_ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
801   if(inter_ret == 0) //name found
802   {
803     _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId);
804     *uid = info.userId;
805     return TRUE;
806   }
807   else if((inter_ret == -ENOENT) || (inter_ret == -ENXIO)) //name has no owner
808     {
809       _dbus_verbose ("Name %s has no owner.\n", name);
810       dbus_set_error (error, DBUS_ERROR_FAILED, "Could not get UID of name '%s': no such name", name);
811     }
812
813   else
814   {
815     _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno);
816     dbus_set_error (error, DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name);
817   }
818
819   return ret;
820 }
821
822 /*
823  *  Asks kdbus for pid of the owner of the name given in the message
824  */
825 dbus_bool_t kdbus_get_connection_unix_process_id(DBusConnection* connection, const char* name, unsigned long* pid, DBusError* error)
826 {
827         struct nameInfo info;
828         int inter_ret;
829         dbus_bool_t ret = FALSE;
830
831         inter_ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
832         if(inter_ret == 0) //name found
833         {
834                 _dbus_verbose("Process id:%llu\n", (unsigned long long) info.processId);
835                 *pid = info.processId;
836                 return TRUE;
837         }
838         else if((inter_ret == -ENOENT) || (inter_ret == -ENXIO)) //name has no owner
839                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not get PID of name '%s': no such name", name);
840         else
841         {
842                 _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno);
843                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not determine PID for '%s'", name);
844         }
845
846         return ret;
847 }
848
849 /*
850  *  Asks kdbus for selinux_security_context of the owner of the name given in the message
851  */
852 dbus_bool_t kdbus_get_connection_unix_selinux_security_context(DBusConnection* connection, DBusMessage* message, DBusMessage* reply, DBusError* error)
853 {
854         char* name = NULL;
855         struct nameInfo info;
856         int inter_ret;
857         dbus_bool_t ret = FALSE;
858
859         dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
860         inter_ret = kdbus_NameQuery(name, dbus_connection_get_transport(connection), &info);
861         if((inter_ret == -ENOENT) || (inter_ret == -ENXIO)) //name has no owner
862                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not get security context of name '%s': no such name", name);
863         else if(inter_ret < 0)
864         {
865                 _dbus_verbose("kdbus error determining security context: err %d (%m)\n", errno);
866                 dbus_set_error (error, DBUS_ERROR_FAILED, "Could not determine security context for '%s'", name);
867         }
868         else
869         {
870                 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
871                 {
872                       _DBUS_SET_OOM (error);
873                       return FALSE;
874                 }
875                 ret = TRUE;
876         }
877
878         return ret;
879 }
880
881 /**
882  * Gets the UNIX user ID of the connection from kdbus, if known. Returns #TRUE if
883  * the uid is filled in.  Always returns #FALSE on non-UNIX platforms
884  * for now., though in theory someone could hook Windows to NIS or
885  * something.  Always returns #FALSE prior to authenticating the
886  * connection.
887  *
888  * The UID of is only read by bus daemon from kdbus. You can not
889  * call this function from client side of the connection.
890  *
891  * You can ask the bus to tell you the UID of another connection though
892  * if you like; this is done with dbus_bus_get_unix_user().
893  *
894  * @param connection the connection
895  * @param uid return location for the user ID
896  * @returns #TRUE if uid is filled in with a valid user ID
897  */
898 dbus_bool_t
899 dbus_connection_get_unix_user (DBusConnection *connection,
900                                unsigned long  *uid)
901 {
902   _dbus_return_val_if_fail (connection != NULL, FALSE);
903   _dbus_return_val_if_fail (uid != NULL, FALSE);
904
905   if(bus_context_is_kdbus(bus_connection_get_context (connection)))
906     return kdbus_get_unix_user(connection, bus_connection_get_name(connection), uid, NULL);
907
908   return dbus_connection_get_unix_user_dbus(connection, uid);
909 }
910
911 /**
912  * Gets the process ID of the connection if any.
913  * Returns #TRUE if the pid is filled in.
914  *
915  * @param connection the connection
916  * @param pid return location for the process ID
917  * @returns #TRUE if uid is filled in with a valid process ID
918  */
919 dbus_bool_t
920 dbus_connection_get_unix_process_id (DBusConnection *connection,
921              unsigned long  *pid)
922 {
923   _dbus_return_val_if_fail (connection != NULL, FALSE);
924   _dbus_return_val_if_fail (pid != NULL, FALSE);
925
926   if(bus_context_is_kdbus(bus_connection_get_context (connection)))
927     return kdbus_get_connection_unix_process_id(connection, bus_connection_get_name(connection), pid, NULL);
928
929   return dbus_connection_get_unix_process_id_dbus(connection, pid);
930 }
931
932 /*
933  * Create connection structure for given name. It is needed to control starters - activatable services
934  * and for ListQueued method (as long as kdbus is not supporting it). This connections don't have it's own
935  * fd so it is set up on the basis of daemon's transport. Functionality of such connection is limited.
936  */
937 DBusConnection* create_phantom_connection(DBusConnection* connection, const char* name, DBusError* error)
938 {
939     DBusConnection *phantom_connection;
940     DBusString Sname;
941
942     _dbus_string_init_const(&Sname, name);
943
944     phantom_connection = _dbus_connection_new_for_used_transport (dbus_connection_get_transport(connection));
945     if(phantom_connection == NULL)
946         return FALSE;
947     if(!bus_connections_setup_connection(bus_connection_get_connections(connection), phantom_connection))
948     {
949         dbus_connection_unref_phantom(phantom_connection);
950         phantom_connection = NULL;
951         dbus_set_error (error, DBUS_ERROR_FAILED , "Name \"%s\" could not be acquired", name);
952         goto out;
953     }
954     if(!bus_connection_complete(phantom_connection, &Sname, error))
955     {
956         bus_connection_disconnected(phantom_connection);
957         phantom_connection = NULL;
958         goto out;
959     }
960
961     _dbus_verbose ("Created phantom connection for %s\n", bus_connection_get_name(phantom_connection));
962
963 out:
964     return phantom_connection;
965 }
966
967 /*
968  * Registers activatable services as kdbus starters.
969  */
970 dbus_bool_t register_kdbus_starters(DBusConnection* connection)
971 {
972     int i,j, len;
973     char **services;
974     dbus_bool_t retval = FALSE;
975     int fd;
976     BusTransaction *transaction;
977     DBusString name;
978     DBusTransport* transport;
979
980     transaction = bus_transaction_new (bus_connection_get_context(connection));
981     if (transaction == NULL)
982         return FALSE;
983
984     if (!bus_activation_list_services (bus_connection_get_activation (connection), &services, &len))
985         return FALSE;
986
987     transport = dbus_connection_get_transport(connection);
988
989     if(!_dbus_transport_get_socket_fd (transport, &fd))
990       return FALSE;
991
992     _dbus_string_init(&name);
993
994     for(i=0; i<len; i++)
995     {
996 #ifdef POLICY_TO_KDBUS
997         if(!register_kdbus_policy(services[i], transport, geteuid()))
998           goto out;
999 #endif
1000
1001         if (request_kdbus_name(fd, services[i], (DBUS_NAME_FLAG_ALLOW_REPLACEMENT | KDBUS_NAME_STARTER) , 0) < 0)
1002             goto out;
1003
1004         if(!_dbus_string_append(&name, services[i]))
1005                 goto out;
1006         if(!bus_registry_ensure (bus_connection_get_registry (connection), &name, connection,
1007                         (DBUS_NAME_FLAG_ALLOW_REPLACEMENT | KDBUS_NAME_STARTER), transaction, NULL))
1008                 goto out;
1009         if(!_dbus_string_set_length(&name, 0))
1010                 goto out;
1011     }
1012     retval = TRUE;
1013
1014 out:
1015     if(retval == FALSE)
1016     {
1017         for(j=0; j<i; j++)
1018             release_kdbus_name(fd, services[j], 0);
1019     }
1020     dbus_free_string_array (services);
1021     _dbus_string_free(&name);
1022     bus_transaction_cancel_and_free(transaction);
1023     return retval;
1024 }
1025
1026 /*
1027  * Updates kdbus starters (activatable services) after configuration was reloaded.
1028  * It releases all previous starters and registers all new.
1029  */
1030 dbus_bool_t update_kdbus_starters(DBusConnection* connection)
1031 {
1032     dbus_bool_t retval = FALSE;
1033     DBusList **services_old;
1034     DBusList *link;
1035     BusService *service = NULL;
1036     BusTransaction *transaction;
1037     int fd;
1038
1039     transaction = bus_transaction_new (bus_connection_get_context(connection));
1040     if (transaction == NULL)
1041         return FALSE;
1042
1043     if(!_dbus_transport_get_socket_fd(dbus_connection_get_transport(connection), &fd))
1044         goto out;
1045
1046     services_old = bus_connection_get_services_owned(connection);
1047     link = _dbus_list_get_first_link(services_old);
1048     link = _dbus_list_get_next_link (services_old, link); //skip org.freedesktop.DBus which is not starter
1049
1050     while (link != NULL)
1051     {
1052         int ret;
1053
1054         service = (BusService*) link->data;
1055         if(service == NULL)
1056             goto out;
1057
1058         ret = release_kdbus_name(fd, bus_service_get_name(service), 0);
1059
1060         if (ret == DBUS_RELEASE_NAME_REPLY_RELEASED)
1061         {
1062             if(!bus_service_remove_owner(service, connection, transaction, NULL))
1063                 _dbus_verbose ("Unable to remove\n");
1064         }
1065         else if(ret < 0)
1066             goto out;
1067
1068         link = _dbus_list_get_next_link (services_old, link);
1069     }
1070
1071     if(!register_kdbus_starters(connection))
1072     {
1073         _dbus_verbose ("Registering kdbus starters for dbus activatable names failed!\n");
1074         goto out;
1075     }
1076     retval = TRUE;
1077
1078 out:
1079         bus_transaction_cancel_and_free(transaction);
1080     return retval;
1081 }
1082
1083 /*
1084  * Analyzes system broadcasts about id and name changes.
1085  * Basing on this it sends NameAcquired and NameLost signals and clear phantom connections.
1086  */
1087 void handleNameOwnerChanged(DBusMessage *msg, BusTransaction *transaction, DBusConnection *connection)
1088 {
1089     const char *name, *old, *new;
1090
1091     if(!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &old, DBUS_TYPE_STRING, &new, DBUS_TYPE_INVALID))
1092     {
1093         _dbus_verbose ("Couldn't get args of NameOwnerChanged signal.\n");//, error.message);
1094         return;
1095     }
1096
1097     _dbus_verbose ("Got NameOwnerChanged signal:\nName: %s\nOld: %s\nNew: %s\n", name, old, new);
1098
1099     if(!strncmp(name, ":1.", 3))/*if it starts from :1. it is unique name - this might be IdRemoved info*/
1100     {
1101         if(!strcmp(name, old))  //yes it is - someone has disconnected
1102         {
1103             DBusConnection* conn;
1104
1105             conn = bus_connections_find_conn_by_name(bus_connection_get_connections(connection), name);
1106             if(conn)
1107                 bus_connection_disconnected(conn);
1108         }
1109     }
1110     else //it is well-known name
1111     {
1112         if((*old != 0) && (strcmp(old, bus_connection_get_name(connection))))
1113         {
1114             DBusMessage *message;
1115
1116             if(bus_connections_find_conn_by_name(bus_connection_get_connections(connection), old) == NULL)
1117                 goto next;
1118
1119             _dbus_verbose ("Owner '%s' lost name '%s'. Sending NameLost.\n", old, name);
1120
1121             message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameLost");
1122             if (message == NULL)
1123                 goto next;
1124
1125             if (!dbus_message_set_destination (message, old) || !dbus_message_append_args (message,
1126                                                                  DBUS_TYPE_STRING, &name,
1127                                                                  DBUS_TYPE_INVALID))
1128             {
1129                 dbus_message_unref (message);
1130                 goto next;
1131             }
1132
1133             bus_transaction_send_from_driver (transaction, connection, message);
1134             dbus_message_unref (message);
1135         }
1136     next:
1137         if((*new != 0) && (strcmp(new, bus_connection_get_name(connection))))
1138         {
1139             DBusMessage *message;
1140
1141             _dbus_verbose ("Owner '%s' acquired name '%s'. Sending NameAcquired.\n", new, name);
1142
1143             message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameAcquired");
1144             if (message == NULL)
1145                 return;
1146
1147             if (!dbus_message_set_destination (message, new) || !dbus_message_append_args (message,
1148                                                                  DBUS_TYPE_STRING, &name,
1149                                                                  DBUS_TYPE_INVALID))
1150             {
1151                 dbus_message_unref (message);
1152                 return;
1153             }
1154
1155             bus_transaction_send_from_driver (transaction, connection, message);
1156             dbus_message_unref (message);
1157         }
1158     }
1159
1160     if(bus_transaction_send(transaction, connection, msg))
1161       _dbus_verbose ("NameOwnerChanged sent\n");
1162     else
1163       _dbus_verbose ("Sending NameOwnerChanged failed\n");
1164 }