3afbd08d1e948cd4cb5013229dc587ca7a17462d
[platform/upstream/dbus.git] / dbus / dbus-transport-kdbus.c
1 /*
2  * dbus-transport-kdbus.c
3  *
4  * Transport layer using kdbus
5  *
6  *  Created on: Jun 20, 2013
7  *      Author: r.pajak
8  *
9  *
10  */
11
12 #include "dbus-transport.h"
13 #include "dbus-transport-kdbus.h"
14 #include <dbus/dbus-transport-protected.h>
15 #include "dbus-connection-internal.h"
16 #include "kdbus.h"
17 #include "dbus-watch.h"
18 #include "dbus-errors.h"
19 #include "dbus-bus.h"
20 #include <linux/types.h>
21 #include <fcntl.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <sys/ioctl.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <sys/mman.h>
30 #include <limits.h>
31 #include <sys/stat.h>
32 #include <openssl/md5.h>
33
34 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
35 #define KDBUS_ITEM_SIZE(s) KDBUS_ALIGN8((s) + KDBUS_PART_HEADER_SIZE)
36
37 #define KDBUS_PART_NEXT(part) \
38         (typeof(part))(((uint8_t *)part) + KDBUS_ALIGN8((part)->size))
39 #define KDBUS_PART_FOREACH(part, head, first)                           \
40         for (part = (head)->first;                                      \
41              (uint8_t *)(part) < (uint8_t *)(head) + (head)->size;      \
42              part = KDBUS_PART_NEXT(part))
43 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
44 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
45
46 #define KDBUS_MSG_DECODE_DEBUG 0
47
48 #define ITER_APPEND_STR(string) \
49 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string))   \
50 { \
51         ret_size = -1;  \
52         goto out;  \
53 }\
54
55 #define MSG_ITEM_BUILD_VEC(data, datasize)                                    \
56         item->type = KDBUS_MSG_PAYLOAD_VEC;                                     \
57         item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);         \
58         item->vec.address = (unsigned long) data;                               \
59         item->vec.size = datasize;
60
61 /**
62  * Opaque object representing a socket file descriptor transport.
63  */
64 typedef struct DBusTransportSocket DBusTransportSocket;
65
66 /**
67  * Implementation details of DBusTransportSocket. All members are private.
68  */
69 struct DBusTransportSocket
70 {
71   DBusTransport base;                   /**< Parent instance */
72   int fd;                               /**< File descriptor. */
73   DBusWatch *read_watch;                /**< Watch for readability. */
74   DBusWatch *write_watch;               /**< Watch for writability. */
75
76   int max_bytes_read_per_iteration;     /**< In kdbus only to control overall message size*/
77   int max_bytes_written_per_iteration;  /**< In kdbus only to control overall message size*/
78
79   int message_bytes_written;            /**< Number of bytes of current
80                                          *   outgoing message that have
81                                          *   been written.
82                                          */
83   DBusString encoded_outgoing;          /**< Encoded version of current
84                                          *   outgoing message.
85                                          */
86   DBusString encoded_incoming;          /**< Encoded version of current
87                                          *   incoming data.
88                                          */
89   void* kdbus_mmap_ptr;                 /**< Mapped memory where Kdbus (kernel) writes
90                                          *   messages incoming to us.
91                                          */
92   int memfd;                            /**< File descriptor to special 
93                                          *   memory pool for bulk data
94                                          *   transfer. Retrieved from 
95                                          *   Kdbus kernel module. 
96                                          */
97   __u64 bloom_size;                                             /**<  bloom filter field size */
98 };
99
100 static dbus_bool_t
101 socket_get_socket_fd (DBusTransport *transport,
102                       int           *fd_p)
103 {
104   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
105
106   *fd_p = socket_transport->fd;
107
108   return TRUE;
109 }
110
111 /*
112  * Adds locally generated message to received messages queue
113  *
114  */
115 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
116 {
117         DBusList *message_link;
118
119         message_link = _dbus_list_alloc_link (message);
120         if (message_link == NULL)
121         {
122                 dbus_message_unref (message);
123                 return FALSE;
124         }
125
126         _dbus_connection_queue_synthesized_message_link(connection, message_link);
127
128         return TRUE;
129 }
130
131 static dbus_bool_t reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
132 {
133         DBusMessage *errMessage;
134         char* error_msg = "";
135
136         if(template)
137         {
138                 error_msg = alloca(strlen(template) + strlen(object));
139                 sprintf(error_msg, template, object);
140         }
141         else if(object)
142                 error_msg = (char*)object;
143
144         errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg);
145         if(errMessage == NULL)
146                 return FALSE;
147         if (add_message_to_received(errMessage, connection))
148                 return TRUE;
149
150         return FALSE;
151 }
152
153 static dbus_bool_t reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection)
154 {
155         DBusMessageIter args;
156         DBusMessage *reply;
157
158         reply = dbus_message_new_method_return(message);
159         if(reply == NULL)
160                 return FALSE;
161         dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
162     dbus_message_iter_init_append(reply, &args);
163     if (!dbus_message_iter_append_basic(&args, data_type, pData))
164     {
165         dbus_message_unref(reply);
166         return FALSE;
167     }
168     if(add_message_to_received(reply, connection))
169         return TRUE;
170
171     return FALSE;
172 }
173
174 /**
175  * Retrieves file descriptor to memory pool from kdbus module.
176  * It is then used for bulk data sending.
177  * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
178  * 
179  */
180 static int kdbus_init_memfd(DBusTransportSocket* socket_transport)
181 {
182         int memfd;
183         
184                 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
185                         _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
186                         return -1;
187                 }
188
189                 socket_transport->memfd = memfd;
190                 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
191         return 0;
192 }
193
194 /**
195  * Initiates Kdbus message structure. 
196  * Calculates it's size, allocates memory and fills some fields.
197  * @param name Well-known name or NULL
198  * @param dst_id Numeric id of recipient
199  * @param body_size size of message body if present
200  * @param use_memfd flag to build memfd message
201  * @param fds_count number of file descriptors used
202  * @param transport transport
203  * @return initialized kdbus message
204  */
205 static struct kdbus_msg* kdbus_init_msg(const char* name, __u64 dst_id, uint64_t body_size, dbus_bool_t use_memfd, int fds_count, DBusTransportSocket *transport)
206 {
207     struct kdbus_msg* msg;
208     uint64_t msg_size;
209
210     msg_size = sizeof(struct kdbus_msg);
211
212     if(use_memfd == TRUE)  // bulk data - memfd - encoded and plain
213         msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
214     else {
215         msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
216         if(body_size)
217                 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
218     }
219
220     if(fds_count)
221         msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
222
223     if (name)
224         msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
225     else if (dst_id == KDBUS_DST_ID_BROADCAST)
226         msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
227
228     msg = malloc(msg_size);
229     if (!msg)
230     {
231         _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
232                 return NULL;
233     }
234
235     memset(msg, 0, msg_size);
236     msg->size = msg_size;
237     msg->payload_type = KDBUS_PAYLOAD_DBUS1;
238     msg->dst_id = name ? 0 : dst_id;
239     msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
240
241     return msg;
242 }
243
244 /**
245  * Builds and sends kdbus message using Dbus message.
246  * Decide whether used payload vector or memfd memory pool.
247  * Handles broadcasts and unicast messages, and passing of Unix fds.
248  * Does error handling.
249  * TODO refactor to be more compact
250  *
251  * @param transport transport
252  * @param message DBus message to be sent
253  * @param encoded flag if the message is encoded
254  * @return size of data sent
255  */
256 static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded)
257 {
258     struct kdbus_msg *msg;
259     struct kdbus_item *item;
260     const char *name;
261     uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
262     const DBusString *header;
263     const DBusString *body;
264     uint64_t ret_size = 0;
265     uint64_t body_size = 0;
266     uint64_t header_size = 0;
267     dbus_bool_t use_memfd;
268     const int *unix_fds;
269     unsigned fds_count;
270     dbus_bool_t autostart;
271
272     // determine name and destination id
273     if((name = dbus_message_get_destination(message)))
274     {
275         dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
276                 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
277         {
278                 dst_id = strtoull(&name[3], NULL, 10);
279                 name = NULL;
280         }    
281     }
282     
283     // get size of data
284     if(encoded)
285         ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
286     else
287     {
288         _dbus_message_get_network_data (message, &header, &body);
289         header_size = _dbus_string_get_length(header);
290         body_size = _dbus_string_get_length(body);
291         ret_size = header_size + body_size;
292     }
293
294     // check if message size is big enough to use memfd kdbus transport
295     use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
296     if(use_memfd) kdbus_init_memfd(transport);
297     
298     _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
299
300     // init basic message fields
301     msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count, transport);
302     msg->cookie = dbus_message_get_serial(message);
303     autostart = dbus_message_get_auto_start (message);
304     if(!autostart)
305         msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
306     
307     // build message contents
308     item = msg->items;
309
310     // case 1 - bulk data transfer - memfd - encoded and plain
311     if(use_memfd)          
312     {
313         char *buf;
314
315         if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
316             {
317                         _dbus_verbose("memfd sealing failed: \n");
318                         goto out;
319             }
320
321             buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
322             if (buf == MAP_FAILED) 
323             {
324                         _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
325                         goto out;
326             }
327
328                 if(encoded)
329                         memcpy(buf, &transport->encoded_outgoing, ret_size);
330                 else
331                 {
332                         memcpy(buf, _dbus_string_get_const_data(header), header_size);
333                         if(body_size) {
334                                 buf+=header_size;
335                                 memcpy(buf, _dbus_string_get_const_data(body),  body_size);
336                                 buf-=header_size;
337                         }
338                 }
339
340                 munmap(buf, ret_size);
341
342                 // seal data - kdbus module needs it
343                 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
344                         _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
345                         ret_size = -1;
346                         goto out;
347                 }
348
349             item->type = KDBUS_MSG_PAYLOAD_MEMFD;
350                 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
351                 item->memfd.size = ret_size;
352                 item->memfd.fd = transport->memfd;
353     // case 2 - small encoded - don't use memfd
354     } else if(encoded) { 
355         _dbus_verbose("sending encoded data\n");
356         MSG_ITEM_BUILD_VEC(&transport->encoded_outgoing, _dbus_string_get_length (&transport->encoded_outgoing));
357
358     // case 3 - small not encoded - don't use memfd
359     } else { 
360         _dbus_verbose("sending normal vector data\n");
361         MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(header), header_size);
362
363         if(body_size)
364         {
365             _dbus_verbose("body attaching\n");
366             item = KDBUS_PART_NEXT(item);
367             MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(body), body_size);
368         }
369     }
370
371     if(fds_count)
372     {
373         item = KDBUS_PART_NEXT(item);
374         item->type = KDBUS_MSG_FDS;
375         item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
376         memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
377     }
378
379         if (name)
380         {
381                 item = KDBUS_PART_NEXT(item);
382                 item->type = KDBUS_MSG_DST_NAME;
383                 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
384                 strcpy(item->str, name);
385         }
386         else if (dst_id == KDBUS_DST_ID_BROADCAST)
387         {
388                 item = KDBUS_PART_NEXT(item);
389                 item->type = KDBUS_MSG_BLOOM;
390                 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
391                 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
392         }
393
394         again:
395         if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
396         {
397                 if(errno == EINTR)
398                         goto again;
399                 if((errno == ESRCH) || (errno == ENXIO) || (errno = EADDRNOTAVAIL))  //when recipient is not available on the bus
400                 {
401                         if(autostart)
402                         {
403                                 //todo start service here, otherwise
404                                 if(reply_with_error(DBUS_ERROR_SERVICE_UNKNOWN, "The name %s was not provided by any .service files", dbus_message_get_destination(message), message, transport->base.connection))
405                                         goto out;
406                         }
407                         else
408                                 if(reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
409                                         goto out;
410
411                 }
412                 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
413                 ret_size = -1;
414         }
415 out:
416     free(msg);
417     close(transport->memfd);
418
419     return ret_size;
420 }
421
422 struct nameInfo
423 {
424         __u64 uniqueId;
425         __u64 userId;
426         __u64 processId;
427         __u32 sec_label_len;
428         char *sec_label;
429 };
430
431 /**
432  * Performs kdbus query of id of the given name
433  *
434  * @param name name to query for
435  * @param fd bus file
436  * @param ownerID place to store id of the name
437  * @return 0 on success, -errno if failed
438  */
439 static int kdbus_NameQuery(char* name, int fd, struct nameInfo* pInfo)
440 {
441         struct kdbus_cmd_name_info *msg;
442         struct kdbus_item *item;
443         uint64_t size;
444         int ret;
445         uint64_t item_size;
446
447         pInfo->sec_label_len = 0;
448         pInfo->sec_label = NULL;
449         
450     item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
451         item_size = (item_size < 56) ? 56 : item_size;  //at least 56 bytes are needed by kernel to place info about name, otherwise error
452     size = sizeof(struct kdbus_cmd_name_info) + item_size;
453
454         msg = malloc(size);
455         if (!msg)
456         {
457                 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
458                 return -1;
459         }
460
461         memset(msg, 0, size);
462         msg->size = size;
463         if((name[0] == ':') && (name[1] == '1') && (name[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
464                 msg->id = strtoull(&name[3], NULL, 10);
465         else
466                 msg->id = 0;
467
468         item = msg->items;
469         item->type = KDBUS_NAME_INFO_ITEM_NAME;
470         item->size = item_size;
471         strcpy(item->str, name);
472
473         again:
474         ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg);
475         if (ret < 0)
476         {
477                 if(errno == EINTR)
478                         goto again;
479                 else if(ret == -ENOBUFS)
480                 {
481                         msg = realloc(msg, msg->size);  //prepare memory
482                         if(msg != NULL)
483                                 goto again;
484                 }
485                 pInfo->uniqueId = 0;
486                 ret = -errno;
487         }
488         else
489         {
490                 pInfo->uniqueId = msg->id;
491                 pInfo->userId = msg->creds.uid;
492                 pInfo->processId = msg->creds.pid;
493 _dbus_verbose ("I'm alive 1\n");
494                 item = msg->items;
495                 while((uint8_t *)(item) < (uint8_t *)(msg) + msg->size)
496                 {
497                         if(item->type == KDBUS_NAME_INFO_ITEM_SECLABEL)
498                         {
499                                 pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1;
500                                 if(pInfo->sec_label_len != 0)
501                                         pInfo->sec_label = malloc(pInfo->sec_label_len);
502                                 if(pInfo->sec_label == NULL)
503                                         ret = -1;
504                                 else
505                                         memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len);
506                                         
507                                 break;
508                         }
509                         item = KDBUS_PART_NEXT(item);
510                 }
511         }
512
513         free(msg);
514         return ret;
515 }
516
517 /**
518  * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
519  * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
520  *
521  * !!! Not all methods are handled !!! Doubt if it is even possible.
522  * If method is not handled, returns error reply org.freedesktop.DBus.Error.UnknownMethod
523  *
524  * Handled methods:
525  * - GetNameOwner
526  * - NameHasOwner
527  * - ListNames
528  *
529  * Not handled methods:
530  * - ListActivatableNames
531  * - StartServiceByName
532  * - UpdateActivationEnvironment
533  * - GetConnectionUnixUser
534  * - GetId
535  */
536 static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
537 {
538         int inter_ret;
539         struct nameInfo info;
540         dbus_bool_t ret_value;
541
542         if(!strcmp(dbus_message_get_member(message), "GetNameOwner"))  //returns id of the well known name
543         {
544                 char* name = NULL;
545
546                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
547                 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
548                 if(inter_ret == 0) //unique id of the name
549                 {
550                         char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
551                         const char* pString = unique_name;
552
553                         sprintf(unique_name, ":1.%llu", (unsigned long long int)info.uniqueId);
554                         _dbus_verbose("Unique name discovered:%s\n", unique_name);
555                         ret_value = reply_1_data(message, DBUS_TYPE_STRING, &pString, transport->connection);
556                 }
557                 else if(inter_ret == -ENOENT)  //name has no owner
558                         return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get owner of name '%s': no such name", name, message, transport->connection);
559                 else
560                 {
561                         _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
562                         ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine unique name for '%s'", name, message, transport->connection);
563                 }
564         }
565         else if(!strcmp(dbus_message_get_member(message), "NameHasOwner"))   //returns if name is currently registered on the bus
566         {
567                 char* name = NULL;
568                 dbus_bool_t result;
569
570                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
571                 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
572                 if((inter_ret == 0) || (inter_ret == -ENOENT))
573                 {
574                         result = (inter_ret == 0) ? TRUE : FALSE;
575                         ret_value = reply_1_data(message, DBUS_TYPE_BOOLEAN, &result, transport->connection);
576                 }
577                 else
578                 {
579                         _dbus_verbose("kdbus error checking if name exists: err %d (%m)\n", errno);
580                         ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine whether name '%s' exists", name, message, transport->connection);
581                 }
582         }
583         else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
584         {
585                 char* name = NULL;
586
587                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
588                 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
589                 if(inter_ret == 0) //name found
590                 {
591                         _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId);
592                         ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.userId, transport->connection);
593                 }
594                 else if(inter_ret == -ENOENT)  //name has no owner
595                         return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get UID of name '%s': no such name", name, message, transport->connection);
596                 else
597                 {
598                         _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno);
599                         ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name, message, transport->connection);
600                 }
601         }
602         else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixProcessID"))
603         {
604                 char* name = NULL;
605
606                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
607                 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
608                 if(inter_ret == 0) //name found
609                         ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.processId, transport->connection);
610                 else if(inter_ret == -ENOENT)  //name has no owner
611                         return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get PID of name '%s': no such name", name, message, transport->connection);
612                 else
613                 {
614                         _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno);
615                         ret_value = reply_with_error(DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,"Could not determine PID for '%s'", name, message, transport->connection);
616                 }
617         }
618         else if(!strcmp(dbus_message_get_member(message), "ListNames"))  //return all well known names on he bus
619         {
620                 struct kdbus_cmd_names* pCmd;
621                 uint64_t cmd_size;
622
623                 cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1);
624                 pCmd = malloc(cmd_size);
625                 if(pCmd == NULL)
626                         goto out;
627                 pCmd->size = cmd_size;
628
629   again:
630                 cmd_size = 0;
631                 if(ioctl(((DBusTransportSocket*)transport)->fd, KDBUS_CMD_NAME_LIST, pCmd))
632                 {
633                         if(errno == EINTR)
634                                 goto again;
635                         if(errno == ENOBUFS)                    //buffer to small to put all names into it
636                                 cmd_size = pCmd->size;          //here kernel tells how much memory it needs
637                         else
638                         {
639                                 _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
640                                 goto out;
641                         }
642                 }
643                 if(cmd_size)  //kernel needs more memory
644                 {
645                         pCmd = realloc(pCmd, cmd_size);  //prepare memory
646                         if(pCmd == NULL)
647                                 return FALSE;
648                         goto again;                                             //and try again
649                 }
650                 else
651                 {
652                         DBusMessage *reply;
653                         DBusMessageIter args;
654                         struct kdbus_cmd_name* pCmd_name;
655                         char* pName;
656
657                         reply = dbus_message_new_method_return(message);
658                         if(reply == NULL)
659                                 goto out;
660                         dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
661                         dbus_message_iter_init_append(reply, &args);
662
663                         for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
664                         {
665                                 pName = pCmd_name->name;
666                                 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
667                                 {
668                                         dbus_message_unref(reply);
669                                         goto out;
670                                 }
671                         }
672
673                         if(add_message_to_received(reply, transport->connection))
674                         {
675                                 free(pCmd);
676                                 return TRUE;
677                         }
678                 }
679 out:
680                 if(pCmd)
681                         free(pCmd);
682                 return FALSE;
683         }
684         else if(!strcmp(dbus_message_get_member(message), "GetId"))
685         {
686                 char* path;
687                 char uuid[DBUS_UUID_LENGTH_BYTES];
688                 struct stat stats;
689                 MD5_CTX md5;
690                 DBusString binary, encoded;
691
692                 ret_value = FALSE;
693                 path = &transport->address[11]; //start of kdbus bus path
694                 if(stat(path, &stats) < -1)
695                 {
696                         _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno);
697                         return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection);
698                 }
699
700                 MD5_Init(&md5);
701         MD5_Update(&md5, path, strlen(path));
702         MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec));
703                 MD5_Final(uuid, &md5);
704
705                 if(!_dbus_string_init (&encoded))
706                         goto outgid;
707                 _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES);
708                 if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded)))
709                         goto outb;
710                 path = (char*)_dbus_string_get_const_data (&encoded);
711                 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection);
712
713         outb:
714                 _dbus_string_free(&binary);
715                 _dbus_string_free(&encoded);
716         outgid:
717                 return ret_value;
718         }
719         else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData"))
720         {
721                 char* name = NULL;
722
723                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
724                 return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection);
725         }
726         else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
727         {
728                 char* name = NULL;
729
730                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
731                 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
732                 if(inter_ret == -ENOENT)  //name has no owner
733                         return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get security context of name '%s': no such name", name, message, transport->connection);
734                 else if(inter_ret < 0)
735                         return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection);
736                 else
737                 {
738                         DBusMessage *reply;
739
740                         ret_value = FALSE;
741                         reply = dbus_message_new_method_return(message);
742                         if(reply != NULL)
743                         {
744                                 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
745                                 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
746                                         dbus_message_unref(reply);
747                                 else if(add_message_to_received(reply, transport->connection))
748                                         ret_value = TRUE;
749                         }
750                 }
751         }
752         else
753                 return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection);
754 /*      else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames"))  //todo
755         {
756
757         }
758         else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
759         {
760
761         }
762         else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
763         {
764
765         }
766         else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
767         {
768
769         }
770         */
771
772         if(info.sec_label)
773                 free(info.sec_label);
774         return ret_value;
775 }
776
777 #if KDBUS_MSG_DECODE_DEBUG == 1
778 static char *msg_id(uint64_t id, char *buf)
779 {
780         if (id == 0)
781                 return "KERNEL";
782         if (id == ~0ULL)
783                 return "BROADCAST";
784         sprintf(buf, "%llu", (unsigned long long)id);
785         return buf;
786 }
787 #endif
788 struct kdbus_enum_table {
789         long long id;
790         const char *name;
791 };
792 #define _STRINGIFY(x) #x
793 #define STRINGIFY(x) _STRINGIFY(x)
794 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
795 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
796 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
797 #define LOOKUP(what)                                                            \
798         const char *enum_##what(long long id) {                                 \
799         size_t i; \
800                 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++)    \
801                         if (id == kdbus_table_##what[i].id)                     \
802                                 return kdbus_table_##what[i].name;              \
803                 return "UNKNOWN";                                               \
804         }
805 const char *enum_MSG(long long id);
806 TABLE(MSG) = {
807         ENUM(_KDBUS_MSG_NULL),
808         ENUM(KDBUS_MSG_PAYLOAD_VEC),
809         ENUM(KDBUS_MSG_PAYLOAD_OFF),
810         ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
811         ENUM(KDBUS_MSG_FDS),
812         ENUM(KDBUS_MSG_BLOOM),
813         ENUM(KDBUS_MSG_DST_NAME),
814         ENUM(KDBUS_MSG_SRC_CREDS),
815         ENUM(KDBUS_MSG_SRC_PID_COMM),
816         ENUM(KDBUS_MSG_SRC_TID_COMM),
817         ENUM(KDBUS_MSG_SRC_EXE),
818         ENUM(KDBUS_MSG_SRC_CMDLINE),
819         ENUM(KDBUS_MSG_SRC_CGROUP),
820         ENUM(KDBUS_MSG_SRC_CAPS),
821         ENUM(KDBUS_MSG_SRC_SECLABEL),
822         ENUM(KDBUS_MSG_SRC_AUDIT),
823         ENUM(KDBUS_MSG_SRC_NAMES),
824         ENUM(KDBUS_MSG_TIMESTAMP),
825         ENUM(KDBUS_MSG_NAME_ADD),
826         ENUM(KDBUS_MSG_NAME_REMOVE),
827         ENUM(KDBUS_MSG_NAME_CHANGE),
828         ENUM(KDBUS_MSG_ID_ADD),
829         ENUM(KDBUS_MSG_ID_REMOVE),
830         ENUM(KDBUS_MSG_REPLY_TIMEOUT),
831         ENUM(KDBUS_MSG_REPLY_DEAD),
832 };
833 LOOKUP(MSG);
834 const char *enum_PAYLOAD(long long id);
835 TABLE(PAYLOAD) = {
836         ENUM(KDBUS_PAYLOAD_KERNEL),
837         ENUM(KDBUS_PAYLOAD_DBUS1),
838         ENUM(KDBUS_PAYLOAD_GVARIANT),
839 };
840 LOOKUP(PAYLOAD);
841
842 /**
843  * Puts locally generated message into received data buffer.
844  * Use only during receiving phase!
845  *
846  * @param message message to load
847  * @param data place to load message
848  * @return size of message
849  */
850 static int put_message_into_data(DBusMessage *message, char* data)
851 {
852         int ret_size;
853     const DBusString *header;
854     const DBusString *body;
855     int size;
856
857     dbus_message_lock (message);
858     _dbus_message_get_network_data (message, &header, &body);
859     ret_size = _dbus_string_get_length(header);
860         memcpy(data, _dbus_string_get_const_data(header), ret_size);
861         data += ret_size;
862         size = _dbus_string_get_length(body);
863         memcpy(data, _dbus_string_get_const_data(body), size);
864         ret_size += size;
865         dbus_message_unref(message);
866
867         return ret_size;
868 }
869 /**
870  * Decodes kdbus message in order to extract dbus message and put it into data and fds.
871  * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
872  * all of them into dbus messages.
873  *
874  * @param msg kdbus message
875  * @param data place to copy dbus message to
876  * @param socket_transport transport
877  * @param fds place to store file descriptors received
878  * @param n_fds place to store quantity of file descriptor
879  * @return number of dbus message's bytes received or -1 on error
880  */
881 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
882 {
883         const struct kdbus_item *item;
884         int ret_size = 0;
885         DBusMessage *message = NULL;
886         DBusMessageIter args;
887         const char* emptyString = "";
888     const char* pString = NULL;
889         char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
890         const char* pDBusName = dbus_name;
891 #if KDBUS_MSG_DECODE_DEBUG == 1
892         char buf[32];
893 #endif
894
895 #if KDBUS_MSG_DECODE_DEBUG == 1
896         _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s â†’ %s, cookie=%llu, timeout=%llu\n",
897                 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
898                 (unsigned long long) msg->flags,
899                 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
900                 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
901 #endif
902
903         *n_fds = 0;
904
905         KDBUS_PART_FOREACH(item, msg, items)
906         {
907                 if (item->size <= KDBUS_PART_HEADER_SIZE)
908                 {
909                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
910                         break;  //??? continue (because dbus will find error) or break
911                 }
912
913                 switch (item->type)
914                 {
915                         case KDBUS_MSG_PAYLOAD_OFF:
916                                 memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
917                                 data += item->vec.size;
918                                 ret_size += item->vec.size;                     
919
920                                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
921                                         enum_MSG(item->type), item->size,
922                                         (unsigned long long)item->vec.offset,
923                                         (unsigned long long)item->vec.size);
924                         break;
925
926                         case KDBUS_MSG_PAYLOAD_MEMFD:
927                         {
928                                 char *buf;
929                                 uint64_t size;
930
931                 size = item->memfd.size;
932                                 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
933                                 
934                                 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
935                                 if (buf == MAP_FAILED) 
936                                 {
937                                         _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
938                                         return -1;
939                                 }
940
941                                 memcpy(data, buf, size); 
942                                 data += size;
943                                 ret_size += size;
944
945                                 munmap(buf, size);
946
947                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
948                                            enum_MSG(item->type), item->size,
949                                            (unsigned long long)item->vec.offset,
950                                            (unsigned long long)item->vec.size);
951                         break;
952                         }
953
954                         case KDBUS_MSG_FDS:
955                         {
956                                 int i;
957
958                                 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
959                                 memcpy(fds, item->fds, *n_fds * sizeof(int));
960                     for (i = 0; i < *n_fds; i++)
961                       _dbus_fd_set_close_on_exec(fds[i]);
962                         break;
963                         }
964
965 #if KDBUS_MSG_DECODE_DEBUG == 1
966                         case KDBUS_MSG_SRC_CREDS:
967                                 _dbus_verbose("  +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
968                                         enum_MSG(item->type), item->size,
969                                         item->creds.uid, item->creds.gid,
970                                         item->creds.pid, item->creds.tid,
971                                         item->creds.starttime);
972                         break;
973
974                         case KDBUS_MSG_SRC_PID_COMM:
975                         case KDBUS_MSG_SRC_TID_COMM:
976                         case KDBUS_MSG_SRC_EXE:
977                         case KDBUS_MSG_SRC_CGROUP:
978                         case KDBUS_MSG_SRC_SECLABEL:
979                         case KDBUS_MSG_DST_NAME:
980                                 _dbus_verbose("  +%s (%llu bytes) '%s' (%zu)\n",
981                                            enum_MSG(item->type), item->size, item->str, strlen(item->str));
982                                 break;
983
984                         case KDBUS_MSG_SRC_CMDLINE:
985                         case KDBUS_MSG_SRC_NAMES: {
986                                 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
987                                 const char *str = item->str;
988                                 int count = 0;
989
990                                 _dbus_verbose("  +%s (%llu bytes) ", enum_MSG(item->type), item->size);
991                                 while (size) {
992                                         _dbus_verbose("'%s' ", str);
993                                         size -= strlen(str) + 1;
994                                         str += strlen(str) + 1;
995                                         count++;
996                                 }
997
998                                 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
999                                 break;
1000                         }
1001
1002                         case KDBUS_MSG_SRC_AUDIT:
1003                                 _dbus_verbose("  +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
1004                                            enum_MSG(item->type), item->size,
1005                                            (unsigned long long)item->data64[0],
1006                                            (unsigned long long)item->data64[1]);
1007                                 break;
1008
1009                         case KDBUS_MSG_SRC_CAPS: {
1010                                 int n;
1011                                 const uint32_t *cap;
1012                                 int i;
1013
1014                                 _dbus_verbose("  +%s (%llu bytes) len=%llu bytes)\n",
1015                                            enum_MSG(item->type), item->size,
1016                                            (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
1017
1018                                 cap = item->data32;
1019                                 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
1020
1021                                 _dbus_verbose("    CapInh=");
1022                                 for (i = 0; i < n; i++)
1023                                         _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
1024
1025                                 _dbus_verbose(" CapPrm=");
1026                                 for (i = 0; i < n; i++)
1027                                         _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
1028
1029                                 _dbus_verbose(" CapEff=");
1030                                 for (i = 0; i < n; i++)
1031                                         _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
1032
1033                                 _dbus_verbose(" CapInh=");
1034                                 for (i = 0; i < n; i++)
1035                                         _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
1036                                 _dbus_verbose("\n");
1037                                 break;
1038                         }
1039
1040                         case KDBUS_MSG_TIMESTAMP:
1041                                 _dbus_verbose("  +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
1042                                            enum_MSG(item->type), item->size,
1043                                            (unsigned long long)item->timestamp.realtime_ns,
1044                                            (unsigned long long)item->timestamp.monotonic_ns);
1045                                 break;
1046 #endif
1047
1048                         case KDBUS_MSG_REPLY_TIMEOUT:
1049                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
1050                                            enum_MSG(item->type), item->size, msg->cookie_reply);
1051
1052                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
1053                                 if(message == NULL)
1054                                 {
1055                                         ret_size = -1;
1056                                         goto out;
1057                                 }
1058
1059                                 ret_size = put_message_into_data(message, data);
1060                         break;
1061
1062                         case KDBUS_MSG_REPLY_DEAD:
1063                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
1064                                            enum_MSG(item->type), item->size, msg->cookie_reply);
1065
1066                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
1067                                 if(message == NULL)
1068                                 {
1069                                         ret_size = -1;
1070                                         goto out;
1071                                 }
1072
1073                                 ret_size = put_message_into_data(message, data);
1074                         break;
1075
1076                         case KDBUS_MSG_NAME_ADD:
1077                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1078                                         enum_MSG(item->type), (unsigned long long) item->size,
1079                                         item->name_change.name, item->name_change.old_id,
1080                                         item->name_change.new_id, item->name_change.flags);
1081
1082                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1083                                 if(message == NULL)
1084                                 {
1085                                         ret_size = -1;
1086                                         goto out;
1087                                 }
1088
1089                                 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
1090                                 pString = item->name_change.name;
1091                                 _dbus_verbose ("Name added: %s\n", pString);
1092                             dbus_message_iter_init_append(message, &args);
1093                             ITER_APPEND_STR(pString)
1094                             ITER_APPEND_STR(emptyString)
1095                             ITER_APPEND_STR(pDBusName)
1096                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1097
1098                                 ret_size = put_message_into_data(message, data);
1099                         break;
1100
1101                         case KDBUS_MSG_NAME_REMOVE:
1102                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1103                                         enum_MSG(item->type), (unsigned long long) item->size,
1104                                         item->name_change.name, item->name_change.old_id,
1105                                         item->name_change.new_id, item->name_change.flags);
1106
1107                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
1108                                 if(message == NULL)
1109                                 {
1110                                         ret_size = -1;
1111                                         goto out;
1112                                 }
1113
1114                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1115                                 pString = item->name_change.name;
1116                                 _dbus_verbose ("Name removed: %s\n", pString);
1117                             dbus_message_iter_init_append(message, &args);
1118                             ITER_APPEND_STR(pString)
1119                             ITER_APPEND_STR(pDBusName)
1120                             ITER_APPEND_STR(emptyString)
1121                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1122
1123                                 ret_size = put_message_into_data(message, data);
1124                         break;
1125
1126                         case KDBUS_MSG_NAME_CHANGE:
1127                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1128                                         enum_MSG(item->type), (unsigned long long) item->size,
1129                                         item->name_change.name, item->name_change.old_id,
1130                                         item->name_change.new_id, item->name_change.flags);
1131
1132                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1133                                 if(message == NULL)
1134                                 {
1135                                         ret_size = -1;
1136                                         goto out;
1137                                 }
1138
1139                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1140                                 pString = item->name_change.name;
1141                                 _dbus_verbose ("Name changed: %s\n", pString);
1142                             dbus_message_iter_init_append(message, &args);
1143                             ITER_APPEND_STR(pString)
1144                             ITER_APPEND_STR(pDBusName)
1145                             sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
1146                             _dbus_verbose ("New id: %s\n", pDBusName);
1147                             ITER_APPEND_STR(pDBusName)
1148                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1149
1150                                 ret_size = put_message_into_data(message, data);
1151                         break;
1152
1153                         case KDBUS_MSG_ID_ADD:
1154                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
1155                                            enum_MSG(item->type), (unsigned long long) item->size,
1156                                            (unsigned long long) item->id_change.id,
1157                                            (unsigned long long) item->id_change.flags);
1158
1159                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1160                                 if(message == NULL)
1161                                 {
1162                                         ret_size = -1;
1163                                         goto out;
1164                                 }
1165
1166                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
1167                             dbus_message_iter_init_append(message, &args);
1168                             ITER_APPEND_STR(pDBusName)
1169                             ITER_APPEND_STR(emptyString)
1170                             ITER_APPEND_STR(pDBusName)
1171                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1172
1173                                 ret_size = put_message_into_data(message, data);
1174                         break;
1175
1176                         case KDBUS_MSG_ID_REMOVE:
1177                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
1178                                            enum_MSG(item->type), (unsigned long long) item->size,
1179                                            (unsigned long long) item->id_change.id,
1180                                            (unsigned long long) item->id_change.flags);
1181
1182                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1183                                 if(message == NULL)
1184                                 {
1185                                         ret_size = -1;
1186                                         goto out;
1187                                 }
1188
1189                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
1190                             dbus_message_iter_init_append(message, &args);
1191                             ITER_APPEND_STR(pDBusName)
1192                             ITER_APPEND_STR(pDBusName)
1193                             ITER_APPEND_STR(emptyString)
1194                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1195
1196                                 ret_size = put_message_into_data(message, data);
1197                         break;
1198 #if KDBUS_MSG_DECODE_DEBUG == 1
1199                         default:
1200                                 _dbus_verbose("  +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1201                         break;
1202 #endif
1203                 }
1204         }
1205
1206 #if KDBUS_MSG_DECODE_DEBUG == 1
1207
1208         if ((char *)item - ((char *)msg + msg->size) >= 8)
1209                 _dbus_verbose("invalid padding at end of message\n");
1210 #endif
1211
1212 out:
1213         if(message)
1214                 dbus_message_unref(message);
1215         return ret_size;
1216 }
1217
1218 /**
1219  * Reads message from kdbus and puts it into dbus buffer and fds
1220  *
1221  * @param transport transport
1222  * @param buffer place to copy received message to
1223  * @param fds place to store file descriptors sent in the message
1224  * @param n_fds place  to store number of file descriptors
1225  * @return size of received message on success, -1 on error
1226  */
1227 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1228 {
1229         int ret_size;
1230         uint64_t __attribute__ ((__aligned__(8))) offset;
1231         struct kdbus_msg *msg;
1232         char *data;
1233         int start;
1234
1235         start = _dbus_string_get_length (buffer);
1236         if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1237         {
1238                 errno = ENOMEM;
1239             return -1;
1240         }
1241         data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
1242
1243         again:
1244         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1245         {
1246                 if(errno == EINTR)
1247                         goto again;
1248                 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1249                 _dbus_string_set_length (buffer, start);
1250                 return -1;
1251         }
1252
1253         msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1254
1255         ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1256
1257         if(ret_size == -1) /* error */
1258         {
1259                 _dbus_string_set_length (buffer, start);
1260                 return -1;
1261         }
1262         else
1263                 _dbus_string_set_length (buffer, start + ret_size);
1264         
1265
1266         again2:
1267         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1268         {
1269                 if(errno == EINTR)
1270                         goto again2;
1271                 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1272                 return -1;
1273         }
1274
1275         return ret_size;
1276 }
1277
1278 static void
1279 free_watches (DBusTransport *transport)
1280 {
1281   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1282
1283   _dbus_verbose ("start\n");
1284
1285   if (socket_transport->read_watch)
1286     {
1287       if (transport->connection)
1288         _dbus_connection_remove_watch_unlocked (transport->connection,
1289                                                 socket_transport->read_watch);
1290       _dbus_watch_invalidate (socket_transport->read_watch);
1291       _dbus_watch_unref (socket_transport->read_watch);
1292       socket_transport->read_watch = NULL;
1293     }
1294
1295   if (socket_transport->write_watch)
1296     {
1297       if (transport->connection)
1298         _dbus_connection_remove_watch_unlocked (transport->connection,
1299                                                 socket_transport->write_watch);
1300       _dbus_watch_invalidate (socket_transport->write_watch);
1301       _dbus_watch_unref (socket_transport->write_watch);
1302       socket_transport->write_watch = NULL;
1303     }
1304
1305   _dbus_verbose ("end\n");
1306 }
1307
1308 static void
1309 socket_finalize (DBusTransport *transport)
1310 {
1311   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1312
1313   _dbus_verbose ("\n");
1314
1315   free_watches (transport);
1316
1317   _dbus_string_free (&socket_transport->encoded_outgoing);
1318   _dbus_string_free (&socket_transport->encoded_incoming);
1319
1320   _dbus_transport_finalize_base (transport);
1321
1322   _dbus_assert (socket_transport->read_watch == NULL);
1323   _dbus_assert (socket_transport->write_watch == NULL);
1324
1325   dbus_free (transport);
1326 }
1327
1328 static void
1329 check_write_watch (DBusTransport *transport)
1330 {
1331   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1332   dbus_bool_t needed;
1333
1334   if (transport->connection == NULL)
1335     return;
1336
1337   if (transport->disconnected)
1338     {
1339       _dbus_assert (socket_transport->write_watch == NULL);
1340       return;
1341     }
1342
1343   _dbus_transport_ref (transport);
1344
1345 #ifdef DBUS_AUTHENTICATION
1346   if (_dbus_transport_get_is_authenticated (transport))
1347 #endif
1348     needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1349 #ifdef DBUS_AUTHENTICATION
1350   else
1351     {
1352       if (transport->send_credentials_pending)
1353         needed = TRUE;
1354       else
1355         {
1356           DBusAuthState auth_state;
1357
1358           auth_state = _dbus_auth_do_work (transport->auth);
1359
1360           /* If we need memory we install the write watch just in case,
1361            * if there's no need for it, it will get de-installed
1362            * next time we try reading.
1363            */
1364           if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1365               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1366             needed = TRUE;
1367           else
1368             needed = FALSE;
1369         }
1370     }
1371 #endif
1372   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1373                  needed, transport->connection, socket_transport->write_watch,
1374                  socket_transport->fd,
1375                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1376
1377   _dbus_connection_toggle_watch_unlocked (transport->connection,
1378                                           socket_transport->write_watch,
1379                                           needed);
1380
1381   _dbus_transport_unref (transport);
1382 }
1383
1384 static void
1385 check_read_watch (DBusTransport *transport)
1386 {
1387   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1388   dbus_bool_t need_read_watch;
1389
1390   _dbus_verbose ("fd = %d\n",socket_transport->fd);
1391
1392   if (transport->connection == NULL)
1393     return;
1394
1395   if (transport->disconnected)
1396     {
1397       _dbus_assert (socket_transport->read_watch == NULL);
1398       return;
1399     }
1400
1401   _dbus_transport_ref (transport);
1402
1403 #ifdef DBUS_AUTHENTICATION
1404   if (_dbus_transport_get_is_authenticated (transport))
1405 #endif
1406     need_read_watch =
1407       (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1408       (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1409 #ifdef DBUS_AUTHENTICATION
1410   else
1411     {
1412       if (transport->receive_credentials_pending)
1413         need_read_watch = TRUE;
1414       else
1415         {
1416           /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1417            * is to avoid spinning on the file descriptor when we're waiting
1418            * to write or for some other part of the auth process
1419            */
1420           DBusAuthState auth_state;
1421
1422           auth_state = _dbus_auth_do_work (transport->auth);
1423
1424           /* If we need memory we install the read watch just in case,
1425            * if there's no need for it, it will get de-installed
1426            * next time we try reading. If we're authenticated we
1427            * install it since we normally have it installed while
1428            * authenticated.
1429            */
1430           if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1431               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1432               auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1433             need_read_watch = TRUE;
1434           else
1435             need_read_watch = FALSE;
1436         }
1437     }
1438 #endif
1439
1440   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
1441   _dbus_connection_toggle_watch_unlocked (transport->connection,
1442                                           socket_transport->read_watch,
1443                                           need_read_watch);
1444
1445   _dbus_transport_unref (transport);
1446 }
1447
1448 static void
1449 do_io_error (DBusTransport *transport)
1450 {
1451   _dbus_transport_ref (transport);
1452   _dbus_transport_disconnect (transport);
1453   _dbus_transport_unref (transport);
1454 }
1455
1456 #ifdef DBUS_AUTHENTICATION
1457 /* return value is whether we successfully read any new data. */
1458 static dbus_bool_t
1459 read_data_into_auth (DBusTransport *transport,
1460                      dbus_bool_t   *oom)
1461 {
1462   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1463   DBusString *buffer;
1464   int bytes_read;
1465
1466   *oom = FALSE;
1467
1468   _dbus_auth_get_buffer (transport->auth, &buffer);
1469
1470   bytes_read = kdbus_read_message(socket_transport, buffer);
1471
1472   _dbus_auth_return_buffer (transport->auth, buffer,
1473                             bytes_read > 0 ? bytes_read : 0);
1474
1475   if (bytes_read > 0)
1476     {
1477       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1478       return TRUE;
1479     }
1480   else if (bytes_read < 0)
1481     {
1482       /* EINTR already handled for us */
1483
1484       if (_dbus_get_is_errno_enomem ())
1485         {
1486           *oom = TRUE;
1487         }
1488       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1489         ; /* do nothing, just return FALSE below */
1490       else
1491         {
1492           _dbus_verbose ("Error reading from remote app: %s\n",
1493                          _dbus_strerror_from_errno ());
1494           do_io_error (transport);
1495         }
1496
1497       return FALSE;
1498     }
1499   else
1500     {
1501       _dbus_assert (bytes_read == 0);
1502
1503       _dbus_verbose ("Disconnected from remote app\n");
1504       do_io_error (transport);
1505
1506       return FALSE;
1507     }
1508 }
1509
1510 /* Return value is whether we successfully wrote any bytes */
1511 static dbus_bool_t
1512 write_data_from_auth (DBusTransport *transport)
1513 {
1514   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1515   int bytes_written;
1516   const DBusString *buffer;
1517
1518   if (!_dbus_auth_get_bytes_to_send (transport->auth,
1519                                      &buffer))
1520     return FALSE;
1521
1522   bytes_written = _dbus_write_socket (socket_transport->fd,
1523                                       buffer,
1524                                       0, _dbus_string_get_length (buffer));
1525
1526   if (bytes_written > 0)
1527     {
1528       _dbus_auth_bytes_sent (transport->auth, bytes_written);
1529       return TRUE;
1530     }
1531   else if (bytes_written < 0)
1532     {
1533       /* EINTR already handled for us */
1534
1535       if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1536         ;
1537       else
1538         {
1539           _dbus_verbose ("Error writing to remote app: %s\n",
1540                          _dbus_strerror_from_errno ());
1541           do_io_error (transport);
1542         }
1543     }
1544
1545   return FALSE;
1546 }
1547
1548 /* FALSE on OOM */
1549 static dbus_bool_t
1550 exchange_credentials (DBusTransport *transport,
1551                       dbus_bool_t    do_reading,
1552                       dbus_bool_t    do_writing)
1553 {
1554   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1555   DBusError error = DBUS_ERROR_INIT;
1556
1557   _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1558                   do_reading, do_writing);
1559
1560   if (do_writing && transport->send_credentials_pending)
1561     {
1562       if (_dbus_send_credentials_socket (socket_transport->fd,
1563                                          &error))
1564         {
1565           transport->send_credentials_pending = FALSE;
1566         }
1567       else
1568         {
1569           _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1570           dbus_error_free (&error);
1571           do_io_error (transport);
1572         }
1573     }
1574
1575   if (do_reading && transport->receive_credentials_pending)
1576     {
1577       /* FIXME this can fail due to IO error _or_ OOM, broken
1578        * (somewhat tricky to fix since the OOM error can be set after
1579        * we already read the credentials byte, so basically we need to
1580        * separate reading the byte and storing it in the
1581        * transport->credentials). Does not really matter for now
1582        * because storing in credentials never actually fails on unix.
1583        */
1584       if (_dbus_read_credentials_socket (socket_transport->fd,
1585                                          transport->credentials,
1586                                          &error))
1587         {
1588           transport->receive_credentials_pending = FALSE;
1589         }
1590       else
1591         {
1592           _dbus_verbose ("Failed to read credentials %s\n", error.message);
1593           dbus_error_free (&error);
1594           do_io_error (transport);
1595         }
1596     }
1597
1598   if (!(transport->send_credentials_pending ||
1599         transport->receive_credentials_pending))
1600     {
1601       if (!_dbus_auth_set_credentials (transport->auth,
1602                                        transport->credentials))
1603         return FALSE;
1604     }
1605
1606   return TRUE;
1607 }
1608
1609 static dbus_bool_t
1610 do_authentication (DBusTransport *transport,
1611                    dbus_bool_t    do_reading,
1612                    dbus_bool_t    do_writing,
1613                    dbus_bool_t   *auth_completed)
1614 {
1615   dbus_bool_t oom;
1616   dbus_bool_t orig_auth_state;
1617
1618   oom = FALSE;
1619
1620   orig_auth_state = _dbus_transport_get_is_authenticated (transport);
1621
1622   /* This is essential to avoid the check_write_watch() at the end,
1623    * we don't want to add a write watch in do_iteration before
1624    * we try writing and get EAGAIN
1625    */
1626   if (orig_auth_state)
1627     {
1628       if (auth_completed)
1629         *auth_completed = FALSE;
1630       return TRUE;
1631     }
1632
1633   _dbus_transport_ref (transport);
1634
1635   while (!_dbus_transport_get_is_authenticated (transport) &&
1636          _dbus_transport_get_is_connected (transport))
1637     {
1638       if (!exchange_credentials (transport, do_reading, do_writing))
1639         {
1640           oom = TRUE;
1641           goto out;
1642         }
1643
1644       if (transport->send_credentials_pending ||
1645           transport->receive_credentials_pending)
1646         {
1647           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1648                          transport->send_credentials_pending,
1649                          transport->receive_credentials_pending);
1650           goto out;
1651         }
1652
1653 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1654       switch (_dbus_auth_do_work (transport->auth))
1655         {
1656         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1657           _dbus_verbose (" %s auth state: waiting for input\n",
1658                          TRANSPORT_SIDE (transport));
1659           if (!do_reading || !read_data_into_auth (transport, &oom))
1660             goto out;
1661           break;
1662
1663         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1664           _dbus_verbose (" %s auth state: waiting for memory\n",
1665                          TRANSPORT_SIDE (transport));
1666           oom = TRUE;
1667           goto out;
1668           break;
1669
1670         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1671           _dbus_verbose (" %s auth state: bytes to send\n",
1672                          TRANSPORT_SIDE (transport));
1673           if (!do_writing || !write_data_from_auth (transport))
1674             goto out;
1675           break;
1676
1677         case DBUS_AUTH_STATE_NEED_DISCONNECT:
1678           _dbus_verbose (" %s auth state: need to disconnect\n",
1679                          TRANSPORT_SIDE (transport));
1680           do_io_error (transport);
1681           break;
1682
1683         case DBUS_AUTH_STATE_AUTHENTICATED:
1684           _dbus_verbose (" %s auth state: authenticated\n",
1685                          TRANSPORT_SIDE (transport));
1686           break;
1687         }
1688     }
1689
1690  out:
1691   if (auth_completed)
1692     *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
1693
1694   check_read_watch (transport);
1695   check_write_watch (transport);
1696   _dbus_transport_unref (transport);
1697
1698   if (oom)
1699     return FALSE;
1700   else
1701     return TRUE;
1702 }
1703 #endif
1704
1705 /* returns false on oom */
1706 static dbus_bool_t
1707 do_writing (DBusTransport *transport)
1708 {
1709         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1710         dbus_bool_t oom;
1711
1712 #ifdef DBUS_AUTHENTICATION
1713         /* No messages without authentication! */
1714         if (!_dbus_transport_get_is_authenticated (transport))
1715     {
1716                 _dbus_verbose ("Not authenticated, not writing anything\n");
1717                 return TRUE;
1718     }
1719 #endif
1720
1721         if (transport->disconnected)
1722     {
1723                 _dbus_verbose ("Not connected, not writing anything\n");
1724                 return TRUE;
1725     }
1726
1727 #if 1
1728         _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1729                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1730                  socket_transport->fd);
1731 #endif
1732
1733         oom = FALSE;
1734
1735         while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1736     {
1737                 int bytes_written;
1738                 DBusMessage *message;
1739                 const DBusString *header;
1740                 const DBusString *body;
1741                 int total_bytes_to_write;
1742                 const char* pDestination;
1743
1744                 message = _dbus_connection_get_message_to_send (transport->connection);
1745                 _dbus_assert (message != NULL);
1746                 dbus_message_lock (message);
1747                 _dbus_message_get_network_data (message, &header, &body);
1748                 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1749                 pDestination = dbus_message_get_destination(message);
1750
1751                 if(pDestination)
1752                 {
1753                         if(!strcmp(pDestination, "org.freedesktop.DBus"))
1754                         {
1755                                 if(emulateOrgFreedesktopDBus(transport, message))
1756                                         bytes_written = total_bytes_to_write;
1757                                 else
1758                                         bytes_written = -1;
1759                                 goto written;
1760                         }
1761                 }
1762                 if (_dbus_auth_needs_encoding (transport->auth))
1763         {
1764                         if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
1765             {
1766                                 if (!_dbus_auth_encode_data (transport->auth,
1767                                            header, &socket_transport->encoded_outgoing))
1768                 {
1769                                         oom = TRUE;
1770                                         goto out;
1771                 }
1772
1773                                 if (!_dbus_auth_encode_data (transport->auth,
1774                                            body, &socket_transport->encoded_outgoing))
1775                 {
1776                                         _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1777                                         oom = TRUE;
1778                                         goto out;
1779                 }
1780             }
1781
1782                         total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
1783                         if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1784                                 return -E2BIG;
1785
1786                         bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
1787         }
1788                 else
1789                 {
1790                         if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1791                                 return -E2BIG;
1792
1793                         bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
1794                 }
1795
1796 written:
1797                 if (bytes_written < 0)
1798                 {
1799                         /* EINTR already handled for us */
1800
1801           /* For some discussion of why we also ignore EPIPE here, see
1802            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1803            */
1804
1805                         if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1806                                 goto out;
1807                         else
1808                         {
1809                                 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1810                                 do_io_error (transport);
1811                                 goto out;
1812                         }
1813                 }
1814                 else
1815                 {
1816                         _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1817                          total_bytes_to_write);
1818
1819                         socket_transport->message_bytes_written += bytes_written;
1820
1821                         _dbus_assert (socket_transport->message_bytes_written <=
1822                         total_bytes_to_write);
1823
1824                           if (socket_transport->message_bytes_written == total_bytes_to_write)
1825                           {
1826                                   socket_transport->message_bytes_written = 0;
1827                                   _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1828                                   _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
1829
1830                                   _dbus_connection_message_sent_unlocked (transport->connection,
1831                                                                                                                   message);
1832                           }
1833                 }
1834     }
1835
1836         out:
1837         if (oom)
1838                 return FALSE;
1839         return TRUE;
1840 }
1841
1842 /* returns false on out-of-memory */
1843 static dbus_bool_t
1844 do_reading (DBusTransport *transport)
1845 {
1846   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1847   DBusString *buffer;
1848   int bytes_read;
1849   dbus_bool_t oom = FALSE;
1850   int *fds, n_fds;
1851
1852   _dbus_verbose ("fd = %d\n",socket_transport->fd);
1853
1854 #ifdef DBUS_AUTHENTICATION
1855   /* No messages without authentication! */
1856   if (!_dbus_transport_get_is_authenticated (transport))
1857     return TRUE;
1858 #endif
1859
1860  again:
1861
1862   /* See if we've exceeded max messages and need to disable reading */
1863   check_read_watch (transport);
1864
1865   _dbus_assert (socket_transport->read_watch != NULL ||
1866                 transport->disconnected);
1867
1868   if (transport->disconnected)
1869     goto out;
1870
1871   if (!dbus_watch_get_enabled (socket_transport->read_watch))
1872     return TRUE;
1873
1874   if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1875   {
1876       _dbus_verbose ("Out of memory reading file descriptors\n");
1877       oom = TRUE;
1878       goto out;
1879   }
1880   _dbus_message_loader_get_buffer (transport->loader, &buffer);
1881
1882   if (_dbus_auth_needs_decoding (transport->auth))
1883   {
1884           bytes_read = kdbus_read_message(socket_transport,  &socket_transport->encoded_incoming, fds, &n_fds);
1885
1886       _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
1887
1888       if (bytes_read > 0)
1889       {
1890           if (!_dbus_auth_decode_data (transport->auth,
1891                                        &socket_transport->encoded_incoming,
1892                                        buffer))
1893           {
1894               _dbus_verbose ("Out of memory decoding incoming data\n");
1895               _dbus_message_loader_return_buffer (transport->loader,
1896                                               buffer,
1897                                               _dbus_string_get_length (buffer));
1898               oom = TRUE;
1899               goto out;
1900           }
1901
1902           _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1903           _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1904       }
1905   }
1906   else
1907           bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1908
1909   if (bytes_read >= 0 && n_fds > 0)
1910     _dbus_verbose("Read %i unix fds\n", n_fds);
1911
1912   _dbus_message_loader_return_buffer (transport->loader,
1913                                       buffer,
1914                                       bytes_read < 0 ? 0 : bytes_read);
1915   _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1916
1917   if (bytes_read < 0)
1918     {
1919       /* EINTR already handled for us */
1920
1921       if (_dbus_get_is_errno_enomem ())
1922         {
1923           _dbus_verbose ("Out of memory in read()/do_reading()\n");
1924           oom = TRUE;
1925           goto out;
1926         }
1927       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1928         goto out;
1929       else
1930         {
1931           _dbus_verbose ("Error reading from remote app: %s\n",
1932                          _dbus_strerror_from_errno ());
1933           do_io_error (transport);
1934           goto out;
1935         }
1936     }
1937   else if (bytes_read == 0)
1938     {
1939       _dbus_verbose ("Disconnected from remote app\n");
1940       do_io_error (transport);
1941       goto out;
1942     }
1943   else
1944     {
1945       _dbus_verbose (" read %d bytes\n", bytes_read);
1946
1947       if (!_dbus_transport_queue_messages (transport))
1948         {
1949           oom = TRUE;
1950           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1951           goto out;
1952         }
1953
1954       /* Try reading more data until we get EAGAIN and return, or
1955        * exceed max bytes per iteration.  If in blocking mode of
1956        * course we'll block instead of returning.
1957        */
1958       goto again;
1959     }
1960
1961  out:
1962   if (oom)
1963     return FALSE;
1964   return TRUE;
1965 }
1966
1967 static dbus_bool_t
1968 unix_error_with_read_to_come (DBusTransport *itransport,
1969                               DBusWatch     *watch,
1970                               unsigned int   flags)
1971 {
1972    DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
1973
1974    if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
1975       return FALSE;
1976
1977   /* If we have a read watch enabled ...
1978      we -might have data incoming ... => handle the HANGUP there */
1979    if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
1980       return FALSE;
1981
1982    return TRUE;
1983 }
1984
1985 static dbus_bool_t
1986 socket_handle_watch (DBusTransport *transport,
1987                    DBusWatch     *watch,
1988                    unsigned int   flags)
1989 {
1990   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1991
1992   _dbus_assert (watch == socket_transport->read_watch ||
1993                 watch == socket_transport->write_watch);
1994   _dbus_assert (watch != NULL);
1995
1996   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1997    * still be in the buffer and do_reading may need several iteration to read
1998    * it all (because of its max_bytes_read_per_iteration limit).
1999    */
2000   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
2001     {
2002       _dbus_verbose ("Hang up or error on watch\n");
2003       _dbus_transport_disconnect (transport);
2004       return TRUE;
2005     }
2006
2007   if (watch == socket_transport->read_watch &&
2008       (flags & DBUS_WATCH_READABLE))
2009     {
2010 #ifdef DBUS_AUTHENTICATION
2011       dbus_bool_t auth_finished;
2012 #endif
2013 #if 1
2014       _dbus_verbose ("handling read watch %p flags = %x\n",
2015                      watch, flags);
2016 #endif
2017 #ifdef DBUS_AUTHENTICATION
2018       if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
2019         return FALSE;
2020
2021       /* We don't want to do a read immediately following
2022        * a successful authentication.  This is so we
2023        * have a chance to propagate the authentication
2024        * state further up.  Specifically, we need to
2025        * process any pending data from the auth object.
2026        */
2027       if (!auth_finished)
2028         {
2029 #endif
2030           if (!do_reading (transport))
2031             {
2032               _dbus_verbose ("no memory to read\n");
2033               return FALSE;
2034             }
2035 #ifdef DBUS_AUTHENTICATION
2036         }
2037       else
2038         {
2039           _dbus_verbose ("Not reading anything since we just completed the authentication\n");
2040         }
2041 #endif
2042     }
2043   else if (watch == socket_transport->write_watch &&
2044            (flags & DBUS_WATCH_WRITABLE))
2045     {
2046 #if 1
2047       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
2048                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
2049 #endif
2050 #ifdef DBUS_AUTHENTICATION
2051       if (!do_authentication (transport, FALSE, TRUE, NULL))
2052         return FALSE;
2053 #endif
2054       if (!do_writing (transport))
2055         {
2056           _dbus_verbose ("no memory to write\n");
2057           return FALSE;
2058         }
2059
2060       /* See if we still need the write watch */
2061       check_write_watch (transport);
2062     }
2063 #ifdef DBUS_ENABLE_VERBOSE_MODE
2064   else
2065     {
2066       if (watch == socket_transport->read_watch)
2067         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
2068                        flags);
2069       else if (watch == socket_transport->write_watch)
2070         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
2071                        flags);
2072       else
2073         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
2074                        watch, dbus_watch_get_socket (watch));
2075     }
2076 #endif /* DBUS_ENABLE_VERBOSE_MODE */
2077
2078   return TRUE;
2079 }
2080
2081 static void
2082 socket_disconnect (DBusTransport *transport)
2083 {
2084   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2085
2086   _dbus_verbose ("\n");
2087
2088   free_watches (transport);
2089
2090   _dbus_close_socket (socket_transport->fd, NULL);
2091   socket_transport->fd = -1;
2092 }
2093
2094 static dbus_bool_t
2095 socket_connection_set (DBusTransport *transport)
2096 {
2097   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2098
2099   _dbus_watch_set_handler (socket_transport->write_watch,
2100                            _dbus_connection_handle_watch,
2101                            transport->connection, NULL);
2102
2103   _dbus_watch_set_handler (socket_transport->read_watch,
2104                            _dbus_connection_handle_watch,
2105                            transport->connection, NULL);
2106
2107   if (!_dbus_connection_add_watch_unlocked (transport->connection,
2108                                             socket_transport->write_watch))
2109     return FALSE;
2110
2111   if (!_dbus_connection_add_watch_unlocked (transport->connection,
2112                                             socket_transport->read_watch))
2113     {
2114       _dbus_connection_remove_watch_unlocked (transport->connection,
2115                                               socket_transport->write_watch);
2116       return FALSE;
2117     }
2118
2119   check_read_watch (transport);
2120   check_write_watch (transport);
2121
2122   return TRUE;
2123 }
2124
2125 /**
2126  * @todo We need to have a way to wake up the select sleep if
2127  * a new iteration request comes in with a flag (read/write) that
2128  * we're not currently serving. Otherwise a call that just reads
2129  * could block a write call forever (if there are no incoming
2130  * messages).
2131  */
2132 static  void
2133 kdbus_do_iteration (DBusTransport *transport,
2134                    unsigned int   flags,
2135                    int            timeout_milliseconds)
2136 {
2137         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2138         DBusPollFD poll_fd;
2139         int poll_res;
2140         int poll_timeout;
2141
2142         _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2143                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
2144                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2145                  timeout_milliseconds,
2146                  socket_transport->read_watch,
2147                  socket_transport->write_watch,
2148                  socket_transport->fd);
2149
2150   /* the passed in DO_READING/DO_WRITING flags indicate whether to
2151    * read/write messages, but regardless of those we may need to block
2152    * for reading/writing to do auth.  But if we do reading for auth,
2153    * we don't want to read any messages yet if not given DO_READING.
2154    */
2155
2156    poll_fd.fd = socket_transport->fd;
2157    poll_fd.events = 0;
2158
2159    if (_dbus_transport_peek_is_authenticated (transport))
2160    {
2161       /* This is kind of a hack; if we have stuff to write, then try
2162        * to avoid the poll. This is probably about a 5% speedup on an
2163        * echo client/server.
2164        *
2165        * If both reading and writing were requested, we want to avoid this
2166        * since it could have funky effects:
2167        *   - both ends spinning waiting for the other one to read
2168        *     data so they can finish writing
2169        *   - prioritizing all writing ahead of reading
2170        */
2171       if ((flags & DBUS_ITERATION_DO_WRITING) &&
2172           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2173           !transport->disconnected &&
2174           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2175       {
2176          do_writing (transport);
2177
2178          if (transport->disconnected ||
2179               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2180             goto out;
2181       }
2182
2183       /* If we get here, we decided to do the poll() after all */
2184       _dbus_assert (socket_transport->read_watch);
2185       if (flags & DBUS_ITERATION_DO_READING)
2186              poll_fd.events |= _DBUS_POLLIN;
2187
2188       _dbus_assert (socket_transport->write_watch);
2189       if (flags & DBUS_ITERATION_DO_WRITING)
2190          poll_fd.events |= _DBUS_POLLOUT;
2191    }
2192    else
2193    {
2194       DBusAuthState auth_state;
2195
2196       auth_state = _dbus_auth_do_work (transport->auth);
2197
2198       if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2199              poll_fd.events |= _DBUS_POLLIN;
2200
2201       if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2202              poll_fd.events |= _DBUS_POLLOUT;
2203    }
2204
2205    if (poll_fd.events)
2206    {
2207       if (flags & DBUS_ITERATION_BLOCK)
2208              poll_timeout = timeout_milliseconds;
2209       else
2210              poll_timeout = 0;
2211
2212       /* For blocking selects we drop the connection lock here
2213        * to avoid blocking out connection access during a potentially
2214        * indefinite blocking call. The io path is still protected
2215        * by the io_path_cond condvar, so we won't reenter this.
2216        */
2217       if (flags & DBUS_ITERATION_BLOCK)
2218       {
2219          _dbus_verbose ("unlock pre poll\n");
2220          _dbus_connection_unlock (transport->connection);
2221       }
2222
2223     again:
2224       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2225
2226       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2227       {
2228          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2229          goto again;
2230       }
2231
2232       if (flags & DBUS_ITERATION_BLOCK)
2233       {
2234          _dbus_verbose ("lock post poll\n");
2235          _dbus_connection_lock (transport->connection);
2236       }
2237
2238       if (poll_res >= 0)
2239       {
2240          if (poll_res == 0)
2241             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2242                                   * valgrind flags it as an error. though it probably
2243                                   * is guaranteed on linux at least.
2244                                   */
2245
2246          if (poll_fd.revents & _DBUS_POLLERR)
2247             do_io_error (transport);
2248          else
2249          {
2250             dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2251             dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2252 #ifdef DBUS_AUTHENTICATION
2253               dbus_bool_t authentication_completed;
2254 #endif
2255
2256             _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2257                              need_read, need_write);
2258 #ifdef DBUS_AUTHENTICATION
2259               do_authentication (transport, need_read, need_write,
2260                                  &authentication_completed);
2261
2262               /* See comment in socket_handle_watch. */
2263               if (authentication_completed)
2264                 goto out;
2265 #endif
2266             if (need_read && (flags & DBUS_ITERATION_DO_READING))
2267                do_reading (transport);
2268             if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2269                do_writing (transport);
2270          }
2271       }
2272       else
2273          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2274    }
2275
2276  out:
2277   /* We need to install the write watch only if we did not
2278    * successfully write everything. Note we need to be careful that we
2279    * don't call check_write_watch *before* do_writing, since it's
2280    * inefficient to add the write watch, and we can avoid it most of
2281    * the time since we can write immediately.
2282    *
2283    * However, we MUST always call check_write_watch(); DBusConnection code
2284    * relies on the fact that running an iteration will notice that
2285    * messages are pending.
2286    */
2287    check_write_watch (transport);
2288
2289    _dbus_verbose (" ... leaving do_iteration()\n");
2290 }
2291
2292 static void
2293 socket_live_messages_changed (DBusTransport *transport)
2294 {
2295   /* See if we should look for incoming messages again */
2296   check_read_watch (transport);
2297 }
2298
2299 static const DBusTransportVTable kdbus_vtable = {
2300   socket_finalize,
2301   socket_handle_watch,
2302   socket_disconnect,
2303   socket_connection_set,
2304   kdbus_do_iteration,
2305   socket_live_messages_changed,
2306   socket_get_socket_fd
2307 };
2308
2309 /**
2310  * Creates a new transport for the given kdbus file descriptor.  The file
2311  * descriptor must be nonblocking.
2312  *
2313  * @param fd the file descriptor.
2314  * @param address the transport's address
2315  * @returns the new transport, or #NULL if no memory.
2316  */
2317 static DBusTransport*
2318 _dbus_transport_new_for_socket_kdbus (int       fd,
2319                                           const DBusString *address)
2320 {
2321         DBusTransportSocket *socket_transport;
2322
2323   socket_transport = dbus_new0 (DBusTransportSocket, 1);
2324   if (socket_transport == NULL)
2325     return NULL;
2326
2327   if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2328     goto failed_0;
2329
2330   if (!_dbus_string_init (&socket_transport->encoded_incoming))
2331     goto failed_1;
2332
2333   socket_transport->write_watch = _dbus_watch_new (fd,
2334                                                  DBUS_WATCH_WRITABLE,
2335                                                  FALSE,
2336                                                  NULL, NULL, NULL);
2337   if (socket_transport->write_watch == NULL)
2338     goto failed_2;
2339
2340   socket_transport->read_watch = _dbus_watch_new (fd,
2341                                                 DBUS_WATCH_READABLE,
2342                                                 FALSE,
2343                                                 NULL, NULL, NULL);
2344   if (socket_transport->read_watch == NULL)
2345     goto failed_3;
2346
2347   if (!_dbus_transport_init_base (&socket_transport->base,
2348                                   &kdbus_vtable,
2349                                   NULL, address))
2350     goto failed_4;
2351
2352 #ifdef DBUS_AUTHENTICATION
2353 #ifdef HAVE_UNIX_FD_PASSING
2354   _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2355 #endif
2356 #endif
2357
2358   socket_transport->fd = fd;
2359   socket_transport->message_bytes_written = 0;
2360
2361   /* These values should probably be tunable or something. */
2362   socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2363   socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2364
2365   socket_transport->kdbus_mmap_ptr = NULL;
2366   socket_transport->memfd = -1;
2367   
2368   return (DBusTransport*) socket_transport;
2369
2370  failed_4:
2371   _dbus_watch_invalidate (socket_transport->read_watch);
2372   _dbus_watch_unref (socket_transport->read_watch);
2373  failed_3:
2374   _dbus_watch_invalidate (socket_transport->write_watch);
2375   _dbus_watch_unref (socket_transport->write_watch);
2376  failed_2:
2377   _dbus_string_free (&socket_transport->encoded_incoming);
2378  failed_1:
2379   _dbus_string_free (&socket_transport->encoded_outgoing);
2380  failed_0:
2381   dbus_free (socket_transport);
2382   return NULL;
2383 }
2384
2385
2386 /**
2387  * Opens a connection to the kdbus bus
2388  *
2389  * This will set FD_CLOEXEC for the socket returned.
2390  *
2391  * @param path the path to UNIX domain socket
2392  * @param error return location for error code
2393  * @returns connection file descriptor or -1 on error
2394  */
2395 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2396 {
2397         int fd;
2398
2399         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2400         _dbus_verbose ("connecting to kdbus bus %s\n", path);
2401
2402         fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2403         if (fd < 0)
2404                 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2405
2406         return fd;
2407 }
2408
2409 /**
2410  * maps memory pool for messages received by the kdbus transport
2411  *
2412  * @param transport transport
2413  * @returns #TRUE on success, otherwise FALSE
2414  */
2415 static dbus_bool_t kdbus_mmap(DBusTransport* transport)
2416 {
2417         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2418
2419         socket_transport->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0);
2420         if (socket_transport->kdbus_mmap_ptr == MAP_FAILED)
2421                 return FALSE;
2422
2423         return TRUE;
2424 }
2425
2426 /**
2427  * Creates a new transport for kdbus.
2428  * This creates a client-side of a transport.
2429  *
2430  * @param path the path to the bus.
2431  * @param error address where an error can be returned.
2432  * @returns a new transport, or #NULL on failure.
2433  */
2434 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2435 {
2436         int fd;
2437         DBusTransport *transport;
2438         DBusString address;
2439
2440         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2441
2442         if (!_dbus_string_init (&address))
2443     {
2444                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2445                 return NULL;
2446     }
2447
2448         fd = -1;
2449
2450         if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2451     {
2452                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2453                 goto failed_0;
2454     }
2455
2456         fd = _dbus_connect_kdbus (path, error);
2457         if (fd < 0)
2458     {
2459                 _DBUS_ASSERT_ERROR_IS_SET (error);
2460                 goto failed_0;
2461     }
2462
2463         _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2464
2465         transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2466         if (transport == NULL)
2467     {
2468                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2469                 goto failed_1;
2470     }
2471
2472         _dbus_string_free (&address);
2473
2474         return transport;
2475
2476         failed_1:
2477                 _dbus_close_socket (fd, NULL);
2478         failed_0:
2479                 _dbus_string_free (&address);
2480         return NULL;
2481 }
2482
2483
2484 /**
2485  * Opens kdbus transport if method from address entry is kdbus
2486  *
2487  * @param entry the address entry to try opening
2488  * @param transport_p return location for the opened transport
2489  * @param error error to be set
2490  * @returns result of the attempt
2491  */
2492 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry  *entry,
2493                                                            DBusTransport    **transport_p,
2494                                                            DBusError         *error)
2495 {
2496         const char *method;
2497
2498         method = dbus_address_entry_get_method (entry);
2499         _dbus_assert (method != NULL);
2500
2501         if (strcmp (method, "kdbus") == 0)
2502     {
2503                 const char *path = dbus_address_entry_get_value (entry, "path");
2504
2505                 if (path == NULL)
2506         {
2507                         _dbus_set_bad_address (error, "kdbus", "path", NULL);
2508                         return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2509         }
2510
2511         *transport_p = _dbus_transport_new_for_kdbus (path, error);
2512
2513         if (*transport_p == NULL)
2514         {
2515                 _DBUS_ASSERT_ERROR_IS_SET (error);
2516                 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2517         }
2518         else
2519         {
2520                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2521                 return DBUS_TRANSPORT_OPEN_OK;
2522         }
2523     }
2524         else
2525     {
2526                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2527                 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
2528     }
2529 }
2530
2531 static struct kdbus_policy *make_policy_name(const char *name)
2532 {
2533         struct kdbus_policy *p;
2534         __u64 size;
2535
2536         size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
2537         p = malloc(size);
2538         if (!p)
2539                 return NULL;
2540         memset(p, 0, size);
2541         p->size = size;
2542         p->type = KDBUS_POLICY_NAME;
2543         strcpy(p->name, name);
2544
2545         return p;
2546 }
2547
2548 static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
2549 {
2550         struct kdbus_policy *p;
2551         __u64 size = sizeof(*p);
2552
2553         p = malloc(size);
2554         if (!p)
2555                 return NULL;
2556
2557         memset(p, 0, size);
2558         p->size = size;
2559         p->type = KDBUS_POLICY_ACCESS;
2560         p->access.type = type;
2561         p->access.bits = bits;
2562         p->access.id = id;
2563
2564         return p;
2565 }
2566
2567 static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
2568 {
2569         struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
2570
2571         if (cmd_policy->size + policy->size > max_size)
2572                 return;
2573
2574         memcpy(dst, policy, policy->size);
2575         cmd_policy->size += KDBUS_ALIGN8(policy->size);
2576         free(policy);
2577 }
2578
2579 /**
2580  * Registers kdbus policy for given connection.
2581  *
2582  * Policy sets rights of the name (unique or well known) on the bus. Without policy it is
2583  * not possible to send or receive messages. It must be set separately for unique id and
2584  * well known name of the connection. It is set after registering on the bus, but before
2585  * requesting for name. The policy is valid for the given name, not for the connection.
2586  *
2587  * Name of the policy equals name on the bus.
2588  *
2589  * @param name name of the policy = name of the connection
2590  * @param connection the connection
2591  * @param error place to store errors
2592  *
2593  * @returns #TRUE on success
2594  */
2595 dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connection, DBusError *error)
2596 {
2597         struct kdbus_cmd_policy *cmd_policy;
2598         struct kdbus_policy *policy;
2599         int size = 0xffff;
2600         int fd;
2601
2602         if(!dbus_connection_get_socket(connection, &fd))
2603         {
2604                 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
2605                 return FALSE;
2606         }
2607
2608         cmd_policy = alloca(size);
2609         memset(cmd_policy, 0, size);
2610
2611         policy = (struct kdbus_policy *) cmd_policy->policies;
2612         cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
2613
2614         policy = make_policy_name(name);
2615         append_policy(cmd_policy, policy, size);
2616
2617         policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
2618         append_policy(cmd_policy, policy, size);
2619
2620         policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
2621         append_policy(cmd_policy, policy, size);
2622
2623         policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
2624         append_policy(cmd_policy, policy, size);
2625
2626         if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
2627         {
2628                 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
2629                 return FALSE;
2630         }
2631
2632         _dbus_verbose("Policy %s set correctly\n", name);
2633         return TRUE;
2634 }
2635
2636 /**
2637  * Kdbus part of dbus_bus_register.
2638  * Shouldn't be used separately because it needs to be surrounded
2639  * by other functions as it is done in dbus_bus_register.
2640  *
2641  * @param name place to store unique name given by bus
2642  * @param connection the connection
2643  * @param error place to store errors
2644  * @returns #TRUE on success
2645  */
2646 dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error)
2647 {
2648         struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
2649         int fd;
2650
2651         hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
2652                            KDBUS_HELLO_ATTACH_COMM |
2653                            KDBUS_HELLO_ATTACH_EXE |
2654                            KDBUS_HELLO_ATTACH_CMDLINE |
2655                            KDBUS_HELLO_ATTACH_CAPS |
2656                            KDBUS_HELLO_ATTACH_CGROUP |
2657                            KDBUS_HELLO_ATTACH_SECLABEL |
2658                            KDBUS_HELLO_ATTACH_AUDIT*/;
2659         hello.size = sizeof(struct kdbus_cmd_hello);
2660         hello.pool_size = RECEIVE_POOL_SIZE;
2661
2662         if(!dbus_connection_get_socket(connection, &fd))
2663         {
2664                 dbus_set_error (error, "failed to get fd for bus registration", NULL);
2665                 return FALSE;
2666         }
2667         if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
2668         {
2669                 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
2670                 return FALSE;
2671         }
2672
2673         sprintf(name, "%llu", (unsigned long long)hello.id);
2674         _dbus_verbose("-- Our peer ID is: %s\n", name);
2675         ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size = hello.bloom_size;
2676
2677         if(!kdbus_mmap(dbus_connection_get_transport(connection)))
2678         {
2679                 dbus_set_error(error,_dbus_error_from_errno (errno), "Error when mmap: %s", _dbus_strerror (errno));
2680                 return FALSE;
2681         }
2682
2683         return TRUE;
2684 }
2685
2686 /**
2687  * kdbus version of dbus_bus_request_name.
2688  *
2689  * Asks the bus to assign the given name to this connection.
2690  *
2691  * Use same flags as original dbus version with one exception below.
2692  * Result flag #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER is currently
2693  * never returned by kdbus, instead DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
2694  * is returned by kdbus.
2695  *
2696  * @param connection the connection
2697  * @param name the name to request
2698  * @param flags flags
2699  * @param error location to store the error
2700  * @returns a result code, -1 if error is set
2701  */
2702 int bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
2703 {
2704         struct kdbus_cmd_name *cmd_name;
2705         int fd;
2706         uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
2707         uint64_t flags_kdbus = 0;
2708
2709         cmd_name = alloca(size);
2710
2711         memset(cmd_name, 0, size);
2712         strcpy(cmd_name->name, name);
2713         cmd_name->size = size;
2714
2715         if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
2716                 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
2717         if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
2718                 flags_kdbus |= KDBUS_NAME_QUEUE;
2719         if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
2720                 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
2721
2722         cmd_name->conn_flags = flags_kdbus;
2723
2724         if(!dbus_connection_get_socket(connection, &fd))
2725         {
2726                 dbus_set_error (error, "failed to get fd for name request", NULL);
2727                 return -1;
2728         }
2729
2730         _dbus_verbose("Request name - flags sent: 0x%llx       !!!!!!!!!\n", cmd_name->conn_flags);
2731
2732         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2733         if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
2734         {
2735                 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
2736                 if(errno == EEXIST)
2737                         return DBUS_REQUEST_NAME_REPLY_EXISTS;
2738                 return -1;
2739         }
2740
2741         _dbus_verbose("Request name - received flag: 0x%llx       !!!!!!!!!\n", cmd_name->conn_flags);
2742
2743         if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
2744                 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
2745         else
2746                 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
2747         /*todo now 1 code is never returned -  DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
2748          * because kdbus never returns it now
2749          */
2750 }
2751
2752 /**
2753  * Checks if the connection's transport is kdbus on the basis of its address
2754  * saves result in DBusConnection for performance.
2755  *
2756  * @param pointer to the connection
2757  * @returns TRUE if kdbus transport, otherwise FALSE
2758  */
2759 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
2760 {
2761         unsigned int is_kdbus;
2762
2763         is_kdbus = dbus_connection_get_is_kdbus(connection);
2764         if(is_kdbus == 0) 
2765         {
2766                 const char* address = _dbus_connection_get_address(connection);
2767
2768                 if(address)
2769                 {
2770                         if(address == strstr(address, "kdbus:path=")) 
2771                         {
2772                                 dbus_connection_set_is_kdbus(connection, 2);
2773                                 return TRUE;
2774                         } else {
2775                                 dbus_connection_set_is_kdbus(connection, 1);
2776                                 return FALSE;
2777                         }
2778                 }
2779         } 
2780         
2781         if(is_kdbus == 2) return TRUE;
2782         if(is_kdbus == 1) return FALSE;
2783         
2784         _dbus_verbose("is_kdbus is not 0 or 1 or 2. Should not happen! \n");
2785         return FALSE;
2786 }
2787
2788 /**
2789  * Seeks key in rule string, and duplicates value of the key into pValue.
2790  * If value is "org.freedesktop.DBus" it is indicated by returning -1, because it
2791  * needs to be handled in different manner.
2792  * Value is duplicated from rule string to newly allocated memory pointe by pValue,
2793  * so it must be freed after use.
2794  *
2795  * @param rule rule to look through
2796  * @param key key to look for
2797  * @param pValue pointer to value of the key found
2798  * @return length of the value string, 0 means not found, -1 means "org.freedesktop.DBus"
2799  */
2800 static int parse_match_key(const char *rule, const char* key, char** pValue)
2801 {
2802         const char* pBegin;
2803         const char* pValueEnd;
2804         int value_length = 0;
2805
2806         pBegin = strstr(rule, key);
2807         if(pBegin)
2808         {
2809                 pBegin += strlen(key);
2810                 pValueEnd = strchr(pBegin, '\'');
2811                 if(pValueEnd)
2812                 {
2813                         value_length = pValueEnd - pBegin;
2814                         *pValue = strndup(pBegin, value_length);
2815                         if(*pValue)
2816                         {
2817                                 if(strcmp(*pValue, "org.freedesktop.DBus") == 0)
2818                                         value_length = -1;
2819                                 _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue);
2820                         }
2821                 }
2822         }
2823         return value_length;
2824 }
2825
2826 /**
2827  * Adds a match rule to match broadcast messages going through the message bus.
2828  * Do no affect messages addressed directly.
2829  *
2830  * The "rule" argument is the string form of a match rule.
2831  *
2832  * In kdbus function do not blocks.
2833  *
2834  * Upper function returns nothing because of blocking issues
2835  * so there is no point to return true or false here.
2836  *
2837  * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism.
2838  * Current mapping:
2839  * interface match key mapped to bloom
2840  * sender match key mapped to src_name
2841  * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired
2842  *
2843  * @param connection connection to the message bus
2844  * @param rule textual form of match rule
2845  * @param error location to store any errors - may be NULL
2846  */
2847 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2848 {
2849         struct kdbus_cmd_match* pCmd_match;
2850         struct kdbus_item *pItem;
2851         int fd;
2852         __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
2853         uint64_t size;
2854         unsigned int kernel_item = 0;
2855         int name_size;
2856         char* pName = NULL;
2857         char* pInterface = NULL;
2858         __u64 bloom_size = ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size;
2859
2860         dbus_connection_get_socket(connection, &fd);
2861
2862         /*parsing rule and calculating size of command*/
2863         size = sizeof(struct kdbus_cmd_match);
2864
2865         if(strstr(rule, "member='NameOwnerChanged'"))
2866         {
2867                 kernel_item = ~0;
2868                 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2;  /*std DBus: 3 name related items plus 2 id related items*/
2869         }
2870         else if(strstr(rule, "member='NameChanged'"))
2871         {
2872                 kernel_item = KDBUS_MATCH_NAME_CHANGE;
2873                 size += KDBUS_ITEM_SIZE(1);
2874         }
2875         else if(strstr(rule, "member='NameLost'"))
2876         {
2877                 kernel_item = KDBUS_MATCH_NAME_REMOVE;
2878                 size += KDBUS_ITEM_SIZE(1);
2879         }
2880         else if(strstr(rule, "member='NameAcquired'"))
2881         {
2882                 kernel_item = KDBUS_MATCH_NAME_ADD;
2883                 size += KDBUS_ITEM_SIZE(1);
2884         }
2885
2886         name_size = parse_match_key(rule, "interface='", &pInterface);
2887         if((name_size == -1) && (kernel_item == 0))   //means org.freedesktop.DBus without specified member
2888         {
2889                 kernel_item = ~0;
2890                 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2;  /* 3 above name related items plus 2 id related items*/
2891         }
2892         else if(name_size > 0)                  /*actual size is not important for interface because bloom size is defined by bus*/
2893                 size += KDBUS_PART_HEADER_SIZE + bloom_size;
2894
2895         name_size = parse_match_key(rule, "sender='", &pName);
2896         if((name_size == -1) && (kernel_item == 0))  //means org.freedesktop.DBus without specified name - same as interface few line above
2897         {
2898                 kernel_item = ~0;
2899                 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above     name related items plus 2 id related items*/
2900         }
2901         else if(name_size > 0)
2902         {
2903                 if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
2904                 {
2905                         src_id = strtoull(&pName[3], NULL, 10);
2906                         free(pName);
2907                         pName = NULL;
2908                 }
2909                 else
2910                         size += KDBUS_ITEM_SIZE(name_size + 1);  //well known name
2911         }
2912
2913         pCmd_match = alloca(size);
2914         if(pCmd_match == NULL)
2915                 goto out;
2916
2917         pCmd_match->id = 0;
2918         pCmd_match->size = size;
2919         pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2920
2921         pItem = pCmd_match->items;
2922         if(kernel_item == ~0)  //all signals from kernel
2923         {
2924                 pCmd_match->src_id = 0;
2925                 pItem->type = KDBUS_MATCH_NAME_CHANGE;
2926                 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2927                 pItem = KDBUS_PART_NEXT(pItem);
2928                 pItem->type = KDBUS_MATCH_NAME_ADD;
2929                 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2930                 pItem = KDBUS_PART_NEXT(pItem);
2931                 pItem->type = KDBUS_MATCH_NAME_REMOVE;
2932                 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2933                 pItem = KDBUS_PART_NEXT(pItem);
2934                 pItem->type = KDBUS_MATCH_ID_ADD;
2935                 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2936                 pItem = KDBUS_PART_NEXT(pItem);
2937                 pItem->type = KDBUS_MATCH_ID_REMOVE;
2938                 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2939         }
2940         else if(kernel_item) //only one item
2941         {
2942                 pCmd_match->src_id = 0;
2943                 pItem->type = kernel_item;
2944                 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2945         }
2946         else
2947         {
2948                 pCmd_match->src_id = src_id;
2949                 if(pName)
2950                 {
2951                         pItem->type = KDBUS_MATCH_SRC_NAME;
2952                         pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
2953                         strcpy(pItem->str, pName);
2954                         pItem = KDBUS_PART_NEXT(pItem);
2955                 }
2956
2957                 if(pInterface)
2958                 {
2959                         pItem->type = KDBUS_MATCH_BLOOM;
2960                         pItem->size = KDBUS_PART_HEADER_SIZE + bloom_size;
2961                         strncpy(pItem->data, pInterface, bloom_size);
2962                 }
2963         }
2964
2965         if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
2966         {
2967                 if(error)
2968                         dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
2969                 _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
2970         }
2971         else
2972                 _dbus_verbose("Added match bus rule %s\n", rule);
2973
2974 out:
2975         if(pName)
2976                 free(pName);
2977         if(pInterface)
2978                 free(pInterface);
2979 }
2980
2981 /**
2982  * Opposing to dbus, in kdbus removes all match rules with given
2983  * cookie, which now is equal to uniqe id.
2984  *
2985  * In kdbus this function will not block
2986  *
2987  * @param connection connection to the message bus
2988  * @param error location to store any errors - may be NULL
2989  */
2990 void dbus_bus_remove_match_kdbus (DBusConnection *connection, DBusError *error)
2991 {
2992         struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
2993         int fd;
2994
2995         dbus_connection_get_socket(connection, &fd);
2996         cmd.cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2997         cmd.id = cmd.cookie;
2998         cmd.size = sizeof(struct kdbus_cmd_match);
2999
3000         if(ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd))
3001         {
3002                 if(error)
3003                         dbus_set_error(error,_dbus_error_from_errno (errno), "error removing match: %s", _dbus_strerror (errno));
3004                 _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno);
3005         }
3006         else
3007                 _dbus_verbose("Match rule removed correctly.\n");
3008 }