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"
32 pthread_mutex_t gDbusInitializedMtx = PTHREAD_MUTEX_INITIALIZER;
33 pthread_cond_t gDbusInitializedCond = PTHREAD_COND_INITIALIZER;
35 typedef enum EDBusObjectType
43 typedef struct SObjectEntry
45 tDBusObjectType objtype; /** libdbus' object */
48 DBusWatch * watch; /** watch "object" */
49 DBusTimeout * timeout; /** timeout "object" */
56 typedef struct SPollInfo
59 struct pollfd fds[10];
60 tObjectEntry objects[10];
64 /// polling information
65 static tPollInfo gPollInfo;
68 DBusConnection* gDbusConn = NULL;
71 DBusConnection* get_dbus_connection(void)
76 //------------------------------------------------------------------------
77 // debugging only until "correct" exit of main loop is possible!!!!!
78 //------------------------------------------------------------------------
80 static int endLoop = 0;
82 void sigHandler(int signo)
86 //------------------------------------------------------------------------
90 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
93 /* function to unregister ojbect path message handler */
94 static void unregisterMessageHandler(DBusConnection *connection, void *user_data)
96 printf("unregisterObjectPath\n");
99 /* catches messages not directed to any registered object path ("garbage collector") */
100 static DBusHandlerResult handleObjectPathMessageFallback(DBusConnection * connection, DBusMessage * message, void * user_data)
102 DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
104 printf("handleObjectPathMessageFallback Object: '%s' -> Interface: '%s' -> Message: '%s'\n",
105 dbus_message_get_sender(message), dbus_message_get_interface(message), dbus_message_get_member(message) );
107 // org.genivi.persistence.admin S I G N A L
108 if((0==strcmp("org.genivi.persistence.admin", dbus_message_get_interface(message))))
110 printf("checkPersAdminSignalInterface '%s' -> '%s'\n", dbus_message_get_interface(message), dbus_message_get_member(message));
111 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
113 printf(" checkPersAdminSignal signal\n");
114 if((0==strcmp("PersistenceModeChanged", dbus_message_get_member(message))))
116 printf(" checkPersAdminSignal message\n");
117 // to do handle signal
118 result = signal_persModeChange(connection, message);
122 printf("handleObjectPathMessageFallback -> unknown signal '%s'\n", dbus_message_get_interface(message));
126 // org.genivi.persistence.admin S I G N A L
127 else if((0==strcmp("org.genivi.persistence.adminconsumer", dbus_message_get_interface(message))))
129 printf("checkPersAdminconsumerSignalInterface '%s' -> '%s'\n", dbus_message_get_interface(message), dbus_message_get_member(message));
130 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
132 if((0==strcmp("PersistenceValueChanged", dbus_message_get_member(message))))
136 dbus_error_init (&error);
141 printf("PersistenceValueChanged signal\n");
142 // to do handle signal
143 PersistenceNotification_s notifyStruct;
144 notifyStruct.pclKeyNotify_Status = pclNotifyStatus_changed;
146 if (!dbus_message_get_args (message, &error, DBUS_TYPE_STRING, ¬ifyStruct.resource_id,
147 DBUS_TYPE_STRING, &ldbid,
148 DBUS_TYPE_STRING, &user_no,
149 DBUS_TYPE_STRING, &seat_no,
152 reply = dbus_message_new_error(message, error.name, error.message);
156 //DLT_LOG(mgrContext, DLT_LOG_ERROR, DLT_STRING("DBus No memory"));
157 printf("DBus No memory\n");
160 if (!dbus_connection_send(connection, reply, 0))
162 //DLT_LOG(mgrContext, DLT_LOG_ERROR, DLT_STRING("DBus No memory"));
163 printf("DBus No memory\n");
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 gChangeNotifyCallback(¬ifyStruct);
178 result = DBUS_HANDLER_RESULT_HANDLED;
180 dbus_connection_flush(connection);
184 // org.genivi.persistence.admin P R O P E R T Y
185 else if((0==strcmp("org.freedesktop.DBus.Properties", dbus_message_get_interface(message))))
187 if(dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
189 if((0==strcmp("EggDBusChanged", dbus_message_get_member(message))))
191 DBusMessageIter array;
192 DBusMessageIter dict;
193 DBusMessageIter variant;
195 char* dictString = NULL;
198 dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, 0, &dict);
199 dbus_message_iter_get_basic(&dict, &dictString);
201 dbus_message_iter_open_container(&dict,DBUS_TYPE_VARIANT, NULL, &variant);
202 dbus_message_iter_get_basic(&dict, &value);
204 dbus_message_iter_close_container(&dict, &variant);
205 dbus_message_iter_close_container(&array, &dict);
207 printf("handleObjectPathMessageFallback ==> value: %d \n", value);
208 // to do handle signal
209 result = DBUS_HANDLER_RESULT_HANDLED;
213 printf("handleObjectPathMessageFallback -> unknown property '%s'\n", dbus_message_get_interface(message));
218 printf("handleObjectPathMessageFallback -> not a signal '%s'\n", dbus_message_get_member(message));
227 static void unregisterObjectPathFallback(DBusConnection *connection, void *user_data)
229 printf("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);
251 printf("Exit dbus main loop!!!!\n");
258 int setup_dbus_mainloop(void)
263 const char *pAddress = getenv("PERS_CLIENT_DBUS_ADDRESS");
265 // enable locking of data structures in the D-Bus library for multi threading.
266 dbus_threads_init_default();
268 dbus_error_init(&err);
270 // Connect to the bus and check for errors
273 printf("Use specific dbus address: %s\n !", pAddress);
274 gDbusConn = dbus_connection_open(pAddress, &err);
276 if(gDbusConn != NULL)
278 if(!dbus_bus_register(gDbusConn, &err))
280 printf("dbus_bus_register() Error %s\n", err.message);
281 dbus_error_free (&err);
286 printf("Registered connection successfully !\n");
291 printf("dbus_connection_open() Error %s\n",err.message);
292 dbus_error_free(&err);
297 printf("Use default dbus bus (DBUS_BUS_SYSTEM) !!!!!!\n");
298 gDbusConn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
301 // wain until dbus main loop has been setup and running
302 pthread_mutex_lock(&gDbusInitializedMtx);
304 // create here the dbus connection and pass to main loop
305 rval = pthread_create(&thread, NULL, run_mainloop, gDbusConn);
308 fprintf(stderr, "Server: - ERROR! pthread_create( run_mainloop ) returned: %d\n", rval);
311 // wait for condition variable
312 pthread_cond_wait(&gDbusInitializedCond, &gDbusInitializedMtx);
314 pthread_mutex_unlock(&gDbusInitializedMtx);
322 static dbus_bool_t addWatch(DBusWatch *watch, void *data)
324 dbus_bool_t result = FALSE;
326 //fprintf(stderr, "addWatch called @%08x flags: %08x enabled: %c\n", (unsigned int)watch, dbus_watch_get_flags(watch), TRUE==dbus_watch_get_enabled(watch)?'x':'-');
328 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
330 int flags = dbus_watch_get_flags(watch);
332 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
333 pEntry->objtype = OT_WATCH;
334 pEntry->watch = watch;
336 gPollInfo.fds[gPollInfo.nfds].fd = dbus_watch_get_unix_fd(watch);
338 if (TRUE==dbus_watch_get_enabled(watch))
340 if (flags&DBUS_WATCH_READABLE)
342 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
344 if (flags&DBUS_WATCH_WRITABLE)
346 gPollInfo.fds[gPollInfo.nfds].events |= POLLOUT;
360 static void removeWatch(DBusWatch *watch, void *data)
362 printf("removeWatch called @0x%08x\n", (int)watch);
367 static void watchToggled(DBusWatch *watch, void *data)
369 printf("watchToggled called @0x%08x\n", (int)watch);
374 static dbus_bool_t addTimeout(DBusTimeout *timeout, void *data)
376 dbus_bool_t ret = FALSE;
378 if (ARRAY_SIZE(gPollInfo.fds)>gPollInfo.nfds)
380 const int interval = dbus_timeout_get_interval(timeout);
381 if ((0<interval)&&(TRUE==dbus_timeout_get_enabled(timeout)))
383 const int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
386 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
387 if (-1!=timerfd_settime(tfd, 0, &its, NULL))
389 tObjectEntry * const pEntry = &gPollInfo.objects[gPollInfo.nfds];
390 pEntry->objtype = OT_TIMEOUT;
391 pEntry->timeout = timeout;
392 gPollInfo.fds[gPollInfo.nfds].fd = tfd;
393 gPollInfo.fds[gPollInfo.nfds].events |= POLLIN;
399 fprintf(stderr, "timerfd_settime() failed %d '%s'\n", errno, strerror(errno));
404 fprintf(stderr, "timerfd_create() failed %d '%s'\n", errno, strerror(errno));
410 fprintf(stderr, "cannot create another fd to be poll()'ed\n");
418 static void removeTimeout(DBusTimeout *timeout, void *data)
421 int i = gPollInfo.nfds;
422 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
426 if (-1==close(gPollInfo.fds[i].fd))
428 fprintf(stderr, "close() timerfd #%d failed %d '%s'\n", gPollInfo.fds[i].fd, errno, strerror(errno));
432 while (gPollInfo.nfds>i)
434 gPollInfo.fds[i] = gPollInfo.fds[i+1];
435 gPollInfo.objects[i] = gPollInfo.objects[i+1];
439 gPollInfo.fds[gPollInfo.nfds].fd = -1;
440 gPollInfo.objects[gPollInfo.nfds].objtype = OT_NONE;
446 /** callback for libdbus' when timeout changed */
447 static void timeoutToggled(DBusTimeout *timeout, void *data)
449 int i = gPollInfo.nfds;
450 while ((0<i--)&&(timeout!=gPollInfo.objects[i].timeout));
451 fprintf(stderr, "timeoutToggled @%x %c %dms @%d [%d]\n", (int)timeout, dbus_timeout_get_enabled(timeout)?'x':'-', dbus_timeout_get_interval(timeout), i, gPollInfo.nfds);
454 const int interval = (TRUE==dbus_timeout_get_enabled(timeout))?dbus_timeout_get_interval(timeout):0;
455 const struct itimerspec its = { .it_value= {interval/1000, interval%1000} };
456 if (-1!=timerfd_settime(gPollInfo.fds[i].fd, 0, &its, NULL))
458 fprintf(stderr, "timerfd_settime() %d failed %d '%s'\n", interval, errno, strerror(errno));
465 int mainLoop(DBusObjectPathVTable vtable, DBusObjectPathVTable vtable2,
466 DBusObjectPathVTable vtableFallback, void* userData)
469 // lock mutex to make sure dbus main loop is running
470 pthread_mutex_lock(&gDbusInitializedMtx);
472 signal(SIGTERM, sigHandler);
473 signal(SIGQUIT, sigHandler);
474 signal(SIGINT, sigHandler);
476 DBusConnection* conn = (DBusConnection*)userData;
477 dbus_error_init(&err);
479 if (dbus_error_is_set(&err))
481 printf("Connection Error (%s)\n", err.message);
482 dbus_error_free(&err);
484 else if (NULL != conn)
486 dbus_connection_set_exit_on_disconnect (conn, FALSE);
487 //printf("connected as '%s'\n", dbus_bus_get_unique_name(conn));
488 if (-1 == (gEfds = eventfd(0, 0)))
490 printf("eventfd() failed w/ errno %d\n", errno);
496 memset(&gPollInfo, 0 , sizeof(gPollInfo));
499 gPollInfo.fds[0].fd = gEfds;
500 gPollInfo.fds[0].events = POLLIN;
502 dbus_bus_add_match(conn, "type='signal',interface='org.genivi.persistence.admin',member='PersistenceModeChanged',path='/org/genivi/persistence/admin'", &err);
504 // register for messages
505 if ( (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/persistence/adminconsumer", &vtable, userData))
506 && (TRUE==dbus_connection_register_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer", &vtable2, userData))
507 && (TRUE==dbus_connection_register_fallback(conn, "/", &vtableFallback, userData)) )
509 if( (TRUE!=dbus_connection_set_watch_functions(conn, addWatch, removeWatch, watchToggled, NULL, NULL))
510 || (TRUE!=dbus_connection_set_timeout_functions(conn, addTimeout, removeTimeout, timeoutToggled, NULL, NULL)) )
512 printf("dbus_connection_set_watch_functions() failed\n");
516 pthread_cond_signal(&gDbusInitializedCond);
517 pthread_mutex_unlock(&gDbusInitializedMtx);
520 bContinue = 0; /* assume error */
522 while (DBUS_DISPATCH_DATA_REMAINS==dbus_connection_dispatch(conn));
524 while ((-1==(ret=poll(gPollInfo.fds, gPollInfo.nfds, -1)))&&(EINTR==errno));
528 fprintf(stderr, "poll() failed w/ errno %d\n", errno);
538 for (i=0; gPollInfo.nfds>i; ++i)
541 if (0!=gPollInfo.fds[i].revents)
543 //fprintf(stderr, "\t[%d] revents 0x%04x\n", i, gPollInfo.fds[i].revents);
545 if (OT_TIMEOUT==gPollInfo.objects[i].objtype)
547 /* time-out occured */
548 unsigned long long nExpCount = 0;
549 if ((ssize_t)sizeof(nExpCount)!=read(gPollInfo.fds[i].fd, &nExpCount, sizeof(nExpCount)))
551 fprintf(stderr, "read failed!?\n");
553 fprintf(stderr, "timeout %x #%d!\n", (int)gPollInfo.objects[i].timeout, (int)nExpCount);
554 if (FALSE==dbus_timeout_handle(gPollInfo.objects[i].timeout))
556 fprintf(stderr, "dbus_timeout_handle() failed!?\n");
560 else if (gPollInfo.fds[i].fd==gEfds)
562 /* internal command */
563 if (0!=(gPollInfo.fds[i].revents & POLLIN))
567 while ((-1==(ret=read(gPollInfo.fds[i].fd, buf, 64)))&&(EINTR==errno));
570 printf("read() failed w/ errno %d | %s\n", errno, strerror(errno));
576 case CMD_PAS_BLOCK_AND_WRITE_BACK:
577 process_block_and_write_data_back((buf[2]), buf[1]);
579 case CMD_LC_PREPARE_SHUTDOWN:
580 process_prepare_shutdown((buf[2]), buf[1]);
586 printf("command %d not handled!\n", buf[0]);
595 if (0!=(gPollInfo.fds[i].revents & POLLIN))
597 flags |= DBUS_WATCH_READABLE;
599 if (0!=(gPollInfo.fds[i].revents & POLLOUT))
601 flags |= DBUS_WATCH_WRITABLE;
603 if (0!=(gPollInfo.fds[i].revents & POLLERR))
605 flags |= DBUS_WATCH_ERROR;
607 if (0!=(gPollInfo.fds[i].revents & POLLHUP))
609 flags |= DBUS_WATCH_HANGUP;
612 bContinue = dbus_watch_handle(gPollInfo.objects[i].watch, flags);
620 while (0!=bContinue);
622 dbus_connection_unregister_object_path(conn, "/org/genivi/persistence/adminconsumer");
623 dbus_connection_unregister_object_path(conn, "/org/genivi/NodeStateManager/LifeCycleConsumer");
624 dbus_connection_unregister_object_path(conn, "/");
628 dbus_connection_unref(conn);
632 pthread_cond_signal(&gDbusInitializedCond);
633 pthread_mutex_unlock(&gDbusInitializedMtx);