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