ua_subscription.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. *
  5. * Copyright 2015-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2015 (c) Chris Iatrou
  7. * Copyright 2015-2016 (c) Sten Grüner
  8. * Copyright 2017-2018 (c) Thomas Stalder, Blue Time Concept SA
  9. * Copyright 2015 (c) Joakim L. Gilje
  10. * Copyright 2016-2017 (c) Florian Palm
  11. * Copyright 2015-2016 (c) Oleksiy Vasylyev
  12. * Copyright 2017 (c) frax2222
  13. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  14. * Copyright 2017 (c) Mattias Bornhager
  15. */
  16. #include "ua_subscription.h"
  17. #include "ua_server_internal.h"
  18. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  19. UA_Subscription *
  20. UA_Subscription_new(UA_Session *session, UA_UInt32 subscriptionId) {
  21. /* Allocate the memory */
  22. UA_Subscription *newSub =
  23. (UA_Subscription*)UA_calloc(1, sizeof(UA_Subscription));
  24. if(!newSub)
  25. return NULL;
  26. /* Remaining members are covered by calloc zeroing out the memory */
  27. newSub->session = session;
  28. newSub->subscriptionId = subscriptionId;
  29. newSub->state = UA_SUBSCRIPTIONSTATE_NORMAL; /* The first publish response is sent immediately */
  30. TAILQ_INIT(&newSub->retransmissionQueue);
  31. TAILQ_INIT(&newSub->notificationQueue);
  32. return newSub;
  33. }
  34. void
  35. UA_Subscription_deleteMembers(UA_Server *server, UA_Subscription *sub) {
  36. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  37. "Delete the subscription", sub->subscriptionId);
  38. Subscription_unregisterPublishCallback(server, sub);
  39. /* Delete monitored Items */
  40. UA_MonitoredItem *mon, *tmp_mon;
  41. LIST_FOREACH_SAFE(mon, &sub->monitoredItems, listEntry, tmp_mon) {
  42. MonitoredItem_delete(server, mon);
  43. }
  44. sub->monitoredItemsSize = 0;
  45. /* Delete Retransmission Queue */
  46. UA_NotificationMessageEntry *nme, *nme_tmp;
  47. TAILQ_FOREACH_SAFE(nme, &sub->retransmissionQueue, listEntry, nme_tmp) {
  48. TAILQ_REMOVE(&sub->retransmissionQueue, nme, listEntry);
  49. UA_NotificationMessage_deleteMembers(&nme->message);
  50. UA_free(nme);
  51. }
  52. sub->retransmissionQueueSize = 0;
  53. }
  54. UA_MonitoredItem *
  55. UA_Subscription_getMonitoredItem(UA_Subscription *sub, UA_UInt32 monitoredItemId) {
  56. UA_MonitoredItem *mon;
  57. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  58. if(mon->monitoredItemId == monitoredItemId)
  59. break;
  60. }
  61. return mon;
  62. }
  63. UA_StatusCode
  64. UA_Subscription_deleteMonitoredItem(UA_Server *server, UA_Subscription *sub,
  65. UA_UInt32 monitoredItemId) {
  66. /* Find the MonitoredItem */
  67. UA_MonitoredItem *mon;
  68. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  69. if(mon->monitoredItemId == monitoredItemId)
  70. break;
  71. }
  72. if(!mon)
  73. return UA_STATUSCODE_BADMONITOREDITEMIDINVALID;
  74. /* Remove the MonitoredItem */
  75. MonitoredItem_delete(server, mon);
  76. sub->monitoredItemsSize--;
  77. return UA_STATUSCODE_GOOD;
  78. }
  79. void
  80. UA_Subscription_addMonitoredItem(UA_Subscription *sub, UA_MonitoredItem *newMon) {
  81. sub->monitoredItemsSize++;
  82. LIST_INSERT_HEAD(&sub->monitoredItems, newMon, listEntry);
  83. }
  84. static void
  85. UA_Subscription_addRetransmissionMessage(UA_Server *server, UA_Subscription *sub,
  86. UA_NotificationMessageEntry *entry) {
  87. /* Release the oldest entry if there is not enough space */
  88. if(server->config.maxRetransmissionQueueSize > 0 &&
  89. sub->retransmissionQueueSize >= server->config.maxRetransmissionQueueSize) {
  90. UA_NotificationMessageEntry *lastentry =
  91. TAILQ_LAST(&sub->retransmissionQueue, ListOfNotificationMessages);
  92. TAILQ_REMOVE(&sub->retransmissionQueue, lastentry, listEntry);
  93. --sub->retransmissionQueueSize;
  94. UA_NotificationMessage_deleteMembers(&lastentry->message);
  95. UA_free(lastentry);
  96. }
  97. /* Add entry */
  98. TAILQ_INSERT_HEAD(&sub->retransmissionQueue, entry, listEntry);
  99. ++sub->retransmissionQueueSize;
  100. }
  101. UA_StatusCode
  102. UA_Subscription_removeRetransmissionMessage(UA_Subscription *sub, UA_UInt32 sequenceNumber) {
  103. /* Find the retransmission message */
  104. UA_NotificationMessageEntry *entry;
  105. TAILQ_FOREACH(entry, &sub->retransmissionQueue, listEntry) {
  106. if(entry->message.sequenceNumber == sequenceNumber)
  107. break;
  108. }
  109. if(!entry)
  110. return UA_STATUSCODE_BADSEQUENCENUMBERUNKNOWN;
  111. /* Remove the retransmission message */
  112. TAILQ_REMOVE(&sub->retransmissionQueue, entry, listEntry);
  113. --sub->retransmissionQueueSize;
  114. UA_NotificationMessage_deleteMembers(&entry->message);
  115. UA_free(entry);
  116. return UA_STATUSCODE_GOOD;
  117. }
  118. /* Iterate over the monitoreditems of the subscription, starting at mon, and
  119. * move notifications into the response. */
  120. static void
  121. moveNotificationsFromMonitoredItems(UA_Subscription *sub, UA_MonitoredItemNotification *mins,
  122. size_t minsSize) {
  123. size_t pos = 0;
  124. UA_Notification *notification, *notification_tmp;
  125. TAILQ_FOREACH_SAFE(notification, &sub->notificationQueue, globalEntry, notification_tmp) {
  126. if(pos >= minsSize)
  127. return;
  128. UA_MonitoredItem *mon = notification->mon;
  129. /* Remove the notification from the queues */
  130. TAILQ_REMOVE(&sub->notificationQueue, notification, globalEntry);
  131. TAILQ_REMOVE(&mon->queue, notification, listEntry);
  132. --mon->queueSize;
  133. --sub->notificationQueueSize;
  134. /* Move the content to the response */
  135. UA_MonitoredItemNotification *min = &mins[pos];
  136. min->clientHandle = mon->clientHandle;
  137. if(mon->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  138. min->value = notification->data.value;
  139. } else {
  140. /* TODO implementation for events */
  141. }
  142. UA_free(notification);
  143. ++pos;
  144. }
  145. }
  146. static UA_StatusCode
  147. prepareNotificationMessage(UA_Subscription *sub, UA_NotificationMessage *message,
  148. size_t notifications) {
  149. /* Array of ExtensionObject to hold different kinds of notifications
  150. * (currently only DataChangeNotifications) */
  151. message->notificationData = UA_ExtensionObject_new();
  152. if(!message->notificationData)
  153. return UA_STATUSCODE_BADOUTOFMEMORY;
  154. message->notificationDataSize = 1;
  155. /* Allocate Notification */
  156. UA_DataChangeNotification *dcn = UA_DataChangeNotification_new();
  157. if(!dcn) {
  158. UA_NotificationMessage_deleteMembers(message);
  159. return UA_STATUSCODE_BADOUTOFMEMORY;
  160. }
  161. UA_ExtensionObject *data = message->notificationData;
  162. data->encoding = UA_EXTENSIONOBJECT_DECODED;
  163. data->content.decoded.data = dcn;
  164. data->content.decoded.type = &UA_TYPES[UA_TYPES_DATACHANGENOTIFICATION];
  165. /* Allocate array of notifications */
  166. dcn->monitoredItems = (UA_MonitoredItemNotification *)
  167. UA_Array_new(notifications,
  168. &UA_TYPES[UA_TYPES_MONITOREDITEMNOTIFICATION]);
  169. if(!dcn->monitoredItems) {
  170. UA_NotificationMessage_deleteMembers(message);
  171. return UA_STATUSCODE_BADOUTOFMEMORY;
  172. }
  173. dcn->monitoredItemsSize = notifications;
  174. /* Move notifications into the response .. the point of no return */
  175. moveNotificationsFromMonitoredItems(sub, dcn->monitoredItems, notifications);
  176. return UA_STATUSCODE_GOOD;
  177. }
  178. /* According to OPC Unified Architecture, Part 4 5.13.1.1 i) The value 0 is
  179. * never used for the sequence number */
  180. static UA_UInt32
  181. UA_Subscription_nextSequenceNumber(UA_UInt32 sequenceNumber) {
  182. UA_UInt32 nextSequenceNumber = sequenceNumber + 1;
  183. if(nextSequenceNumber == 0)
  184. nextSequenceNumber = 1;
  185. return nextSequenceNumber;
  186. }
  187. static void
  188. publishCallback(UA_Server *server, UA_Subscription *sub) {
  189. sub->readyNotifications = sub->notificationQueueSize;
  190. UA_Subscription_publish(server, sub);
  191. }
  192. void
  193. UA_Subscription_publish(UA_Server *server, UA_Subscription *sub) {
  194. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  195. "Publish Callback", sub->subscriptionId);
  196. /* Dequeue a response */
  197. UA_PublishResponseEntry *pre = UA_Session_dequeuePublishReq(sub->session);
  198. if(pre) {
  199. sub->currentLifetimeCount = 0; /* Reset the LifetimeCounter */
  200. } else {
  201. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  202. "Subscription %u | The publish queue is empty",
  203. sub->subscriptionId);
  204. ++sub->currentLifetimeCount;
  205. if(sub->currentLifetimeCount > sub->lifeTimeCount) {
  206. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  207. "Subscription %u | End of lifetime "
  208. "for subscription", sub->subscriptionId);
  209. UA_Session_deleteSubscription(server, sub->session, sub->subscriptionId);
  210. /* TODO: send a StatusChangeNotification with Bad_Timeout */
  211. return;
  212. }
  213. }
  214. if (sub->readyNotifications > sub->notificationQueueSize)
  215. sub->readyNotifications = sub->notificationQueueSize;
  216. /* Count the available notifications */
  217. UA_UInt32 notifications = sub->readyNotifications;
  218. if(!sub->publishingEnabled)
  219. notifications = 0;
  220. UA_Boolean moreNotifications = false;
  221. if(notifications > sub->notificationsPerPublish) {
  222. notifications = sub->notificationsPerPublish;
  223. moreNotifications = true;
  224. }
  225. /* Return if no notifications and no keepalive */
  226. if(notifications == 0) {
  227. ++sub->currentKeepAliveCount;
  228. if(sub->currentKeepAliveCount < sub->maxKeepAliveCount) {
  229. if(pre)
  230. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  231. return;
  232. }
  233. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  234. "Subscription %u | Sending a KeepAlive",
  235. sub->subscriptionId);
  236. }
  237. /* We want to send a response. Is it possible? */
  238. UA_SecureChannel *channel = sub->session->header.channel;
  239. if(!channel || !pre) {
  240. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  241. "Subscription %u | Want to send a publish response but can't. "
  242. "The subscription is late.", sub->subscriptionId);
  243. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  244. if(pre)
  245. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  246. return;
  247. }
  248. /* Prepare the response */
  249. UA_PublishResponse *response = &pre->response;
  250. UA_NotificationMessage *message = &response->notificationMessage;
  251. UA_NotificationMessageEntry *retransmission = NULL;
  252. if(notifications > 0) {
  253. /* Allocate the retransmission entry */
  254. retransmission = (UA_NotificationMessageEntry*)UA_malloc(sizeof(UA_NotificationMessageEntry));
  255. if(!retransmission) {
  256. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  257. "Subscription %u | Could not allocate memory for retransmission. "
  258. "The subscription is late.", sub->subscriptionId);
  259. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  260. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  261. return;
  262. }
  263. /* Prepare the response */
  264. UA_StatusCode retval = prepareNotificationMessage(sub, message, notifications);
  265. if(retval != UA_STATUSCODE_GOOD) {
  266. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  267. "Subscription %u | Could not prepare the notification message. "
  268. "The subscription is late.", sub->subscriptionId);
  269. UA_free(retransmission);
  270. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  271. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  272. return;
  273. }
  274. }
  275. /* <-- The point of no return --> */
  276. /* Adjust the number of ready notifications */
  277. UA_assert(sub->readyNotifications >= notifications);
  278. sub->readyNotifications -= notifications;
  279. /* Set up the response */
  280. response->responseHeader.timestamp = UA_DateTime_now();
  281. response->subscriptionId = sub->subscriptionId;
  282. response->moreNotifications = moreNotifications;
  283. message->publishTime = response->responseHeader.timestamp;
  284. /* Set the sequence number. The sequence number will be reused if there are
  285. * no notifications (and this is a keepalive message). */
  286. message->sequenceNumber = UA_Subscription_nextSequenceNumber(sub->sequenceNumber);
  287. if(notifications != 0) {
  288. /* There are notifications. So we can't reuse the sequence number. */
  289. sub->sequenceNumber = message->sequenceNumber;
  290. /* Put the notification message into the retransmission queue. This
  291. * needs to be done here, so that the message itself is included in the
  292. * available sequence numbers for acknowledgement. */
  293. retransmission->message = response->notificationMessage;
  294. UA_Subscription_addRetransmissionMessage(server, sub, retransmission);
  295. }
  296. /* Get the available sequence numbers from the retransmission queue */
  297. size_t available = sub->retransmissionQueueSize;
  298. UA_STACKARRAY(UA_UInt32, seqNumbers, available);
  299. if(available > 0) {
  300. response->availableSequenceNumbers = seqNumbers;
  301. response->availableSequenceNumbersSize = available;
  302. size_t i = 0;
  303. UA_NotificationMessageEntry *nme;
  304. TAILQ_FOREACH(nme, &sub->retransmissionQueue, listEntry) {
  305. response->availableSequenceNumbers[i] = nme->message.sequenceNumber;
  306. ++i;
  307. }
  308. }
  309. /* Send the response */
  310. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  311. "Subscription %u | Sending out a publish response "
  312. "with %u notifications", sub->subscriptionId,
  313. (UA_UInt32)notifications);
  314. UA_SecureChannel_sendSymmetricMessage(sub->session->header.channel, pre->requestId,
  315. UA_MESSAGETYPE_MSG, response,
  316. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  317. /* Reset subscription state to normal */
  318. sub->state = UA_SUBSCRIPTIONSTATE_NORMAL;
  319. sub->currentKeepAliveCount = 0;
  320. /* Free the response */
  321. UA_Array_delete(response->results, response->resultsSize, &UA_TYPES[UA_TYPES_UINT32]);
  322. UA_free(pre); /* No need for UA_PublishResponse_deleteMembers */
  323. /* Repeat sending responses if there are more notifications to send */
  324. if(moreNotifications)
  325. UA_Subscription_publish(server, sub);
  326. }
  327. UA_Boolean
  328. UA_Subscription_reachedPublishReqLimit(UA_Server *server, UA_Session *session) {
  329. UA_LOG_DEBUG_SESSION(server->config.logger, session, "Reached number of publish request limit");
  330. /* Dequeue a response */
  331. UA_PublishResponseEntry *pre = UA_Session_dequeuePublishReq(session);
  332. /* Cannot publish without a response */
  333. if(!pre) {
  334. UA_LOG_FATAL_SESSION(server->config.logger, session, "No publish requests available");
  335. return false;
  336. }
  337. /* <-- The point of no return --> */
  338. UA_PublishResponse *response = &pre->response;
  339. UA_NotificationMessage *message = &response->notificationMessage;
  340. /* Set up the response. Note that this response has no related subscription id */
  341. response->responseHeader.timestamp = UA_DateTime_now();
  342. response->responseHeader.serviceResult = UA_STATUSCODE_BADTOOMANYPUBLISHREQUESTS;
  343. response->subscriptionId = 0;
  344. response->moreNotifications = false;
  345. message->publishTime = response->responseHeader.timestamp;
  346. message->sequenceNumber = 0;
  347. response->availableSequenceNumbersSize = 0;
  348. /* Send the response */
  349. UA_LOG_DEBUG_SESSION(server->config.logger, session,
  350. "Sending out a publish response triggered by too many publish requests");
  351. UA_SecureChannel_sendSymmetricMessage(session->header.channel, pre->requestId,
  352. UA_MESSAGETYPE_MSG, response, &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  353. /* Free the response */
  354. UA_Array_delete(response->results, response->resultsSize, &UA_TYPES[UA_TYPES_UINT32]);
  355. UA_free(pre); /* no need for UA_PublishResponse_deleteMembers */
  356. return true;
  357. }
  358. UA_StatusCode
  359. Subscription_registerPublishCallback(UA_Server *server, UA_Subscription *sub) {
  360. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  361. "Subscription %u | Register subscription "
  362. "publishing callback", sub->subscriptionId);
  363. if(sub->publishCallbackIsRegistered)
  364. return UA_STATUSCODE_GOOD;
  365. UA_StatusCode retval =
  366. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)publishCallback,
  367. sub, (UA_UInt32)sub->publishingInterval, &sub->publishCallbackId);
  368. if(retval != UA_STATUSCODE_GOOD)
  369. return retval;
  370. sub->publishCallbackIsRegistered = true;
  371. return UA_STATUSCODE_GOOD;
  372. }
  373. UA_StatusCode
  374. Subscription_unregisterPublishCallback(UA_Server *server, UA_Subscription *sub) {
  375. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  376. "Unregister subscription publishing callback", sub->subscriptionId);
  377. if(!sub->publishCallbackIsRegistered)
  378. return UA_STATUSCODE_GOOD;
  379. UA_StatusCode retval = UA_Server_removeRepeatedCallback(server, sub->publishCallbackId);
  380. if(retval != UA_STATUSCODE_GOOD)
  381. return retval;
  382. sub->publishCallbackIsRegistered = false;
  383. return UA_STATUSCODE_GOOD;
  384. }
  385. /* When the session has publish requests stored but the last subscription is
  386. * deleted... Send out empty responses */
  387. void
  388. UA_Subscription_answerPublishRequestsNoSubscription(UA_Server *server, UA_Session *session) {
  389. /* No session or there are remaining subscriptions */
  390. if(!session || LIST_FIRST(&session->serverSubscriptions))
  391. return;
  392. /* Send a response for every queued request */
  393. UA_PublishResponseEntry *pre;
  394. while((pre = UA_Session_dequeuePublishReq(session))) {
  395. UA_PublishResponse *response = &pre->response;
  396. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOSUBSCRIPTION;
  397. response->responseHeader.timestamp = UA_DateTime_now();
  398. UA_SecureChannel_sendSymmetricMessage(session->header.channel, pre->requestId, UA_MESSAGETYPE_MSG,
  399. response, &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  400. UA_PublishResponse_deleteMembers(response);
  401. UA_free(pre);
  402. }
  403. }
  404. #endif /* UA_ENABLE_SUBSCRIPTIONS */