1 /******************************************************************************
4 * Company XS Embedded GmbH
5 *****************************************************************************/
6 /******************************************************************************
7 * This Source Code Form is subject to the terms of the
8 * Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed
9 * with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 ******************************************************************************/
12 * @file persistence_client_library_dbus_service.c
13 * @ingroup Persistence client library
14 * @author Ingo Huerner
15 * @brief Implementation of the persistence client library dbus service.
20 #include "persistence_client_library_dbus_service.h"
21 #include "persistence_client_library_lc_interface.h"
22 #include "persistence_client_library_pas_interface.h"
23 #include "../include_protected/persistence_client_library_data_organization.h"
31 pthread_cond_t gDbusInitializedCond = PTHREAD_COND_INITIALIZER;
32 pthread_mutex_t gDbusInitializedMtx = PTHREAD_MUTEX_INITIALIZER;
33 pthread_mutex_t gDbusPendingRegMtx = PTHREAD_MUTEX_INITIALIZER;
34 pthread_mutex_t gMainLoopMtx = PTHREAD_MUTEX_INITIALIZER;
39 typedef enum EDBusObjectType
47 typedef struct SObjectEntry
49 tDBusObjectType objtype; /** libdbus' object */
52 DBusWatch * watch; /** watch "object" */
53 DBusTimeout * timeout; /** timeout "object" */
60 typedef struct SPollInfo
63 struct pollfd fds[10];
64 tObjectEntry objects[10];
68 /// polling information
69 static tPollInfo gPollInfo;
73 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
76 /* function to unregister ojbect path message handler */
77 static void unregisterMessageHandler(DBusConnection *connection, void *user_data)
79 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("unregisterObjectPath\n"));
82 /* catches messages not directed to any registered object path ("garbage collector") */
83 static DBusHandlerResult handleObjectPathMessageFallback(DBusConnection * connection, DBusMessage * message, void * user_data)
85 DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
87 // org.genivi.persistence.admin S I G N A L
88 if((0==strcmp("org.genivi.persistence.admin", dbus_message_get_interface(message))))
90 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
92 if((0==strcmp("PersistenceModeChanged", dbus_message_get_member(message))))
94 // to do handle signal
95 result = signal_persModeChange(connection, message);
99 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> unknown signal:"), DLT_STRING(dbus_message_get_interface(message)) );
103 // org.genivi.persistence.admin S I G N A L
104 else if((0==strcmp("org.genivi.persistence.adminconsumer", dbus_message_get_interface(message))))
106 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
108 pclNotification_s notifyStruct;
109 int validMessage = 0;
111 if((0==strcmp("PersistenceResChange", dbus_message_get_member(message))))
113 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_changed;
116 else if((0==strcmp("PersistenceResDelete", dbus_message_get_member(message))))
118 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_deleted;
121 else if((0==strcmp("PersistenceRes", dbus_message_get_member(message))))
123 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_created;
127 if(validMessage == 1)
131 dbus_error_init (&error);
136 if (!dbus_message_get_args(message, &error, DBUS_TYPE_STRING, ¬ifyStruct.resource_id,
137 DBUS_TYPE_STRING, &ldbid,
138 DBUS_TYPE_STRING, &user_no,
139 DBUS_TYPE_STRING, &seat_no,
142 reply = dbus_message_new_error(message, error.name, error.message);
146 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => DBus No memory"), DLT_STRING(dbus_message_get_interface(message)) );
149 if (!dbus_connection_send(connection, reply, 0))
151 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => DBus No memory"), DLT_STRING(dbus_message_get_interface(message)) );
154 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;;
155 dbus_message_unref(reply);
159 notifyStruct.ldbid = atoi(ldbid);
160 notifyStruct.user_no = atoi(user_no);
161 notifyStruct.seat_no = atoi(seat_no);
163 // call the registered callback function
164 gChangeNotifyCallback(¬ifyStruct);
166 result = DBUS_HANDLER_RESULT_HANDLED;
168 dbus_connection_flush(connection);
172 // org.genivi.persistence.admin P R O P E R T Y
173 else if((0==strcmp("org.freedesktop.DBus.Properties", dbus_message_get_interface(message))))
175 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
177 if((0==strcmp("EggDBusChanged", dbus_message_get_member(message))))
179 DBusMessageIter array;
180 DBusMessageIter dict;
181 DBusMessageIter variant;
183 char* dictString = NULL;
186 dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, 0, &dict);
187 dbus_message_iter_get_basic(&dict, &dictString);
189 dbus_message_iter_open_container(&dict,DBUS_TYPE_VARIANT, NULL, &variant);
190 dbus_message_iter_get_basic(&dict, &value);
192 dbus_message_iter_close_container(&dict, &variant);
193 dbus_message_iter_close_container(&array, &dict);
195 // to do handle signal
196 result = DBUS_HANDLER_RESULT_HANDLED;
200 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> unknown property:"), DLT_STRING(dbus_message_get_interface(message)) );
205 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> not a signal:"), DLT_STRING(dbus_message_get_member(message)) );
214 static void unregisterObjectPathFallback(DBusConnection *connection, void *user_data)
216 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("unregisterObjectPathFallback\n"));
221 void* run_mainloop(void* dataPtr)
223 // persistence admin message
224 static const struct DBusObjectPathVTable vtablePersAdmin
225 = {unregisterMessageHandler, checkPersAdminMsg, NULL, };
228 static const struct DBusObjectPathVTable vtableLifecycle
229 = {unregisterMessageHandler, checkLifecycleMsg, NULL, };
232 static const struct DBusObjectPathVTable vtableFallback
233 = {unregisterObjectPathFallback, handleObjectPathMessageFallback, NULL, };
236 mainLoop(vtablePersAdmin, vtableLifecycle, vtableFallback, dataPtr);
243 int setup_dbus_mainloop(void)
248 DBusConnection* conn = NULL;
250 const char *pAddress = getenv("PERS_CLIENT_DBUS_ADDRESS");
252 // enable locking of data structures in the D-Bus library for multi threading.
253 dbus_threads_init_default();
254 dbus_error_init(&err);
256 // wain until dbus main loop has been setup and running
257 pthread_mutex_lock(&gDbusInitializedMtx);
259 // Connect to the bus and check for errors
262 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("setup_dbus_mainloop -> Use specific dbus address:"), DLT_STRING(pAddress) );
264 conn = dbus_connection_open_private(pAddress, &err);
268 if(!dbus_bus_register(conn, &err))
270 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("dbus_bus_register() Error :"), DLT_STRING(err.message) );
271 dbus_error_free (&err);
277 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("dbus_connection_open_private() Error :"), DLT_STRING(err.message) );
278 dbus_error_free(&err);
284 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("Use default dbus bus (DBUS_BUS_SYSTEM)"));
286 conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
289 // create here the dbus connection and pass to main loop
290 rval = pthread_create(&thread, NULL, run_mainloop, conn);
293 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("pthread_create( DBUS run_mainloop ) returned an error:"), DLT_INT(rval) );
297 // wait for condition variable
298 pthread_cond_wait(&gDbusInitializedCond, &gDbusInitializedMtx);
300 pthread_mutex_unlock(&gDbusInitializedMtx);
308 static dbus_bool_t addWatch(DBusWatch *watch, void *data)
310 dbus_bool_t result = FALSE;
312 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
314 int flags = dbus_watch_get_flags(watch);
316 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
317 pEntry->objtype = OT_WATCH;
318 pEntry->watch = watch;
320 gPollInfo.fds[gPollInfo.nfds].fd = dbus_watch_get_unix_fd(watch);
322 if (TRUE==dbus_watch_get_enabled(watch))
324 if (flags&DBUS_WATCH_READABLE)
326 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
328 if (flags&DBUS_WATCH_WRITABLE)
330 gPollInfo.fds[gPollInfo.nfds].events |= POLLOUT;
344 static void removeWatch(DBusWatch *watch, void *data)
346 void* w_data = dbus_watch_get_data(watch);
348 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("removeWatch called "), DLT_INT( (int)watch) );
353 dbus_watch_set_data(watch, NULL, NULL);
358 static void watchToggled(DBusWatch *watch, void *data)
360 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("watchToggled called "), DLT_INT( (int)watch) );
362 if(dbus_watch_get_enabled(watch))
363 addWatch(watch, data);
365 removeWatch(watch, data);
370 static dbus_bool_t addTimeout(DBusTimeout *timeout, void *data)
372 dbus_bool_t ret = FALSE;
374 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
376 const int interval = dbus_timeout_get_interval(timeout);
377 if ((0<interval)&&(TRUE==dbus_timeout_get_enabled(timeout)))
379 const int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
382 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
383 if (-1!=timerfd_settime(tfd, 0, &its, NULL))
385 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
386 pEntry->objtype = OT_TIMEOUT;
387 pEntry->timeout = timeout;
388 gPollInfo.fds[gPollInfo.nfds].fd = tfd;
389 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
395 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => timerfd_settime() failed"), DLT_STRING(strerror(errno)) );
400 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => timerfd_create() failed"), DLT_STRING(strerror(errno)) );
406 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => cannot create another fd to be poll()'ed"));
414 static void removeTimeout(DBusTimeout *timeout, void *data)
417 int i = gPollInfo.nfds;
418 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
422 if (-1==close(gPollInfo.fds[i].fd))
424 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("removeTimeout => close() timerfd"), DLT_STRING(strerror(errno)) );
428 while (gPollInfo.nfds>i)
430 gPollInfo.fds[i] = gPollInfo.fds[i+1];
431 gPollInfo.objects[i] = gPollInfo.objects[i+1];
435 gPollInfo.fds[gPollInfo.nfds].fd = -1;
436 gPollInfo.objects[gPollInfo.nfds].objtype = OT_NONE;
442 /** callback for libdbus' when timeout changed */
443 static void timeoutToggled(DBusTimeout *timeout, void *data)
445 int i = gPollInfo.nfds;
446 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
447 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("timeoutToggled") );
450 const int interval = (TRUE==dbus_timeout_get_enabled(timeout))?dbus_timeout_get_interval(timeout):0;
451 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
452 if (-1!=timerfd_settime(gPollInfo.fds[i].fd, 0, &its, NULL))
454 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("timeoutToggled => timerfd_settime()"), DLT_STRING(strerror(errno)) );
461 int mainLoop(DBusObjectPathVTable vtable, DBusObjectPathVTable vtable2,
462 DBusObjectPathVTable vtableFallback, void* userData)
465 // lock mutex to make sure dbus main loop is running
466 pthread_mutex_lock(&gDbusInitializedMtx);
468 DBusConnection* conn = (DBusConnection*)userData;
469 dbus_error_init(&err);
471 if (dbus_error_is_set(&err))
473 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => Connection Error:"), DLT_STRING(err.message) );
474 dbus_error_free(&err);
476 else if (NULL != conn)
478 dbus_connection_set_exit_on_disconnect(conn, FALSE);
479 if (-1 == (gEfds = eventfd(0, 0)))
481 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => eventfd() failed w/ errno:"), DLT_INT(errno) );
486 memset(&gPollInfo, 0 , sizeof(gPollInfo));
489 gPollInfo.fds[0].fd = gEfds;
490 gPollInfo.fds[0].events = POLLIN;
492 dbus_bus_add_match(conn, "type='signal',interface='org.genivi.persistence.admin',member='PersistenceModeChanged',path='/org/genivi/persistence/admin'", &err);
494 // register for messages
495 if ( (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/persistence/adminconsumer", &vtable, userData))
496 && (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer", &vtable2, userData))
497 && (TRUE==dbus_connection_register_fallback(conn, "/", &vtableFallback, userData)) )
499 if( (TRUE!=dbus_connection_set_watch_functions(conn, addWatch, removeWatch, watchToggled, NULL, NULL))
500 || (TRUE!=dbus_connection_set_timeout_functions(conn, addTimeout, removeTimeout, timeoutToggled, NULL, NULL)) )
502 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => dbus_connection_set_watch_functions() failed"));
506 pthread_cond_signal(&gDbusInitializedCond);
507 pthread_mutex_unlock(&gDbusInitializedMtx);
510 bContinue = 0; /* assume error */
512 while (DBUS_DISPATCH_DATA_REMAINS==dbus_connection_dispatch(conn));
514 while ((-1==(ret=poll(gPollInfo.fds, gPollInfo.nfds, -1)))&&(EINTR==errno));
518 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => poll() failed w/ errno "), DLT_INT(errno) );
528 for (i=0; gPollInfo.nfds>i; ++i)
531 if (0!=gPollInfo.fds[i].revents)
533 if (OT_TIMEOUT==gPollInfo.objects[i].objtype)
535 /* time-out occured */
536 unsigned long long nExpCount = 0;
537 if ((ssize_t)sizeof(nExpCount)!=read(gPollInfo.fds[i].fd, &nExpCount, sizeof(nExpCount)))
539 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => read failed"));
541 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => timeout"));
543 if (FALSE==dbus_timeout_handle(gPollInfo.objects[i].timeout))
545 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => dbus_timeout_handle() failed!?"));
549 else if (gPollInfo.fds[i].fd == gEfds)
551 /* internal command */
552 if (0!=(gPollInfo.fds[i].revents & POLLIN))
556 while ((-1==(ret = read(gPollInfo.fds[i].fd, buf, 64)))&&(EINTR == errno));
559 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => read() failed"), DLT_STRING(strerror(errno)) );
565 case CMD_PAS_BLOCK_AND_WRITE_BACK:
566 process_block_and_write_data_back((buf[2]), buf[1]);
568 case CMD_LC_PREPARE_SHUTDOWN:
569 process_prepare_shutdown((buf[2]), buf[1]);
571 case CMD_SEND_NOTIFY_SIGNAL:
572 process_send_notification_signal(conn);
574 case CMD_REG_NOTIFY_SIGNAL:
575 process_reg_notification_signal(conn);
577 case CMD_SEND_PAS_REQUEST:
578 process_send_pas_request(conn, (buf[2]), buf[1]);
580 case CMD_SEND_PAS_REGISTER:
581 process_send_pas_register(conn, (buf[1]), buf[2]);
583 case CMD_SEND_LC_REQUEST:
584 process_send_lifecycle_request(conn, (buf[2]), buf[1]);
586 case CMD_SEND_LC_REGISTER:
587 process_send_lifecycle_register(conn, (buf[1]), buf[2]);
593 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => command not handled"), DLT_INT(buf[0]) );
596 pthread_mutex_unlock(&gMainLoopMtx);
603 if (0!=(gPollInfo.fds[i].revents & POLLIN))
605 flags |= DBUS_WATCH_READABLE;
607 if (0!=(gPollInfo.fds[i].revents & POLLOUT))
609 flags |= DBUS_WATCH_WRITABLE;
611 if (0!=(gPollInfo.fds[i].revents & POLLERR))
613 flags |= DBUS_WATCH_ERROR;
615 if (0!=(gPollInfo.fds[i].revents & POLLHUP))
617 flags |= DBUS_WATCH_HANGUP;
620 bContinue = dbus_watch_handle(gPollInfo.objects[i].watch, flags);
626 while (0!=bContinue);
628 dbus_connection_unregister_object_path(conn, "/org/genivi/persistence/adminconsumer");
629 dbus_connection_unregister_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer");
630 dbus_connection_unregister_object_path(conn, "/");
634 dbus_connection_close(conn);
635 dbus_connection_unref(conn);
639 pthread_cond_signal(&gDbusInitializedCond);
640 pthread_mutex_unlock(&gDbusInitializedMtx);
646 int deliverToMainloop(tCmd mainloopCmd, unsigned int param1, unsigned int param2)
652 pthread_mutex_lock(&gMainLoopMtx);
654 cmd = ( ((uint64_t)param2 << 32) | ((uint64_t)param1 << 16) | mainloopCmd);
656 if(-1 == write(gEfds, &cmd, (sizeof(uint64_t))))
658 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("deliverToMainloop => failed to write to pipe"), DLT_INT(errno));