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 "persistence_client_library_dbus_cmd.h"
24 #include "../include_protected/persistence_client_library_data_organization.h"
34 pthread_cond_t gDbusInitializedCond = PTHREAD_COND_INITIALIZER;
35 pthread_mutex_t gDbusInitializedMtx = PTHREAD_MUTEX_INITIALIZER;
37 pthread_mutex_t gDbusPendingRegMtx = PTHREAD_MUTEX_INITIALIZER;
40 pthread_mutex_t gDeliverpMtx = PTHREAD_MUTEX_INITIALIZER;
42 pthread_mutex_t gMainCondMtx = PTHREAD_MUTEX_INITIALIZER;
43 pthread_cond_t gMainLoopCond = PTHREAD_COND_INITIALIZER;
45 pthread_t gMainLoopThread;
48 int gEfds; // communication channel int dbus mainloop
51 typedef enum EDBusObjectType
59 typedef struct SObjectEntry
61 tDBusObjectType objtype; /** libdbus' object */
64 DBusWatch * watch; /** watch "object" */
65 DBusTimeout * timeout; /** timeout "object" */
72 typedef struct SPollInfo
75 struct pollfd fds[10];
76 tObjectEntry objects[10];
80 /// polling information
81 static tPollInfo gPollInfo;
85 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
88 /* function to unregister ojbect path message handler */
89 static void unregisterMessageHandler(DBusConnection *connection, void *user_data)
91 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("unregisterObjectPath\n"));
94 /* catches messages not directed to any registered object path ("garbage collector") */
95 static DBusHandlerResult handleObjectPathMessageFallback(DBusConnection * connection, DBusMessage * message, void * user_data)
97 DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
99 // org.genivi.persistence.admin S I G N A L
100 if((0==strcmp("org.genivi.persistence.admin", dbus_message_get_interface(message))))
102 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
104 if((0==strcmp("PersistenceModeChanged", dbus_message_get_member(message))))
106 // to do handle signal
107 result = signal_persModeChange(connection, message);
111 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> unknown signal:"), DLT_STRING(dbus_message_get_interface(message)) );
115 // org.genivi.persistence.admin S I G N A L
116 else if((0==strcmp("org.genivi.persistence.adminconsumer", dbus_message_get_interface(message))))
118 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
120 pclNotification_s notifyStruct;
121 int validMessage = 0;
123 if((0==strcmp("PersistenceResChange", dbus_message_get_member(message))))
125 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_changed;
128 else if((0==strcmp("PersistenceResDelete", dbus_message_get_member(message))))
130 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_deleted;
133 else if((0==strcmp("PersistenceRes", dbus_message_get_member(message))))
135 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_created;
139 if(validMessage == 1)
143 dbus_error_init (&error);
148 if (!dbus_message_get_args(message, &error, DBUS_TYPE_STRING, ¬ifyStruct.resource_id,
149 DBUS_TYPE_STRING, &ldbid,
150 DBUS_TYPE_STRING, &user_no,
151 DBUS_TYPE_STRING, &seat_no,
154 reply = dbus_message_new_error(message, error.name, error.message);
158 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => DBus No memory"), DLT_STRING(dbus_message_get_interface(message)) );
161 if (!dbus_connection_send(connection, reply, 0))
163 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => DBus No memory"), DLT_STRING(dbus_message_get_interface(message)) );
166 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;;
167 dbus_message_unref(reply);
171 notifyStruct.ldbid = atoi(ldbid);
172 notifyStruct.user_no = atoi(user_no);
173 notifyStruct.seat_no = atoi(seat_no);
175 // call the registered callback function
176 if(gChangeNotifyCallback != NULL )
178 gChangeNotifyCallback(¬ifyStruct);
182 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => gChangeNotifyCallback is not set (possibly NULL)") );
184 result = DBUS_HANDLER_RESULT_HANDLED;
186 dbus_connection_flush(connection);
190 // org.genivi.persistence.admin P R O P E R T Y
191 else if((0==strcmp("org.freedesktop.DBus.Properties", dbus_message_get_interface(message))))
193 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
195 if((0==strcmp("EggDBusChanged", dbus_message_get_member(message))))
197 DBusMessageIter array;
198 DBusMessageIter dict;
199 DBusMessageIter variant;
201 char* dictString = NULL;
204 dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, 0, &dict);
205 dbus_message_iter_get_basic(&dict, &dictString);
207 dbus_message_iter_open_container(&dict,DBUS_TYPE_VARIANT, NULL, &variant);
208 dbus_message_iter_get_basic(&dict, &value);
210 dbus_message_iter_close_container(&dict, &variant);
211 dbus_message_iter_close_container(&array, &dict);
213 // to do handle signal
214 result = DBUS_HANDLER_RESULT_HANDLED;
218 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> unknown property:"), DLT_STRING(dbus_message_get_interface(message)) );
223 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> not a signal:"), DLT_STRING(dbus_message_get_member(message)) );
231 static void unregisterObjectPathFallback(DBusConnection *connection, void *user_data)
233 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("unregisterObjectPathFallback\n"));
238 void* run_mainloop(void* dataPtr)
240 // persistence admin message
241 static const struct DBusObjectPathVTable vtablePersAdmin
242 = {unregisterMessageHandler, checkPersAdminMsg, NULL, };
245 static const struct DBusObjectPathVTable vtableLifecycle
246 = {unregisterMessageHandler, checkLifecycleMsg, NULL, };
249 static const struct DBusObjectPathVTable vtableFallback
250 = {unregisterObjectPathFallback, handleObjectPathMessageFallback, NULL, };
253 mainLoop(vtablePersAdmin, vtableLifecycle, vtableFallback, dataPtr);
260 int setup_dbus_mainloop(void)
264 DBusConnection* conn = NULL;
266 const char *pAddress = getenv("PERS_CLIENT_DBUS_ADDRESS");
268 dbus_error_init(&err);
270 // wait until dbus main loop has been setup and running
271 pthread_mutex_lock(&gDbusInitializedMtx);
273 // Connect to the bus and check for errors
276 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("setup_dbus_mainloop -> Use specific dbus address:"), DLT_STRING(pAddress) );
278 conn = dbus_connection_open_private(pAddress, &err);
282 if(!dbus_bus_register(conn, &err))
284 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("dbus_bus_register() Error :"), DLT_STRING(err.message) );
285 dbus_error_free (&err);
286 pthread_mutex_unlock(&gDbusInitializedMtx);
292 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("dbus_connection_open_private() Error :"), DLT_STRING(err.message) );
293 dbus_error_free(&err);
294 pthread_mutex_unlock(&gDbusInitializedMtx);
300 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("Use default dbus bus (DBUS_BUS_SYSTEM)"));
302 conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
305 // create here the dbus connection and pass to main loop
306 rval = pthread_create(&gMainLoopThread, NULL, run_mainloop, conn);
309 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("pthread_create( DBUS run_mainloop ) returned an error:"), DLT_INT(rval) );
310 pthread_mutex_unlock(&gDbusInitializedMtx);
314 // wait for condition variable
315 pthread_cond_wait(&gDbusInitializedCond, &gDbusInitializedMtx);
317 pthread_mutex_unlock(&gDbusInitializedMtx);
325 static dbus_bool_t addWatch(DBusWatch *watch, void *data)
327 dbus_bool_t result = FALSE;
329 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
331 int flags = dbus_watch_get_flags(watch);
333 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
334 pEntry->objtype = OT_WATCH;
335 pEntry->watch = watch;
337 gPollInfo.fds[gPollInfo.nfds].fd = dbus_watch_get_unix_fd(watch);
339 if (TRUE==dbus_watch_get_enabled(watch))
341 if (flags&DBUS_WATCH_READABLE)
343 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
345 if (flags&DBUS_WATCH_WRITABLE)
347 gPollInfo.fds[gPollInfo.nfds].events |= POLLOUT;
361 static void removeWatch(DBusWatch *watch, void *data)
363 void* w_data = dbus_watch_get_data(watch);
365 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("removeWatch called "), DLT_INT( (int)watch) );
370 dbus_watch_set_data(watch, NULL, NULL);
375 static void watchToggled(DBusWatch *watch, void *data)
377 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("watchToggled called "), DLT_INT( (int)watch) );
379 if(dbus_watch_get_enabled(watch))
380 addWatch(watch, data);
382 removeWatch(watch, data);
387 static dbus_bool_t addTimeout(DBusTimeout *timeout, void *data)
389 dbus_bool_t ret = FALSE;
391 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
393 const int interval = dbus_timeout_get_interval(timeout);
394 if ((0<interval)&&(TRUE==dbus_timeout_get_enabled(timeout)))
396 const int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
399 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
400 if (-1!=timerfd_settime(tfd, 0, &its, NULL))
402 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
403 pEntry->objtype = OT_TIMEOUT;
404 pEntry->timeout = timeout;
405 gPollInfo.fds[gPollInfo.nfds].fd = tfd;
406 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
412 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => timerfd_settime() failed"), DLT_STRING(strerror(errno)) );
417 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => timerfd_create() failed"), DLT_STRING(strerror(errno)) );
423 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => cannot create another fd to be poll()'ed"));
431 static void removeTimeout(DBusTimeout *timeout, void *data)
434 int i = gPollInfo.nfds;
435 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
439 if (-1==close(gPollInfo.fds[i].fd))
441 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("removeTimeout => close() timerfd"), DLT_STRING(strerror(errno)) );
445 while (gPollInfo.nfds>i)
447 gPollInfo.fds[i] = gPollInfo.fds[i+1];
448 gPollInfo.objects[i] = gPollInfo.objects[i+1];
452 gPollInfo.fds[gPollInfo.nfds].fd = -1;
453 gPollInfo.objects[gPollInfo.nfds].objtype = OT_NONE;
459 /** callback for libdbus' when timeout changed */
460 static void timeoutToggled(DBusTimeout *timeout, void *data)
462 int i = gPollInfo.nfds;
463 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
464 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("timeoutToggled") );
467 const int interval = (TRUE==dbus_timeout_get_enabled(timeout))?dbus_timeout_get_interval(timeout):0;
468 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
469 if (-1!=timerfd_settime(gPollInfo.fds[i].fd, 0, &its, NULL))
471 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("timeoutToggled => timerfd_settime()"), DLT_STRING(strerror(errno)) );
478 int mainLoop(DBusObjectPathVTable vtable, DBusObjectPathVTable vtable2,
479 DBusObjectPathVTable vtableFallback, void* userData)
482 // lock mutex to make sure dbus main loop is running
483 pthread_mutex_lock(&gDbusInitializedMtx);
485 DBusConnection* conn = (DBusConnection*)userData;
486 dbus_error_init(&err);
488 if (dbus_error_is_set(&err))
490 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => Connection Error:"), DLT_STRING(err.message) );
491 dbus_error_free(&err);
493 else if (NULL != conn)
495 dbus_connection_set_exit_on_disconnect(conn, FALSE);
496 if (-1 == (gEfds = eventfd(0, 0)))
498 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => eventfd() failed w/ errno:"), DLT_INT(errno) );
503 memset(&gPollInfo, 0 , sizeof(gPollInfo));
506 gPollInfo.fds[0].fd = gEfds;
507 gPollInfo.fds[0].events = POLLIN;
509 dbus_bus_add_match(conn, "type='signal',interface='org.genivi.persistence.admin',member='PersistenceModeChanged',path='/org/genivi/persistence/admin'", &err);
511 // register for messages
512 if ( (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer", &vtable2, userData))
513 #if USE_PASINTERFACE == 1
514 && (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/persistence/adminconsumer", &vtable, userData))
516 && (TRUE==dbus_connection_register_fallback(conn, "/", &vtableFallback, userData)) )
518 if( (TRUE!=dbus_connection_set_watch_functions(conn, addWatch, removeWatch, watchToggled, NULL, NULL))
519 || (TRUE!=dbus_connection_set_timeout_functions(conn, addTimeout, removeTimeout, timeoutToggled, NULL, NULL)) )
521 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => dbus_connection_set_watch_functions() failed"));
525 pthread_cond_signal(&gDbusInitializedCond);
526 pthread_mutex_unlock(&gDbusInitializedMtx);
529 bContinue = 0; /* assume error */
531 while (DBUS_DISPATCH_DATA_REMAINS==dbus_connection_dispatch(conn));
533 while ((-1==(ret=poll(gPollInfo.fds, gPollInfo.nfds, -1)))&&(EINTR==errno));
537 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => poll() failed w/ errno "), DLT_INT(errno) );
547 for (i=0; gPollInfo.nfds>i; ++i)
550 if (0!=gPollInfo.fds[i].revents)
552 if (OT_TIMEOUT==gPollInfo.objects[i].objtype)
554 /* time-out occured */
555 unsigned long long nExpCount = 0;
556 if ((ssize_t)sizeof(nExpCount)!=read(gPollInfo.fds[i].fd, &nExpCount, sizeof(nExpCount)))
558 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => read failed"));
560 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => timeout"));
562 if (FALSE==dbus_timeout_handle(gPollInfo.objects[i].timeout))
564 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => dbus_timeout_handle() failed!?"));
568 else if (gPollInfo.fds[i].fd == gEfds)
570 /* internal command */
571 if (0!=(gPollInfo.fds[i].revents & POLLIN))
575 while ((-1==(ret = read(gPollInfo.fds[i].fd, buf, 64)))&&(EINTR == errno));
578 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => read() failed"), DLT_STRING(strerror(errno)) );
582 pthread_mutex_lock(&gMainCondMtx);
585 case CMD_PAS_BLOCK_AND_WRITE_BACK:
586 process_block_and_write_data_back((buf[2]), buf[1]);
587 process_send_pas_request(conn, (buf[2]), buf[1]);
589 case CMD_LC_PREPARE_SHUTDOWN:
590 process_prepare_shutdown((buf[2]), buf[1]);
591 process_send_lifecycle_request(conn, (buf[2]), buf[1]);
593 case CMD_SEND_NOTIFY_SIGNAL:
594 process_send_notification_signal(conn);
596 case CMD_REG_NOTIFY_SIGNAL:
597 process_reg_notification_signal(conn);
599 case CMD_SEND_PAS_REGISTER:
600 process_send_pas_register(conn, (buf[1]), buf[2]);
602 case CMD_SEND_LC_REGISTER:
603 process_send_lifecycle_register(conn, (buf[1]), buf[2]);
609 // ******************************************************
611 case CMD_SEND_LC_REQUEST: // remove
612 process_send_lifecycle_request(conn, (buf[2]), buf[1]);
614 case CMD_SEND_PAS_REQUEST: /// remove
615 process_send_pas_request(conn, (buf[2]), buf[1]);
618 // ******************************************************
620 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => command not handled"), DLT_INT(buf[0]) );
623 pthread_cond_signal(&gMainLoopCond);
624 pthread_mutex_unlock(&gMainCondMtx);
631 if (0!=(gPollInfo.fds[i].revents & POLLIN))
633 flags |= DBUS_WATCH_READABLE;
635 if (0!=(gPollInfo.fds[i].revents & POLLOUT))
637 flags |= DBUS_WATCH_WRITABLE;
639 if (0!=(gPollInfo.fds[i].revents & POLLERR))
641 flags |= DBUS_WATCH_ERROR;
643 if (0!=(gPollInfo.fds[i].revents & POLLHUP))
645 flags |= DBUS_WATCH_HANGUP;
648 bContinue = dbus_watch_handle(gPollInfo.objects[i].watch, flags);
654 while (0!=bContinue);
656 #if USE_PASINTERFACE == 1
657 dbus_connection_unregister_object_path(conn, "/org/genivi/persistence/adminconsumer");
659 dbus_connection_unregister_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer");
660 dbus_connection_unregister_object_path(conn, "/");
664 dbus_connection_close(conn);
665 dbus_connection_unref(conn);
669 pthread_cond_signal(&gDbusInitializedCond);
670 pthread_mutex_unlock(&gDbusInitializedMtx);
676 int deliverToMainloop(tCmd mainloopCmd, unsigned int param1, unsigned int param2)
680 pthread_mutex_lock(&gDeliverpMtx);
683 pthread_mutex_lock(&gMainCondMtx);
685 deliverToMainloop_NM(mainloopCmd, param1, param2);
687 pthread_cond_wait(&gMainLoopCond, &gMainCondMtx);
688 pthread_mutex_unlock(&gMainCondMtx);
691 pthread_mutex_unlock(&gDeliverpMtx);
696 int deliverToMainloop_NM(tCmd mainloopCmd, unsigned int param1, unsigned int param2)
701 cmd = ( ((uint64_t)param2 << 32) | ((uint64_t)param1 << 16) | mainloopCmd);
703 if(-1 == write(gEfds, &cmd, (sizeof(uint64_t))))
705 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("deliverToMainloop => failed to write to pipe"), DLT_INT(errno));