ua_subscription.c 19 KB

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