ua_subscription.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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-2018 (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) Ari Breitkreuz, fortiss GmbH
  15. * Copyright 2017 (c) Mattias Bornhager
  16. * Copyright 2018 (c) Hilscher Gesellschaft für Systemautomation mbH (Author: Martin Lang)
  17. */
  18. #include "ua_server_internal.h"
  19. #include "ua_subscription.h"
  20. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  21. UA_Subscription *
  22. UA_Subscription_new(UA_Session *session, UA_UInt32 subscriptionId) {
  23. /* Allocate the memory */
  24. UA_Subscription *newSub =
  25. (UA_Subscription*)UA_calloc(1, sizeof(UA_Subscription));
  26. if(!newSub)
  27. return NULL;
  28. /* Remaining members are covered by calloc zeroing out the memory */
  29. newSub->session = session;
  30. newSub->subscriptionId = subscriptionId;
  31. newSub->state = UA_SUBSCRIPTIONSTATE_NORMAL; /* The first publish response is sent immediately */
  32. /* Even if the first publish response is a keepalive the sequence number is 1.
  33. * This can happen by a subscription without a monitored item (see CTT test scripts). */
  34. newSub->nextSequenceNumber = 1;
  35. TAILQ_INIT(&newSub->retransmissionQueue);
  36. TAILQ_INIT(&newSub->notificationQueue);
  37. return newSub;
  38. }
  39. void
  40. UA_Subscription_deleteMembers(UA_Server *server, UA_Subscription *sub) {
  41. UA_LOCK_ASSERT(server->serviceMutex, 1);
  42. Subscription_unregisterPublishCallback(server, sub);
  43. /* Delete monitored Items */
  44. UA_MonitoredItem *mon, *tmp_mon;
  45. LIST_FOREACH_SAFE(mon, &sub->monitoredItems, listEntry, tmp_mon) {
  46. LIST_REMOVE(mon, listEntry);
  47. UA_LOG_INFO_SESSION(&server->config.logger, sub->session,
  48. "Subscription %u | MonitoredItem %i | "
  49. "Deleted the MonitoredItem", sub->subscriptionId,
  50. mon->monitoredItemId);
  51. UA_MonitoredItem_delete(server, mon);
  52. }
  53. UA_assert(server->numMonitoredItems >= sub->monitoredItemsSize);
  54. server->numMonitoredItems -= sub->monitoredItemsSize;
  55. sub->monitoredItemsSize = 0;
  56. /* Delete Retransmission Queue */
  57. UA_NotificationMessageEntry *nme, *nme_tmp;
  58. TAILQ_FOREACH_SAFE(nme, &sub->retransmissionQueue, listEntry, nme_tmp) {
  59. TAILQ_REMOVE(&sub->retransmissionQueue, nme, listEntry);
  60. UA_NotificationMessage_clear(&nme->message);
  61. UA_free(nme);
  62. --sub->session->totalRetransmissionQueueSize;
  63. --sub->retransmissionQueueSize;
  64. }
  65. UA_assert(sub->retransmissionQueueSize == 0);
  66. UA_LOG_INFO_SESSION(&server->config.logger, sub->session,
  67. "Subscription %u | Deleted the Subscription",
  68. sub->subscriptionId);
  69. }
  70. UA_MonitoredItem *
  71. UA_Subscription_getMonitoredItem(UA_Subscription *sub, UA_UInt32 monitoredItemId) {
  72. UA_MonitoredItem *mon;
  73. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  74. if(mon->monitoredItemId == monitoredItemId)
  75. break;
  76. }
  77. return mon;
  78. }
  79. UA_StatusCode
  80. UA_Subscription_deleteMonitoredItem(UA_Server *server, UA_Subscription *sub,
  81. UA_UInt32 monitoredItemId) {
  82. UA_LOCK_ASSERT(server->serviceMutex, 1);
  83. /* Find the MonitoredItem */
  84. UA_MonitoredItem *mon;
  85. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  86. if(mon->monitoredItemId == monitoredItemId)
  87. break;
  88. }
  89. if(!mon)
  90. return UA_STATUSCODE_BADMONITOREDITEMIDINVALID;
  91. UA_LOG_INFO_SESSION(&server->config.logger, sub->session,
  92. "Subscription %u | MonitoredItem %i | "
  93. "Delete the MonitoredItem", sub->subscriptionId,
  94. mon->monitoredItemId);
  95. /* Remove the MonitoredItem */
  96. LIST_REMOVE(mon, listEntry);
  97. UA_assert(sub->monitoredItemsSize > 0);
  98. UA_assert(server->numMonitoredItems > 0);
  99. sub->monitoredItemsSize--;
  100. server->numMonitoredItems--;
  101. /* Remove content and delayed free */
  102. UA_MonitoredItem_delete(server, mon);
  103. return UA_STATUSCODE_GOOD;
  104. }
  105. void
  106. UA_Subscription_addMonitoredItem(UA_Server *server, UA_Subscription *sub, UA_MonitoredItem *newMon) {
  107. sub->monitoredItemsSize++;
  108. server->numMonitoredItems++;
  109. LIST_INSERT_HEAD(&sub->monitoredItems, newMon, listEntry);
  110. }
  111. static void
  112. removeOldestRetransmissionMessage(UA_Session *session) {
  113. UA_NotificationMessageEntry *oldestEntry = NULL;
  114. UA_Subscription *oldestSub = NULL;
  115. UA_Subscription *sub;
  116. LIST_FOREACH(sub, &session->serverSubscriptions, listEntry) {
  117. UA_NotificationMessageEntry *first =
  118. TAILQ_LAST(&sub->retransmissionQueue, ListOfNotificationMessages);
  119. if(!first)
  120. continue;
  121. if(!oldestEntry || oldestEntry->message.publishTime > first->message.publishTime) {
  122. oldestEntry = first;
  123. oldestSub = sub;
  124. }
  125. }
  126. UA_assert(oldestEntry);
  127. UA_assert(oldestSub);
  128. TAILQ_REMOVE(&oldestSub->retransmissionQueue, oldestEntry, listEntry);
  129. UA_NotificationMessage_clear(&oldestEntry->message);
  130. UA_free(oldestEntry);
  131. --session->totalRetransmissionQueueSize;
  132. --oldestSub->retransmissionQueueSize;
  133. }
  134. static void
  135. UA_Subscription_addRetransmissionMessage(UA_Server *server, UA_Subscription *sub,
  136. UA_NotificationMessageEntry *entry) {
  137. /* Release the oldest entry if there is not enough space */
  138. if(server->config.maxRetransmissionQueueSize > 0 &&
  139. sub->session->totalRetransmissionQueueSize >= server->config.maxRetransmissionQueueSize) {
  140. UA_LOG_WARNING_SESSION(&server->config.logger, sub->session, "Subscription %u | "
  141. "Retransmission queue overflow", sub->subscriptionId);
  142. removeOldestRetransmissionMessage(sub->session);
  143. }
  144. /* Add entry */
  145. TAILQ_INSERT_TAIL(&sub->retransmissionQueue, entry, listEntry);
  146. ++sub->session->totalRetransmissionQueueSize;
  147. ++sub->retransmissionQueueSize;
  148. }
  149. UA_StatusCode
  150. UA_Subscription_removeRetransmissionMessage(UA_Subscription *sub, UA_UInt32 sequenceNumber) {
  151. /* Find the retransmission message */
  152. UA_NotificationMessageEntry *entry;
  153. TAILQ_FOREACH(entry, &sub->retransmissionQueue, listEntry) {
  154. if(entry->message.sequenceNumber == sequenceNumber)
  155. break;
  156. }
  157. if(!entry)
  158. return UA_STATUSCODE_BADSEQUENCENUMBERUNKNOWN;
  159. /* Remove the retransmission message */
  160. TAILQ_REMOVE(&sub->retransmissionQueue, entry, listEntry);
  161. --sub->session->totalRetransmissionQueueSize;
  162. --sub->retransmissionQueueSize;
  163. UA_NotificationMessage_clear(&entry->message);
  164. UA_free(entry);
  165. return UA_STATUSCODE_GOOD;
  166. }
  167. static UA_StatusCode
  168. prepareNotificationMessage(UA_Server *server, UA_Subscription *sub,
  169. UA_NotificationMessage *message, size_t notifications) {
  170. UA_assert(notifications > 0);
  171. /* Allocate an ExtensionObject for events and data */
  172. message->notificationData = (UA_ExtensionObject*)
  173. UA_Array_new(2, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]);
  174. if(!message->notificationData)
  175. return UA_STATUSCODE_BADOUTOFMEMORY;
  176. message->notificationDataSize = 2;
  177. /* Pre-allocate DataChangeNotifications */
  178. size_t notificationDataIdx = 0;
  179. UA_DataChangeNotification *dcn = NULL;
  180. if(sub->dataChangeNotifications > 0) {
  181. dcn = UA_DataChangeNotification_new();
  182. if(!dcn) {
  183. UA_NotificationMessage_clear(message);
  184. return UA_STATUSCODE_BADOUTOFMEMORY;
  185. }
  186. message->notificationData->encoding = UA_EXTENSIONOBJECT_DECODED;
  187. message->notificationData->content.decoded.data = dcn;
  188. message->notificationData->content.decoded.type = &UA_TYPES[UA_TYPES_DATACHANGENOTIFICATION];
  189. size_t dcnSize = sub->dataChangeNotifications;
  190. if(dcnSize > notifications)
  191. dcnSize = notifications;
  192. dcn->monitoredItems = (UA_MonitoredItemNotification*)
  193. UA_Array_new(dcnSize, &UA_TYPES[UA_TYPES_MONITOREDITEMNOTIFICATION]);
  194. if(!dcn->monitoredItems) {
  195. UA_NotificationMessage_clear(message);
  196. return UA_STATUSCODE_BADOUTOFMEMORY;
  197. }
  198. dcn->monitoredItemsSize = dcnSize;
  199. notificationDataIdx++;
  200. }
  201. #ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
  202. UA_EventNotificationList *enl = NULL;
  203. UA_StatusChangeNotification *scn = NULL;
  204. /* Pre-allocate either StatusChange or EventNotifications. Sending a
  205. * (single) StatusChangeNotification has priority. */
  206. if(sub->statusChangeNotifications > 0) {
  207. scn = UA_StatusChangeNotification_new();
  208. if(!scn) {
  209. UA_NotificationMessage_clear(message);
  210. return UA_STATUSCODE_BADOUTOFMEMORY;
  211. }
  212. message->notificationData[notificationDataIdx].encoding = UA_EXTENSIONOBJECT_DECODED;
  213. message->notificationData[notificationDataIdx].content.decoded.data = scn;
  214. message->notificationData[notificationDataIdx].content.decoded.type = &UA_TYPES[UA_TYPES_STATUSCHANGENOTIFICATION];
  215. notificationDataIdx++;
  216. } else if(sub->eventNotifications > 0) {
  217. enl = UA_EventNotificationList_new();
  218. if(!enl) {
  219. UA_NotificationMessage_clear(message);
  220. return UA_STATUSCODE_BADOUTOFMEMORY;
  221. }
  222. message->notificationData[notificationDataIdx].encoding = UA_EXTENSIONOBJECT_DECODED;
  223. message->notificationData[notificationDataIdx].content.decoded.data = enl;
  224. message->notificationData[notificationDataIdx].content.decoded.type = &UA_TYPES[UA_TYPES_EVENTNOTIFICATIONLIST];
  225. size_t enlSize = sub->eventNotifications;
  226. if(enlSize > notifications)
  227. enlSize = notifications;
  228. enl->events = (UA_EventFieldList*) UA_Array_new(enlSize, &UA_TYPES[UA_TYPES_EVENTFIELDLIST]);
  229. if(!enl->events) {
  230. UA_NotificationMessage_clear(message);
  231. return UA_STATUSCODE_BADOUTOFMEMORY;
  232. }
  233. enl->eventsSize = enlSize;
  234. notificationDataIdx++;
  235. }
  236. #endif
  237. UA_assert(notificationDataIdx > 0);
  238. message->notificationDataSize = notificationDataIdx;
  239. /* <-- The point of no return --> */
  240. size_t totalNotifications = 0; /* How many notifications were moved to the response overall? */
  241. size_t dcnPos = 0; /* How many DataChangeNotifications were put into the list? */
  242. #ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
  243. size_t enlPos = 0; /* How many EventNotifications were moved into the list */
  244. #endif
  245. UA_Notification *notification, *notification_tmp;
  246. TAILQ_FOREACH_SAFE(notification, &sub->notificationQueue, globalEntry, notification_tmp) {
  247. if(totalNotifications >= notifications)
  248. break;
  249. UA_MonitoredItem *mon = notification->mon;
  250. /* Remove from the queues and decrease the counters */
  251. UA_Notification_dequeue(server, notification);
  252. /* Move the content to the response */
  253. #ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
  254. if(mon->attributeId == UA_ATTRIBUTEID_EVENTNOTIFIER) {
  255. UA_assert(enl != NULL); /* Have at least one event notification */
  256. /* Move the content to the response */
  257. UA_EventFieldList *efl = &enl->events[enlPos];
  258. *efl = notification->data.event.fields;
  259. UA_EventFieldList_init(&notification->data.event.fields);
  260. efl->clientHandle = mon->clientHandle;
  261. enlPos++;
  262. } else
  263. #endif
  264. {
  265. UA_assert(dcn != NULL); /* Have at least one change notification */
  266. /* Move the content to the response */
  267. UA_MonitoredItemNotification *min = &dcn->monitoredItems[dcnPos];
  268. min->clientHandle = mon->clientHandle;
  269. min->value = notification->data.value;
  270. UA_DataValue_init(&notification->data.value); /* Reset after the value has been moved */
  271. dcnPos++;
  272. }
  273. UA_Notification_delete(notification);
  274. totalNotifications++;
  275. }
  276. /* Set sizes */
  277. if(dcn) {
  278. dcn->monitoredItemsSize = dcnPos;
  279. if(dcnPos == 0) {
  280. UA_free(dcn->monitoredItems);
  281. dcn->monitoredItems = NULL;
  282. }
  283. }
  284. #ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
  285. if(enl) {
  286. enl->eventsSize = enlPos;
  287. if(enlPos == 0) {
  288. UA_free(enl->events);
  289. enl->events = NULL;
  290. }
  291. }
  292. #endif
  293. return UA_STATUSCODE_GOOD;
  294. }
  295. /* According to OPC Unified Architecture, Part 4 5.13.1.1 i) The value 0 is
  296. * never used for the sequence number */
  297. static UA_UInt32
  298. UA_Subscription_nextSequenceNumber(UA_UInt32 sequenceNumber) {
  299. UA_UInt32 nextSequenceNumber = sequenceNumber + 1;
  300. if(nextSequenceNumber == 0)
  301. nextSequenceNumber = 1;
  302. return nextSequenceNumber;
  303. }
  304. static void
  305. publishCallback(UA_Server *server, UA_Subscription *sub) {
  306. sub->readyNotifications = sub->notificationQueueSize;
  307. UA_LOCK(server->serviceMutex);
  308. UA_Subscription_publish(server, sub);
  309. UA_UNLOCK(server->serviceMutex);
  310. }
  311. void
  312. UA_Subscription_publish(UA_Server *server, UA_Subscription *sub) {
  313. UA_LOCK_ASSERT(server->serviceMutex, 1);
  314. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session, "Subscription %u | "
  315. "Publish Callback", sub->subscriptionId);
  316. /* Dequeue a response */
  317. UA_PublishResponseEntry *pre = UA_Session_dequeuePublishReq(sub->session);
  318. if(pre) {
  319. sub->currentLifetimeCount = 0; /* Reset the LifetimeCounter */
  320. } else {
  321. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session,
  322. "Subscription %u | The publish queue is empty",
  323. sub->subscriptionId);
  324. ++sub->currentLifetimeCount;
  325. if(sub->currentLifetimeCount > sub->lifeTimeCount) {
  326. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session,
  327. "Subscription %u | End of lifetime "
  328. "for subscription", sub->subscriptionId);
  329. UA_Session_deleteSubscription(server, sub->session, sub->subscriptionId);
  330. /* TODO: send a StatusChangeNotification with Bad_Timeout */
  331. return;
  332. }
  333. }
  334. /* If there are several late publish responses... */
  335. if(sub->readyNotifications > sub->notificationQueueSize)
  336. sub->readyNotifications = sub->notificationQueueSize;
  337. /* Count the available notifications */
  338. UA_UInt32 notifications = sub->readyNotifications;
  339. if(!sub->publishingEnabled)
  340. notifications = 0;
  341. UA_Boolean moreNotifications = false;
  342. if(notifications > sub->notificationsPerPublish) {
  343. notifications = sub->notificationsPerPublish;
  344. moreNotifications = true;
  345. }
  346. /* Return if no notifications and no keepalive */
  347. if(notifications == 0) {
  348. ++sub->currentKeepAliveCount;
  349. if(sub->currentKeepAliveCount < sub->maxKeepAliveCount) {
  350. if(pre)
  351. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  352. return;
  353. }
  354. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session,
  355. "Subscription %u | Sending a KeepAlive",
  356. sub->subscriptionId);
  357. }
  358. /* We want to send a response. Is the channel open? */
  359. UA_SecureChannel *channel = sub->session->header.channel;
  360. if(!channel || !pre) {
  361. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session,
  362. "Subscription %u | Want to send a publish response but can't. "
  363. "The subscription is late.", sub->subscriptionId);
  364. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  365. if(pre)
  366. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  367. return;
  368. }
  369. /* Prepare the response */
  370. UA_PublishResponse *response = &pre->response;
  371. UA_NotificationMessage *message = &response->notificationMessage;
  372. UA_NotificationMessageEntry *retransmission = NULL;
  373. if(notifications > 0) {
  374. if(server->config.enableRetransmissionQueue) {
  375. /* Allocate the retransmission entry */
  376. retransmission = (UA_NotificationMessageEntry*)UA_malloc(sizeof(UA_NotificationMessageEntry));
  377. if(!retransmission) {
  378. UA_LOG_WARNING_SESSION(&server->config.logger, sub->session,
  379. "Subscription %u | Could not allocate memory for retransmission. "
  380. "The subscription is late.", sub->subscriptionId);
  381. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  382. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  383. return;
  384. }
  385. }
  386. /* Prepare the response */
  387. UA_StatusCode retval = prepareNotificationMessage(server, sub, message, notifications);
  388. if(retval != UA_STATUSCODE_GOOD) {
  389. UA_LOG_WARNING_SESSION(&server->config.logger, sub->session,
  390. "Subscription %u | Could not prepare the notification message. "
  391. "The subscription is late.", sub->subscriptionId);
  392. /* If the retransmission queue is enabled a retransmission message is allocated */
  393. if(retransmission)
  394. UA_free(retransmission);
  395. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  396. UA_Session_queuePublishReq(sub->session, pre, true); /* Re-enqueue */
  397. return;
  398. }
  399. }
  400. /* <-- The point of no return --> */
  401. /* Adjust the number of ready notifications */
  402. UA_assert(sub->readyNotifications >= notifications);
  403. sub->readyNotifications -= notifications;
  404. /* Set up the response */
  405. response->responseHeader.timestamp = UA_DateTime_now();
  406. response->subscriptionId = sub->subscriptionId;
  407. response->moreNotifications = moreNotifications;
  408. message->publishTime = response->responseHeader.timestamp;
  409. /* Set sequence number to message. Started at 1 which is given
  410. * during creating a new subscription. The 1 is required for
  411. * initial publish response with or without an monitored item. */
  412. message->sequenceNumber = sub->nextSequenceNumber;
  413. if(notifications > 0) {
  414. /* If the retransmission queue is enabled a retransmission message is allocated */
  415. if(retransmission) {
  416. /* Put the notification message into the retransmission queue. This
  417. * needs to be done here, so that the message itself is included in the
  418. * available sequence numbers for acknowledgement. */
  419. retransmission->message = response->notificationMessage;
  420. UA_Subscription_addRetransmissionMessage(server, sub, retransmission);
  421. }
  422. /* Only if a notification was created, the sequence number must be increased.
  423. * For a keepalive the sequence number can be reused. */
  424. sub->nextSequenceNumber = UA_Subscription_nextSequenceNumber(sub->nextSequenceNumber);
  425. }
  426. /* Get the available sequence numbers from the retransmission queue */
  427. size_t available = sub->retransmissionQueueSize;
  428. UA_STACKARRAY(UA_UInt32, seqNumbers, available);
  429. if(available > 0) {
  430. response->availableSequenceNumbers = seqNumbers;
  431. response->availableSequenceNumbersSize = available;
  432. size_t i = 0;
  433. UA_NotificationMessageEntry *nme;
  434. TAILQ_FOREACH(nme, &sub->retransmissionQueue, listEntry) {
  435. response->availableSequenceNumbers[i] = nme->message.sequenceNumber;
  436. ++i;
  437. }
  438. }
  439. /* Send the response */
  440. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session,
  441. "Subscription %u | Sending out a publish response "
  442. "with %u notifications", sub->subscriptionId,
  443. (UA_UInt32)notifications);
  444. UA_SecureChannel_sendSymmetricMessage(sub->session->header.channel, pre->requestId,
  445. UA_MESSAGETYPE_MSG, response,
  446. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  447. /* Reset subscription state to normal */
  448. sub->state = UA_SUBSCRIPTIONSTATE_NORMAL;
  449. sub->currentKeepAliveCount = 0;
  450. /* Free the response */
  451. UA_Array_delete(response->results, response->resultsSize, &UA_TYPES[UA_TYPES_UINT32]);
  452. UA_free(pre); /* No need for UA_PublishResponse_clear */
  453. /* Repeat sending responses if there are more notifications to send */
  454. if(moreNotifications)
  455. UA_Subscription_publish(server, sub);
  456. }
  457. UA_Boolean
  458. UA_Subscription_reachedPublishReqLimit(UA_Server *server, UA_Session *session) {
  459. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  460. "Reached number of publish request limit");
  461. /* Dequeue a response */
  462. UA_PublishResponseEntry *pre = UA_Session_dequeuePublishReq(session);
  463. /* Cannot publish without a response */
  464. if(!pre) {
  465. UA_LOG_FATAL_SESSION(&server->config.logger, session, "No publish requests available");
  466. return false;
  467. }
  468. /* <-- The point of no return --> */
  469. UA_PublishResponse *response = &pre->response;
  470. UA_NotificationMessage *message = &response->notificationMessage;
  471. /* Set up the response. Note that this response has no related subscription id */
  472. response->responseHeader.timestamp = UA_DateTime_now();
  473. response->responseHeader.serviceResult = UA_STATUSCODE_BADTOOMANYPUBLISHREQUESTS;
  474. response->subscriptionId = 0;
  475. response->moreNotifications = false;
  476. message->publishTime = response->responseHeader.timestamp;
  477. message->sequenceNumber = 0;
  478. response->availableSequenceNumbersSize = 0;
  479. /* Send the response */
  480. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  481. "Sending out a publish response triggered by too many publish requests");
  482. UA_SecureChannel_sendSymmetricMessage(session->header.channel, pre->requestId,
  483. UA_MESSAGETYPE_MSG, response, &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  484. /* Free the response */
  485. UA_Array_delete(response->results, response->resultsSize, &UA_TYPES[UA_TYPES_UINT32]);
  486. UA_free(pre); /* no need for UA_PublishResponse_clear */
  487. return true;
  488. }
  489. UA_StatusCode
  490. Subscription_registerPublishCallback(UA_Server *server, UA_Subscription *sub) {
  491. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session,
  492. "Subscription %u | Register subscription "
  493. "publishing callback", sub->subscriptionId);
  494. UA_LOCK_ASSERT(server->serviceMutex, 1);
  495. if(sub->publishCallbackIsRegistered)
  496. return UA_STATUSCODE_GOOD;
  497. UA_StatusCode retval =
  498. addRepeatedCallback(server, (UA_ServerCallback)publishCallback,
  499. sub, (UA_UInt32)sub->publishingInterval, &sub->publishCallbackId);
  500. if(retval != UA_STATUSCODE_GOOD)
  501. return retval;
  502. sub->publishCallbackIsRegistered = true;
  503. return UA_STATUSCODE_GOOD;
  504. }
  505. void
  506. Subscription_unregisterPublishCallback(UA_Server *server, UA_Subscription *sub) {
  507. UA_LOG_DEBUG_SESSION(&server->config.logger, sub->session, "Subscription %u | "
  508. "Unregister subscription publishing callback", sub->subscriptionId);
  509. if(!sub->publishCallbackIsRegistered)
  510. return;
  511. removeCallback(server, sub->publishCallbackId);
  512. sub->publishCallbackIsRegistered = false;
  513. }
  514. /* When the session has publish requests stored but the last subscription is
  515. * deleted... Send out empty responses */
  516. void
  517. UA_Subscription_answerPublishRequestsNoSubscription(UA_Server *server, UA_Session *session) {
  518. /* No session or there are remaining subscriptions */
  519. if(!session || LIST_FIRST(&session->serverSubscriptions))
  520. return;
  521. /* Send a response for every queued request */
  522. UA_PublishResponseEntry *pre;
  523. while((pre = UA_Session_dequeuePublishReq(session))) {
  524. UA_PublishResponse *response = &pre->response;
  525. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOSUBSCRIPTION;
  526. response->responseHeader.timestamp = UA_DateTime_now();
  527. UA_SecureChannel_sendSymmetricMessage(session->header.channel, pre->requestId, UA_MESSAGETYPE_MSG,
  528. response, &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  529. UA_PublishResponse_clear(response);
  530. UA_free(pre);
  531. }
  532. }
  533. #endif /* UA_ENABLE_SUBSCRIPTIONS */