ua_subscription.c 19 KB

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