6c1d05a2bc2cd8ba49f8075b7f68e96be5e28617
[platform/upstream/dbus.git] / dbus / dbus-transport-kdbus.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport-kdbus.c  kdbus subclasses of DBusTransport
3  *
4  * Copyright (C) 2002, 2003, 2004, 2006  Red Hat Inc
5  * Copyright (C) 2013  Samsung Electronics
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version and under the terms of the GNU
13  * Lesser General Public License as published by the
14  * Free Software Foundation; either version 2.1 of the License, or (at
15  * your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25  *
26  */
27 #include "dbus-transport.h"
28 #include "dbus-transport-kdbus.h"
29 #include "dbus-transport-protected.h"
30 #include "dbus-connection-internal.h"
31 #include "kdbus.h"
32 #include "dbus-watch.h"
33 #include "dbus-errors.h"
34 #include "dbus-bus.h"
35 #include "kdbus-common.h"
36 #include <linux/types.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <sys/ioctl.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <sys/mman.h>
46 #include <limits.h>
47 #include <sys/stat.h>
48
49 #define KDBUS_PART_FOREACH(part, head, first)                           \
50         for (part = (head)->first;                                      \
51              (uint8_t *)(part) < (uint8_t *)(head) + (head)->size;      \
52              part = KDBUS_PART_NEXT(part))
53 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
54 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
55
56 #define KDBUS_MSG_DECODE_DEBUG 0
57 //#define DBUS_AUTHENTICATION
58
59 #define ITER_APPEND_STR(string) \
60 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string))   \
61 { \
62         ret_size = -1;  \
63         goto out;  \
64 }\
65
66 #define MSG_ITEM_BUILD_VEC(data, datasize)                                    \
67         item->type = KDBUS_MSG_PAYLOAD_VEC;                                     \
68         item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);         \
69         item->vec.address = (unsigned long) data;                               \
70         item->vec.size = datasize;
71
72 /**
73  * Opaque object representing a transport. In kdbus transport it has nothing common
74  * with socket, but the name was preserved to comply with  upper functions.
75  */
76 typedef struct DBusTransportKdbus DBusTransportKdbus;
77
78 /**
79  * Implementation details of DBusTransportSocket. All members are private.
80  */
81 struct DBusTransportKdbus
82 {
83   DBusTransport base;                   /**< Parent instance */
84   int fd;                               /**< File descriptor. */
85   DBusWatch *read_watch;                /**< Watch for readability. */
86   DBusWatch *write_watch;               /**< Watch for writability. */
87
88   int max_bytes_read_per_iteration;     /**< In kdbus only to control overall message size*/
89   int max_bytes_written_per_iteration;  /**< In kdbus only to control overall message size*/
90
91   int message_bytes_written;            /**< Number of bytes of current
92                                          *   outgoing message that have
93                                          *   been written.
94                                          */
95   DBusString encoded_outgoing;          /**< Encoded version of current
96                                          *   outgoing message.
97                                          */
98   DBusString encoded_incoming;          /**< Encoded version of current
99                                          *   incoming data.
100                                          */
101   void* kdbus_mmap_ptr;                 /**< Mapped memory where Kdbus (kernel) writes
102                                          *   messages incoming to us.
103                                          */
104   int memfd;                            /**< File descriptor to special 
105                                          *   memory pool for bulk data
106                                          *   transfer. Retrieved from 
107                                          *   Kdbus kernel module. 
108                                          */
109   __u64 bloom_size;                                             /**<  bloom filter field size */
110   char* sender;                         /**< uniqe name of the sender */
111 };
112
113 __u64 dbus_transport_get_bloom_size(DBusTransport* transport)
114 {
115   return ((DBusTransportKdbus*)transport)->bloom_size;
116 }
117
118 /*
119  * Adds locally generated message to received messages queue
120  *
121  */
122 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
123 {
124         DBusList *message_link;
125
126         message_link = _dbus_list_alloc_link (message);
127         if (message_link == NULL)
128         {
129                 dbus_message_unref (message);
130                 return FALSE;
131         }
132
133         _dbus_connection_queue_synthesized_message_link(connection, message_link);
134
135         return TRUE;
136 }
137
138 /*
139  * Generates local error message as a reply to message given as parameter
140  * and adds generated error message to received messages queue.
141  */
142 static int reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
143 {
144         DBusMessage *errMessage;
145         char* error_msg = "";
146
147         if(template)
148         {
149                 error_msg = alloca(strlen(template) + strlen(object));
150                 sprintf(error_msg, template, object);
151         }
152         else if(object)
153                 error_msg = (char*)object;
154
155         errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg);
156         if(errMessage == NULL)
157                 return -1;
158         if (add_message_to_received(errMessage, connection))
159                 return 0;
160
161         return -1;
162 }
163
164 /*
165  *  Generates reply to the message given as a parameter with one item in the reply body
166  *  and adds generated reply message to received messages queue.
167  */
168 static int reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection)
169 {
170         DBusMessageIter args;
171         DBusMessage *reply;
172
173         reply = dbus_message_new_method_return(message);
174         if(reply == NULL)
175                 return -1;
176         dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
177     dbus_message_iter_init_append(reply, &args);
178     if (!dbus_message_iter_append_basic(&args, data_type, pData))
179     {
180         dbus_message_unref(reply);
181         return -1;
182     }
183     if(add_message_to_received(reply, connection))
184         return 0;
185
186     return -1;
187 }
188
189 /*
190 static int reply_ack(DBusMessage *message, DBusConnection* connection)
191 {
192         DBusMessage *reply;
193
194         reply = dbus_message_new_method_return(message);
195         if(reply == NULL)
196                 return -1;
197     if(add_message_to_received(reply, connection))
198         return 0;
199     return -1;
200 }*/
201
202 /**
203  * Retrieves file descriptor to memory pool from kdbus module.
204  * It is then used for bulk data sending.
205  * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
206  * 
207  */
208 static int kdbus_init_memfd(DBusTransportKdbus* socket_transport)
209 {
210         int memfd;
211         
212                 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
213                         _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
214                         return -1;
215                 }
216
217                 socket_transport->memfd = memfd;
218                 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
219         return 0;
220 }
221
222 /**
223  * Initiates Kdbus message structure. 
224  * Calculates it's size, allocates memory and fills some fields.
225  * @param name Well-known name or NULL
226  * @param dst_id Numeric id of recipient
227  * @param body_size size of message body if present
228  * @param use_memfd flag to build memfd message
229  * @param fds_count number of file descriptors used
230  * @param transport transport
231  * @return initialized kdbus message
232  */
233 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, DBusTransportKdbus *transport)
234 {
235     struct kdbus_msg* msg;
236     uint64_t msg_size;
237
238     msg_size = sizeof(struct kdbus_msg);
239
240     if(use_memfd == TRUE)  // bulk data - memfd - encoded and plain
241         msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
242     else {
243         msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
244         if(body_size)
245                 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
246     }
247
248     if(fds_count)
249         msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
250
251     if (name)
252         msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
253     else if (dst_id == KDBUS_DST_ID_BROADCAST)
254         msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
255
256     msg = malloc(msg_size);
257     if (!msg)
258     {
259         _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
260                 return NULL;
261     }
262
263     memset(msg, 0, msg_size);
264     msg->size = msg_size;
265     msg->payload_type = KDBUS_PAYLOAD_DBUS1;
266     msg->dst_id = name ? 0 : dst_id;
267     msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
268
269     return msg;
270 }
271
272 /**
273  * Builds and sends kdbus message using DBus message.
274  * Decide whether used payload vector or memfd memory pool.
275  * Handles broadcasts and unicast messages, and passing of Unix fds.
276  * Does error handling.
277  * TODO refactor to be more compact
278  *
279  * @param transport transport
280  * @param message DBus message to be sent
281  * @param encoded flag if the message is encoded
282  * @return size of data sent
283  */
284 static int kdbus_write_msg(DBusTransportKdbus *transport, DBusMessage *message, const char* destination, dbus_bool_t encoded)
285 {
286     struct kdbus_msg *msg;
287     struct kdbus_item *item;
288     uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
289     const DBusString *header;
290     const DBusString *body;
291     uint64_t ret_size = 0;
292     uint64_t body_size = 0;
293     uint64_t header_size = 0;
294     dbus_bool_t use_memfd;
295     const int *unix_fds;
296     unsigned fds_count;
297     dbus_bool_t autostart;
298
299     // determine destination and destination id
300     if(destination)
301     {
302         dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
303                 if((destination[0] == ':') && (destination[1] == '1') && (destination[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
304         {
305                 dst_id = strtoull(&destination[3], NULL, 10);
306                 destination = NULL;
307         }    
308     }
309     
310     // get size of data
311     if(encoded)
312         ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
313     else
314     {
315         _dbus_message_get_network_data (message, &header, &body);
316         header_size = _dbus_string_get_length(header);
317         body_size = _dbus_string_get_length(body);
318         ret_size = header_size + body_size;
319     }
320
321     // check if message size is big enough to use memfd kdbus transport
322     use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
323     if(use_memfd) kdbus_init_memfd(transport);
324     
325     _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
326
327     // init basic message fields
328     msg = kdbus_init_msg(destination, dst_id, body_size, use_memfd, fds_count, transport);
329     msg->cookie = dbus_message_get_serial(message);
330     autostart = dbus_message_get_auto_start (message);
331     if(!autostart)
332         msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
333     
334     // build message contents
335     item = msg->items;
336
337     // case 1 - bulk data transfer - memfd - encoded and plain
338     if(use_memfd)          
339     {
340         char *buf;
341
342         if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
343             {
344                         _dbus_verbose("memfd sealing failed: \n");
345                         goto out;
346             }
347
348             buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
349             if (buf == MAP_FAILED) 
350             {
351                         _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
352                         goto out;
353             }
354
355                 if(encoded)
356                         memcpy(buf, &transport->encoded_outgoing, ret_size);
357                 else
358                 {
359                         memcpy(buf, _dbus_string_get_const_data(header), header_size);
360                         if(body_size) {
361                                 buf+=header_size;
362                                 memcpy(buf, _dbus_string_get_const_data(body),  body_size);
363                                 buf-=header_size;
364                         }
365                 }
366
367                 munmap(buf, ret_size);
368
369                 // seal data - kdbus module needs it
370                 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
371                         _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
372                         ret_size = -1;
373                         goto out;
374                 }
375
376             item->type = KDBUS_MSG_PAYLOAD_MEMFD;
377                 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
378                 item->memfd.size = ret_size;
379                 item->memfd.fd = transport->memfd;
380     // case 2 - small encoded - don't use memfd
381     } else if(encoded) { 
382         _dbus_verbose("sending encoded data\n");
383         MSG_ITEM_BUILD_VEC(&transport->encoded_outgoing, _dbus_string_get_length (&transport->encoded_outgoing));
384
385     // case 3 - small not encoded - don't use memfd
386     } else { 
387         _dbus_verbose("sending normal vector data\n");
388         MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(header), header_size);
389
390         if(body_size)
391         {
392             _dbus_verbose("body attaching\n");
393             item = KDBUS_PART_NEXT(item);
394             MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(body), body_size);
395         }
396     }
397
398     if(fds_count)
399     {
400         item = KDBUS_PART_NEXT(item);
401         item->type = KDBUS_MSG_FDS;
402         item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
403         memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
404     }
405
406         if (destination)
407         {
408                 item = KDBUS_PART_NEXT(item);
409                 item->type = KDBUS_MSG_DST_NAME;
410                 item->size = KDBUS_PART_HEADER_SIZE + strlen(destination) + 1;
411                 memcpy(item->str, destination, item->size - KDBUS_PART_HEADER_SIZE);
412         }
413         else if (dst_id == KDBUS_DST_ID_BROADCAST)
414         {
415                 item = KDBUS_PART_NEXT(item);
416                 item->type = KDBUS_MSG_BLOOM;
417                 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
418                 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
419         }
420
421         again:
422         if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
423         {
424                 if(errno == EINTR)
425                         goto again;
426                 else if(errno == ENXIO) //no such id on the bus
427                 {
428             if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
429                 goto out;
430                 }
431         else if((errno == ESRCH) || (errno = EADDRNOTAVAIL))  //when well known name is not available on the bus
432                 {
433                         if(autostart)
434                         {
435                                 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))
436                                         goto out;
437                         }
438                         else
439                     if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
440                         goto out;
441                 }
442                 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
443                 ret_size = -1;
444         }
445 out:
446     free(msg);
447     if(use_memfd)
448         close(transport->memfd);
449
450     return ret_size;
451 }
452
453 /**
454  * Performs kdbus hello - registration on the kdbus bus
455  *
456  * @param name place to store unique name given by bus
457  * @param transportS transport structure
458  * @returns #TRUE on success
459  */
460 static dbus_bool_t bus_register_kdbus(char* name, DBusTransportKdbus* transportS)
461 {
462         struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
463
464         hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
465                            KDBUS_HELLO_ATTACH_COMM |
466                            KDBUS_HELLO_ATTACH_EXE |
467                            KDBUS_HELLO_ATTACH_CMDLINE |
468                            KDBUS_HELLO_ATTACH_CAPS |
469                            KDBUS_HELLO_ATTACH_CGROUP |
470                            KDBUS_HELLO_ATTACH_SECLABEL |
471                            KDBUS_HELLO_ATTACH_AUDIT*/;
472         hello.size = sizeof(struct kdbus_cmd_hello);
473         hello.pool_size = RECEIVE_POOL_SIZE;
474
475         if (ioctl(transportS->fd, KDBUS_CMD_HELLO, &hello))
476         {
477                 _dbus_verbose ("Failed to send hello: %m, %d",errno);
478                 return FALSE;
479         }
480
481         sprintf(name, "%llu", (unsigned long long)hello.id);
482         _dbus_verbose("-- Our peer ID is: %s\n", name);
483         transportS->bloom_size = hello.bloom_size;
484
485         transportS->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, transportS->fd, 0);
486         if (transportS->kdbus_mmap_ptr == MAP_FAILED)
487         {
488                 _dbus_verbose("Error when mmap: %m, %d",errno);
489                 return FALSE;
490         }
491
492         return TRUE;
493 }
494
495 /**
496  * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
497  * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
498  *
499  * Now it captures only Hello message, which must be handled locally.
500  * All the rest is passed to dbus-daemon.
501  */
502 static int emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
503 {
504   if(!strcmp(dbus_message_get_member(message), "Hello"))
505     {
506       char* name = NULL;
507
508       name = malloc(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."));
509       if(name == NULL)
510         return -1;
511       strcpy(name, ":1.");
512       if(!bus_register_kdbus(&name[3], (DBusTransportKdbus*)transport))
513         goto out;
514       if(!register_kdbus_policy(&name[3], transport, geteuid()))
515         goto out;
516
517       ((DBusTransportKdbus*)transport)->sender = name;
518
519       if(!reply_1_data(message, DBUS_TYPE_STRING, &name, transport->connection))
520         return 0;
521
522     out:
523       free(name);
524     }
525   else
526     return 1;  //send to daemon
527
528   return -1;
529 }
530
531 #if KDBUS_MSG_DECODE_DEBUG == 1
532 static char *msg_id(uint64_t id, char *buf)
533 {
534         if (id == 0)
535                 return "KERNEL";
536         if (id == ~0ULL)
537                 return "BROADCAST";
538         sprintf(buf, "%llu", (unsigned long long)id);
539         return buf;
540 }
541 #endif
542 struct kdbus_enum_table {
543         long long id;
544         const char *name;
545 };
546 #define _STRINGIFY(x) #x
547 #define STRINGIFY(x) _STRINGIFY(x)
548 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
549 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
550 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
551 #define LOOKUP(what)                                                            \
552         const char *enum_##what(long long id) {                                 \
553         size_t i; \
554                 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++)    \
555                         if (id == kdbus_table_##what[i].id)                     \
556                                 return kdbus_table_##what[i].name;              \
557                 return "UNKNOWN";                                               \
558         }
559 const char *enum_MSG(long long id);
560 TABLE(MSG) = {
561         ENUM(_KDBUS_MSG_NULL),
562         ENUM(KDBUS_MSG_PAYLOAD_VEC),
563         ENUM(KDBUS_MSG_PAYLOAD_OFF),
564         ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
565         ENUM(KDBUS_MSG_FDS),
566         ENUM(KDBUS_MSG_BLOOM),
567         ENUM(KDBUS_MSG_DST_NAME),
568         ENUM(KDBUS_MSG_SRC_CREDS),
569         ENUM(KDBUS_MSG_SRC_PID_COMM),
570         ENUM(KDBUS_MSG_SRC_TID_COMM),
571         ENUM(KDBUS_MSG_SRC_EXE),
572         ENUM(KDBUS_MSG_SRC_CMDLINE),
573         ENUM(KDBUS_MSG_SRC_CGROUP),
574         ENUM(KDBUS_MSG_SRC_CAPS),
575         ENUM(KDBUS_MSG_SRC_SECLABEL),
576         ENUM(KDBUS_MSG_SRC_AUDIT),
577         ENUM(KDBUS_MSG_SRC_NAMES),
578         ENUM(KDBUS_MSG_TIMESTAMP),
579         ENUM(KDBUS_MSG_NAME_ADD),
580         ENUM(KDBUS_MSG_NAME_REMOVE),
581         ENUM(KDBUS_MSG_NAME_CHANGE),
582         ENUM(KDBUS_MSG_ID_ADD),
583         ENUM(KDBUS_MSG_ID_REMOVE),
584         ENUM(KDBUS_MSG_REPLY_TIMEOUT),
585         ENUM(KDBUS_MSG_REPLY_DEAD),
586 };
587 LOOKUP(MSG);
588 const char *enum_PAYLOAD(long long id);
589 TABLE(PAYLOAD) = {
590         ENUM(KDBUS_PAYLOAD_KERNEL),
591         ENUM(KDBUS_PAYLOAD_DBUS1),
592         ENUM(KDBUS_PAYLOAD_GVARIANT),
593 };
594 LOOKUP(PAYLOAD);
595
596 /**
597  * Puts locally generated message into received data buffer.
598  * Use only during receiving phase!
599  *
600  * @param message message to load
601  * @param data place to load message
602  * @return size of message
603  */
604 static int put_message_into_data(DBusMessage *message, char* data)
605 {
606         int ret_size;
607     const DBusString *header;
608     const DBusString *body;
609     int size;
610
611     dbus_message_set_serial(message, 1);
612     dbus_message_lock (message);
613     _dbus_message_get_network_data (message, &header, &body);
614     ret_size = _dbus_string_get_length(header);
615         memcpy(data, _dbus_string_get_const_data(header), ret_size);
616         data += ret_size;
617         size = _dbus_string_get_length(body);
618         memcpy(data, _dbus_string_get_const_data(body), size);
619         ret_size += size;
620
621         return ret_size;
622 }
623
624 /**
625  * Get the length of the kdbus message content.
626  *
627  * @param msg kdbus message
628  * @return the length of the kdbus message
629  */
630 static int kdbus_message_size(const struct kdbus_msg* msg)
631 {
632         const struct kdbus_item *item;
633         int ret_size = 0;
634
635         KDBUS_PART_FOREACH(item, msg, items)
636         {
637                 if (item->size <= KDBUS_PART_HEADER_SIZE)
638                 {
639                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
640                         return -1;
641                 }
642                 switch (item->type)
643                 {
644                         case KDBUS_MSG_PAYLOAD_OFF:
645                                 ret_size += item->vec.size;
646                                 break;
647                         case KDBUS_MSG_PAYLOAD_MEMFD:
648                                 ret_size += item->memfd.size;
649                                 break;
650                         default:
651                                 break;
652                 }
653         }
654
655         return ret_size;
656 }
657
658 /**
659  * Decodes kdbus message in order to extract dbus message and put it into data and fds.
660  * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
661  * all of them into dbus messages.
662  *
663  * @param msg kdbus message
664  * @param data place to copy dbus message to
665  * @param kdbus_transport transport
666  * @param fds place to store file descriptors received
667  * @param n_fds place to store quantity of file descriptor
668  * @return number of dbus message's bytes received or -1 on error
669  */
670 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportKdbus* kdbus_transport, int* fds, int* n_fds)
671 {
672         const struct kdbus_item *item;
673         int ret_size = 0;
674         DBusMessage *message = NULL;
675         DBusMessageIter args;
676         const char* emptyString = "";
677     const char* pString = NULL;
678         char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
679         const char* pDBusName = dbus_name;
680 #if KDBUS_MSG_DECODE_DEBUG == 1
681         char buf[32];
682 #endif
683
684 #if KDBUS_MSG_DECODE_DEBUG == 1
685         _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s â†’ %s, cookie=%llu, timeout=%llu\n",
686                 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
687                 (unsigned long long) msg->flags,
688                 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
689                 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
690 #endif
691
692         *n_fds = 0;
693
694         KDBUS_PART_FOREACH(item, msg, items)
695         {
696                 if (item->size <= KDBUS_PART_HEADER_SIZE)
697                 {
698                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
699                         break;  //??? continue (because dbus will find error) or break
700                 }
701
702                 switch (item->type)
703                 {
704                         case KDBUS_MSG_PAYLOAD_OFF:
705                                 memcpy(data, (char *)kdbus_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
706                                 data += item->vec.size;
707                                 ret_size += item->vec.size;
708
709                                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
710                                         enum_MSG(item->type), item->size,
711                                         (unsigned long long)item->vec.offset,
712                                         (unsigned long long)item->vec.size);
713                         break;
714
715                         case KDBUS_MSG_PAYLOAD_MEMFD:
716                         {
717                                 char *buf;
718                                 uint64_t size;
719
720                                 size = item->memfd.size;
721                                 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
722
723                                 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
724                                 if (buf == MAP_FAILED)
725                                 {
726                                         _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
727                                         return -1;
728                                 }
729
730                                 memcpy(data, buf, size);
731                                 data += size;
732                                 ret_size += size;
733
734                                 munmap(buf, size);
735
736                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
737                                            enum_MSG(item->type), item->size,
738                                            (unsigned long long)item->vec.offset,
739                                            (unsigned long long)item->vec.size);
740                         break;
741                         }
742
743                         case KDBUS_MSG_FDS:
744                         {
745                                 int i;
746
747                                 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
748                                 memcpy(fds, item->fds, *n_fds * sizeof(int));
749                     for (i = 0; i < *n_fds; i++)
750                       _dbus_fd_set_close_on_exec(fds[i]);
751                         break;
752                         }
753
754 #if KDBUS_MSG_DECODE_DEBUG == 1
755                         case KDBUS_MSG_SRC_CREDS:
756                                 _dbus_verbose("  +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
757                                         enum_MSG(item->type), item->size,
758                                         item->creds.uid, item->creds.gid,
759                                         item->creds.pid, item->creds.tid,
760                                         item->creds.starttime);
761                         break;
762
763                         case KDBUS_MSG_SRC_PID_COMM:
764                         case KDBUS_MSG_SRC_TID_COMM:
765                         case KDBUS_MSG_SRC_EXE:
766                         case KDBUS_MSG_SRC_CGROUP:
767                         case KDBUS_MSG_SRC_SECLABEL:
768                         case KDBUS_MSG_DST_NAME:
769                                 _dbus_verbose("  +%s (%llu bytes) '%s' (%zu)\n",
770                                            enum_MSG(item->type), item->size, item->str, strlen(item->str));
771                                 break;
772
773                         case KDBUS_MSG_SRC_CMDLINE:
774                         case KDBUS_MSG_SRC_NAMES: {
775                                 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
776                                 const char *str = item->str;
777                                 int count = 0;
778
779                                 _dbus_verbose("  +%s (%llu bytes) ", enum_MSG(item->type), item->size);
780                                 while (size) {
781                                         _dbus_verbose("'%s' ", str);
782                                         size -= strlen(str) + 1;
783                                         str += strlen(str) + 1;
784                                         count++;
785                                 }
786
787                                 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
788                                 break;
789                         }
790
791                         case KDBUS_MSG_SRC_AUDIT:
792                                 _dbus_verbose("  +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
793                                            enum_MSG(item->type), item->size,
794                                            (unsigned long long)item->data64[0],
795                                            (unsigned long long)item->data64[1]);
796                                 break;
797
798                         case KDBUS_MSG_SRC_CAPS: {
799                                 int n;
800                                 const uint32_t *cap;
801                                 int i;
802
803                                 _dbus_verbose("  +%s (%llu bytes) len=%llu bytes)\n",
804                                            enum_MSG(item->type), item->size,
805                                            (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
806
807                                 cap = item->data32;
808                                 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
809
810                                 _dbus_verbose("    CapInh=");
811                                 for (i = 0; i < n; i++)
812                                         _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
813
814                                 _dbus_verbose(" CapPrm=");
815                                 for (i = 0; i < n; i++)
816                                         _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
817
818                                 _dbus_verbose(" CapEff=");
819                                 for (i = 0; i < n; i++)
820                                         _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
821
822                                 _dbus_verbose(" CapInh=");
823                                 for (i = 0; i < n; i++)
824                                         _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
825                                 _dbus_verbose("\n");
826                                 break;
827                         }
828
829                         case KDBUS_MSG_TIMESTAMP:
830                                 _dbus_verbose("  +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
831                                            enum_MSG(item->type), item->size,
832                                            (unsigned long long)item->timestamp.realtime_ns,
833                                            (unsigned long long)item->timestamp.monotonic_ns);
834                                 break;
835 #endif
836
837                         case KDBUS_MSG_REPLY_TIMEOUT:
838                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
839                                            enum_MSG(item->type), item->size, msg->cookie_reply);
840
841                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
842                                 if(message == NULL)
843                                 {
844                                         ret_size = -1;
845                                         goto out;
846                                 }
847
848                                 ret_size = put_message_into_data(message, data);
849                         break;
850
851                         case KDBUS_MSG_REPLY_DEAD:
852                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
853                                            enum_MSG(item->type), item->size, msg->cookie_reply);
854
855                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
856                                 if(message == NULL)
857                                 {
858                                         ret_size = -1;
859                                         goto out;
860                                 }
861
862                                 ret_size = put_message_into_data(message, data);
863                         break;
864
865                         case KDBUS_MSG_NAME_ADD:
866                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
867                                         enum_MSG(item->type), (unsigned long long) item->size,
868                                         item->name_change.name, item->name_change.old_id,
869                                         item->name_change.new_id, item->name_change.flags);
870
871                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
872                                 if(message == NULL)
873                                 {
874                                         ret_size = -1;
875                                         goto out;
876                                 }
877
878                                 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
879                                 pString = item->name_change.name;
880                                 _dbus_verbose ("Name added: %s\n", pString);
881                             dbus_message_iter_init_append(message, &args);
882                             ITER_APPEND_STR(pString)
883                             ITER_APPEND_STR(emptyString)
884                             ITER_APPEND_STR(pDBusName)
885                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
886
887                                 ret_size = put_message_into_data(message, data);
888                         break;
889
890                         case KDBUS_MSG_NAME_REMOVE:
891                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
892                                         enum_MSG(item->type), (unsigned long long) item->size,
893                                         item->name_change.name, item->name_change.old_id,
894                                         item->name_change.new_id, item->name_change.flags);
895
896                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
897                                 if(message == NULL)
898                                 {
899                                         ret_size = -1;
900                                         goto out;
901                                 }
902
903                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
904                                 pString = item->name_change.name;
905                                 _dbus_verbose ("Name removed: %s\n", pString);
906                             dbus_message_iter_init_append(message, &args);
907                             ITER_APPEND_STR(pString)
908                             ITER_APPEND_STR(pDBusName)
909                             ITER_APPEND_STR(emptyString)
910                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
911
912                                 ret_size = put_message_into_data(message, data);
913                         break;
914
915                         case KDBUS_MSG_NAME_CHANGE:
916                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
917                                         enum_MSG(item->type), (unsigned long long) item->size,
918                                         item->name_change.name, item->name_change.old_id,
919                                         item->name_change.new_id, item->name_change.flags);
920
921                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
922                                 if(message == NULL)
923                                 {
924                                         ret_size = -1;
925                                         goto out;
926                                 }
927
928                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
929                                 pString = item->name_change.name;
930                                 _dbus_verbose ("Name changed: %s\n", pString);
931                             dbus_message_iter_init_append(message, &args);
932                             ITER_APPEND_STR(pString)
933                             ITER_APPEND_STR(pDBusName)
934                             sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
935                             _dbus_verbose ("New id: %s\n", pDBusName);
936                             ITER_APPEND_STR(pDBusName)
937                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
938
939                                 ret_size = put_message_into_data(message, data);
940                         break;
941
942                         case KDBUS_MSG_ID_ADD:
943                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
944                                            enum_MSG(item->type), (unsigned long long) item->size,
945                                            (unsigned long long) item->id_change.id,
946                                            (unsigned long long) item->id_change.flags);
947
948                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
949                                 if(message == NULL)
950                                 {
951                                         ret_size = -1;
952                                         goto out;
953                                 }
954
955                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
956                             dbus_message_iter_init_append(message, &args);
957                             ITER_APPEND_STR(pDBusName)
958                             ITER_APPEND_STR(emptyString)
959                             ITER_APPEND_STR(pDBusName)
960                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
961
962                                 ret_size = put_message_into_data(message, data);
963                         break;
964
965                         case KDBUS_MSG_ID_REMOVE:
966                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
967                                            enum_MSG(item->type), (unsigned long long) item->size,
968                                            (unsigned long long) item->id_change.id,
969                                            (unsigned long long) item->id_change.flags);
970
971                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
972                                 if(message == NULL)
973                                 {
974                                         ret_size = -1;
975                                         goto out;
976                                 }
977
978                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
979                             dbus_message_iter_init_append(message, &args);
980                             ITER_APPEND_STR(pDBusName)
981                             ITER_APPEND_STR(pDBusName)
982                             ITER_APPEND_STR(emptyString)
983                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
984
985                                 ret_size = put_message_into_data(message, data);
986                         break;
987 #if KDBUS_MSG_DECODE_DEBUG == 1
988                         default:
989                                 _dbus_verbose("  +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
990                         break;
991 #endif
992                 }
993         }
994
995 #if KDBUS_MSG_DECODE_DEBUG == 1
996
997         if ((char *)item - ((char *)msg + msg->size) >= 8)
998                 _dbus_verbose("invalid padding at end of message\n");
999 #endif
1000
1001 out:
1002         if(message)
1003                 dbus_message_unref(message);
1004         return ret_size;
1005 }
1006
1007 /**
1008  * Reads message from kdbus and puts it into dbus buffer and fds
1009  *
1010  * @param transport transport
1011  * @param buffer place to copy received message to
1012  * @param fds place to store file descriptors sent in the message
1013  * @param n_fds place  to store number of file descriptors
1014  * @return size of received message on success, -1 on error
1015  */
1016 static int kdbus_read_message(DBusTransportKdbus *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1017 {
1018         int ret_size, buf_size;
1019         uint64_t __attribute__ ((__aligned__(8))) offset;
1020         struct kdbus_msg *msg;
1021         char *data;
1022         int start;
1023
1024         start = _dbus_string_get_length (buffer);
1025
1026         again:
1027         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1028         {
1029                 if(errno == EINTR)
1030                         goto again;
1031                 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1032                 _dbus_string_set_length (buffer, start);
1033                 return -1;
1034         }
1035
1036         msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1037
1038         buf_size = kdbus_message_size(msg);
1039         if (buf_size == -1)
1040         {
1041                 _dbus_verbose("kdbus error - too short message: %d (%m)\n", errno);
1042                 return -1;
1043         }
1044
1045         /* What is the maximum size of the locally generated message?
1046            I just assume 2048 bytes */
1047         buf_size = MAX(buf_size, 2048);
1048
1049         if (!_dbus_string_lengthen (buffer, buf_size))
1050         {
1051                 errno = ENOMEM;
1052                 return -1;
1053         }
1054         data = _dbus_string_get_data_len (buffer, start, buf_size);
1055
1056         ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1057
1058         if(ret_size == -1) /* error */
1059         {
1060                 _dbus_string_set_length (buffer, start);
1061                 return -1;
1062         }
1063         else if (buf_size != ret_size) /* case of locally generated message */
1064         {
1065                 _dbus_string_set_length (buffer, start + ret_size);
1066         }
1067
1068         again2:
1069         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1070         {
1071                 if(errno == EINTR)
1072                         goto again2;
1073                 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1074                 return -1;
1075         }
1076
1077         return ret_size;
1078 }
1079 /*
1080  * copy-paste from socket transport with needed renames only.
1081  */
1082 static void
1083 free_watches (DBusTransport *transport)
1084 {
1085   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1086
1087   _dbus_verbose ("start\n");
1088
1089   if (kdbus_transport->read_watch)
1090     {
1091       if (transport->connection)
1092         _dbus_connection_remove_watch_unlocked (transport->connection,
1093                                                 kdbus_transport->read_watch);
1094       _dbus_watch_invalidate (kdbus_transport->read_watch);
1095       _dbus_watch_unref (kdbus_transport->read_watch);
1096       kdbus_transport->read_watch = NULL;
1097     }
1098
1099   if (kdbus_transport->write_watch)
1100     {
1101       if (transport->connection)
1102         _dbus_connection_remove_watch_unlocked (transport->connection,
1103                                                 kdbus_transport->write_watch);
1104       _dbus_watch_invalidate (kdbus_transport->write_watch);
1105       _dbus_watch_unref (kdbus_transport->write_watch);
1106       kdbus_transport->write_watch = NULL;
1107     }
1108
1109   _dbus_verbose ("end\n");
1110 }
1111
1112 /*
1113  * copy-paste from socket transport with needed renames only.
1114  */
1115 static void
1116 transport_finalize (DBusTransport *transport)
1117 {
1118   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1119
1120   _dbus_verbose ("\n");
1121
1122   free_watches (transport);
1123
1124   _dbus_string_free (&kdbus_transport->encoded_outgoing);
1125   _dbus_string_free (&kdbus_transport->encoded_incoming);
1126
1127   _dbus_transport_finalize_base (transport);
1128
1129   _dbus_assert (kdbus_transport->read_watch == NULL);
1130   _dbus_assert (kdbus_transport->write_watch == NULL);
1131
1132   dbus_free (transport);
1133 }
1134
1135 /*
1136  * copy-paste from socket transport with needed renames only.
1137  */
1138 static void
1139 check_write_watch (DBusTransport *transport)
1140 {
1141   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1142   dbus_bool_t needed;
1143
1144   if (transport->connection == NULL)
1145     return;
1146
1147   if (transport->disconnected)
1148     {
1149       _dbus_assert (kdbus_transport->write_watch == NULL);
1150       return;
1151     }
1152
1153   _dbus_transport_ref (transport);
1154
1155 #ifdef DBUS_AUTHENTICATION
1156   if (_dbus_transport_try_to_authenticate (transport))
1157 #endif
1158     needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1159 #ifdef DBUS_AUTHENTICATION
1160   else
1161     {
1162       if (transport->send_credentials_pending)
1163         needed = TRUE;
1164       else
1165         {
1166           DBusAuthState auth_state;
1167
1168           auth_state = _dbus_auth_do_work (transport->auth);
1169
1170           /* If we need memory we install the write watch just in case,
1171            * if there's no need for it, it will get de-installed
1172            * next time we try reading.
1173            */
1174           if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1175               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1176             needed = TRUE;
1177           else
1178             needed = FALSE;
1179         }
1180     }
1181 #endif
1182   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1183                  needed, transport->connection, kdbus_transport->write_watch,
1184                  kdbus_transport->fd,
1185                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1186
1187   _dbus_connection_toggle_watch_unlocked (transport->connection,
1188                                           kdbus_transport->write_watch,
1189                                           needed);
1190
1191   _dbus_transport_unref (transport);
1192 }
1193
1194 /*
1195  * copy-paste from socket transport with needed renames only.
1196  */
1197 static void
1198 check_read_watch (DBusTransport *transport)
1199 {
1200   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1201   dbus_bool_t need_read_watch;
1202
1203   _dbus_verbose ("fd = %d\n",kdbus_transport->fd);
1204
1205   if (transport->connection == NULL)
1206     return;
1207
1208   if (transport->disconnected)
1209     {
1210       _dbus_assert (kdbus_transport->read_watch == NULL);
1211       return;
1212     }
1213
1214   _dbus_transport_ref (transport);
1215
1216 #ifdef DBUS_AUTHENTICATION
1217   if (_dbus_transport_try_to_authenticate (transport))
1218 #endif
1219     need_read_watch =
1220       (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1221       (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1222 #ifdef DBUS_AUTHENTICATION
1223   else
1224     {
1225       if (transport->receive_credentials_pending)
1226         need_read_watch = TRUE;
1227       else
1228         {
1229           /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1230            * is to avoid spinning on the file descriptor when we're waiting
1231            * to write or for some other part of the auth process
1232            */
1233           DBusAuthState auth_state;
1234
1235           auth_state = _dbus_auth_do_work (transport->auth);
1236
1237           /* If we need memory we install the read watch just in case,
1238            * if there's no need for it, it will get de-installed
1239            * next time we try reading. If we're authenticated we
1240            * install it since we normally have it installed while
1241            * authenticated.
1242            */
1243           if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1244               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1245               auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1246             need_read_watch = TRUE;
1247           else
1248             need_read_watch = FALSE;
1249         }
1250     }
1251 #endif
1252
1253   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
1254   _dbus_connection_toggle_watch_unlocked (transport->connection,
1255                                           kdbus_transport->read_watch,
1256                                           need_read_watch);
1257
1258   _dbus_transport_unref (transport);
1259 }
1260
1261 /*
1262  * copy-paste from socket transport.
1263  */
1264 static void
1265 do_io_error (DBusTransport *transport)
1266 {
1267   _dbus_transport_ref (transport);
1268   _dbus_transport_disconnect (transport);
1269   _dbus_transport_unref (transport);
1270 }
1271
1272 #ifdef DBUS_AUTHENTICATION
1273 /* return value is whether we successfully read any new data. */
1274 static dbus_bool_t
1275 read_data_into_auth (DBusTransport *transport,
1276                      dbus_bool_t   *oom)
1277 {
1278   DBusTransportKdbus *socket_transport = (DBusTransportKdbus*) transport;
1279   DBusString *buffer;
1280   int bytes_read;
1281   int *fds, n_fds;
1282
1283   *oom = FALSE;
1284
1285   _dbus_auth_get_buffer (transport->auth, &buffer);
1286
1287   bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1288
1289   _dbus_auth_return_buffer (transport->auth, buffer,
1290                             bytes_read > 0 ? bytes_read : 0);
1291
1292   if (bytes_read > 0)
1293     {
1294       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1295       return TRUE;
1296     }
1297   else if (bytes_read < 0)
1298     {
1299       /* EINTR already handled for us */
1300
1301       if (_dbus_get_is_errno_enomem ())
1302         {
1303           *oom = TRUE;
1304         }
1305       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1306         ; /* do nothing, just return FALSE below */
1307       else
1308         {
1309           _dbus_verbose ("Error reading from remote app: %s\n",
1310                          _dbus_strerror_from_errno ());
1311           do_io_error (transport);
1312         }
1313
1314       return FALSE;
1315     }
1316   else
1317     {
1318       _dbus_assert (bytes_read == 0);
1319
1320       _dbus_verbose ("Disconnected from remote app\n");
1321       do_io_error (transport);
1322
1323       return FALSE;
1324     }
1325 }
1326
1327 static int kdbus_send_auth (DBusTransport *transport,  const DBusString *buffer)
1328 {
1329         int len;
1330         int bytes_written = -1;
1331         struct kdbus_msg *msg;
1332         struct kdbus_item *item;
1333
1334         len = _dbus_string_get_length (buffer);
1335 //      data = _dbus_string_get_const_data_len (buffer, 0, len);
1336
1337         msg = kdbus_init_msg(NULL, 1, 0, FALSE, 0, (DBusTransportKdbus*)transport);
1338         item = msg->items;
1339         MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data_len (buffer, 0, len), len);
1340
1341     again:
1342     if(ioctl(((DBusTransportKdbus*)transport)->fd, KDBUS_CMD_MSG_SEND, msg))
1343     {
1344         if(errno == EINTR)
1345             goto again;
1346         _dbus_verbose ("Error writing auth: %d, %m\n", errno);
1347     }
1348     else
1349         bytes_written = len;
1350
1351         return bytes_written;
1352 }
1353
1354 /* Return value is whether we successfully wrote any bytes */
1355 static dbus_bool_t
1356 write_data_from_auth (DBusTransport *transport)
1357 {
1358 //  DBusTransportKdbus *socket_transport = (DBusTransportSocket*) transport;
1359   int bytes_written;
1360   const DBusString *buffer;
1361
1362   if (!_dbus_auth_get_bytes_to_send (transport->auth,
1363                                      &buffer))
1364     return FALSE;
1365
1366   bytes_written = kdbus_send_auth (transport, buffer);
1367
1368   if (bytes_written > 0)
1369     {
1370       _dbus_auth_bytes_sent (transport->auth, bytes_written);
1371       return TRUE;
1372     }
1373   else if (bytes_written < 0)
1374     {
1375       /* EINTR already handled for us */
1376
1377       if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1378         ;
1379       else
1380         {
1381           _dbus_verbose ("Error writing to remote app: %s\n",
1382                          _dbus_strerror_from_errno ());
1383           do_io_error (transport);
1384         }
1385     }
1386
1387   return FALSE;
1388 }
1389
1390 /* FALSE on OOM */
1391 static dbus_bool_t
1392 exchange_credentials (DBusTransport *transport,
1393                       dbus_bool_t    do_reading,
1394                       dbus_bool_t    do_writing)
1395 {
1396   DBusTransportKdbus *socket_transport = (DBusTransportKdbus*) transport;
1397   DBusError error = DBUS_ERROR_INIT;
1398
1399   _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1400                   do_reading, do_writing);
1401
1402   if (do_writing && transport->send_credentials_pending)
1403     {
1404       if (_dbus_send_credentials_socket (socket_transport->fd,
1405                                          &error))
1406         {
1407           transport->send_credentials_pending = FALSE;
1408         }
1409       else
1410         {
1411           _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1412           dbus_error_free (&error);
1413           do_io_error (transport);
1414         }
1415     }
1416
1417   if (do_reading && transport->receive_credentials_pending)
1418     {
1419       /* FIXME this can fail due to IO error _or_ OOM, broken
1420        * (somewhat tricky to fix since the OOM error can be set after
1421        * we already read the credentials byte, so basically we need to
1422        * separate reading the byte and storing it in the
1423        * transport->credentials). Does not really matter for now
1424        * because storing in credentials never actually fails on unix.
1425        */
1426       if (_dbus_read_credentials_socket (socket_transport->fd,
1427                                          transport->credentials,
1428                                          &error))
1429         {
1430           transport->receive_credentials_pending = FALSE;
1431         }
1432       else
1433         {
1434           _dbus_verbose ("Failed to read credentials %s\n", error.message);
1435           dbus_error_free (&error);
1436           do_io_error (transport);
1437         }
1438     }
1439
1440   if (!(transport->send_credentials_pending ||
1441         transport->receive_credentials_pending))
1442     {
1443       if (!_dbus_auth_set_credentials (transport->auth,
1444                                        transport->credentials))
1445         return FALSE;
1446     }
1447
1448   return TRUE;
1449 }
1450
1451 static dbus_bool_t
1452 do_authentication (DBusTransport *transport,
1453                    dbus_bool_t    do_reading,
1454                    dbus_bool_t    do_writing,
1455                    dbus_bool_t   *auth_completed)
1456 {
1457   dbus_bool_t oom;
1458   dbus_bool_t orig_auth_state;
1459
1460   oom = FALSE;
1461
1462   orig_auth_state = _dbus_transport_try_to_authenticate (transport);
1463
1464   /* This is essential to avoid the check_write_watch() at the end,
1465    * we don't want to add a write watch in do_iteration before
1466    * we try writing and get EAGAIN
1467    */
1468   if (orig_auth_state)
1469     {
1470       if (auth_completed)
1471         *auth_completed = FALSE;
1472       return TRUE;
1473     }
1474
1475   _dbus_transport_ref (transport);
1476
1477    while (!_dbus_transport_try_to_authenticate (transport) &&
1478          _dbus_transport_get_is_connected (transport))
1479     {
1480       if (!exchange_credentials (transport, do_reading, do_writing))
1481         {
1482           oom = TRUE;
1483           goto out;
1484         }
1485
1486       if (transport->send_credentials_pending ||
1487           transport->receive_credentials_pending)
1488         {
1489           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1490                          transport->send_credentials_pending,
1491                          transport->receive_credentials_pending);
1492           goto out;
1493         }
1494
1495 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1496       switch (_dbus_auth_do_work (transport->auth))
1497         {
1498         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1499           _dbus_verbose (" %s auth state: waiting for input\n",
1500                          TRANSPORT_SIDE (transport));
1501           if (!do_reading || !read_data_into_auth (transport, &oom))
1502             goto out;
1503           break;
1504
1505         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1506           _dbus_verbose (" %s auth state: waiting for memory\n",
1507                          TRANSPORT_SIDE (transport));
1508           oom = TRUE;
1509           goto out;
1510           break;
1511
1512         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1513           _dbus_verbose (" %s auth state: bytes to send\n",
1514                          TRANSPORT_SIDE (transport));
1515           if (!do_writing || !write_data_from_auth (transport))
1516             goto out;
1517           break;
1518
1519         case DBUS_AUTH_STATE_NEED_DISCONNECT:
1520           _dbus_verbose (" %s auth state: need to disconnect\n",
1521                          TRANSPORT_SIDE (transport));
1522           do_io_error (transport);
1523           break;
1524
1525         case DBUS_AUTH_STATE_AUTHENTICATED:
1526           _dbus_verbose (" %s auth state: authenticated\n",
1527                          TRANSPORT_SIDE (transport));
1528           break;
1529         }
1530     }
1531
1532  out:
1533   if (auth_completed)
1534     *auth_completed = (orig_auth_state != _dbus_transport_try_to_authenticate (transport));
1535
1536   check_read_watch (transport);
1537   check_write_watch (transport);
1538   _dbus_transport_unref (transport);
1539
1540   if (oom)
1541     return FALSE;
1542   else
1543     return TRUE;
1544 }
1545 #endif
1546
1547 /* returns false on oom */
1548 static dbus_bool_t
1549 do_writing (DBusTransport *transport)
1550 {
1551         DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1552         dbus_bool_t oom;
1553
1554 #ifdef DBUS_AUTHENTICATION
1555         /* No messages without authentication! */
1556         if (!_dbus_transport_try_to_authenticate (transport))
1557     {
1558                 _dbus_verbose ("Not authenticated, not writing anything\n");
1559                 return TRUE;
1560     }
1561 #endif
1562
1563         if (transport->disconnected)
1564     {
1565                 _dbus_verbose ("Not connected, not writing anything\n");
1566                 return TRUE;
1567     }
1568
1569 #if 1
1570         _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1571                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1572                  kdbus_transport->fd);
1573 #endif
1574
1575         oom = FALSE;
1576
1577         while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1578     {
1579                 int bytes_written;
1580                 DBusMessage *message;
1581                 const DBusString *header;
1582                 const DBusString *body;
1583                 int total_bytes_to_write;
1584                 const char* pDestination;
1585
1586                 message = _dbus_connection_get_message_to_send (transport->connection);
1587                 _dbus_assert (message != NULL);
1588                 if(dbus_message_get_sender(message) == NULL)  //needed for daemon to pass pending activation messages
1589                 {
1590             dbus_message_unlock(message);
1591             dbus_message_set_sender(message, kdbus_transport->sender);
1592             dbus_message_lock (message);
1593                 }
1594                 _dbus_message_get_network_data (message, &header, &body);
1595                 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1596                 pDestination = dbus_message_get_destination(message);
1597
1598                 if(pDestination)
1599                 {
1600                         if(!strcmp(pDestination, DBUS_SERVICE_DBUS))
1601                         {
1602                                 if(!strcmp(dbus_message_get_interface(message), DBUS_INTERFACE_DBUS))
1603                                 {
1604                                         int ret;
1605
1606                                         ret = emulateOrgFreedesktopDBus(transport, message);
1607                                         if(ret < 0)
1608                                         {
1609                                                 bytes_written = -1;
1610                                                 goto written;
1611                                         }
1612                                         else if(ret == 0)
1613                                         {
1614                                                 bytes_written = total_bytes_to_write;
1615                                                 goto written;
1616                                         }
1617                                         //else send to "daemon" as to normal recipient
1618                                 }
1619                         }
1620                 }
1621                 if (_dbus_auth_needs_encoding (transport->auth))
1622         {
1623                         if (_dbus_string_get_length (&kdbus_transport->encoded_outgoing) == 0)
1624             {
1625                                 if (!_dbus_auth_encode_data (transport->auth,
1626                                            header, &kdbus_transport->encoded_outgoing))
1627                 {
1628                                         oom = TRUE;
1629                                         goto out;
1630                 }
1631
1632                                 if (!_dbus_auth_encode_data (transport->auth,
1633                                            body, &kdbus_transport->encoded_outgoing))
1634                 {
1635                                         _dbus_string_set_length (&kdbus_transport->encoded_outgoing, 0);
1636                                         oom = TRUE;
1637                                         goto out;
1638                 }
1639             }
1640
1641                         total_bytes_to_write = _dbus_string_get_length (&kdbus_transport->encoded_outgoing);
1642                         if(total_bytes_to_write > kdbus_transport->max_bytes_written_per_iteration)
1643                                 return -E2BIG;
1644
1645                         bytes_written = kdbus_write_msg(kdbus_transport, message, pDestination, TRUE);
1646         }
1647                 else
1648                 {
1649                         if(total_bytes_to_write > kdbus_transport->max_bytes_written_per_iteration)
1650                                 return -E2BIG;
1651
1652                         bytes_written = kdbus_write_msg(kdbus_transport, message, pDestination, FALSE);
1653                 }
1654
1655 written:
1656                 if (bytes_written < 0)
1657                 {
1658                         /* EINTR already handled for us */
1659
1660           /* For some discussion of why we also ignore EPIPE here, see
1661            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1662            */
1663
1664                         if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1665                                 goto out;
1666                         else
1667                         {
1668                                 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1669                                 do_io_error (transport);
1670                                 goto out;
1671                         }
1672                 }
1673                 else
1674                 {
1675                         _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1676                          total_bytes_to_write);
1677
1678                         kdbus_transport->message_bytes_written += bytes_written;
1679
1680                         _dbus_assert (kdbus_transport->message_bytes_written <=
1681                         total_bytes_to_write);
1682
1683                           if (kdbus_transport->message_bytes_written == total_bytes_to_write)
1684                           {
1685                                   kdbus_transport->message_bytes_written = 0;
1686                                   _dbus_string_set_length (&kdbus_transport->encoded_outgoing, 0);
1687                                   _dbus_string_compact (&kdbus_transport->encoded_outgoing, 2048);
1688
1689                                   _dbus_connection_message_sent_unlocked (transport->connection,
1690                                                                                                                   message);
1691                           }
1692                 }
1693     }
1694
1695         out:
1696         if (oom)
1697                 return FALSE;
1698         return TRUE;
1699 }
1700
1701 /* returns false on out-of-memory */
1702 static dbus_bool_t
1703 do_reading (DBusTransport *transport)
1704 {
1705   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1706   DBusString *buffer;
1707   int bytes_read;
1708   dbus_bool_t oom = FALSE;
1709   int *fds, n_fds;
1710
1711   _dbus_verbose ("fd = %d\n",kdbus_transport->fd);
1712
1713 #ifdef DBUS_AUTHENTICATION
1714   /* No messages without authentication! */
1715   if (!_dbus_transport_try_to_authenticate (transport))
1716     return TRUE;
1717 #endif
1718
1719  again:
1720
1721   /* See if we've exceeded max messages and need to disable reading */
1722   check_read_watch (transport);
1723
1724   _dbus_assert (kdbus_transport->read_watch != NULL ||
1725                 transport->disconnected);
1726
1727   if (transport->disconnected)
1728     goto out;
1729
1730   if (!dbus_watch_get_enabled (kdbus_transport->read_watch))
1731     return TRUE;
1732
1733   if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1734   {
1735       _dbus_verbose ("Out of memory reading file descriptors\n");
1736       oom = TRUE;
1737       goto out;
1738   }
1739   _dbus_message_loader_get_buffer (transport->loader, &buffer);
1740
1741   if (_dbus_auth_needs_decoding (transport->auth))
1742   {
1743           bytes_read = kdbus_read_message(kdbus_transport,  &kdbus_transport->encoded_incoming, fds, &n_fds);
1744
1745       _dbus_assert (_dbus_string_get_length (&kdbus_transport->encoded_incoming) == bytes_read);
1746
1747       if (bytes_read > 0)
1748       {
1749           if (!_dbus_auth_decode_data (transport->auth,
1750                                        &kdbus_transport->encoded_incoming,
1751                                        buffer))
1752           {
1753               _dbus_verbose ("Out of memory decoding incoming data\n");
1754               _dbus_message_loader_return_buffer (transport->loader,
1755                                               buffer,
1756                                               _dbus_string_get_length (buffer));
1757               oom = TRUE;
1758               goto out;
1759           }
1760
1761           _dbus_string_set_length (&kdbus_transport->encoded_incoming, 0);
1762           _dbus_string_compact (&kdbus_transport->encoded_incoming, 2048);
1763       }
1764   }
1765   else
1766           bytes_read = kdbus_read_message(kdbus_transport, buffer, fds, &n_fds);
1767
1768   if (bytes_read >= 0 && n_fds > 0)
1769     _dbus_verbose("Read %i unix fds\n", n_fds);
1770
1771   _dbus_message_loader_return_buffer (transport->loader,
1772                                       buffer,
1773                                       bytes_read < 0 ? 0 : bytes_read);
1774   _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1775
1776   if (bytes_read < 0)
1777     {
1778       /* EINTR already handled for us */
1779
1780       if (_dbus_get_is_errno_enomem ())
1781         {
1782           _dbus_verbose ("Out of memory in read()/do_reading()\n");
1783           oom = TRUE;
1784           goto out;
1785         }
1786       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1787         goto out;
1788       else
1789         {
1790           _dbus_verbose ("Error reading from remote app: %s\n",
1791                          _dbus_strerror_from_errno ());
1792           do_io_error (transport);
1793           goto out;
1794         }
1795     }
1796   else if (bytes_read == 0)
1797     {
1798       _dbus_verbose ("Disconnected from remote app\n");
1799       do_io_error (transport);
1800       goto out;
1801     }
1802   else
1803     {
1804       _dbus_verbose (" read %d bytes\n", bytes_read);
1805
1806       if (!_dbus_transport_queue_messages (transport))
1807         {
1808           oom = TRUE;
1809           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1810           goto out;
1811         }
1812
1813       /* Try reading more data until we get EAGAIN and return, or
1814        * exceed max bytes per iteration.  If in blocking mode of
1815        * course we'll block instead of returning.
1816        */
1817       goto again;
1818     }
1819
1820  out:
1821   if (oom)
1822     return FALSE;
1823   return TRUE;
1824 }
1825
1826 /*
1827  * copy-paste from socket transport.
1828  */
1829 static dbus_bool_t
1830 unix_error_with_read_to_come (DBusTransport *itransport,
1831                               DBusWatch     *watch,
1832                               unsigned int   flags)
1833 {
1834    DBusTransportKdbus *transport = (DBusTransportKdbus *) itransport;
1835
1836    if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
1837       return FALSE;
1838
1839   /* If we have a read watch enabled ...
1840      we -might have data incoming ... => handle the HANGUP there */
1841    if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
1842       return FALSE;
1843
1844    return TRUE;
1845 }
1846
1847 /*
1848  * copy-paste from socket transport with needed renames only.
1849  */
1850 static dbus_bool_t
1851 kdbus_handle_watch (DBusTransport *transport,
1852                    DBusWatch     *watch,
1853                    unsigned int   flags)
1854 {
1855   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1856
1857   _dbus_assert (watch == kdbus_transport->read_watch ||
1858                 watch == kdbus_transport->write_watch);
1859   _dbus_assert (watch != NULL);
1860
1861   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1862    * still be in the buffer and do_reading may need several iteration to read
1863    * it all (because of its max_bytes_read_per_iteration limit).
1864    */
1865   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
1866     {
1867       _dbus_verbose ("Hang up or error on watch\n");
1868       _dbus_transport_disconnect (transport);
1869       return TRUE;
1870     }
1871
1872   if (watch == kdbus_transport->read_watch &&
1873       (flags & DBUS_WATCH_READABLE))
1874     {
1875 #ifdef DBUS_AUTHENTICATION
1876       dbus_bool_t auth_finished;
1877 #endif
1878 #if 1
1879       _dbus_verbose ("handling read watch %p flags = %x\n",
1880                      watch, flags);
1881 #endif
1882 #ifdef DBUS_AUTHENTICATION
1883       if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
1884         return FALSE;
1885
1886       /* We don't want to do a read immediately following
1887        * a successful authentication.  This is so we
1888        * have a chance to propagate the authentication
1889        * state further up.  Specifically, we need to
1890        * process any pending data from the auth object.
1891        */
1892       if (!auth_finished)
1893         {
1894 #endif
1895           if (!do_reading (transport))
1896             {
1897               _dbus_verbose ("no memory to read\n");
1898               return FALSE;
1899             }
1900 #ifdef DBUS_AUTHENTICATION
1901         }
1902       else
1903         {
1904           _dbus_verbose ("Not reading anything since we just completed the authentication\n");
1905         }
1906 #endif
1907     }
1908   else if (watch == kdbus_transport->write_watch &&
1909            (flags & DBUS_WATCH_WRITABLE))
1910     {
1911 #if 1
1912       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1913                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1914 #endif
1915 #ifdef DBUS_AUTHENTICATION
1916       if (!do_authentication (transport, FALSE, TRUE, NULL))
1917         return FALSE;
1918 #endif
1919       if (!do_writing (transport))
1920         {
1921           _dbus_verbose ("no memory to write\n");
1922           return FALSE;
1923         }
1924
1925       /* See if we still need the write watch */
1926       check_write_watch (transport);
1927     }
1928 #ifdef DBUS_ENABLE_VERBOSE_MODE
1929   else
1930     {
1931       if (watch == kdbus_transport->read_watch)
1932         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
1933                        flags);
1934       else if (watch == kdbus_transport->write_watch)
1935         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
1936                        flags);
1937       else
1938         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
1939                        watch, dbus_watch_get_socket (watch));
1940     }
1941 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1942
1943   return TRUE;
1944 }
1945
1946 /*
1947  * copy-paste from socket transport with needed renames only.
1948  */
1949 static void
1950 kdbus_disconnect (DBusTransport *transport)
1951 {
1952   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1953
1954   _dbus_verbose ("\n");
1955
1956   free_watches (transport);
1957
1958   _dbus_close_socket (kdbus_transport->fd, NULL);
1959   kdbus_transport->fd = -1;
1960 }
1961
1962 /*
1963  * copy-paste from socket transport with needed renames only.
1964  */
1965 static dbus_bool_t
1966 kdbus_connection_set (DBusTransport *transport)
1967 {
1968   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1969
1970   dbus_connection_set_is_authenticated(transport->connection); //now we don't have authentication in kdbus
1971
1972   _dbus_watch_set_handler (kdbus_transport->write_watch,
1973                            _dbus_connection_handle_watch,
1974                            transport->connection, NULL);
1975
1976   _dbus_watch_set_handler (kdbus_transport->read_watch,
1977                            _dbus_connection_handle_watch,
1978                            transport->connection, NULL);
1979
1980   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1981                                             kdbus_transport->write_watch))
1982     return FALSE;
1983
1984   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1985                                             kdbus_transport->read_watch))
1986     {
1987       _dbus_connection_remove_watch_unlocked (transport->connection,
1988                                               kdbus_transport->write_watch);
1989       return FALSE;
1990     }
1991
1992   check_read_watch (transport);
1993   check_write_watch (transport);
1994
1995   return TRUE;
1996 }
1997
1998 /**  original dbus copy-pasted comment
1999  * @todo We need to have a way to wake up the select sleep if
2000  * a new iteration request comes in with a flag (read/write) that
2001  * we're not currently serving. Otherwise a call that just reads
2002  * could block a write call forever (if there are no incoming
2003  * messages).
2004  */
2005 static  void
2006 kdbus_do_iteration (DBusTransport *transport,
2007                    unsigned int   flags,
2008                    int            timeout_milliseconds)
2009 {
2010         DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
2011         DBusPollFD poll_fd;
2012         int poll_res;
2013         int poll_timeout;
2014
2015         _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2016                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
2017                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2018                  timeout_milliseconds,
2019                  kdbus_transport->read_watch,
2020                  kdbus_transport->write_watch,
2021                  kdbus_transport->fd);
2022
2023   /* the passed in DO_READING/DO_WRITING flags indicate whether to
2024    * read/write messages, but regardless of those we may need to block
2025    * for reading/writing to do auth.  But if we do reading for auth,
2026    * we don't want to read any messages yet if not given DO_READING.
2027    */
2028
2029    poll_fd.fd = kdbus_transport->fd;
2030    poll_fd.events = 0;
2031
2032    if (_dbus_transport_try_to_authenticate (transport))
2033    {
2034       /* This is kind of a hack; if we have stuff to write, then try
2035        * to avoid the poll. This is probably about a 5% speedup on an
2036        * echo client/server.
2037        *
2038        * If both reading and writing were requested, we want to avoid this
2039        * since it could have funky effects:
2040        *   - both ends spinning waiting for the other one to read
2041        *     data so they can finish writing
2042        *   - prioritizing all writing ahead of reading
2043        */
2044       if ((flags & DBUS_ITERATION_DO_WRITING) &&
2045           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2046           !transport->disconnected &&
2047           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2048       {
2049          do_writing (transport);
2050
2051          if (transport->disconnected ||
2052               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2053             goto out;
2054       }
2055
2056       /* If we get here, we decided to do the poll() after all */
2057       _dbus_assert (kdbus_transport->read_watch);
2058       if (flags & DBUS_ITERATION_DO_READING)
2059              poll_fd.events |= _DBUS_POLLIN;
2060
2061       _dbus_assert (kdbus_transport->write_watch);
2062       if (flags & DBUS_ITERATION_DO_WRITING)
2063          poll_fd.events |= _DBUS_POLLOUT;
2064    }
2065    else
2066    {
2067       DBusAuthState auth_state;
2068
2069       auth_state = _dbus_auth_do_work (transport->auth);
2070
2071       if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2072              poll_fd.events |= _DBUS_POLLIN;
2073
2074       if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2075              poll_fd.events |= _DBUS_POLLOUT;
2076    }
2077
2078    if (poll_fd.events)
2079    {
2080       if (flags & DBUS_ITERATION_BLOCK)
2081              poll_timeout = timeout_milliseconds;
2082       else
2083              poll_timeout = 0;
2084
2085       /* For blocking selects we drop the connection lock here
2086        * to avoid blocking out connection access during a potentially
2087        * indefinite blocking call. The io path is still protected
2088        * by the io_path_cond condvar, so we won't reenter this.
2089        */
2090       if (flags & DBUS_ITERATION_BLOCK)
2091       {
2092          _dbus_verbose ("unlock pre poll\n");
2093          _dbus_connection_unlock (transport->connection);
2094       }
2095
2096     again:
2097       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2098
2099       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2100       {
2101          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2102          goto again;
2103       }
2104
2105       if (flags & DBUS_ITERATION_BLOCK)
2106       {
2107          _dbus_verbose ("lock post poll\n");
2108          _dbus_connection_lock (transport->connection);
2109       }
2110
2111       if (poll_res >= 0)
2112       {
2113          if (poll_res == 0)
2114             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2115                                   * valgrind flags it as an error. though it probably
2116                                   * is guaranteed on linux at least.
2117                                   */
2118
2119          if (poll_fd.revents & _DBUS_POLLERR)
2120             do_io_error (transport);
2121          else
2122          {
2123             dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2124             dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2125 #ifdef DBUS_AUTHENTICATION
2126               dbus_bool_t authentication_completed;
2127 #endif
2128
2129             _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2130                              need_read, need_write);
2131 #ifdef DBUS_AUTHENTICATION
2132               do_authentication (transport, need_read, need_write,
2133                                  &authentication_completed);
2134
2135               /* See comment in socket_handle_watch. */
2136               if (authentication_completed)
2137                 goto out;
2138 #endif
2139             if (need_read && (flags & DBUS_ITERATION_DO_READING))
2140                do_reading (transport);
2141             if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2142                do_writing (transport);
2143          }
2144       }
2145       else
2146          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2147    }
2148
2149  out:
2150   /* We need to install the write watch only if we did not
2151    * successfully write everything. Note we need to be careful that we
2152    * don't call check_write_watch *before* do_writing, since it's
2153    * inefficient to add the write watch, and we can avoid it most of
2154    * the time since we can write immediately.
2155    *
2156    * However, we MUST always call check_write_watch(); DBusConnection code
2157    * relies on the fact that running an iteration will notice that
2158    * messages are pending.
2159    */
2160    check_write_watch (transport);
2161
2162    _dbus_verbose (" ... leaving do_iteration()\n");
2163 }
2164
2165 /*
2166  * copy-paste from socket transport with needed renames only.
2167  */
2168 static void
2169 kdbus_live_messages_changed (DBusTransport *transport)
2170 {
2171   /* See if we should look for incoming messages again */
2172   check_read_watch (transport);
2173 }
2174
2175 static dbus_bool_t
2176 kdbus_get_kdbus_fd (DBusTransport *transport,
2177                       int           *fd_p)
2178 {
2179   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
2180
2181   *fd_p = kdbus_transport->fd;
2182
2183   return TRUE;
2184 }
2185
2186 static const DBusTransportVTable kdbus_vtable = {
2187   transport_finalize,
2188   kdbus_handle_watch,
2189   kdbus_disconnect,
2190   kdbus_connection_set,
2191   kdbus_do_iteration,
2192   kdbus_live_messages_changed,
2193   kdbus_get_kdbus_fd
2194 };
2195
2196 /**
2197  * Creates a new transport for the given kdbus file descriptor.  The file
2198  * descriptor must be nonblocking.
2199  *
2200  * @param fd the file descriptor.
2201  * @param address the transport's address
2202  * @returns the new transport, or #NULL if no memory.
2203  */
2204 static DBusTransport*
2205 _dbus_transport_new_kdbus_transport (int fd, const DBusString *address)
2206 {
2207         DBusTransportKdbus *kdbus_transport;
2208
2209   kdbus_transport = dbus_new0 (DBusTransportKdbus, 1);
2210   if (kdbus_transport == NULL)
2211     return NULL;
2212
2213   if (!_dbus_string_init (&kdbus_transport->encoded_outgoing))
2214     goto failed_0;
2215
2216   if (!_dbus_string_init (&kdbus_transport->encoded_incoming))
2217     goto failed_1;
2218
2219   kdbus_transport->write_watch = _dbus_watch_new (fd,
2220                                                  DBUS_WATCH_WRITABLE,
2221                                                  FALSE,
2222                                                  NULL, NULL, NULL);
2223   if (kdbus_transport->write_watch == NULL)
2224     goto failed_2;
2225
2226   kdbus_transport->read_watch = _dbus_watch_new (fd,
2227                                                 DBUS_WATCH_READABLE,
2228                                                 FALSE,
2229                                                 NULL, NULL, NULL);
2230   if (kdbus_transport->read_watch == NULL)
2231     goto failed_3;
2232
2233   if (!_dbus_transport_init_base (&kdbus_transport->base,
2234                                   &kdbus_vtable,
2235                                   NULL, address))
2236     goto failed_4;
2237
2238 #ifdef DBUS_AUTHENTICATION
2239 #ifdef HAVE_UNIX_FD_PASSING
2240   _dbus_auth_set_unix_fd_possible(kdbus_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2241 #endif
2242 #endif
2243
2244   kdbus_transport->fd = fd;
2245   kdbus_transport->message_bytes_written = 0;
2246
2247   /* These values should probably be tunable or something. */
2248   kdbus_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2249   kdbus_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2250
2251   kdbus_transport->kdbus_mmap_ptr = NULL;
2252   kdbus_transport->memfd = -1;
2253   
2254   return (DBusTransport*) kdbus_transport;
2255
2256  failed_4:
2257   _dbus_watch_invalidate (kdbus_transport->read_watch);
2258   _dbus_watch_unref (kdbus_transport->read_watch);
2259  failed_3:
2260   _dbus_watch_invalidate (kdbus_transport->write_watch);
2261   _dbus_watch_unref (kdbus_transport->write_watch);
2262  failed_2:
2263   _dbus_string_free (&kdbus_transport->encoded_incoming);
2264  failed_1:
2265   _dbus_string_free (&kdbus_transport->encoded_outgoing);
2266  failed_0:
2267   dbus_free (kdbus_transport);
2268   return NULL;
2269 }
2270
2271 /**
2272  * Opens a connection to the kdbus bus
2273  *
2274  * This will set FD_CLOEXEC for the socket returned.
2275  *
2276  * @param path the path to UNIX domain socket
2277  * @param error return location for error code
2278  * @returns connection file descriptor or -1 on error
2279  */
2280 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2281 {
2282         int fd;
2283
2284         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2285         _dbus_verbose ("connecting to kdbus bus %s\n", path);
2286
2287         fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2288         if (fd < 0)
2289                 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2290
2291         return fd;
2292 }
2293
2294 /**
2295  * Creates a new transport for kdbus.
2296  * This creates a client-side of a transport.
2297  *
2298  * @param path the path to the bus.
2299  * @param error address where an error can be returned.
2300  * @returns a new transport, or #NULL on failure.
2301  */
2302 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2303 {
2304         int fd;
2305         DBusTransport *transport;
2306         DBusString address;
2307
2308         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2309
2310         if (!_dbus_string_init (&address))
2311     {
2312                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2313                 return NULL;
2314     }
2315
2316         fd = -1;
2317
2318         if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2319     {
2320                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2321                 goto failed_0;
2322     }
2323
2324         fd = _dbus_connect_kdbus (path, error);
2325         if (fd < 0)
2326     {
2327                 _DBUS_ASSERT_ERROR_IS_SET (error);
2328                 goto failed_0;
2329     }
2330
2331         _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2332
2333         transport = _dbus_transport_new_kdbus_transport (fd, &address);
2334         if (transport == NULL)
2335     {
2336                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2337                 goto failed_1;
2338     }
2339
2340         _dbus_string_free (&address);
2341
2342         return transport;
2343
2344         failed_1:
2345                 _dbus_close_socket (fd, NULL);
2346         failed_0:
2347                 _dbus_string_free (&address);
2348         return NULL;
2349 }
2350
2351
2352 /**
2353  * Opens kdbus transport if method from address entry is kdbus
2354  *
2355  * @param entry the address entry to try opening
2356  * @param transport_p return location for the opened transport
2357  * @param error error to be set
2358  * @returns result of the attempt
2359  */
2360 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry  *entry,
2361                                                            DBusTransport    **transport_p,
2362                                                            DBusError         *error)
2363 {
2364         const char *method;
2365
2366         method = dbus_address_entry_get_method (entry);
2367         _dbus_assert (method != NULL);
2368
2369         if (strcmp (method, "kdbus") == 0)
2370     {
2371                 const char *path = dbus_address_entry_get_value (entry, "path");
2372
2373                 if (path == NULL)
2374         {
2375                         _dbus_set_bad_address (error, "kdbus", "path", NULL);
2376                         return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2377         }
2378
2379         *transport_p = _dbus_transport_new_for_kdbus (path, error);
2380
2381         if (*transport_p == NULL)
2382         {
2383                 _DBUS_ASSERT_ERROR_IS_SET (error);
2384                 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2385         }
2386         else
2387         {
2388                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2389                 return DBUS_TRANSPORT_OPEN_OK;
2390         }
2391     }
2392         else
2393     {
2394                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2395                 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
2396     }
2397 }