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