D-Bus: Simplify message building error paths
[mech_eap.git] / wpa_supplicant / dbus / dbus_new_helpers.c
1 /*
2  * WPA Supplicant / dbus-based control interface
3  * Copyright (c) 2006, Dan Williams <dcbw@redhat.com> and Red Hat, Inc.
4  * Copyright (c) 2009, Witold Sowa <witold.sowa@gmail.com>
5  *
6  * This software may be distributed under the terms of the BSD license.
7  * See README for more details.
8  */
9
10 #include "utils/includes.h"
11
12 #include "utils/common.h"
13 #include "utils/eloop.h"
14 #include "dbus_common.h"
15 #include "dbus_common_i.h"
16 #include "dbus_new.h"
17 #include "dbus_new_helpers.h"
18 #include "dbus_dict_helpers.h"
19
20
21 static dbus_bool_t fill_dict_with_properties(
22         DBusMessageIter *dict_iter,
23         const struct wpa_dbus_property_desc *props,
24         const char *interface, void *user_data, DBusError *error)
25 {
26         DBusMessageIter entry_iter;
27         const struct wpa_dbus_property_desc *dsc;
28
29         for (dsc = props; dsc && dsc->dbus_property; dsc++) {
30                 /* Only return properties for the requested D-Bus interface */
31                 if (os_strncmp(dsc->dbus_interface, interface,
32                                WPAS_DBUS_INTERFACE_MAX) != 0)
33                         continue;
34
35                 /* Skip write-only properties */
36                 if (dsc->getter == NULL)
37                         continue;
38
39                 if (!dbus_message_iter_open_container(dict_iter,
40                                                       DBUS_TYPE_DICT_ENTRY,
41                                                       NULL, &entry_iter) ||
42                     !dbus_message_iter_append_basic(&entry_iter,
43                                                     DBUS_TYPE_STRING,
44                                                     &dsc->dbus_property))
45                         goto error;
46
47                 /* An error getting a property fails the request entirely */
48                 if (!dsc->getter(&entry_iter, error, user_data))
49                         return FALSE;
50
51                 if (!dbus_message_iter_close_container(dict_iter, &entry_iter))
52                         goto error;
53         }
54
55         return TRUE;
56
57 error:
58         dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, "no memory");
59         return FALSE;
60 }
61
62
63 /**
64  * get_all_properties - Responds for GetAll properties calls on object
65  * @message: Message with GetAll call
66  * @interface: interface name which properties will be returned
67  * @property_dsc: list of object's properties
68  * Returns: Message with dict of variants as argument with properties values
69  *
70  * Iterates over all properties registered with object and execute getters
71  * of those, which are readable and which interface matches interface
72  * specified as argument. Returned message contains one dict argument
73  * with properties names as keys and theirs values as values.
74  */
75 static DBusMessage * get_all_properties(DBusMessage *message, char *interface,
76                                         struct wpa_dbus_object_desc *obj_dsc)
77 {
78         DBusMessage *reply;
79         DBusMessageIter iter, dict_iter;
80         DBusError error;
81
82         reply = dbus_message_new_method_return(message);
83         if (reply == NULL) {
84                 wpa_printf(MSG_ERROR, "%s: out of memory creating dbus reply",
85                            __func__);
86                 return NULL;
87         }
88
89         dbus_message_iter_init_append(reply, &iter);
90         if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) {
91                 wpa_printf(MSG_ERROR, "%s: out of memory creating reply",
92                            __func__);
93                 dbus_message_unref(reply);
94                 reply = dbus_message_new_error(message, DBUS_ERROR_NO_MEMORY,
95                                                "out of memory");
96                 return reply;
97         }
98
99         dbus_error_init(&error);
100         if (!fill_dict_with_properties(&dict_iter, obj_dsc->properties,
101                                        interface, obj_dsc->user_data, &error))
102         {
103                 dbus_message_unref(reply);
104                 reply = wpas_dbus_reply_new_from_error(message, &error,
105                                                        DBUS_ERROR_INVALID_ARGS,
106                                                        "No readable properties"
107                                                        " in this interface");
108                 dbus_error_free(&error);
109                 return reply;
110         }
111
112         if (!wpa_dbus_dict_close_write(&iter, &dict_iter)) {
113                 dbus_message_unref(reply);
114                 return dbus_message_new_error(message, DBUS_ERROR_NO_MEMORY,
115                                               "out of memory");
116         }
117
118         return reply;
119 }
120
121
122 static int is_signature_correct(DBusMessage *message,
123                                 const struct wpa_dbus_method_desc *method_dsc)
124 {
125         /* According to DBus documentation max length of signature is 255 */
126 #define MAX_SIG_LEN 256
127         char registered_sig[MAX_SIG_LEN], *pos;
128         const char *sig = dbus_message_get_signature(message);
129         int ret;
130         const struct wpa_dbus_argument *arg;
131
132         pos = registered_sig;
133         *pos = '\0';
134
135         for (arg = method_dsc->args; arg && arg->name; arg++) {
136                 if (arg->dir == ARG_IN) {
137                         size_t blen = registered_sig + MAX_SIG_LEN - pos;
138                         ret = os_snprintf(pos, blen, "%s", arg->type);
139                         if (os_snprintf_error(blen, ret))
140                                 return 0;
141                         pos += ret;
142                 }
143         }
144
145         return !os_strncmp(registered_sig, sig, MAX_SIG_LEN);
146 }
147
148
149 static DBusMessage * properties_get_all(DBusMessage *message, char *interface,
150                                         struct wpa_dbus_object_desc *obj_dsc)
151 {
152         if (os_strcmp(dbus_message_get_signature(message), "s") != 0)
153                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
154                                               NULL);
155
156         return get_all_properties(message, interface, obj_dsc);
157 }
158
159
160 static DBusMessage * properties_get(DBusMessage *message,
161                                     const struct wpa_dbus_property_desc *dsc,
162                                     void *user_data)
163 {
164         DBusMessage *reply;
165         DBusMessageIter iter;
166         DBusError error;
167
168         if (os_strcmp(dbus_message_get_signature(message), "ss")) {
169                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
170                                               NULL);
171         }
172
173         if (dsc->getter == NULL) {
174                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
175                                               "Property is write-only");
176         }
177
178         reply = dbus_message_new_method_return(message);
179         dbus_message_iter_init_append(reply, &iter);
180
181         dbus_error_init(&error);
182         if (dsc->getter(&iter, &error, user_data) == FALSE) {
183                 dbus_message_unref(reply);
184                 reply = wpas_dbus_reply_new_from_error(
185                         message, &error, DBUS_ERROR_FAILED,
186                         "Failed to read property");
187                 dbus_error_free(&error);
188         }
189
190         return reply;
191 }
192
193
194 static DBusMessage * properties_set(DBusMessage *message,
195                                     const struct wpa_dbus_property_desc *dsc,
196                                     void *user_data)
197 {
198         DBusMessage *reply;
199         DBusMessageIter iter;
200         DBusError error;
201
202         if (os_strcmp(dbus_message_get_signature(message), "ssv")) {
203                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
204                                               NULL);
205         }
206
207         if (dsc->setter == NULL) {
208                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
209                                               "Property is read-only");
210         }
211
212         dbus_message_iter_init(message, &iter);
213         /* Skip the interface name and the property name */
214         dbus_message_iter_next(&iter);
215         dbus_message_iter_next(&iter);
216
217         /* Iter will now point to the property's new value */
218         dbus_error_init(&error);
219         if (dsc->setter(&iter, &error, user_data) == TRUE) {
220                 /* Success */
221                 reply = dbus_message_new_method_return(message);
222         } else {
223                 reply = wpas_dbus_reply_new_from_error(
224                         message, &error, DBUS_ERROR_FAILED,
225                         "Failed to set property");
226                 dbus_error_free(&error);
227         }
228
229         return reply;
230 }
231
232
233 static DBusMessage *
234 properties_get_or_set(DBusMessage *message, DBusMessageIter *iter,
235                       char *interface,
236                       struct wpa_dbus_object_desc *obj_dsc)
237 {
238         const struct wpa_dbus_property_desc *property_dsc;
239         char *property;
240         const char *method;
241
242         method = dbus_message_get_member(message);
243         property_dsc = obj_dsc->properties;
244
245         /* Second argument: property name (DBUS_TYPE_STRING) */
246         if (!dbus_message_iter_next(iter) ||
247             dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING) {
248                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
249                                               NULL);
250         }
251         dbus_message_iter_get_basic(iter, &property);
252
253         while (property_dsc && property_dsc->dbus_property) {
254                 /* compare property names and
255                  * interfaces */
256                 if (!os_strncmp(property_dsc->dbus_property, property,
257                                 WPAS_DBUS_METHOD_SIGNAL_PROP_MAX) &&
258                     !os_strncmp(property_dsc->dbus_interface, interface,
259                                 WPAS_DBUS_INTERFACE_MAX))
260                         break;
261
262                 property_dsc++;
263         }
264         if (property_dsc == NULL || property_dsc->dbus_property == NULL) {
265                 wpa_printf(MSG_DEBUG, "no property handler for %s.%s on %s",
266                            interface, property,
267                            dbus_message_get_path(message));
268                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
269                                               "No such property");
270         }
271
272         if (os_strncmp(WPA_DBUS_PROPERTIES_GET, method,
273                        WPAS_DBUS_METHOD_SIGNAL_PROP_MAX) == 0) {
274                 wpa_printf(MSG_MSGDUMP, "%s: Get(%s)", __func__, property);
275                 return properties_get(message, property_dsc,
276                                       obj_dsc->user_data);
277         }
278
279         wpa_printf(MSG_MSGDUMP, "%s: Set(%s)", __func__, property);
280         return properties_set(message, property_dsc, obj_dsc->user_data);
281 }
282
283
284 static DBusMessage * properties_handler(DBusMessage *message,
285                                         struct wpa_dbus_object_desc *obj_dsc)
286 {
287         DBusMessageIter iter;
288         char *interface;
289         const char *method;
290
291         method = dbus_message_get_member(message);
292         dbus_message_iter_init(message, &iter);
293
294         if (!os_strncmp(WPA_DBUS_PROPERTIES_GET, method,
295                         WPAS_DBUS_METHOD_SIGNAL_PROP_MAX) ||
296             !os_strncmp(WPA_DBUS_PROPERTIES_SET, method,
297                         WPAS_DBUS_METHOD_SIGNAL_PROP_MAX) ||
298             !os_strncmp(WPA_DBUS_PROPERTIES_GETALL, method,
299                         WPAS_DBUS_METHOD_SIGNAL_PROP_MAX)) {
300                 /* First argument: interface name (DBUS_TYPE_STRING) */
301                 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
302                 {
303                         return dbus_message_new_error(message,
304                                                       DBUS_ERROR_INVALID_ARGS,
305                                                       NULL);
306                 }
307
308                 dbus_message_iter_get_basic(&iter, &interface);
309
310                 if (!os_strncmp(WPA_DBUS_PROPERTIES_GETALL, method,
311                                 WPAS_DBUS_METHOD_SIGNAL_PROP_MAX)) {
312                         /* GetAll */
313                         return properties_get_all(message, interface, obj_dsc);
314                 }
315                 /* Get or Set */
316                 return properties_get_or_set(message, &iter, interface,
317                                              obj_dsc);
318         }
319         return dbus_message_new_error(message, DBUS_ERROR_UNKNOWN_METHOD,
320                                       NULL);
321 }
322
323
324 static DBusMessage * msg_method_handler(DBusMessage *message,
325                                         struct wpa_dbus_object_desc *obj_dsc)
326 {
327         const struct wpa_dbus_method_desc *method_dsc = obj_dsc->methods;
328         const char *method;
329         const char *msg_interface;
330
331         method = dbus_message_get_member(message);
332         msg_interface = dbus_message_get_interface(message);
333
334         /* try match call to any registered method */
335         while (method_dsc && method_dsc->dbus_method) {
336                 /* compare method names and interfaces */
337                 if (!os_strncmp(method_dsc->dbus_method, method,
338                                 WPAS_DBUS_METHOD_SIGNAL_PROP_MAX) &&
339                     !os_strncmp(method_dsc->dbus_interface, msg_interface,
340                                 WPAS_DBUS_INTERFACE_MAX))
341                         break;
342
343                 method_dsc++;
344         }
345         if (method_dsc == NULL || method_dsc->dbus_method == NULL) {
346                 wpa_printf(MSG_DEBUG, "no method handler for %s.%s on %s",
347                            msg_interface, method,
348                            dbus_message_get_path(message));
349                 return dbus_message_new_error(message,
350                                               DBUS_ERROR_UNKNOWN_METHOD, NULL);
351         }
352
353         if (!is_signature_correct(message, method_dsc)) {
354                 return dbus_message_new_error(message, DBUS_ERROR_INVALID_ARGS,
355                                               NULL);
356         }
357
358         return method_dsc->method_handler(message,
359                                           obj_dsc->user_data);
360 }
361
362
363 /**
364  * message_handler - Handles incoming DBus messages
365  * @connection: DBus connection on which message was received
366  * @message: Received message
367  * @user_data: pointer to description of object to which message was sent
368  * Returns: Returns information whether message was handled or not
369  *
370  * Reads message interface and method name, then checks if they matches one
371  * of the special cases i.e. introspection call or properties get/getall/set
372  * methods and handles it. Else it iterates over registered methods list
373  * and tries to match method's name and interface to those read from message
374  * If appropriate method was found its handler function is called and
375  * response is sent. Otherwise, the DBUS_ERROR_UNKNOWN_METHOD error message
376  * will be sent.
377  */
378 static DBusHandlerResult message_handler(DBusConnection *connection,
379                                          DBusMessage *message, void *user_data)
380 {
381         struct wpa_dbus_object_desc *obj_dsc = user_data;
382         const char *method;
383         const char *path;
384         const char *msg_interface;
385         DBusMessage *reply;
386
387         /* get method, interface and path the message is addressed to */
388         method = dbus_message_get_member(message);
389         path = dbus_message_get_path(message);
390         msg_interface = dbus_message_get_interface(message);
391         if (!method || !path || !msg_interface)
392                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
393
394         wpa_printf(MSG_MSGDUMP, "dbus: %s.%s (%s) [%s]",
395                    msg_interface, method, path,
396                    dbus_message_get_signature(message));
397
398         /* if message is introspection method call */
399         if (!os_strncmp(WPA_DBUS_INTROSPECTION_METHOD, method,
400                         WPAS_DBUS_METHOD_SIGNAL_PROP_MAX) &&
401             !os_strncmp(WPA_DBUS_INTROSPECTION_INTERFACE, msg_interface,
402                         WPAS_DBUS_INTERFACE_MAX)) {
403 #ifdef CONFIG_CTRL_IFACE_DBUS_INTRO
404                 reply = wpa_dbus_introspect(message, obj_dsc);
405 #else /* CONFIG_CTRL_IFACE_DBUS_INTRO */
406                 reply = dbus_message_new_error(
407                         message, DBUS_ERROR_UNKNOWN_METHOD,
408                         "wpa_supplicant was compiled without "
409                         "introspection support.");
410 #endif /* CONFIG_CTRL_IFACE_DBUS_INTRO */
411         } else if (!os_strncmp(WPA_DBUS_PROPERTIES_INTERFACE, msg_interface,
412                              WPAS_DBUS_INTERFACE_MAX)) {
413                 /* if message is properties method call */
414                 reply = properties_handler(message, obj_dsc);
415         } else {
416                 reply = msg_method_handler(message, obj_dsc);
417         }
418
419         /* If handler succeed returning NULL, reply empty message */
420         if (!reply)
421                 reply = dbus_message_new_method_return(message);
422         if (reply) {
423                 if (!dbus_message_get_no_reply(message))
424                         dbus_connection_send(connection, reply, NULL);
425                 dbus_message_unref(reply);
426         }
427
428         wpa_dbus_flush_all_changed_properties(connection);
429
430         return DBUS_HANDLER_RESULT_HANDLED;
431 }
432
433
434 /**
435  * free_dbus_object_desc - Frees object description data structure
436  * @connection: DBus connection
437  * @obj_dsc: Object description to free
438  *
439  * Frees each of properties, methods and signals description lists and
440  * the object description structure itself.
441  */
442 void free_dbus_object_desc(struct wpa_dbus_object_desc *obj_dsc)
443 {
444         if (!obj_dsc)
445                 return;
446
447         /* free handler's argument */
448         if (obj_dsc->user_data_free_func)
449                 obj_dsc->user_data_free_func(obj_dsc->user_data);
450
451         os_free(obj_dsc->path);
452         os_free(obj_dsc->prop_changed_flags);
453         os_free(obj_dsc);
454 }
455
456
457 static void free_dbus_object_desc_cb(DBusConnection *connection, void *obj_dsc)
458 {
459         free_dbus_object_desc(obj_dsc);
460 }
461
462 /**
463  * wpa_dbus_ctrl_iface_init - Initialize dbus control interface
464  * @application_data: Pointer to application specific data structure
465  * @dbus_path: DBus path to interface object
466  * @dbus_service: DBus service name to register with
467  * @messageHandler: a pointer to function which will handle dbus messages
468  * coming on interface
469  * Returns: 0 on success, -1 on failure
470  *
471  * Initialize the dbus control interface and start receiving commands from
472  * external programs over the bus.
473  */
474 int wpa_dbus_ctrl_iface_init(struct wpas_dbus_priv *iface,
475                              char *dbus_path, char *dbus_service,
476                              struct wpa_dbus_object_desc *obj_desc)
477 {
478         DBusError error;
479         int ret = -1;
480         DBusObjectPathVTable wpa_vtable = {
481                 &free_dbus_object_desc_cb, &message_handler,
482                 NULL, NULL, NULL, NULL
483         };
484
485         obj_desc->connection = iface->con;
486         obj_desc->path = os_strdup(dbus_path);
487
488         /* Register the message handler for the global dbus interface */
489         if (!dbus_connection_register_object_path(iface->con,
490                                                   dbus_path, &wpa_vtable,
491                                                   obj_desc)) {
492                 wpa_printf(MSG_ERROR, "dbus: Could not set up message "
493                            "handler");
494                 return -1;
495         }
496
497         /* Register our service with the message bus */
498         dbus_error_init(&error);
499         switch (dbus_bus_request_name(iface->con, dbus_service,
500                                       0, &error)) {
501         case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER:
502                 ret = 0;
503                 break;
504         case DBUS_REQUEST_NAME_REPLY_EXISTS:
505         case DBUS_REQUEST_NAME_REPLY_IN_QUEUE:
506         case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER:
507                 wpa_printf(MSG_ERROR, "dbus: Could not request service name: "
508                            "already registered");
509                 break;
510         default:
511                 wpa_printf(MSG_ERROR, "dbus: Could not request service name: "
512                            "%s %s", error.name, error.message);
513                 break;
514         }
515         dbus_error_free(&error);
516
517         if (ret != 0)
518                 return -1;
519
520         wpa_printf(MSG_DEBUG, "Providing DBus service '%s'.", dbus_service);
521
522         return 0;
523 }
524
525
526 /**
527  * wpa_dbus_register_object_per_iface - Register a new object with dbus
528  * @ctrl_iface: pointer to dbus private data
529  * @path: DBus path to object
530  * @ifname: interface name
531  * @obj_desc: description of object's methods, signals and properties
532  * Returns: 0 on success, -1 on error
533  *
534  * Registers a new interface with dbus and assigns it a dbus object path.
535  */
536 int wpa_dbus_register_object_per_iface(
537         struct wpas_dbus_priv *ctrl_iface,
538         const char *path, const char *ifname,
539         struct wpa_dbus_object_desc *obj_desc)
540 {
541         DBusConnection *con;
542         DBusError error;
543
544         DBusObjectPathVTable vtable = {
545                 &free_dbus_object_desc_cb, &message_handler,
546                 NULL, NULL, NULL, NULL
547         };
548
549         /* Do nothing if the control interface is not turned on */
550         if (ctrl_iface == NULL)
551                 return 0;
552
553         con = ctrl_iface->con;
554         obj_desc->connection = con;
555         obj_desc->path = os_strdup(path);
556
557         dbus_error_init(&error);
558         /* Register the message handler for the interface functions */
559         if (!dbus_connection_try_register_object_path(con, path, &vtable,
560                                                       obj_desc, &error)) {
561                 if (!os_strcmp(error.name, DBUS_ERROR_OBJECT_PATH_IN_USE)) {
562                         wpa_printf(MSG_DEBUG, "dbus: %s", error.message);
563                 } else {
564                         wpa_printf(MSG_ERROR, "dbus: Could not set up message "
565                                    "handler for interface %s object %s",
566                                    ifname, path);
567                         wpa_printf(MSG_ERROR, "dbus error: %s", error.name);
568                         wpa_printf(MSG_ERROR, "dbus: %s", error.message);
569                 }
570                 dbus_error_free(&error);
571                 return -1;
572         }
573
574         dbus_error_free(&error);
575         return 0;
576 }
577
578
579 static void flush_object_timeout_handler(void *eloop_ctx, void *timeout_ctx);
580
581
582 /**
583  * wpa_dbus_unregister_object_per_iface - Unregisters DBus object
584  * @ctrl_iface: Pointer to dbus private data
585  * @path: DBus path to object which will be unregistered
586  * Returns: Zero on success and -1 on failure
587  *
588  * Unregisters DBus object given by its path
589  */
590 int wpa_dbus_unregister_object_per_iface(
591         struct wpas_dbus_priv *ctrl_iface, const char *path)
592 {
593         DBusConnection *con = ctrl_iface->con;
594         struct wpa_dbus_object_desc *obj_desc = NULL;
595
596         dbus_connection_get_object_path_data(con, path, (void **) &obj_desc);
597         if (!obj_desc) {
598                 wpa_printf(MSG_ERROR, "dbus: %s: Could not obtain object's "
599                            "private data: %s", __func__, path);
600                 return 0;
601         }
602
603         eloop_cancel_timeout(flush_object_timeout_handler, con, obj_desc);
604
605         if (!dbus_connection_unregister_object_path(con, path))
606                 return -1;
607
608         return 0;
609 }
610
611
612 static dbus_bool_t put_changed_properties(
613         const struct wpa_dbus_object_desc *obj_dsc, const char *interface,
614         DBusMessageIter *dict_iter, int clear_changed)
615 {
616         DBusMessageIter entry_iter;
617         const struct wpa_dbus_property_desc *dsc;
618         int i;
619         DBusError error;
620
621         for (dsc = obj_dsc->properties, i = 0; dsc && dsc->dbus_property;
622              dsc++, i++) {
623                 if (obj_dsc->prop_changed_flags == NULL ||
624                     !obj_dsc->prop_changed_flags[i])
625                         continue;
626                 if (os_strcmp(dsc->dbus_interface, interface) != 0)
627                         continue;
628                 if (clear_changed)
629                         obj_dsc->prop_changed_flags[i] = 0;
630
631                 if (!dbus_message_iter_open_container(dict_iter,
632                                                       DBUS_TYPE_DICT_ENTRY,
633                                                       NULL, &entry_iter) ||
634                     !dbus_message_iter_append_basic(&entry_iter,
635                                                     DBUS_TYPE_STRING,
636                                                     &dsc->dbus_property))
637                         return FALSE;
638
639                 dbus_error_init(&error);
640                 if (!dsc->getter(&entry_iter, &error, obj_dsc->user_data)) {
641                         if (dbus_error_is_set (&error)) {
642                                 wpa_printf(MSG_ERROR, "dbus: %s: Cannot get "
643                                            "new value of property %s: (%s) %s",
644                                            __func__, dsc->dbus_property,
645                                            error.name, error.message);
646                         } else {
647                                 wpa_printf(MSG_ERROR, "dbus: %s: Cannot get "
648                                            "new value of property %s",
649                                            __func__, dsc->dbus_property);
650                         }
651                         dbus_error_free(&error);
652                         return FALSE;
653                 }
654
655                 if (!dbus_message_iter_close_container(dict_iter, &entry_iter))
656                         return FALSE;
657         }
658
659         return TRUE;
660 }
661
662
663 static void do_send_prop_changed_signal(
664         DBusConnection *con, const char *path, const char *interface,
665         const struct wpa_dbus_object_desc *obj_dsc)
666 {
667         DBusMessage *msg;
668         DBusMessageIter signal_iter, dict_iter;
669
670         msg = dbus_message_new_signal(path, DBUS_INTERFACE_PROPERTIES,
671                                       "PropertiesChanged");
672         if (msg == NULL)
673                 return;
674
675         dbus_message_iter_init_append(msg, &signal_iter);
676
677         if (!dbus_message_iter_append_basic(&signal_iter, DBUS_TYPE_STRING,
678                                             &interface) ||
679             /* Changed properties dict */
680             !dbus_message_iter_open_container(&signal_iter, DBUS_TYPE_ARRAY,
681                                               "{sv}", &dict_iter) ||
682             !put_changed_properties(obj_dsc, interface, &dict_iter, 0) ||
683             !dbus_message_iter_close_container(&signal_iter, &dict_iter) ||
684             /* Invalidated properties array (empty) */
685             !dbus_message_iter_open_container(&signal_iter, DBUS_TYPE_ARRAY,
686                                               "s", &dict_iter) ||
687             !dbus_message_iter_close_container(&signal_iter, &dict_iter))
688                 goto err;
689
690         dbus_connection_send(con, msg, NULL);
691
692 out:
693         dbus_message_unref(msg);
694         return;
695
696 err:
697         wpa_printf(MSG_DEBUG, "dbus: %s: Failed to construct signal",
698                    __func__);
699         goto out;
700 }
701
702
703 static void do_send_deprecated_prop_changed_signal(
704         DBusConnection *con, const char *path, const char *interface,
705         const struct wpa_dbus_object_desc *obj_dsc)
706 {
707         DBusMessage *msg;
708         DBusMessageIter signal_iter, dict_iter;
709
710         msg = dbus_message_new_signal(path, interface, "PropertiesChanged");
711         if (msg == NULL)
712                 return;
713
714         dbus_message_iter_init_append(msg, &signal_iter);
715
716         if (!dbus_message_iter_open_container(&signal_iter, DBUS_TYPE_ARRAY,
717                                               "{sv}", &dict_iter) ||
718             !put_changed_properties(obj_dsc, interface, &dict_iter, 1) ||
719             !dbus_message_iter_close_container(&signal_iter, &dict_iter))
720                 goto err;
721
722         dbus_connection_send(con, msg, NULL);
723
724 out:
725         dbus_message_unref(msg);
726         return;
727
728 err:
729         wpa_printf(MSG_DEBUG, "dbus: %s: Failed to construct signal",
730                    __func__);
731         goto out;
732 }
733
734
735 static void send_prop_changed_signal(
736         DBusConnection *con, const char *path, const char *interface,
737         const struct wpa_dbus_object_desc *obj_dsc)
738 {
739         /*
740          * First, send property change notification on the standardized
741          * org.freedesktop.DBus.Properties interface. This call will not
742          * clear the property change bits, so that they are preserved for
743          * the call that follows.
744          */
745         do_send_prop_changed_signal(con, path, interface, obj_dsc);
746
747         /*
748          * Now send PropertiesChanged on our own interface for backwards
749          * compatibility. This is deprecated and will be removed in a future
750          * release.
751          */
752         do_send_deprecated_prop_changed_signal(con, path, interface, obj_dsc);
753
754         /* Property change bits have now been cleared. */
755 }
756
757
758 static void flush_object_timeout_handler(void *eloop_ctx, void *timeout_ctx)
759 {
760         DBusConnection *con = eloop_ctx;
761         struct wpa_dbus_object_desc *obj_desc = timeout_ctx;
762
763         wpa_printf(MSG_DEBUG, "dbus: %s: Timeout - sending changed properties "
764                    "of object %s", __func__, obj_desc->path);
765         wpa_dbus_flush_object_changed_properties(con, obj_desc->path);
766 }
767
768
769 static void recursive_flush_changed_properties(DBusConnection *con,
770                                                const char *path)
771 {
772         char **objects = NULL;
773         char subobj_path[WPAS_DBUS_OBJECT_PATH_MAX];
774         int i;
775
776         wpa_dbus_flush_object_changed_properties(con, path);
777
778         if (!dbus_connection_list_registered(con, path, &objects))
779                 goto out;
780
781         for (i = 0; objects[i]; i++) {
782                 os_snprintf(subobj_path, WPAS_DBUS_OBJECT_PATH_MAX,
783                             "%s/%s", path, objects[i]);
784                 recursive_flush_changed_properties(con, subobj_path);
785         }
786
787 out:
788         dbus_free_string_array(objects);
789 }
790
791
792 /**
793  * wpa_dbus_flush_all_changed_properties - Send all PropertiesChanged signals
794  * @con: DBus connection
795  *
796  * Traverses through all registered objects and sends PropertiesChanged for
797  * each properties.
798  */
799 void wpa_dbus_flush_all_changed_properties(DBusConnection *con)
800 {
801         recursive_flush_changed_properties(con, WPAS_DBUS_NEW_PATH);
802 }
803
804
805 /**
806  * wpa_dbus_flush_object_changed_properties - Send PropertiesChanged for object
807  * @con: DBus connection
808  * @path: path to a DBus object for which PropertiesChanged will be sent.
809  *
810  * Iterates over all properties registered with object and for each interface
811  * containing properties marked as changed, sends a PropertiesChanged signal
812  * containing names and new values of properties that have changed.
813  *
814  * You need to call this function after wpa_dbus_mark_property_changed()
815  * if you want to send PropertiesChanged signal immediately (i.e., without
816  * waiting timeout to expire). PropertiesChanged signal for an object is sent
817  * automatically short time after first marking property as changed. All
818  * PropertiesChanged signals are sent automatically after responding on DBus
819  * message, so if you marked a property changed as a result of DBus call
820  * (e.g., param setter), you usually do not need to call this function.
821  */
822 void wpa_dbus_flush_object_changed_properties(DBusConnection *con,
823                                               const char *path)
824 {
825         struct wpa_dbus_object_desc *obj_desc = NULL;
826         const struct wpa_dbus_property_desc *dsc;
827         int i;
828
829         dbus_connection_get_object_path_data(con, path, (void **) &obj_desc);
830         if (!obj_desc)
831                 return;
832         eloop_cancel_timeout(flush_object_timeout_handler, con, obj_desc);
833
834         for (dsc = obj_desc->properties, i = 0; dsc && dsc->dbus_property;
835              dsc++, i++) {
836                 if (obj_desc->prop_changed_flags == NULL ||
837                     !obj_desc->prop_changed_flags[i])
838                         continue;
839                 send_prop_changed_signal(con, path, dsc->dbus_interface,
840                                          obj_desc);
841         }
842 }
843
844
845 #define WPA_DBUS_SEND_PROP_CHANGED_TIMEOUT 5000
846
847
848 /**
849  * wpa_dbus_mark_property_changed - Mark a property as changed and
850  * @iface: dbus priv struct
851  * @path: path to DBus object which property has changed
852  * @interface: interface containing changed property
853  * @property: property name which has changed
854  *
855  * Iterates over all properties registered with an object and marks the one
856  * given in parameters as changed. All parameters registered for an object
857  * within a single interface will be aggregated together and sent in one
858  * PropertiesChanged signal when function
859  * wpa_dbus_flush_object_changed_properties() is called.
860  */
861 void wpa_dbus_mark_property_changed(struct wpas_dbus_priv *iface,
862                                     const char *path, const char *interface,
863                                     const char *property)
864 {
865         struct wpa_dbus_object_desc *obj_desc = NULL;
866         const struct wpa_dbus_property_desc *dsc;
867         int i = 0;
868
869         if (iface == NULL)
870                 return;
871
872         dbus_connection_get_object_path_data(iface->con, path,
873                                              (void **) &obj_desc);
874         if (!obj_desc) {
875                 wpa_printf(MSG_ERROR, "dbus: wpa_dbus_property_changed: "
876                            "could not obtain object's private data: %s", path);
877                 return;
878         }
879
880         for (dsc = obj_desc->properties; dsc && dsc->dbus_property; dsc++, i++)
881                 if (os_strcmp(property, dsc->dbus_property) == 0 &&
882                     os_strcmp(interface, dsc->dbus_interface) == 0) {
883                         if (obj_desc->prop_changed_flags)
884                                 obj_desc->prop_changed_flags[i] = 1;
885                         break;
886                 }
887
888         if (!dsc || !dsc->dbus_property) {
889                 wpa_printf(MSG_ERROR, "dbus: wpa_dbus_property_changed: "
890                            "no property %s in object %s", property, path);
891                 return;
892         }
893
894         if (!eloop_is_timeout_registered(flush_object_timeout_handler,
895                                          iface->con, obj_desc)) {
896                 eloop_register_timeout(0, WPA_DBUS_SEND_PROP_CHANGED_TIMEOUT,
897                                        flush_object_timeout_handler,
898                                        iface->con, obj_desc);
899         }
900 }
901
902
903 /**
904  * wpa_dbus_get_object_properties - Put object's properties into dictionary
905  * @iface: dbus priv struct
906  * @path: path to DBus object which properties will be obtained
907  * @interface: interface name which properties will be obtained
908  * @iter: DBus message iter at which to append property dictionary.
909  *
910  * Iterates over all properties registered with object and execute getters
911  * of those, which are readable and which interface matches interface
912  * specified as argument. Obtained properties values are stored in
913  * dict_iter dictionary.
914  */
915 dbus_bool_t wpa_dbus_get_object_properties(struct wpas_dbus_priv *iface,
916                                            const char *path,
917                                            const char *interface,
918                                            DBusMessageIter *iter)
919 {
920         struct wpa_dbus_object_desc *obj_desc = NULL;
921         DBusMessageIter dict_iter;
922         DBusError error;
923
924         dbus_connection_get_object_path_data(iface->con, path,
925                                              (void **) &obj_desc);
926         if (!obj_desc) {
927                 wpa_printf(MSG_ERROR, "dbus: %s: could not obtain object's "
928                            "private data: %s", __func__, path);
929                 return FALSE;
930         }
931
932         if (!wpa_dbus_dict_open_write(iter, &dict_iter)) {
933                 wpa_printf(MSG_ERROR, "dbus: %s: failed to open message dict",
934                            __func__);
935                 return FALSE;
936         }
937
938         dbus_error_init(&error);
939         if (!fill_dict_with_properties(&dict_iter, obj_desc->properties,
940                                        interface, obj_desc->user_data,
941                                        &error)) {
942                 wpa_printf(MSG_ERROR, "dbus: %s: failed to get object"
943                            " properties: (%s) %s", __func__,
944                            dbus_error_is_set(&error) ? error.name : "none",
945                            dbus_error_is_set(&error) ? error.message : "none");
946                 dbus_error_free(&error);
947                 return FALSE;
948         }
949
950         return wpa_dbus_dict_close_write(iter, &dict_iter);
951 }
952
953 /**
954  * wpas_dbus_new_decompose_object_path - Decompose an interface object path into parts
955  * @path: The dbus object path
956  * @sep: Separating part (e.g., "Networks" or "PersistentGroups")
957  * @item: (out) The part following the specified separator, if any
958  * Returns: The object path of the interface this path refers to
959  *
960  * For a given object path, decomposes the object path into object id and
961  * requested part, if those parts exist. The caller is responsible for freeing
962  * the returned value. The *item pointer points to that allocated value and must
963  * not be freed separately.
964  *
965  * As an example, path = "/fi/w1/wpa_supplicant1/Interfaces/1/Networks/0" and
966  * sep = "Networks" would result in "/fi/w1/wpa_supplicant1/Interfaces/1"
967  * getting returned and *items set to point to "0".
968  */
969 char * wpas_dbus_new_decompose_object_path(const char *path, const char *sep,
970                                            char **item)
971 {
972         const unsigned int dev_path_prefix_len =
973                 os_strlen(WPAS_DBUS_NEW_PATH_INTERFACES "/");
974         char *obj_path_only;
975         char *pos;
976         size_t sep_len;
977
978         *item = NULL;
979
980         /* Verify that this starts with our interface prefix */
981         if (os_strncmp(path, WPAS_DBUS_NEW_PATH_INTERFACES "/",
982                        dev_path_prefix_len) != 0)
983                 return NULL; /* not our path */
984
985         /* Ensure there's something at the end of the path */
986         if ((path + dev_path_prefix_len)[0] == '\0')
987                 return NULL;
988
989         obj_path_only = os_strdup(path);
990         if (obj_path_only == NULL)
991                 return NULL;
992
993         pos = obj_path_only + dev_path_prefix_len;
994         pos = os_strchr(pos, '/');
995         if (pos == NULL)
996                 return obj_path_only; /* no next item on the path */
997
998          /* Separate network interface prefix from the path */
999         *pos++ = '\0';
1000
1001         sep_len = os_strlen(sep);
1002         if (os_strncmp(pos, sep, sep_len) != 0 || pos[sep_len] != '/')
1003                 return obj_path_only; /* no match */
1004
1005          /* return a pointer to the requested item */
1006         *item = pos + sep_len + 1;
1007         return obj_path_only;
1008 }
1009
1010
1011 /**
1012  * wpas_dbus_reply_new_from_error - Create a new D-Bus error message from a
1013  *   dbus error structure
1014  * @message: The original request message for which the error is a reply
1015  * @error: The error containing a name and a descriptive error cause
1016  * @fallback_name: A generic error name if @error was not set
1017  * @fallback_string: A generic error string if @error was not set
1018  * Returns: A new D-Bus error message
1019  *
1020  * Given a DBusMessage structure, creates a new D-Bus error message using
1021  * the error name and string contained in that structure.
1022  */
1023 DBusMessage * wpas_dbus_reply_new_from_error(DBusMessage *message,
1024                                              DBusError *error,
1025                                              const char *fallback_name,
1026                                              const char *fallback_string)
1027 {
1028         if (error && error->name && error->message) {
1029                 return dbus_message_new_error(message, error->name,
1030                                               error->message);
1031         }
1032         if (fallback_name && fallback_string) {
1033                 return dbus_message_new_error(message, fallback_name,
1034                                               fallback_string);
1035         }
1036         return NULL;
1037 }