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