[lib-fix] libdbus refactored to eliminate "is kdbus" queries and branches in non...
[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 FALSE;
1141                         goto again;                                             //and try again
1142                 }
1143                 else
1144                 {
1145                         DBusMessage *reply;
1146                         DBusMessageIter args;
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, &args);
1155
1156                         for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
1157                         {
1158                                 pName = pCmd_name->name;
1159                                 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
1160                                 {
1161                                         dbus_message_unref(reply);
1162                                         goto out;
1163                                 }
1164                         }
1165
1166                         if(add_message_to_received(reply, transport->connection))
1167                         {
1168                                 free(pCmd);
1169                                 return TRUE;
1170                         }
1171                 }
1172 out:
1173                 if(pCmd)
1174                         free(pCmd);
1175                 return FALSE;
1176         }
1177         else if(!strcmp(dbus_message_get_member(message), "GetId"))
1178         {
1179                 char* path;
1180                 char uuid[DBUS_UUID_LENGTH_BYTES];
1181                 struct stat stats;
1182                 MD5_CTX md5;
1183                 DBusString binary, encoded;
1184
1185                 ret_value = FALSE;
1186                 path = &transport->address[11]; //start of kdbus bus path
1187                 if(stat(path, &stats) < -1)
1188                 {
1189                         _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno);
1190                         return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection);
1191                 }
1192
1193                 MD5_Init(&md5);
1194         MD5_Update(&md5, path, strlen(path));
1195         MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec));
1196                 MD5_Final(uuid, &md5);
1197
1198                 if(!_dbus_string_init (&encoded))
1199                         goto outgid;
1200                 _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES);
1201                 if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded)))
1202                         goto outb;
1203                 path = (char*)_dbus_string_get_const_data (&encoded);
1204                 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection);
1205
1206         outb:
1207                 _dbus_string_free(&binary);
1208                 _dbus_string_free(&encoded);
1209         outgid:
1210                 return ret_value;
1211         }
1212         else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData"))
1213         {
1214                 char* name = NULL;
1215
1216                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1217                 return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection);
1218         }
1219         else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
1220         {
1221                 char* name = NULL;
1222
1223                 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1224                 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1225                 if(inter_ret == -ENOENT)  //name has no owner
1226                         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);
1227                 else if(inter_ret < 0)
1228                         return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection);
1229                 else
1230                 {
1231                         DBusMessage *reply;
1232
1233                         ret_value = FALSE;
1234                         reply = dbus_message_new_method_return(message);
1235                         if(reply != NULL)
1236                         {
1237                                 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
1238                                 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
1239                                         dbus_message_unref(reply);
1240                                 else if(add_message_to_received(reply, transport->connection))
1241                                         ret_value = TRUE;
1242                         }
1243                 }
1244         }
1245         else
1246                 return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection);
1247 /*      else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames"))  //todo
1248         {
1249
1250         }
1251         else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
1252         {
1253
1254         }
1255         else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
1256         {
1257
1258         }
1259         else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
1260         {
1261
1262         }
1263         */
1264
1265         if(info.sec_label)
1266                 free(info.sec_label);
1267         return ret_value;
1268 }
1269
1270 #if KDBUS_MSG_DECODE_DEBUG == 1
1271 static char *msg_id(uint64_t id, char *buf)
1272 {
1273         if (id == 0)
1274                 return "KERNEL";
1275         if (id == ~0ULL)
1276                 return "BROADCAST";
1277         sprintf(buf, "%llu", (unsigned long long)id);
1278         return buf;
1279 }
1280 #endif
1281 struct kdbus_enum_table {
1282         long long id;
1283         const char *name;
1284 };
1285 #define _STRINGIFY(x) #x
1286 #define STRINGIFY(x) _STRINGIFY(x)
1287 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
1288 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
1289 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
1290 #define LOOKUP(what)                                                            \
1291         const char *enum_##what(long long id) {                                 \
1292         size_t i; \
1293                 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++)    \
1294                         if (id == kdbus_table_##what[i].id)                     \
1295                                 return kdbus_table_##what[i].name;              \
1296                 return "UNKNOWN";                                               \
1297         }
1298 const char *enum_MSG(long long id);
1299 TABLE(MSG) = {
1300         ENUM(_KDBUS_MSG_NULL),
1301         ENUM(KDBUS_MSG_PAYLOAD_VEC),
1302         ENUM(KDBUS_MSG_PAYLOAD_OFF),
1303         ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
1304         ENUM(KDBUS_MSG_FDS),
1305         ENUM(KDBUS_MSG_BLOOM),
1306         ENUM(KDBUS_MSG_DST_NAME),
1307         ENUM(KDBUS_MSG_SRC_CREDS),
1308         ENUM(KDBUS_MSG_SRC_PID_COMM),
1309         ENUM(KDBUS_MSG_SRC_TID_COMM),
1310         ENUM(KDBUS_MSG_SRC_EXE),
1311         ENUM(KDBUS_MSG_SRC_CMDLINE),
1312         ENUM(KDBUS_MSG_SRC_CGROUP),
1313         ENUM(KDBUS_MSG_SRC_CAPS),
1314         ENUM(KDBUS_MSG_SRC_SECLABEL),
1315         ENUM(KDBUS_MSG_SRC_AUDIT),
1316         ENUM(KDBUS_MSG_SRC_NAMES),
1317         ENUM(KDBUS_MSG_TIMESTAMP),
1318         ENUM(KDBUS_MSG_NAME_ADD),
1319         ENUM(KDBUS_MSG_NAME_REMOVE),
1320         ENUM(KDBUS_MSG_NAME_CHANGE),
1321         ENUM(KDBUS_MSG_ID_ADD),
1322         ENUM(KDBUS_MSG_ID_REMOVE),
1323         ENUM(KDBUS_MSG_REPLY_TIMEOUT),
1324         ENUM(KDBUS_MSG_REPLY_DEAD),
1325 };
1326 LOOKUP(MSG);
1327 const char *enum_PAYLOAD(long long id);
1328 TABLE(PAYLOAD) = {
1329         ENUM(KDBUS_PAYLOAD_KERNEL),
1330         ENUM(KDBUS_PAYLOAD_DBUS1),
1331         ENUM(KDBUS_PAYLOAD_GVARIANT),
1332 };
1333 LOOKUP(PAYLOAD);
1334
1335 /**
1336  * Puts locally generated message into received data buffer.
1337  * Use only during receiving phase!
1338  *
1339  * @param message message to load
1340  * @param data place to load message
1341  * @return size of message
1342  */
1343 static int put_message_into_data(DBusMessage *message, char* data)
1344 {
1345         int ret_size;
1346     const DBusString *header;
1347     const DBusString *body;
1348     int size;
1349
1350     dbus_message_set_serial(message, 1);
1351     dbus_message_lock (message);
1352     _dbus_message_get_network_data (message, &header, &body);
1353     ret_size = _dbus_string_get_length(header);
1354         memcpy(data, _dbus_string_get_const_data(header), ret_size);
1355         data += ret_size;
1356         size = _dbus_string_get_length(body);
1357         memcpy(data, _dbus_string_get_const_data(body), size);
1358         ret_size += size;
1359
1360         return ret_size;
1361 }
1362 /**
1363  * Decodes kdbus message in order to extract dbus message and put it into data and fds.
1364  * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
1365  * all of them into dbus messages.
1366  *
1367  * @param msg kdbus message
1368  * @param data place to copy dbus message to
1369  * @param socket_transport transport
1370  * @param fds place to store file descriptors received
1371  * @param n_fds place to store quantity of file descriptor
1372  * @return number of dbus message's bytes received or -1 on error
1373  */
1374 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
1375 {
1376         const struct kdbus_item *item;
1377         int ret_size = 0;
1378         DBusMessage *message = NULL;
1379         DBusMessageIter args;
1380         const char* emptyString = "";
1381     const char* pString = NULL;
1382         char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
1383         const char* pDBusName = dbus_name;
1384 #if KDBUS_MSG_DECODE_DEBUG == 1
1385         char buf[32];
1386 #endif
1387
1388 #if KDBUS_MSG_DECODE_DEBUG == 1
1389         _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s â†’ %s, cookie=%llu, timeout=%llu\n",
1390                 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
1391                 (unsigned long long) msg->flags,
1392                 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
1393                 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
1394 #endif
1395
1396         *n_fds = 0;
1397
1398         KDBUS_PART_FOREACH(item, msg, items)
1399         {
1400                 if (item->size <= KDBUS_PART_HEADER_SIZE)
1401                 {
1402                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
1403                         break;  //??? continue (because dbus will find error) or break
1404                 }
1405
1406                 switch (item->type)
1407                 {
1408                         case KDBUS_MSG_PAYLOAD_OFF:
1409                                 memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
1410                                 data += item->vec.size;
1411                                 ret_size += item->vec.size;                     
1412
1413                                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
1414                                         enum_MSG(item->type), item->size,
1415                                         (unsigned long long)item->vec.offset,
1416                                         (unsigned long long)item->vec.size);
1417                         break;
1418
1419                         case KDBUS_MSG_PAYLOAD_MEMFD:
1420                         {
1421                                 char *buf;
1422                                 uint64_t size;
1423
1424                 size = item->memfd.size;
1425                                 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
1426                                 
1427                                 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
1428                                 if (buf == MAP_FAILED) 
1429                                 {
1430                                         _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
1431                                         return -1;
1432                                 }
1433
1434                                 memcpy(data, buf, size); 
1435                                 data += size;
1436                                 ret_size += size;
1437
1438                                 munmap(buf, size);
1439
1440                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
1441                                            enum_MSG(item->type), item->size,
1442                                            (unsigned long long)item->vec.offset,
1443                                            (unsigned long long)item->vec.size);
1444                         break;
1445                         }
1446
1447                         case KDBUS_MSG_FDS:
1448                         {
1449                                 int i;
1450
1451                                 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
1452                                 memcpy(fds, item->fds, *n_fds * sizeof(int));
1453                     for (i = 0; i < *n_fds; i++)
1454                       _dbus_fd_set_close_on_exec(fds[i]);
1455                         break;
1456                         }
1457
1458 #if KDBUS_MSG_DECODE_DEBUG == 1
1459                         case KDBUS_MSG_SRC_CREDS:
1460                                 _dbus_verbose("  +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
1461                                         enum_MSG(item->type), item->size,
1462                                         item->creds.uid, item->creds.gid,
1463                                         item->creds.pid, item->creds.tid,
1464                                         item->creds.starttime);
1465                         break;
1466
1467                         case KDBUS_MSG_SRC_PID_COMM:
1468                         case KDBUS_MSG_SRC_TID_COMM:
1469                         case KDBUS_MSG_SRC_EXE:
1470                         case KDBUS_MSG_SRC_CGROUP:
1471                         case KDBUS_MSG_SRC_SECLABEL:
1472                         case KDBUS_MSG_DST_NAME:
1473                                 _dbus_verbose("  +%s (%llu bytes) '%s' (%zu)\n",
1474                                            enum_MSG(item->type), item->size, item->str, strlen(item->str));
1475                                 break;
1476
1477                         case KDBUS_MSG_SRC_CMDLINE:
1478                         case KDBUS_MSG_SRC_NAMES: {
1479                                 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
1480                                 const char *str = item->str;
1481                                 int count = 0;
1482
1483                                 _dbus_verbose("  +%s (%llu bytes) ", enum_MSG(item->type), item->size);
1484                                 while (size) {
1485                                         _dbus_verbose("'%s' ", str);
1486                                         size -= strlen(str) + 1;
1487                                         str += strlen(str) + 1;
1488                                         count++;
1489                                 }
1490
1491                                 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
1492                                 break;
1493                         }
1494
1495                         case KDBUS_MSG_SRC_AUDIT:
1496                                 _dbus_verbose("  +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
1497                                            enum_MSG(item->type), item->size,
1498                                            (unsigned long long)item->data64[0],
1499                                            (unsigned long long)item->data64[1]);
1500                                 break;
1501
1502                         case KDBUS_MSG_SRC_CAPS: {
1503                                 int n;
1504                                 const uint32_t *cap;
1505                                 int i;
1506
1507                                 _dbus_verbose("  +%s (%llu bytes) len=%llu bytes)\n",
1508                                            enum_MSG(item->type), item->size,
1509                                            (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
1510
1511                                 cap = item->data32;
1512                                 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
1513
1514                                 _dbus_verbose("    CapInh=");
1515                                 for (i = 0; i < n; i++)
1516                                         _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
1517
1518                                 _dbus_verbose(" CapPrm=");
1519                                 for (i = 0; i < n; i++)
1520                                         _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
1521
1522                                 _dbus_verbose(" CapEff=");
1523                                 for (i = 0; i < n; i++)
1524                                         _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
1525
1526                                 _dbus_verbose(" CapInh=");
1527                                 for (i = 0; i < n; i++)
1528                                         _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
1529                                 _dbus_verbose("\n");
1530                                 break;
1531                         }
1532
1533                         case KDBUS_MSG_TIMESTAMP:
1534                                 _dbus_verbose("  +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
1535                                            enum_MSG(item->type), item->size,
1536                                            (unsigned long long)item->timestamp.realtime_ns,
1537                                            (unsigned long long)item->timestamp.monotonic_ns);
1538                                 break;
1539 #endif
1540
1541                         case KDBUS_MSG_REPLY_TIMEOUT:
1542                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
1543                                            enum_MSG(item->type), item->size, msg->cookie_reply);
1544
1545                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
1546                                 if(message == NULL)
1547                                 {
1548                                         ret_size = -1;
1549                                         goto out;
1550                                 }
1551
1552                                 ret_size = put_message_into_data(message, data);
1553                         break;
1554
1555                         case KDBUS_MSG_REPLY_DEAD:
1556                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
1557                                            enum_MSG(item->type), item->size, msg->cookie_reply);
1558
1559                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
1560                                 if(message == NULL)
1561                                 {
1562                                         ret_size = -1;
1563                                         goto out;
1564                                 }
1565
1566                                 ret_size = put_message_into_data(message, data);
1567                         break;
1568
1569                         case KDBUS_MSG_NAME_ADD:
1570                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1571                                         enum_MSG(item->type), (unsigned long long) item->size,
1572                                         item->name_change.name, item->name_change.old_id,
1573                                         item->name_change.new_id, item->name_change.flags);
1574
1575                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1576                                 if(message == NULL)
1577                                 {
1578                                         ret_size = -1;
1579                                         goto out;
1580                                 }
1581
1582                                 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
1583                                 pString = item->name_change.name;
1584                                 _dbus_verbose ("Name added: %s\n", pString);
1585                             dbus_message_iter_init_append(message, &args);
1586                             ITER_APPEND_STR(pString)
1587                             ITER_APPEND_STR(emptyString)
1588                             ITER_APPEND_STR(pDBusName)
1589                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1590
1591                                 ret_size = put_message_into_data(message, data);
1592                         break;
1593
1594                         case KDBUS_MSG_NAME_REMOVE:
1595                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1596                                         enum_MSG(item->type), (unsigned long long) item->size,
1597                                         item->name_change.name, item->name_change.old_id,
1598                                         item->name_change.new_id, item->name_change.flags);
1599
1600                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
1601                                 if(message == NULL)
1602                                 {
1603                                         ret_size = -1;
1604                                         goto out;
1605                                 }
1606
1607                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1608                                 pString = item->name_change.name;
1609                                 _dbus_verbose ("Name removed: %s\n", pString);
1610                             dbus_message_iter_init_append(message, &args);
1611                             ITER_APPEND_STR(pString)
1612                             ITER_APPEND_STR(pDBusName)
1613                             ITER_APPEND_STR(emptyString)
1614                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1615
1616                                 ret_size = put_message_into_data(message, data);
1617                         break;
1618
1619                         case KDBUS_MSG_NAME_CHANGE:
1620                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1621                                         enum_MSG(item->type), (unsigned long long) item->size,
1622                                         item->name_change.name, item->name_change.old_id,
1623                                         item->name_change.new_id, item->name_change.flags);
1624
1625                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1626                                 if(message == NULL)
1627                                 {
1628                                         ret_size = -1;
1629                                         goto out;
1630                                 }
1631
1632                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1633                                 pString = item->name_change.name;
1634                                 _dbus_verbose ("Name changed: %s\n", pString);
1635                             dbus_message_iter_init_append(message, &args);
1636                             ITER_APPEND_STR(pString)
1637                             ITER_APPEND_STR(pDBusName)
1638                             sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
1639                             _dbus_verbose ("New id: %s\n", pDBusName);
1640                             ITER_APPEND_STR(pDBusName)
1641                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1642
1643                                 ret_size = put_message_into_data(message, data);
1644                         break;
1645
1646                         case KDBUS_MSG_ID_ADD:
1647                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
1648                                            enum_MSG(item->type), (unsigned long long) item->size,
1649                                            (unsigned long long) item->id_change.id,
1650                                            (unsigned long long) item->id_change.flags);
1651
1652                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1653                                 if(message == NULL)
1654                                 {
1655                                         ret_size = -1;
1656                                         goto out;
1657                                 }
1658
1659                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
1660                             dbus_message_iter_init_append(message, &args);
1661                             ITER_APPEND_STR(pDBusName)
1662                             ITER_APPEND_STR(emptyString)
1663                             ITER_APPEND_STR(pDBusName)
1664                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1665
1666                                 ret_size = put_message_into_data(message, data);
1667                         break;
1668
1669                         case KDBUS_MSG_ID_REMOVE:
1670                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
1671                                            enum_MSG(item->type), (unsigned long long) item->size,
1672                                            (unsigned long long) item->id_change.id,
1673                                            (unsigned long long) item->id_change.flags);
1674
1675                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1676                                 if(message == NULL)
1677                                 {
1678                                         ret_size = -1;
1679                                         goto out;
1680                                 }
1681
1682                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
1683                             dbus_message_iter_init_append(message, &args);
1684                             ITER_APPEND_STR(pDBusName)
1685                             ITER_APPEND_STR(pDBusName)
1686                             ITER_APPEND_STR(emptyString)
1687                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1688
1689                                 ret_size = put_message_into_data(message, data);
1690                         break;
1691 #if KDBUS_MSG_DECODE_DEBUG == 1
1692                         default:
1693                                 _dbus_verbose("  +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1694                         break;
1695 #endif
1696                 }
1697         }
1698
1699 #if KDBUS_MSG_DECODE_DEBUG == 1
1700
1701         if ((char *)item - ((char *)msg + msg->size) >= 8)
1702                 _dbus_verbose("invalid padding at end of message\n");
1703 #endif
1704
1705 out:
1706         if(message)
1707                 dbus_message_unref(message);
1708         return ret_size;
1709 }
1710
1711 /**
1712  * Reads message from kdbus and puts it into dbus buffer and fds
1713  *
1714  * @param transport transport
1715  * @param buffer place to copy received message to
1716  * @param fds place to store file descriptors sent in the message
1717  * @param n_fds place  to store number of file descriptors
1718  * @return size of received message on success, -1 on error
1719  */
1720 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1721 {
1722         int ret_size;
1723         uint64_t __attribute__ ((__aligned__(8))) offset;
1724         struct kdbus_msg *msg;
1725         char *data;
1726         int start;
1727
1728         start = _dbus_string_get_length (buffer);
1729         if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1730         {
1731                 errno = ENOMEM;
1732             return -1;
1733         }
1734         data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
1735
1736         again:
1737         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1738         {
1739                 if(errno == EINTR)
1740                         goto again;
1741                 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1742                 _dbus_string_set_length (buffer, start);
1743                 return -1;
1744         }
1745
1746         msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1747
1748         ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1749
1750         if(ret_size == -1) /* error */
1751         {
1752                 _dbus_string_set_length (buffer, start);
1753                 return -1;
1754         }
1755         else
1756                 _dbus_string_set_length (buffer, start + ret_size);
1757         
1758
1759         again2:
1760         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1761         {
1762                 if(errno == EINTR)
1763                         goto again2;
1764                 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1765                 return -1;
1766         }
1767
1768         return ret_size;
1769 }
1770
1771 static void
1772 free_watches (DBusTransport *transport)
1773 {
1774   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1775
1776   _dbus_verbose ("start\n");
1777
1778   if (socket_transport->read_watch)
1779     {
1780       if (transport->connection)
1781         _dbus_connection_remove_watch_unlocked (transport->connection,
1782                                                 socket_transport->read_watch);
1783       _dbus_watch_invalidate (socket_transport->read_watch);
1784       _dbus_watch_unref (socket_transport->read_watch);
1785       socket_transport->read_watch = NULL;
1786     }
1787
1788   if (socket_transport->write_watch)
1789     {
1790       if (transport->connection)
1791         _dbus_connection_remove_watch_unlocked (transport->connection,
1792                                                 socket_transport->write_watch);
1793       _dbus_watch_invalidate (socket_transport->write_watch);
1794       _dbus_watch_unref (socket_transport->write_watch);
1795       socket_transport->write_watch = NULL;
1796     }
1797
1798   _dbus_verbose ("end\n");
1799 }
1800
1801 static void
1802 socket_finalize (DBusTransport *transport)
1803 {
1804   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1805
1806   _dbus_verbose ("\n");
1807
1808   free_watches (transport);
1809
1810   _dbus_string_free (&socket_transport->encoded_outgoing);
1811   _dbus_string_free (&socket_transport->encoded_incoming);
1812
1813   _dbus_transport_finalize_base (transport);
1814
1815   _dbus_assert (socket_transport->read_watch == NULL);
1816   _dbus_assert (socket_transport->write_watch == NULL);
1817
1818   dbus_free (transport);
1819 }
1820
1821 static void
1822 check_write_watch (DBusTransport *transport)
1823 {
1824   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1825   dbus_bool_t needed;
1826
1827   if (transport->connection == NULL)
1828     return;
1829
1830   if (transport->disconnected)
1831     {
1832       _dbus_assert (socket_transport->write_watch == NULL);
1833       return;
1834     }
1835
1836   _dbus_transport_ref (transport);
1837
1838 #ifdef DBUS_AUTHENTICATION
1839   if (_dbus_transport_get_is_authenticated (transport))
1840 #endif
1841     needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1842 #ifdef DBUS_AUTHENTICATION
1843   else
1844     {
1845       if (transport->send_credentials_pending)
1846         needed = TRUE;
1847       else
1848         {
1849           DBusAuthState auth_state;
1850
1851           auth_state = _dbus_auth_do_work (transport->auth);
1852
1853           /* If we need memory we install the write watch just in case,
1854            * if there's no need for it, it will get de-installed
1855            * next time we try reading.
1856            */
1857           if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1858               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1859             needed = TRUE;
1860           else
1861             needed = FALSE;
1862         }
1863     }
1864 #endif
1865   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1866                  needed, transport->connection, socket_transport->write_watch,
1867                  socket_transport->fd,
1868                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1869
1870   _dbus_connection_toggle_watch_unlocked (transport->connection,
1871                                           socket_transport->write_watch,
1872                                           needed);
1873
1874   _dbus_transport_unref (transport);
1875 }
1876
1877 static void
1878 check_read_watch (DBusTransport *transport)
1879 {
1880   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1881   dbus_bool_t need_read_watch;
1882
1883   _dbus_verbose ("fd = %d\n",socket_transport->fd);
1884
1885   if (transport->connection == NULL)
1886     return;
1887
1888   if (transport->disconnected)
1889     {
1890       _dbus_assert (socket_transport->read_watch == NULL);
1891       return;
1892     }
1893
1894   _dbus_transport_ref (transport);
1895
1896 #ifdef DBUS_AUTHENTICATION
1897   if (_dbus_transport_get_is_authenticated (transport))
1898 #endif
1899     need_read_watch =
1900       (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1901       (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1902 #ifdef DBUS_AUTHENTICATION
1903   else
1904     {
1905       if (transport->receive_credentials_pending)
1906         need_read_watch = TRUE;
1907       else
1908         {
1909           /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1910            * is to avoid spinning on the file descriptor when we're waiting
1911            * to write or for some other part of the auth process
1912            */
1913           DBusAuthState auth_state;
1914
1915           auth_state = _dbus_auth_do_work (transport->auth);
1916
1917           /* If we need memory we install the read watch just in case,
1918            * if there's no need for it, it will get de-installed
1919            * next time we try reading. If we're authenticated we
1920            * install it since we normally have it installed while
1921            * authenticated.
1922            */
1923           if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1924               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1925               auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1926             need_read_watch = TRUE;
1927           else
1928             need_read_watch = FALSE;
1929         }
1930     }
1931 #endif
1932
1933   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
1934   _dbus_connection_toggle_watch_unlocked (transport->connection,
1935                                           socket_transport->read_watch,
1936                                           need_read_watch);
1937
1938   _dbus_transport_unref (transport);
1939 }
1940
1941 static void
1942 do_io_error (DBusTransport *transport)
1943 {
1944   _dbus_transport_ref (transport);
1945   _dbus_transport_disconnect (transport);
1946   _dbus_transport_unref (transport);
1947 }
1948
1949 #ifdef DBUS_AUTHENTICATION
1950 /* return value is whether we successfully read any new data. */
1951 static dbus_bool_t
1952 read_data_into_auth (DBusTransport *transport,
1953                      dbus_bool_t   *oom)
1954 {
1955   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1956   DBusString *buffer;
1957   int bytes_read;
1958
1959   *oom = FALSE;
1960
1961   _dbus_auth_get_buffer (transport->auth, &buffer);
1962
1963   bytes_read = kdbus_read_message(socket_transport, buffer);
1964
1965   _dbus_auth_return_buffer (transport->auth, buffer,
1966                             bytes_read > 0 ? bytes_read : 0);
1967
1968   if (bytes_read > 0)
1969     {
1970       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1971       return TRUE;
1972     }
1973   else if (bytes_read < 0)
1974     {
1975       /* EINTR already handled for us */
1976
1977       if (_dbus_get_is_errno_enomem ())
1978         {
1979           *oom = TRUE;
1980         }
1981       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1982         ; /* do nothing, just return FALSE below */
1983       else
1984         {
1985           _dbus_verbose ("Error reading from remote app: %s\n",
1986                          _dbus_strerror_from_errno ());
1987           do_io_error (transport);
1988         }
1989
1990       return FALSE;
1991     }
1992   else
1993     {
1994       _dbus_assert (bytes_read == 0);
1995
1996       _dbus_verbose ("Disconnected from remote app\n");
1997       do_io_error (transport);
1998
1999       return FALSE;
2000     }
2001 }
2002
2003 /* Return value is whether we successfully wrote any bytes */
2004 static dbus_bool_t
2005 write_data_from_auth (DBusTransport *transport)
2006 {
2007   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2008   int bytes_written;
2009   const DBusString *buffer;
2010
2011   if (!_dbus_auth_get_bytes_to_send (transport->auth,
2012                                      &buffer))
2013     return FALSE;
2014
2015   bytes_written = _dbus_write_socket (socket_transport->fd,
2016                                       buffer,
2017                                       0, _dbus_string_get_length (buffer));
2018
2019   if (bytes_written > 0)
2020     {
2021       _dbus_auth_bytes_sent (transport->auth, bytes_written);
2022       return TRUE;
2023     }
2024   else if (bytes_written < 0)
2025     {
2026       /* EINTR already handled for us */
2027
2028       if (_dbus_get_is_errno_eagain_or_ewouldblock ())
2029         ;
2030       else
2031         {
2032           _dbus_verbose ("Error writing to remote app: %s\n",
2033                          _dbus_strerror_from_errno ());
2034           do_io_error (transport);
2035         }
2036     }
2037
2038   return FALSE;
2039 }
2040
2041 /* FALSE on OOM */
2042 static dbus_bool_t
2043 exchange_credentials (DBusTransport *transport,
2044                       dbus_bool_t    do_reading,
2045                       dbus_bool_t    do_writing)
2046 {
2047   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2048   DBusError error = DBUS_ERROR_INIT;
2049
2050   _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
2051                   do_reading, do_writing);
2052
2053   if (do_writing && transport->send_credentials_pending)
2054     {
2055       if (_dbus_send_credentials_socket (socket_transport->fd,
2056                                          &error))
2057         {
2058           transport->send_credentials_pending = FALSE;
2059         }
2060       else
2061         {
2062           _dbus_verbose ("Failed to write credentials: %s\n", error.message);
2063           dbus_error_free (&error);
2064           do_io_error (transport);
2065         }
2066     }
2067
2068   if (do_reading && transport->receive_credentials_pending)
2069     {
2070       /* FIXME this can fail due to IO error _or_ OOM, broken
2071        * (somewhat tricky to fix since the OOM error can be set after
2072        * we already read the credentials byte, so basically we need to
2073        * separate reading the byte and storing it in the
2074        * transport->credentials). Does not really matter for now
2075        * because storing in credentials never actually fails on unix.
2076        */
2077       if (_dbus_read_credentials_socket (socket_transport->fd,
2078                                          transport->credentials,
2079                                          &error))
2080         {
2081           transport->receive_credentials_pending = FALSE;
2082         }
2083       else
2084         {
2085           _dbus_verbose ("Failed to read credentials %s\n", error.message);
2086           dbus_error_free (&error);
2087           do_io_error (transport);
2088         }
2089     }
2090
2091   if (!(transport->send_credentials_pending ||
2092         transport->receive_credentials_pending))
2093     {
2094       if (!_dbus_auth_set_credentials (transport->auth,
2095                                        transport->credentials))
2096         return FALSE;
2097     }
2098
2099   return TRUE;
2100 }
2101
2102 static dbus_bool_t
2103 do_authentication (DBusTransport *transport,
2104                    dbus_bool_t    do_reading,
2105                    dbus_bool_t    do_writing,
2106                    dbus_bool_t   *auth_completed)
2107 {
2108   dbus_bool_t oom;
2109   dbus_bool_t orig_auth_state;
2110
2111   oom = FALSE;
2112
2113   orig_auth_state = _dbus_transport_get_is_authenticated (transport);
2114
2115   /* This is essential to avoid the check_write_watch() at the end,
2116    * we don't want to add a write watch in do_iteration before
2117    * we try writing and get EAGAIN
2118    */
2119   if (orig_auth_state)
2120     {
2121       if (auth_completed)
2122         *auth_completed = FALSE;
2123       return TRUE;
2124     }
2125
2126   _dbus_transport_ref (transport);
2127
2128   while (!_dbus_transport_get_is_authenticated (transport) &&
2129          _dbus_transport_get_is_connected (transport))
2130     {
2131       if (!exchange_credentials (transport, do_reading, do_writing))
2132         {
2133           oom = TRUE;
2134           goto out;
2135         }
2136
2137       if (transport->send_credentials_pending ||
2138           transport->receive_credentials_pending)
2139         {
2140           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
2141                          transport->send_credentials_pending,
2142                          transport->receive_credentials_pending);
2143           goto out;
2144         }
2145
2146 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
2147       switch (_dbus_auth_do_work (transport->auth))
2148         {
2149         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
2150           _dbus_verbose (" %s auth state: waiting for input\n",
2151                          TRANSPORT_SIDE (transport));
2152           if (!do_reading || !read_data_into_auth (transport, &oom))
2153             goto out;
2154           break;
2155
2156         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
2157           _dbus_verbose (" %s auth state: waiting for memory\n",
2158                          TRANSPORT_SIDE (transport));
2159           oom = TRUE;
2160           goto out;
2161           break;
2162
2163         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
2164           _dbus_verbose (" %s auth state: bytes to send\n",
2165                          TRANSPORT_SIDE (transport));
2166           if (!do_writing || !write_data_from_auth (transport))
2167             goto out;
2168           break;
2169
2170         case DBUS_AUTH_STATE_NEED_DISCONNECT:
2171           _dbus_verbose (" %s auth state: need to disconnect\n",
2172                          TRANSPORT_SIDE (transport));
2173           do_io_error (transport);
2174           break;
2175
2176         case DBUS_AUTH_STATE_AUTHENTICATED:
2177           _dbus_verbose (" %s auth state: authenticated\n",
2178                          TRANSPORT_SIDE (transport));
2179           break;
2180         }
2181     }
2182
2183  out:
2184   if (auth_completed)
2185     *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
2186
2187   check_read_watch (transport);
2188   check_write_watch (transport);
2189   _dbus_transport_unref (transport);
2190
2191   if (oom)
2192     return FALSE;
2193   else
2194     return TRUE;
2195 }
2196 #endif
2197
2198 /* returns false on oom */
2199 static dbus_bool_t
2200 do_writing (DBusTransport *transport)
2201 {
2202         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2203         dbus_bool_t oom;
2204
2205 #ifdef DBUS_AUTHENTICATION
2206         /* No messages without authentication! */
2207         if (!_dbus_transport_get_is_authenticated (transport))
2208     {
2209                 _dbus_verbose ("Not authenticated, not writing anything\n");
2210                 return TRUE;
2211     }
2212 #endif
2213
2214         if (transport->disconnected)
2215     {
2216                 _dbus_verbose ("Not connected, not writing anything\n");
2217                 return TRUE;
2218     }
2219
2220 #if 1
2221         _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
2222                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
2223                  socket_transport->fd);
2224 #endif
2225
2226         oom = FALSE;
2227
2228         while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2229     {
2230                 int bytes_written;
2231                 DBusMessage *message;
2232                 const DBusString *header;
2233                 const DBusString *body;
2234                 int total_bytes_to_write;
2235                 const char* pDestination;
2236
2237                 message = _dbus_connection_get_message_to_send (transport->connection);
2238                 _dbus_assert (message != NULL);
2239                 dbus_message_unlock(message);
2240             dbus_message_set_sender(message, socket_transport->sender);
2241                 dbus_message_lock (message);
2242                 _dbus_message_get_network_data (message, &header, &body);
2243                 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
2244                 pDestination = dbus_message_get_destination(message);
2245
2246                 if(pDestination)
2247                 {
2248                         if(!strcmp(pDestination, "org.freedesktop.DBus"))
2249                         {
2250                                 if(!strcmp(dbus_message_get_interface(message), DBUS_INTERFACE_DBUS))
2251                                 {
2252                                         int ret;
2253
2254                                         ret = emulateOrgFreedesktopDBus(transport, message);
2255                                         if(ret < 0)
2256                                         {
2257                                                 bytes_written = -1;
2258                                                 goto written;
2259                                         }
2260                                         else if(ret == 0)
2261                                         {
2262                                                 bytes_written = total_bytes_to_write;
2263                                                 goto written;
2264                                         }
2265                                         //else send to "daemon" as to normal recipient
2266                                 }
2267                         }
2268                 }
2269                 if (_dbus_auth_needs_encoding (transport->auth))
2270         {
2271                         if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
2272             {
2273                                 if (!_dbus_auth_encode_data (transport->auth,
2274                                            header, &socket_transport->encoded_outgoing))
2275                 {
2276                                         oom = TRUE;
2277                                         goto out;
2278                 }
2279
2280                                 if (!_dbus_auth_encode_data (transport->auth,
2281                                            body, &socket_transport->encoded_outgoing))
2282                 {
2283                                         _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
2284                                         oom = TRUE;
2285                                         goto out;
2286                 }
2287             }
2288
2289                         total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
2290                         if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
2291                                 return -E2BIG;
2292
2293                         bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
2294         }
2295                 else
2296                 {
2297                         if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
2298                                 return -E2BIG;
2299
2300                         bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
2301                 }
2302
2303 written:
2304                 if (bytes_written < 0)
2305                 {
2306                         /* EINTR already handled for us */
2307
2308           /* For some discussion of why we also ignore EPIPE here, see
2309            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
2310            */
2311
2312                         if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
2313                                 goto out;
2314                         else
2315                         {
2316                                 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
2317                                 do_io_error (transport);
2318                                 goto out;
2319                         }
2320                 }
2321                 else
2322                 {
2323                         _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
2324                          total_bytes_to_write);
2325
2326                         socket_transport->message_bytes_written += bytes_written;
2327
2328                         _dbus_assert (socket_transport->message_bytes_written <=
2329                         total_bytes_to_write);
2330
2331                           if (socket_transport->message_bytes_written == total_bytes_to_write)
2332                           {
2333                                   socket_transport->message_bytes_written = 0;
2334                                   _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
2335                                   _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
2336
2337                                   _dbus_connection_message_sent_unlocked (transport->connection,
2338                                                                                                                   message);
2339                           }
2340                 }
2341     }
2342
2343         out:
2344         if (oom)
2345                 return FALSE;
2346         return TRUE;
2347 }
2348
2349 /* returns false on out-of-memory */
2350 static dbus_bool_t
2351 do_reading (DBusTransport *transport)
2352 {
2353   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2354   DBusString *buffer;
2355   int bytes_read;
2356   dbus_bool_t oom = FALSE;
2357   int *fds, n_fds;
2358
2359   _dbus_verbose ("fd = %d\n",socket_transport->fd);
2360
2361 #ifdef DBUS_AUTHENTICATION
2362   /* No messages without authentication! */
2363   if (!_dbus_transport_get_is_authenticated (transport))
2364     return TRUE;
2365 #endif
2366
2367  again:
2368
2369   /* See if we've exceeded max messages and need to disable reading */
2370   check_read_watch (transport);
2371
2372   _dbus_assert (socket_transport->read_watch != NULL ||
2373                 transport->disconnected);
2374
2375   if (transport->disconnected)
2376     goto out;
2377
2378   if (!dbus_watch_get_enabled (socket_transport->read_watch))
2379     return TRUE;
2380
2381   if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
2382   {
2383       _dbus_verbose ("Out of memory reading file descriptors\n");
2384       oom = TRUE;
2385       goto out;
2386   }
2387   _dbus_message_loader_get_buffer (transport->loader, &buffer);
2388
2389   if (_dbus_auth_needs_decoding (transport->auth))
2390   {
2391           bytes_read = kdbus_read_message(socket_transport,  &socket_transport->encoded_incoming, fds, &n_fds);
2392
2393       _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
2394
2395       if (bytes_read > 0)
2396       {
2397           if (!_dbus_auth_decode_data (transport->auth,
2398                                        &socket_transport->encoded_incoming,
2399                                        buffer))
2400           {
2401               _dbus_verbose ("Out of memory decoding incoming data\n");
2402               _dbus_message_loader_return_buffer (transport->loader,
2403                                               buffer,
2404                                               _dbus_string_get_length (buffer));
2405               oom = TRUE;
2406               goto out;
2407           }
2408
2409           _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
2410           _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
2411       }
2412   }
2413   else
2414           bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
2415
2416   if (bytes_read >= 0 && n_fds > 0)
2417     _dbus_verbose("Read %i unix fds\n", n_fds);
2418
2419   _dbus_message_loader_return_buffer (transport->loader,
2420                                       buffer,
2421                                       bytes_read < 0 ? 0 : bytes_read);
2422   _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
2423
2424   if (bytes_read < 0)
2425     {
2426       /* EINTR already handled for us */
2427
2428       if (_dbus_get_is_errno_enomem ())
2429         {
2430           _dbus_verbose ("Out of memory in read()/do_reading()\n");
2431           oom = TRUE;
2432           goto out;
2433         }
2434       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
2435         goto out;
2436       else
2437         {
2438           _dbus_verbose ("Error reading from remote app: %s\n",
2439                          _dbus_strerror_from_errno ());
2440           do_io_error (transport);
2441           goto out;
2442         }
2443     }
2444   else if (bytes_read == 0)
2445     {
2446       _dbus_verbose ("Disconnected from remote app\n");
2447       do_io_error (transport);
2448       goto out;
2449     }
2450   else
2451     {
2452       _dbus_verbose (" read %d bytes\n", bytes_read);
2453
2454       if (!_dbus_transport_queue_messages (transport))
2455         {
2456           oom = TRUE;
2457           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
2458           goto out;
2459         }
2460
2461       /* Try reading more data until we get EAGAIN and return, or
2462        * exceed max bytes per iteration.  If in blocking mode of
2463        * course we'll block instead of returning.
2464        */
2465       goto again;
2466     }
2467
2468  out:
2469   if (oom)
2470     return FALSE;
2471   return TRUE;
2472 }
2473
2474 static dbus_bool_t
2475 unix_error_with_read_to_come (DBusTransport *itransport,
2476                               DBusWatch     *watch,
2477                               unsigned int   flags)
2478 {
2479    DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
2480
2481    if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
2482       return FALSE;
2483
2484   /* If we have a read watch enabled ...
2485      we -might have data incoming ... => handle the HANGUP there */
2486    if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
2487       return FALSE;
2488
2489    return TRUE;
2490 }
2491
2492 static dbus_bool_t
2493 socket_handle_watch (DBusTransport *transport,
2494                    DBusWatch     *watch,
2495                    unsigned int   flags)
2496 {
2497   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2498
2499   _dbus_assert (watch == socket_transport->read_watch ||
2500                 watch == socket_transport->write_watch);
2501   _dbus_assert (watch != NULL);
2502
2503   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
2504    * still be in the buffer and do_reading may need several iteration to read
2505    * it all (because of its max_bytes_read_per_iteration limit).
2506    */
2507   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
2508     {
2509       _dbus_verbose ("Hang up or error on watch\n");
2510       _dbus_transport_disconnect (transport);
2511       return TRUE;
2512     }
2513
2514   if (watch == socket_transport->read_watch &&
2515       (flags & DBUS_WATCH_READABLE))
2516     {
2517 #ifdef DBUS_AUTHENTICATION
2518       dbus_bool_t auth_finished;
2519 #endif
2520 #if 1
2521       _dbus_verbose ("handling read watch %p flags = %x\n",
2522                      watch, flags);
2523 #endif
2524 #ifdef DBUS_AUTHENTICATION
2525       if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
2526         return FALSE;
2527
2528       /* We don't want to do a read immediately following
2529        * a successful authentication.  This is so we
2530        * have a chance to propagate the authentication
2531        * state further up.  Specifically, we need to
2532        * process any pending data from the auth object.
2533        */
2534       if (!auth_finished)
2535         {
2536 #endif
2537           if (!do_reading (transport))
2538             {
2539               _dbus_verbose ("no memory to read\n");
2540               return FALSE;
2541             }
2542 #ifdef DBUS_AUTHENTICATION
2543         }
2544       else
2545         {
2546           _dbus_verbose ("Not reading anything since we just completed the authentication\n");
2547         }
2548 #endif
2549     }
2550   else if (watch == socket_transport->write_watch &&
2551            (flags & DBUS_WATCH_WRITABLE))
2552     {
2553 #if 1
2554       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
2555                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
2556 #endif
2557 #ifdef DBUS_AUTHENTICATION
2558       if (!do_authentication (transport, FALSE, TRUE, NULL))
2559         return FALSE;
2560 #endif
2561       if (!do_writing (transport))
2562         {
2563           _dbus_verbose ("no memory to write\n");
2564           return FALSE;
2565         }
2566
2567       /* See if we still need the write watch */
2568       check_write_watch (transport);
2569     }
2570 #ifdef DBUS_ENABLE_VERBOSE_MODE
2571   else
2572     {
2573       if (watch == socket_transport->read_watch)
2574         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
2575                        flags);
2576       else if (watch == socket_transport->write_watch)
2577         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
2578                        flags);
2579       else
2580         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
2581                        watch, dbus_watch_get_socket (watch));
2582     }
2583 #endif /* DBUS_ENABLE_VERBOSE_MODE */
2584
2585   return TRUE;
2586 }
2587
2588 static void
2589 socket_disconnect (DBusTransport *transport)
2590 {
2591   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2592
2593   _dbus_verbose ("\n");
2594
2595   free_watches (transport);
2596
2597   _dbus_close_socket (socket_transport->fd, NULL);
2598   socket_transport->fd = -1;
2599 }
2600
2601 static dbus_bool_t
2602 kdbus_connection_set (DBusTransport *transport)
2603 {
2604   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2605
2606   dbus_connection_set_is_authenticated(transport->connection); //todo remove when authentication will work
2607
2608   _dbus_watch_set_handler (socket_transport->write_watch,
2609                            _dbus_connection_handle_watch,
2610                            transport->connection, NULL);
2611
2612   _dbus_watch_set_handler (socket_transport->read_watch,
2613                            _dbus_connection_handle_watch,
2614                            transport->connection, NULL);
2615
2616   if (!_dbus_connection_add_watch_unlocked (transport->connection,
2617                                             socket_transport->write_watch))
2618     return FALSE;
2619
2620   if (!_dbus_connection_add_watch_unlocked (transport->connection,
2621                                             socket_transport->read_watch))
2622     {
2623       _dbus_connection_remove_watch_unlocked (transport->connection,
2624                                               socket_transport->write_watch);
2625       return FALSE;
2626     }
2627
2628   check_read_watch (transport);
2629   check_write_watch (transport);
2630
2631   return TRUE;
2632 }
2633
2634 /**
2635  * @todo We need to have a way to wake up the select sleep if
2636  * a new iteration request comes in with a flag (read/write) that
2637  * we're not currently serving. Otherwise a call that just reads
2638  * could block a write call forever (if there are no incoming
2639  * messages).
2640  */
2641 static  void
2642 kdbus_do_iteration (DBusTransport *transport,
2643                    unsigned int   flags,
2644                    int            timeout_milliseconds)
2645 {
2646         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2647         DBusPollFD poll_fd;
2648         int poll_res;
2649         int poll_timeout;
2650
2651         _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2652                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
2653                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2654                  timeout_milliseconds,
2655                  socket_transport->read_watch,
2656                  socket_transport->write_watch,
2657                  socket_transport->fd);
2658
2659   /* the passed in DO_READING/DO_WRITING flags indicate whether to
2660    * read/write messages, but regardless of those we may need to block
2661    * for reading/writing to do auth.  But if we do reading for auth,
2662    * we don't want to read any messages yet if not given DO_READING.
2663    */
2664
2665    poll_fd.fd = socket_transport->fd;
2666    poll_fd.events = 0;
2667
2668    if (_dbus_transport_peek_is_authenticated (transport))
2669    {
2670       /* This is kind of a hack; if we have stuff to write, then try
2671        * to avoid the poll. This is probably about a 5% speedup on an
2672        * echo client/server.
2673        *
2674        * If both reading and writing were requested, we want to avoid this
2675        * since it could have funky effects:
2676        *   - both ends spinning waiting for the other one to read
2677        *     data so they can finish writing
2678        *   - prioritizing all writing ahead of reading
2679        */
2680       if ((flags & DBUS_ITERATION_DO_WRITING) &&
2681           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2682           !transport->disconnected &&
2683           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2684       {
2685          do_writing (transport);
2686
2687          if (transport->disconnected ||
2688               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2689             goto out;
2690       }
2691
2692       /* If we get here, we decided to do the poll() after all */
2693       _dbus_assert (socket_transport->read_watch);
2694       if (flags & DBUS_ITERATION_DO_READING)
2695              poll_fd.events |= _DBUS_POLLIN;
2696
2697       _dbus_assert (socket_transport->write_watch);
2698       if (flags & DBUS_ITERATION_DO_WRITING)
2699          poll_fd.events |= _DBUS_POLLOUT;
2700    }
2701    else
2702    {
2703       DBusAuthState auth_state;
2704
2705       auth_state = _dbus_auth_do_work (transport->auth);
2706
2707       if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2708              poll_fd.events |= _DBUS_POLLIN;
2709
2710       if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2711              poll_fd.events |= _DBUS_POLLOUT;
2712    }
2713
2714    if (poll_fd.events)
2715    {
2716       if (flags & DBUS_ITERATION_BLOCK)
2717              poll_timeout = timeout_milliseconds;
2718       else
2719              poll_timeout = 0;
2720
2721       /* For blocking selects we drop the connection lock here
2722        * to avoid blocking out connection access during a potentially
2723        * indefinite blocking call. The io path is still protected
2724        * by the io_path_cond condvar, so we won't reenter this.
2725        */
2726       if (flags & DBUS_ITERATION_BLOCK)
2727       {
2728          _dbus_verbose ("unlock pre poll\n");
2729          _dbus_connection_unlock (transport->connection);
2730       }
2731
2732     again:
2733       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2734
2735       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2736       {
2737          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2738          goto again;
2739       }
2740
2741       if (flags & DBUS_ITERATION_BLOCK)
2742       {
2743          _dbus_verbose ("lock post poll\n");
2744          _dbus_connection_lock (transport->connection);
2745       }
2746
2747       if (poll_res >= 0)
2748       {
2749          if (poll_res == 0)
2750             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2751                                   * valgrind flags it as an error. though it probably
2752                                   * is guaranteed on linux at least.
2753                                   */
2754
2755          if (poll_fd.revents & _DBUS_POLLERR)
2756             do_io_error (transport);
2757          else
2758          {
2759             dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2760             dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2761 #ifdef DBUS_AUTHENTICATION
2762               dbus_bool_t authentication_completed;
2763 #endif
2764
2765             _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2766                              need_read, need_write);
2767 #ifdef DBUS_AUTHENTICATION
2768               do_authentication (transport, need_read, need_write,
2769                                  &authentication_completed);
2770
2771               /* See comment in socket_handle_watch. */
2772               if (authentication_completed)
2773                 goto out;
2774 #endif
2775             if (need_read && (flags & DBUS_ITERATION_DO_READING))
2776                do_reading (transport);
2777             if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2778                do_writing (transport);
2779          }
2780       }
2781       else
2782          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2783    }
2784
2785  out:
2786   /* We need to install the write watch only if we did not
2787    * successfully write everything. Note we need to be careful that we
2788    * don't call check_write_watch *before* do_writing, since it's
2789    * inefficient to add the write watch, and we can avoid it most of
2790    * the time since we can write immediately.
2791    *
2792    * However, we MUST always call check_write_watch(); DBusConnection code
2793    * relies on the fact that running an iteration will notice that
2794    * messages are pending.
2795    */
2796    check_write_watch (transport);
2797
2798    _dbus_verbose (" ... leaving do_iteration()\n");
2799 }
2800
2801 static void
2802 socket_live_messages_changed (DBusTransport *transport)
2803 {
2804   /* See if we should look for incoming messages again */
2805   check_read_watch (transport);
2806 }
2807
2808 static const DBusTransportVTable kdbus_vtable = {
2809   socket_finalize,
2810   socket_handle_watch,
2811   socket_disconnect,
2812   kdbus_connection_set,
2813   kdbus_do_iteration,
2814   socket_live_messages_changed,
2815   socket_get_socket_fd
2816 };
2817
2818 /**
2819  * Creates a new transport for the given kdbus file descriptor.  The file
2820  * descriptor must be nonblocking.
2821  *
2822  * @param fd the file descriptor.
2823  * @param address the transport's address
2824  * @returns the new transport, or #NULL if no memory.
2825  */
2826 static DBusTransport*
2827 _dbus_transport_new_for_socket_kdbus (int       fd,
2828                                           const DBusString *address)
2829 {
2830         DBusTransportSocket *socket_transport;
2831
2832   socket_transport = dbus_new0 (DBusTransportSocket, 1);
2833   if (socket_transport == NULL)
2834     return NULL;
2835
2836   if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2837     goto failed_0;
2838
2839   if (!_dbus_string_init (&socket_transport->encoded_incoming))
2840     goto failed_1;
2841
2842   socket_transport->write_watch = _dbus_watch_new (fd,
2843                                                  DBUS_WATCH_WRITABLE,
2844                                                  FALSE,
2845                                                  NULL, NULL, NULL);
2846   if (socket_transport->write_watch == NULL)
2847     goto failed_2;
2848
2849   socket_transport->read_watch = _dbus_watch_new (fd,
2850                                                 DBUS_WATCH_READABLE,
2851                                                 FALSE,
2852                                                 NULL, NULL, NULL);
2853   if (socket_transport->read_watch == NULL)
2854     goto failed_3;
2855
2856   if (!_dbus_transport_init_base (&socket_transport->base,
2857                                   &kdbus_vtable,
2858                                   NULL, address))
2859     goto failed_4;
2860
2861 #ifdef DBUS_AUTHENTICATION
2862 #ifdef HAVE_UNIX_FD_PASSING
2863   _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2864 #endif
2865 #endif
2866
2867   socket_transport->fd = fd;
2868   socket_transport->message_bytes_written = 0;
2869
2870   /* These values should probably be tunable or something. */
2871   socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2872   socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2873
2874   socket_transport->kdbus_mmap_ptr = NULL;
2875   socket_transport->memfd = -1;
2876   
2877   return (DBusTransport*) socket_transport;
2878
2879  failed_4:
2880   _dbus_watch_invalidate (socket_transport->read_watch);
2881   _dbus_watch_unref (socket_transport->read_watch);
2882  failed_3:
2883   _dbus_watch_invalidate (socket_transport->write_watch);
2884   _dbus_watch_unref (socket_transport->write_watch);
2885  failed_2:
2886   _dbus_string_free (&socket_transport->encoded_incoming);
2887  failed_1:
2888   _dbus_string_free (&socket_transport->encoded_outgoing);
2889  failed_0:
2890   dbus_free (socket_transport);
2891   return NULL;
2892 }
2893
2894
2895 /**
2896  * Opens a connection to the kdbus bus
2897  *
2898  * This will set FD_CLOEXEC for the socket returned.
2899  *
2900  * @param path the path to UNIX domain socket
2901  * @param error return location for error code
2902  * @returns connection file descriptor or -1 on error
2903  */
2904 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2905 {
2906         int fd;
2907
2908         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2909         _dbus_verbose ("connecting to kdbus bus %s\n", path);
2910
2911         fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2912         if (fd < 0)
2913                 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2914
2915         return fd;
2916 }
2917
2918 /**
2919  * Creates a new transport for kdbus.
2920  * This creates a client-side of a transport.
2921  *
2922  * @param path the path to the bus.
2923  * @param error address where an error can be returned.
2924  * @returns a new transport, or #NULL on failure.
2925  */
2926 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2927 {
2928         int fd;
2929         DBusTransport *transport;
2930         DBusString address;
2931
2932         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2933
2934         if (!_dbus_string_init (&address))
2935     {
2936                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2937                 return NULL;
2938     }
2939
2940         fd = -1;
2941
2942         if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2943     {
2944                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2945                 goto failed_0;
2946     }
2947
2948         fd = _dbus_connect_kdbus (path, error);
2949         if (fd < 0)
2950     {
2951                 _DBUS_ASSERT_ERROR_IS_SET (error);
2952                 goto failed_0;
2953     }
2954
2955         _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2956
2957         transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2958         if (transport == NULL)
2959     {
2960                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2961                 goto failed_1;
2962     }
2963
2964         _dbus_string_free (&address);
2965
2966         return transport;
2967
2968         failed_1:
2969                 _dbus_close_socket (fd, NULL);
2970         failed_0:
2971                 _dbus_string_free (&address);
2972         return NULL;
2973 }
2974
2975
2976 /**
2977  * Opens kdbus transport if method from address entry is kdbus
2978  *
2979  * @param entry the address entry to try opening
2980  * @param transport_p return location for the opened transport
2981  * @param error error to be set
2982  * @returns result of the attempt
2983  */
2984 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry  *entry,
2985                                                            DBusTransport    **transport_p,
2986                                                            DBusError         *error)
2987 {
2988         const char *method;
2989
2990         method = dbus_address_entry_get_method (entry);
2991         _dbus_assert (method != NULL);
2992
2993         if (strcmp (method, "kdbus") == 0)
2994     {
2995                 const char *path = dbus_address_entry_get_value (entry, "path");
2996
2997                 if (path == NULL)
2998         {
2999                         _dbus_set_bad_address (error, "kdbus", "path", NULL);
3000                         return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
3001         }
3002
3003         *transport_p = _dbus_transport_new_for_kdbus (path, error);
3004
3005         if (*transport_p == NULL)
3006         {
3007                 _DBUS_ASSERT_ERROR_IS_SET (error);
3008                 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
3009         }
3010         else
3011         {
3012                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3013                 return DBUS_TRANSPORT_OPEN_OK;
3014         }
3015     }
3016         else
3017     {
3018                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3019                 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
3020     }
3021 }