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