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"
33 pthread_cond_t gDbusInitializedCond = PTHREAD_COND_INITIALIZER;
34 pthread_mutex_t gDbusInitializedMtx = PTHREAD_MUTEX_INITIALIZER;
36 pthread_mutex_t gDbusPendingRegMtx = PTHREAD_MUTEX_INITIALIZER;
38 pthread_mutex_t gMainLoopMtx = PTHREAD_MUTEX_INITIALIZER;
39 pthread_cond_t gMainLoopCond = PTHREAD_COND_INITIALIZER;
41 pthread_t gMainLoopThread;
44 int gEfds; // communication channel int dbus mainloop
47 typedef enum EDBusObjectType
55 typedef struct SObjectEntry
57 tDBusObjectType objtype; /** libdbus' object */
60 DBusWatch * watch; /** watch "object" */
61 DBusTimeout * timeout; /** timeout "object" */
68 typedef struct SPollInfo
71 struct pollfd fds[10];
72 tObjectEntry objects[10];
76 /// polling information
77 static tPollInfo gPollInfo;
81 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
84 /* function to unregister ojbect path message handler */
85 static void unregisterMessageHandler(DBusConnection *connection, void *user_data)
87 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("unregisterObjectPath\n"));
90 /* catches messages not directed to any registered object path ("garbage collector") */
91 static DBusHandlerResult handleObjectPathMessageFallback(DBusConnection * connection, DBusMessage * message, void * user_data)
93 DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
95 // org.genivi.persistence.admin S I G N A L
96 if((0==strcmp("org.genivi.persistence.admin", dbus_message_get_interface(message))))
98 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
100 if((0==strcmp("PersistenceModeChanged", dbus_message_get_member(message))))
102 // to do handle signal
103 result = signal_persModeChange(connection, message);
107 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> unknown signal:"), DLT_STRING(dbus_message_get_interface(message)) );
111 // org.genivi.persistence.admin S I G N A L
112 else if((0==strcmp("org.genivi.persistence.adminconsumer", dbus_message_get_interface(message))))
114 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
116 pclNotification_s notifyStruct;
117 int validMessage = 0;
119 if((0==strcmp("PersistenceResChange", dbus_message_get_member(message))))
121 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_changed;
124 else if((0==strcmp("PersistenceResDelete", dbus_message_get_member(message))))
126 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_deleted;
129 else if((0==strcmp("PersistenceRes", dbus_message_get_member(message))))
131 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_created;
135 if(validMessage == 1)
139 dbus_error_init (&error);
144 if (!dbus_message_get_args(message, &error, DBUS_TYPE_STRING, ¬ifyStruct.resource_id,
145 DBUS_TYPE_STRING, &ldbid,
146 DBUS_TYPE_STRING, &user_no,
147 DBUS_TYPE_STRING, &seat_no,
150 reply = dbus_message_new_error(message, error.name, error.message);
154 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => DBus No memory"), DLT_STRING(dbus_message_get_interface(message)) );
157 if (!dbus_connection_send(connection, reply, 0))
159 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => DBus No memory"), DLT_STRING(dbus_message_get_interface(message)) );
162 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;;
163 dbus_message_unref(reply);
167 notifyStruct.ldbid = atoi(ldbid);
168 notifyStruct.user_no = atoi(user_no);
169 notifyStruct.seat_no = atoi(seat_no);
171 // call the registered callback function
172 if(gChangeNotifyCallback != NULL )
174 gChangeNotifyCallback(¬ifyStruct);
178 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback => gChangeNotifyCallback is not set (possibly NULL)") );
180 result = DBUS_HANDLER_RESULT_HANDLED;
182 dbus_connection_flush(connection);
186 // org.genivi.persistence.admin P R O P E R T Y
187 else if((0==strcmp("org.freedesktop.DBus.Properties", dbus_message_get_interface(message))))
189 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
191 if((0==strcmp("EggDBusChanged", dbus_message_get_member(message))))
193 DBusMessageIter array;
194 DBusMessageIter dict;
195 DBusMessageIter variant;
197 char* dictString = NULL;
200 dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, 0, &dict);
201 dbus_message_iter_get_basic(&dict, &dictString);
203 dbus_message_iter_open_container(&dict,DBUS_TYPE_VARIANT, NULL, &variant);
204 dbus_message_iter_get_basic(&dict, &value);
206 dbus_message_iter_close_container(&dict, &variant);
207 dbus_message_iter_close_container(&array, &dict);
209 // to do handle signal
210 result = DBUS_HANDLER_RESULT_HANDLED;
214 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> unknown property:"), DLT_STRING(dbus_message_get_interface(message)) );
219 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("handleObjectPathMessageFallback -> not a signal:"), DLT_STRING(dbus_message_get_member(message)) );
227 static void unregisterObjectPathFallback(DBusConnection *connection, void *user_data)
229 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("unregisterObjectPathFallback\n"));
234 void* run_mainloop(void* dataPtr)
236 // persistence admin message
237 static const struct DBusObjectPathVTable vtablePersAdmin
238 = {unregisterMessageHandler, checkPersAdminMsg, NULL, };
241 static const struct DBusObjectPathVTable vtableLifecycle
242 = {unregisterMessageHandler, checkLifecycleMsg, NULL, };
245 static const struct DBusObjectPathVTable vtableFallback
246 = {unregisterObjectPathFallback, handleObjectPathMessageFallback, NULL, };
249 mainLoop(vtablePersAdmin, vtableLifecycle, vtableFallback, dataPtr);
256 int setup_dbus_mainloop(void)
260 DBusConnection* conn = NULL;
262 const char *pAddress = getenv("PERS_CLIENT_DBUS_ADDRESS");
264 dbus_error_init(&err);
266 // wait until dbus main loop has been setup and running
267 pthread_mutex_lock(&gDbusInitializedMtx);
269 // Connect to the bus and check for errors
272 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("setup_dbus_mainloop -> Use specific dbus address:"), DLT_STRING(pAddress) );
274 conn = dbus_connection_open_private(pAddress, &err);
278 if(!dbus_bus_register(conn, &err))
280 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("dbus_bus_register() Error :"), DLT_STRING(err.message) );
281 dbus_error_free (&err);
282 pthread_mutex_unlock(&gDbusInitializedMtx);
288 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("dbus_connection_open_private() Error :"), DLT_STRING(err.message) );
289 dbus_error_free(&err);
290 pthread_mutex_unlock(&gDbusInitializedMtx);
296 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("Use default dbus bus (DBUS_BUS_SYSTEM)"));
298 conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
301 // create here the dbus connection and pass to main loop
302 rval = pthread_create(&gMainLoopThread, NULL, run_mainloop, conn);
305 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("pthread_create( DBUS run_mainloop ) returned an error:"), DLT_INT(rval) );
306 pthread_mutex_unlock(&gDbusInitializedMtx);
310 // wait for condition variable
311 pthread_cond_wait(&gDbusInitializedCond, &gDbusInitializedMtx);
313 pthread_mutex_unlock(&gDbusInitializedMtx);
321 static dbus_bool_t addWatch(DBusWatch *watch, void *data)
323 dbus_bool_t result = FALSE;
325 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
327 int flags = dbus_watch_get_flags(watch);
329 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
330 pEntry->objtype = OT_WATCH;
331 pEntry->watch = watch;
333 gPollInfo.fds[gPollInfo.nfds].fd = dbus_watch_get_unix_fd(watch);
335 if (TRUE==dbus_watch_get_enabled(watch))
337 if (flags&DBUS_WATCH_READABLE)
339 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
341 if (flags&DBUS_WATCH_WRITABLE)
343 gPollInfo.fds[gPollInfo.nfds].events |= POLLOUT;
357 static void removeWatch(DBusWatch *watch, void *data)
359 void* w_data = dbus_watch_get_data(watch);
361 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("removeWatch called "), DLT_INT( (int)watch) );
366 dbus_watch_set_data(watch, NULL, NULL);
371 static void watchToggled(DBusWatch *watch, void *data)
373 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("watchToggled called "), DLT_INT( (int)watch) );
375 if(dbus_watch_get_enabled(watch))
376 addWatch(watch, data);
378 removeWatch(watch, data);
383 static dbus_bool_t addTimeout(DBusTimeout *timeout, void *data)
385 dbus_bool_t ret = FALSE;
387 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
389 const int interval = dbus_timeout_get_interval(timeout);
390 if ((0<interval)&&(TRUE==dbus_timeout_get_enabled(timeout)))
392 const int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
395 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
396 if (-1!=timerfd_settime(tfd, 0, &its, NULL))
398 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
399 pEntry->objtype = OT_TIMEOUT;
400 pEntry->timeout = timeout;
401 gPollInfo.fds[gPollInfo.nfds].fd = tfd;
402 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
408 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => timerfd_settime() failed"), DLT_STRING(strerror(errno)) );
413 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => timerfd_create() failed"), DLT_STRING(strerror(errno)) );
419 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("addTimeout => cannot create another fd to be poll()'ed"));
427 static void removeTimeout(DBusTimeout *timeout, void *data)
430 int i = gPollInfo.nfds;
431 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
435 if (-1==close(gPollInfo.fds[i].fd))
437 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("removeTimeout => close() timerfd"), DLT_STRING(strerror(errno)) );
441 while (gPollInfo.nfds>i)
443 gPollInfo.fds[i] = gPollInfo.fds[i+1];
444 gPollInfo.objects[i] = gPollInfo.objects[i+1];
448 gPollInfo.fds[gPollInfo.nfds].fd = -1;
449 gPollInfo.objects[gPollInfo.nfds].objtype = OT_NONE;
455 /** callback for libdbus' when timeout changed */
456 static void timeoutToggled(DBusTimeout *timeout, void *data)
458 int i = gPollInfo.nfds;
459 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
460 DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("timeoutToggled") );
463 const int interval = (TRUE==dbus_timeout_get_enabled(timeout))?dbus_timeout_get_interval(timeout):0;
464 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
465 if (-1!=timerfd_settime(gPollInfo.fds[i].fd, 0, &its, NULL))
467 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("timeoutToggled => timerfd_settime()"), DLT_STRING(strerror(errno)) );
474 int mainLoop(DBusObjectPathVTable vtable, DBusObjectPathVTable vtable2,
475 DBusObjectPathVTable vtableFallback, void* userData)
478 // lock mutex to make sure dbus main loop is running
479 pthread_mutex_lock(&gDbusInitializedMtx);
481 DBusConnection* conn = (DBusConnection*)userData;
482 dbus_error_init(&err);
484 if (dbus_error_is_set(&err))
486 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => Connection Error:"), DLT_STRING(err.message) );
487 dbus_error_free(&err);
489 else if (NULL != conn)
491 dbus_connection_set_exit_on_disconnect(conn, FALSE);
492 if (-1 == (gEfds = eventfd(0, 0)))
494 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => eventfd() failed w/ errno:"), DLT_INT(errno) );
499 memset(&gPollInfo, 0 , sizeof(gPollInfo));
502 gPollInfo.fds[0].fd = gEfds;
503 gPollInfo.fds[0].events = POLLIN;
505 dbus_bus_add_match(conn, "type='signal',interface='org.genivi.persistence.admin',member='PersistenceModeChanged',path='/org/genivi/persistence/admin'", &err);
507 // register for messages
508 if ( (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer", &vtable2, userData))
509 #if USE_PASINTERFACE == 1
510 && (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/persistence/adminconsumer", &vtable, userData))
512 && (TRUE==dbus_connection_register_fallback(conn, "/", &vtableFallback, userData)) )
514 if( (TRUE!=dbus_connection_set_watch_functions(conn, addWatch, removeWatch, watchToggled, NULL, NULL))
515 || (TRUE!=dbus_connection_set_timeout_functions(conn, addTimeout, removeTimeout, timeoutToggled, NULL, NULL)) )
517 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => dbus_connection_set_watch_functions() failed"));
521 pthread_cond_signal(&gDbusInitializedCond);
522 pthread_mutex_unlock(&gDbusInitializedMtx);
525 bContinue = 0; /* assume error */
527 while (DBUS_DISPATCH_DATA_REMAINS==dbus_connection_dispatch(conn));
529 while ((-1==(ret=poll(gPollInfo.fds, gPollInfo.nfds, -1)))&&(EINTR==errno));
533 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => poll() failed w/ errno "), DLT_INT(errno) );
543 for (i=0; gPollInfo.nfds>i; ++i)
546 if (0!=gPollInfo.fds[i].revents)
548 if (OT_TIMEOUT==gPollInfo.objects[i].objtype)
550 /* time-out occured */
551 unsigned long long nExpCount = 0;
552 if ((ssize_t)sizeof(nExpCount)!=read(gPollInfo.fds[i].fd, &nExpCount, sizeof(nExpCount)))
554 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => read failed"));
556 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => timeout"));
558 if (FALSE==dbus_timeout_handle(gPollInfo.objects[i].timeout))
560 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => dbus_timeout_handle() failed!?"));
564 else if (gPollInfo.fds[i].fd == gEfds)
566 /* internal command */
567 if (0!=(gPollInfo.fds[i].revents & POLLIN))
571 while ((-1==(ret = read(gPollInfo.fds[i].fd, buf, 64)))&&(EINTR == errno));
574 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => read() failed"), DLT_STRING(strerror(errno)) );
578 pthread_mutex_lock(&gMainLoopMtx);
581 case CMD_PAS_BLOCK_AND_WRITE_BACK:
582 process_block_and_write_data_back((buf[2]), buf[1]);
583 process_send_pas_request(conn, (buf[2]), buf[1]);
585 case CMD_LC_PREPARE_SHUTDOWN:
586 process_prepare_shutdown((buf[2]), buf[1]);
587 process_send_lifecycle_request(conn, (buf[2]), buf[1]);
589 case CMD_SEND_NOTIFY_SIGNAL:
590 process_send_notification_signal(conn);
592 case CMD_REG_NOTIFY_SIGNAL:
593 process_reg_notification_signal(conn);
595 case CMD_SEND_PAS_REGISTER:
596 process_send_pas_register(conn, (buf[1]), buf[2]);
598 case CMD_SEND_LC_REGISTER:
599 process_send_lifecycle_register(conn, (buf[1]), buf[2]);
605 // ******************************************************
607 case CMD_SEND_LC_REQUEST: // remove
608 process_send_lifecycle_request(conn, (buf[2]), buf[1]);
610 case CMD_SEND_PAS_REQUEST: /// remove
611 process_send_pas_request(conn, (buf[2]), buf[1]);
614 // ******************************************************
616 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("mainLoop => command not handled"), DLT_INT(buf[0]) );
619 pthread_cond_signal(&gMainLoopCond);
620 pthread_mutex_unlock(&gMainLoopMtx);
627 if (0!=(gPollInfo.fds[i].revents & POLLIN))
629 flags |= DBUS_WATCH_READABLE;
631 if (0!=(gPollInfo.fds[i].revents & POLLOUT))
633 flags |= DBUS_WATCH_WRITABLE;
635 if (0!=(gPollInfo.fds[i].revents & POLLERR))
637 flags |= DBUS_WATCH_ERROR;
639 if (0!=(gPollInfo.fds[i].revents & POLLHUP))
641 flags |= DBUS_WATCH_HANGUP;
644 bContinue = dbus_watch_handle(gPollInfo.objects[i].watch, flags);
650 while (0!=bContinue);
652 #if USE_PASINTERFACE == 1
653 dbus_connection_unregister_object_path(conn, "/org/genivi/persistence/adminconsumer");
655 dbus_connection_unregister_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer");
656 dbus_connection_unregister_object_path(conn, "/");
660 dbus_connection_close(conn);
661 dbus_connection_unref(conn);
665 pthread_cond_signal(&gDbusInitializedCond);
666 pthread_mutex_unlock(&gDbusInitializedMtx);
672 int deliverToMainloop(tCmd mainloopCmd, unsigned int param1, unsigned int param2)
676 pthread_mutex_lock(&gMainLoopMtx);
678 deliverToMainloop_NM(mainloopCmd, param1, param2);
680 // wait for condition variable
681 pthread_cond_wait(&gMainLoopCond, &gMainLoopMtx);
682 pthread_mutex_unlock(&gMainLoopMtx);
687 int deliverToMainloop_NM(tCmd mainloopCmd, unsigned int param1, unsigned int param2)
692 cmd = ( ((uint64_t)param2 << 32) | ((uint64_t)param1 << 16) | mainloopCmd);
694 if(-1 == write(gEfds, &cmd, (sizeof(uint64_t))))
696 DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("deliverToMainloop => failed to write to pipe"), DLT_INT(errno));