ua_subscription.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. #include "ua_subscription.h"
  5. #include "ua_server_internal.h"
  6. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  7. UA_Subscription *
  8. UA_Subscription_new(UA_Session *session, UA_UInt32 subscriptionID) {
  9. /* Allocate the memory */
  10. UA_Subscription *newItem =
  11. (UA_Subscription*)UA_calloc(1, sizeof(UA_Subscription));
  12. if(!newItem)
  13. return NULL;
  14. /* Remaining members are covered by calloc zeroing out the memory */
  15. newItem->session = session;
  16. newItem->subscriptionID = subscriptionID;
  17. newItem->state = UA_SUBSCRIPTIONSTATE_NORMAL; /* The first publish response is sent immediately */
  18. TAILQ_INIT(&newItem->retransmissionQueue);
  19. return newItem;
  20. }
  21. void
  22. UA_Subscription_deleteMembers(UA_Subscription *subscription, UA_Server *server) {
  23. Subscription_unregisterPublishCallback(server, subscription);
  24. /* Delete monitored Items */
  25. UA_MonitoredItem *mon, *tmp_mon;
  26. LIST_FOREACH_SAFE(mon, &subscription->monitoredItems, listEntry, tmp_mon) {
  27. LIST_REMOVE(mon, listEntry);
  28. MonitoredItem_delete(server, mon);
  29. }
  30. /* Delete Retransmission Queue */
  31. UA_NotificationMessageEntry *nme, *nme_tmp;
  32. TAILQ_FOREACH_SAFE(nme, &subscription->retransmissionQueue, listEntry, nme_tmp) {
  33. TAILQ_REMOVE(&subscription->retransmissionQueue, nme, listEntry);
  34. UA_NotificationMessage_deleteMembers(&nme->message);
  35. UA_free(nme);
  36. }
  37. subscription->retransmissionQueueSize = 0;
  38. }
  39. UA_MonitoredItem *
  40. UA_Subscription_getMonitoredItem(UA_Subscription *sub,
  41. UA_UInt32 monitoredItemID) {
  42. UA_MonitoredItem *mon;
  43. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  44. if(mon->itemId == monitoredItemID)
  45. break;
  46. }
  47. return mon;
  48. }
  49. UA_StatusCode
  50. UA_Subscription_deleteMonitoredItem(UA_Server *server,
  51. UA_Subscription *sub,
  52. UA_UInt32 monitoredItemID) {
  53. /* Find the MonitoredItem */
  54. UA_MonitoredItem *mon;
  55. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  56. if(mon->itemId == monitoredItemID)
  57. break;
  58. }
  59. if(!mon)
  60. return UA_STATUSCODE_BADMONITOREDITEMIDINVALID;
  61. /* Remove the MonitoredItem */
  62. LIST_REMOVE(mon, listEntry);
  63. MonitoredItem_delete(server, mon);
  64. return UA_STATUSCODE_GOOD;
  65. }
  66. static size_t
  67. countQueuedNotifications(UA_Subscription *sub,
  68. UA_Boolean *moreNotifications) {
  69. if(!sub->publishingEnabled)
  70. return 0;
  71. size_t notifications = 0;
  72. UA_MonitoredItem *mon;
  73. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  74. MonitoredItem_queuedValue *qv;
  75. TAILQ_FOREACH(qv, &mon->queue, listEntry) {
  76. if(notifications >= sub->notificationsPerPublish) {
  77. *moreNotifications = true;
  78. break;
  79. }
  80. ++notifications;
  81. }
  82. }
  83. return notifications;
  84. }
  85. static void
  86. UA_Subscription_addRetransmissionMessage(UA_Server *server, UA_Subscription *sub,
  87. UA_NotificationMessageEntry *entry) {
  88. /* Release the oldest entry if there is not enough space */
  89. if(server->config.maxRetransmissionQueueSize > 0 &&
  90. sub->retransmissionQueueSize >= server->config.maxRetransmissionQueueSize) {
  91. UA_NotificationMessageEntry *lastentry =
  92. TAILQ_LAST(&sub->retransmissionQueue, ListOfNotificationMessages);
  93. TAILQ_REMOVE(&sub->retransmissionQueue, lastentry, listEntry);
  94. --sub->retransmissionQueueSize;
  95. UA_NotificationMessage_deleteMembers(&lastentry->message);
  96. UA_free(lastentry);
  97. }
  98. /* Add entry */
  99. TAILQ_INSERT_HEAD(&sub->retransmissionQueue, entry, listEntry);
  100. ++sub->retransmissionQueueSize;
  101. }
  102. UA_StatusCode
  103. UA_Subscription_removeRetransmissionMessage(UA_Subscription *sub,
  104. UA_UInt32 sequenceNumber) {
  105. /* Find the retransmission message */
  106. UA_NotificationMessageEntry *entry;
  107. TAILQ_FOREACH(entry, &sub->retransmissionQueue, listEntry) {
  108. if(entry->message.sequenceNumber == sequenceNumber)
  109. break;
  110. }
  111. if(!entry)
  112. return UA_STATUSCODE_BADSEQUENCENUMBERUNKNOWN;
  113. /* Remove the retransmission message */
  114. TAILQ_REMOVE(&sub->retransmissionQueue, entry, listEntry);
  115. --sub->retransmissionQueueSize;
  116. UA_NotificationMessage_deleteMembers(&entry->message);
  117. UA_free(entry);
  118. return UA_STATUSCODE_GOOD;
  119. }
  120. static UA_StatusCode
  121. prepareNotificationMessage(UA_Subscription *sub,
  122. UA_NotificationMessage *message,
  123. size_t notifications) {
  124. /* Array of ExtensionObject to hold different kinds of notifications
  125. * (currently only DataChangeNotifications) */
  126. message->notificationData = UA_ExtensionObject_new();
  127. if(!message->notificationData)
  128. return UA_STATUSCODE_BADOUTOFMEMORY;
  129. message->notificationDataSize = 1;
  130. /* Allocate Notification */
  131. UA_DataChangeNotification *dcn = UA_DataChangeNotification_new();
  132. if(!dcn) {
  133. UA_NotificationMessage_deleteMembers(message);
  134. return UA_STATUSCODE_BADOUTOFMEMORY;
  135. }
  136. UA_ExtensionObject *data = message->notificationData;
  137. data->encoding = UA_EXTENSIONOBJECT_DECODED;
  138. data->content.decoded.data = dcn;
  139. data->content.decoded.type = &UA_TYPES[UA_TYPES_DATACHANGENOTIFICATION];
  140. /* Allocate array of notifications */
  141. dcn->monitoredItems = (UA_MonitoredItemNotification *)
  142. UA_Array_new(notifications, &UA_TYPES[UA_TYPES_MONITOREDITEMNOTIFICATION]);
  143. if(!dcn->monitoredItems) {
  144. UA_NotificationMessage_deleteMembers(message);
  145. return UA_STATUSCODE_BADOUTOFMEMORY;
  146. }
  147. dcn->monitoredItemsSize = notifications;
  148. /* Move notifications into the response .. the point of no return */
  149. size_t l = 0;
  150. UA_MonitoredItem *mon;
  151. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  152. MonitoredItem_queuedValue *qv, *qv_tmp;
  153. TAILQ_FOREACH_SAFE(qv, &mon->queue, listEntry, qv_tmp) {
  154. if(l >= notifications)
  155. return UA_STATUSCODE_GOOD;
  156. UA_MonitoredItemNotification *min = &dcn->monitoredItems[l];
  157. min->clientHandle = qv->clientHandle;
  158. min->value = qv->value;
  159. TAILQ_REMOVE(&mon->queue, qv, listEntry);
  160. UA_free(qv);
  161. --mon->currentQueueSize;
  162. ++l;
  163. }
  164. }
  165. return UA_STATUSCODE_GOOD;
  166. }
  167. void
  168. UA_Subscription_publishCallback(UA_Server *server, UA_Subscription *sub) {
  169. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  170. "Subscription %u | Publish Callback",
  171. sub->subscriptionID);
  172. /* Count the available notifications */
  173. UA_Boolean moreNotifications = false;
  174. size_t notifications = countQueuedNotifications(sub, &moreNotifications);
  175. /* Return if nothing to do */
  176. if(notifications == 0) {
  177. ++sub->currentKeepAliveCount;
  178. if(sub->currentKeepAliveCount < sub->maxKeepAliveCount)
  179. return;
  180. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  181. "Subscription %u | Sending a KeepAlive",
  182. sub->subscriptionID);
  183. }
  184. /* Check if the securechannel is valid */
  185. UA_SecureChannel *channel = sub->session->channel;
  186. if(!channel)
  187. return;
  188. /* Dequeue a response */
  189. UA_PublishResponseEntry *pre = SIMPLEQ_FIRST(&sub->session->responseQueue);
  190. /* Cannot publish without a response */
  191. if(!pre) {
  192. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  193. "Subscription %u | Cannot send a publish response "
  194. "since the publish queue is empty", sub->subscriptionID);
  195. if(sub->state != UA_SUBSCRIPTIONSTATE_LATE) {
  196. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  197. } else {
  198. ++sub->currentLifetimeCount;
  199. if(sub->currentLifetimeCount > sub->lifeTimeCount) {
  200. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  201. "Subscription %u | End of lifetime for subscription",
  202. sub->subscriptionID);
  203. UA_Session_deleteSubscription(server, sub->session, sub->subscriptionID);
  204. }
  205. }
  206. return;
  207. }
  208. UA_PublishResponse *response = &pre->response;
  209. UA_NotificationMessage *message = &response->notificationMessage;
  210. UA_NotificationMessageEntry *retransmission = NULL;
  211. if(notifications > 0) {
  212. /* Allocate the retransmission entry */
  213. retransmission =
  214. (UA_NotificationMessageEntry*)UA_malloc(sizeof(UA_NotificationMessageEntry));
  215. if(!retransmission) {
  216. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  217. "Subscription %u | Could not allocate memory "
  218. "for retransmission", sub->subscriptionID);
  219. return;
  220. }
  221. /* Prepare the response */
  222. UA_StatusCode retval =
  223. prepareNotificationMessage(sub, message, notifications);
  224. if(retval != UA_STATUSCODE_GOOD) {
  225. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  226. "Subscription %u | Could not prepare the "
  227. "notification message", sub->subscriptionID);
  228. UA_free(retransmission);
  229. return;
  230. }
  231. }
  232. /* <-- The point of no return --> */
  233. /* Remove the response from the response queue */
  234. SIMPLEQ_REMOVE_HEAD(&sub->session->responseQueue, listEntry);
  235. /* Set up the response */
  236. response->responseHeader.timestamp = UA_DateTime_now();
  237. response->subscriptionId = sub->subscriptionID;
  238. response->moreNotifications = moreNotifications;
  239. message->publishTime = response->responseHeader.timestamp;
  240. if(notifications == 0) {
  241. /* Send sequence number for the next notification */
  242. message->sequenceNumber = sub->sequenceNumber + 1;
  243. } else {
  244. /* Increase the sequence number */
  245. message->sequenceNumber = ++sub->sequenceNumber;
  246. /* Put the notification message into the retransmission queue. This needs to
  247. * be done here, so that the message itself is included in the available
  248. * sequence numbers for acknowledgement. */
  249. retransmission->message = response->notificationMessage;
  250. UA_Subscription_addRetransmissionMessage(server, sub, retransmission);
  251. }
  252. /* Get the available sequence numbers from the retransmission queue */
  253. size_t available = sub->retransmissionQueueSize;
  254. if(available > 0) {
  255. response->availableSequenceNumbers =
  256. (UA_UInt32*)UA_alloca(available * sizeof(UA_UInt32));
  257. response->availableSequenceNumbersSize = available;
  258. size_t i = 0;
  259. UA_NotificationMessageEntry *nme;
  260. TAILQ_FOREACH(nme, &sub->retransmissionQueue, listEntry) {
  261. response->availableSequenceNumbers[i] = nme->message.sequenceNumber;
  262. ++i;
  263. }
  264. }
  265. /* Send the response */
  266. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  267. "Subscription %u | Sending out a publish response with %u "
  268. "notifications", sub->subscriptionID, (UA_UInt32)notifications);
  269. UA_SecureChannel_sendBinaryMessage(sub->session->channel, pre->requestId, response,
  270. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  271. /* Reset subscription state to normal. */
  272. sub->state = UA_SUBSCRIPTIONSTATE_NORMAL;
  273. sub->currentKeepAliveCount = 0;
  274. sub->currentLifetimeCount = 0;
  275. /* Free the response */
  276. UA_Array_delete(response->results, response->resultsSize,
  277. &UA_TYPES[UA_TYPES_UINT32]);
  278. UA_free(pre); /* no need for UA_PublishResponse_deleteMembers */
  279. /* Repeat if there are more notifications to send */
  280. if(moreNotifications)
  281. UA_Subscription_publishCallback(server, sub);
  282. }
  283. UA_StatusCode
  284. Subscription_registerPublishCallback(UA_Server *server, UA_Subscription *sub) {
  285. if(sub->publishCallbackIsRegistered)
  286. return UA_STATUSCODE_GOOD;
  287. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  288. "Subscription %u | Register subscription publishing callback",
  289. sub->subscriptionID);
  290. UA_StatusCode retval =
  291. UA_Server_addRepeatedCallback(server,
  292. (UA_ServerCallback)UA_Subscription_publishCallback,
  293. sub, (UA_UInt32)sub->publishingInterval,
  294. &sub->publishCallbackId);
  295. if(retval == UA_STATUSCODE_GOOD)
  296. sub->publishCallbackIsRegistered = true;
  297. return retval;
  298. }
  299. UA_StatusCode
  300. Subscription_unregisterPublishCallback(UA_Server *server, UA_Subscription *sub) {
  301. if(!sub->publishCallbackIsRegistered)
  302. return UA_STATUSCODE_GOOD;
  303. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  304. "Subscription %u | Unregister subscription "
  305. "publishing callback", sub->subscriptionID);
  306. sub->publishCallbackIsRegistered = false;
  307. return UA_Server_removeRepeatedCallback(server, sub->publishCallbackId);
  308. }
  309. /* When the session has publish requests stored but the last subscription is
  310. * deleted... Send out empty responses */
  311. void
  312. UA_Subscription_answerPublishRequestsNoSubscription(UA_Server *server,
  313. UA_Session *session) {
  314. /* No session or there are remaining subscriptions */
  315. if(!session || LIST_FIRST(&session->serverSubscriptions))
  316. return;
  317. /* Send a response for every queued request */
  318. UA_PublishResponseEntry *pre;
  319. while((pre = SIMPLEQ_FIRST(&session->responseQueue))) {
  320. SIMPLEQ_REMOVE_HEAD(&session->responseQueue, listEntry);
  321. UA_PublishResponse *response = &pre->response;
  322. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOSUBSCRIPTION;
  323. response->responseHeader.timestamp = UA_DateTime_now();
  324. UA_SecureChannel_sendBinaryMessage(session->channel, pre->requestId, response,
  325. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  326. UA_PublishResponse_deleteMembers(response);
  327. UA_free(pre);
  328. }
  329. }
  330. #endif /* UA_ENABLE_SUBSCRIPTIONS */