ua_subscription.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. #include "ua_types_encoding_binary.h"
  7. #include "ua_services.h"
  8. #include "ua_nodestore.h"
  9. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  10. #define UA_VALUENCODING_MAXSTACK 512
  11. /*****************/
  12. /* MonitoredItem */
  13. /*****************/
  14. UA_MonitoredItem * UA_MonitoredItem_new() {
  15. UA_MonitoredItem *newItem = (UA_MonitoredItem *)UA_malloc(sizeof(UA_MonitoredItem));
  16. if(!newItem)
  17. return NULL;
  18. newItem->subscription = NULL;
  19. newItem->currentQueueSize = 0;
  20. newItem->maxQueueSize = 0;
  21. newItem->monitoredItemType = UA_MONITOREDITEMTYPE_CHANGENOTIFY; /* currently hardcoded */
  22. newItem->timestampsToReturn = UA_TIMESTAMPSTORETURN_SOURCE;
  23. UA_String_init(&newItem->indexRange);
  24. TAILQ_INIT(&newItem->queue);
  25. UA_NodeId_init(&newItem->monitoredNodeId);
  26. newItem->lastSampledValue = UA_BYTESTRING_NULL;
  27. memset(&newItem->sampleJobGuid, 0, sizeof(UA_Guid));
  28. newItem->sampleJobIsRegistered = false;
  29. newItem->itemId = 0;
  30. return newItem;
  31. }
  32. void MonitoredItem_delete(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  33. MonitoredItem_unregisterSampleJob(server, monitoredItem);
  34. /* clear the queued samples */
  35. MonitoredItem_queuedValue *val, *val_tmp;
  36. TAILQ_FOREACH_SAFE(val, &monitoredItem->queue, listEntry, val_tmp) {
  37. TAILQ_REMOVE(&monitoredItem->queue, val, listEntry);
  38. UA_DataValue_deleteMembers(&val->value);
  39. UA_free(val);
  40. }
  41. monitoredItem->currentQueueSize = 0;
  42. LIST_REMOVE(monitoredItem, listEntry);
  43. UA_String_deleteMembers(&monitoredItem->indexRange);
  44. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  45. UA_NodeId_deleteMembers(&monitoredItem->monitoredNodeId);
  46. UA_free(monitoredItem);
  47. }
  48. static void
  49. ensureSpaceInMonitoredItemQueue(UA_MonitoredItem *mon) {
  50. if(mon->currentQueueSize < mon->maxQueueSize)
  51. return;
  52. MonitoredItem_queuedValue *queueItem;
  53. if(mon->discardOldest)
  54. queueItem = TAILQ_FIRST(&mon->queue);
  55. else
  56. queueItem = TAILQ_LAST(&mon->queue,
  57. memberstruct(UA_MonitoredItem,QueueOfQueueDataValues));
  58. UA_assert(queueItem); /* When the currentQueueSize > 0, then there is an item */
  59. TAILQ_REMOVE(&mon->queue, queueItem, listEntry);
  60. UA_DataValue_deleteMembers(&queueItem->value);
  61. UA_free(queueItem);
  62. --mon->currentQueueSize;
  63. }
  64. /* Errors are returned as no change detected */
  65. static UA_Boolean
  66. detectValueChangeWithFilter(UA_MonitoredItem *mon, UA_DataValue *value,
  67. UA_ByteString *encoding) {
  68. /* Encode the data for comparison */
  69. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  70. if(binsize == 0)
  71. return false;
  72. /* Allocate buffer on the heap if necessary */
  73. if(binsize > UA_VALUENCODING_MAXSTACK &&
  74. UA_ByteString_allocBuffer(encoding, binsize) != UA_STATUSCODE_GOOD)
  75. return false;
  76. /* Encode the value */
  77. size_t encodingOffset = 0;
  78. UA_StatusCode retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  79. NULL, NULL, encoding, &encodingOffset);
  80. if(retval != UA_STATUSCODE_GOOD)
  81. return false;
  82. /* The value has changed */
  83. encoding->length = encodingOffset;
  84. return !mon->lastSampledValue.data || !UA_String_equal(encoding, &mon->lastSampledValue);
  85. }
  86. /* Has this sample changed from the last one? The method may allocate additional
  87. * space for the encoding buffer. Detect the change in encoding->data. */
  88. static UA_Boolean
  89. detectValueChange(UA_MonitoredItem *mon, UA_DataValue *value, UA_ByteString *encoding) {
  90. /* Apply Filter */
  91. UA_Boolean hasValue = value->hasValue;
  92. if(mon->trigger == UA_DATACHANGETRIGGER_STATUS)
  93. value->hasValue = false;
  94. UA_Boolean hasServerTimestamp = value->hasServerTimestamp;
  95. UA_Boolean hasServerPicoseconds = value->hasServerPicoseconds;
  96. value->hasServerTimestamp = false;
  97. value->hasServerPicoseconds = false;
  98. UA_Boolean hasSourceTimestamp = value->hasSourceTimestamp;
  99. UA_Boolean hasSourcePicoseconds = value->hasSourcePicoseconds;
  100. if(mon->trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  101. value->hasSourceTimestamp = false;
  102. value->hasSourcePicoseconds = false;
  103. }
  104. /* Detect the Value Change */
  105. UA_Boolean res = detectValueChangeWithFilter(mon, value, encoding);
  106. /* Reset the filter */
  107. value->hasValue = hasValue;
  108. value->hasServerTimestamp = hasServerTimestamp;
  109. value->hasServerPicoseconds = hasServerPicoseconds;
  110. value->hasSourceTimestamp = hasSourceTimestamp;
  111. value->hasSourcePicoseconds = hasSourcePicoseconds;
  112. return res;
  113. }
  114. /* Returns whether a new sample was created */
  115. static UA_Boolean
  116. sampleCallbackWithValue(UA_Server *server, UA_Subscription *sub,
  117. UA_MonitoredItem *monitoredItem,
  118. UA_DataValue *value, UA_ByteString *valueEncoding) {
  119. /* Store the pointer to the stack-allocated bytestring to see if a heap-allocation
  120. * was necessary */
  121. UA_Byte *stackValueEncoding = valueEncoding->data;
  122. /* Has the value changed? */
  123. UA_Boolean changed = detectValueChange(monitoredItem, value, valueEncoding);
  124. if(!changed)
  125. return false;
  126. /* Allocate the entry for the publish queue */
  127. MonitoredItem_queuedValue *newQueueItem =
  128. (MonitoredItem_queuedValue *)UA_malloc(sizeof(MonitoredItem_queuedValue));
  129. if(!newQueueItem) {
  130. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  131. "Subscription %u | MonitoredItem %i | "
  132. "Item for the publishing queue could not be allocated",
  133. sub->subscriptionID, monitoredItem->itemId);
  134. return false;
  135. }
  136. /* Copy valueEncoding on the heap for the next comparison (if not already done) */
  137. if(valueEncoding->data == stackValueEncoding) {
  138. UA_ByteString cbs;
  139. if(UA_ByteString_copy(valueEncoding, &cbs) != UA_STATUSCODE_GOOD) {
  140. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  141. "Subscription %u | MonitoredItem %i | "
  142. "ByteString to compare values could not be created",
  143. sub->subscriptionID, monitoredItem->itemId);
  144. UA_free(newQueueItem);
  145. return false;
  146. }
  147. *valueEncoding = cbs;
  148. }
  149. /* Prepare the newQueueItem */
  150. if(value->hasValue && value->value.storageType == UA_VARIANT_DATA_NODELETE) {
  151. /* Make a deep copy of the value */
  152. if(UA_DataValue_copy(value, &newQueueItem->value) != UA_STATUSCODE_GOOD) {
  153. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  154. "Subscription %u | MonitoredItem %i | "
  155. "Item for the publishing queue could not be prepared",
  156. sub->subscriptionID, monitoredItem->itemId);
  157. UA_free(newQueueItem);
  158. return false;
  159. }
  160. } else {
  161. newQueueItem->value = *value; /* Just copy the value and do not release it */
  162. }
  163. newQueueItem->clientHandle = monitoredItem->clientHandle;
  164. /* <-- Point of no return --> */
  165. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  166. "Subscription %u | MonitoredItem %u | Sampled a new value",
  167. sub->subscriptionID, monitoredItem->itemId);
  168. /* Replace the encoding for comparison */
  169. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  170. monitoredItem->lastSampledValue = *valueEncoding;
  171. /* Add the sample to the queue for publication */
  172. ensureSpaceInMonitoredItemQueue(monitoredItem);
  173. TAILQ_INSERT_TAIL(&monitoredItem->queue, newQueueItem, listEntry);
  174. ++monitoredItem->currentQueueSize;
  175. return true;;
  176. }
  177. void UA_MoniteredItem_SampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  178. UA_Subscription *sub = monitoredItem->subscription;
  179. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  180. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  181. "Subscription %u | MonitoredItem %i | "
  182. "Not a data change notification",
  183. sub->subscriptionID, monitoredItem->itemId);
  184. return;
  185. }
  186. /* Read the value */
  187. UA_ReadValueId rvid;
  188. UA_ReadValueId_init(&rvid);
  189. rvid.nodeId = monitoredItem->monitoredNodeId;
  190. rvid.attributeId = monitoredItem->attributeID;
  191. rvid.indexRange = monitoredItem->indexRange;
  192. UA_DataValue value;
  193. UA_DataValue_init(&value);
  194. Service_Read_single(server, sub->session, monitoredItem->timestampsToReturn,
  195. &rvid, &value);
  196. /* Stack-allocate some memory for the value encoding. We might heap-allocate
  197. * more memory if needed. This is just enough for scalars and small
  198. * structures. */
  199. UA_Byte *stackValueEncoding = (UA_Byte *)UA_alloca(UA_VALUENCODING_MAXSTACK);
  200. UA_ByteString valueEncoding;
  201. valueEncoding.data = stackValueEncoding;
  202. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  203. /* Create a sample and compare with the last value */
  204. UA_Boolean newNotification = sampleCallbackWithValue(server, sub, monitoredItem,
  205. &value, &valueEncoding);
  206. /* Clean up */
  207. if(!newNotification) {
  208. if(valueEncoding.data != stackValueEncoding)
  209. UA_ByteString_deleteMembers(&valueEncoding);
  210. UA_DataValue_deleteMembers(&value);
  211. }
  212. }
  213. UA_StatusCode
  214. MonitoredItem_registerSampleJob(UA_Server *server, UA_MonitoredItem *mon) {
  215. UA_Job job;
  216. job.type = UA_JOBTYPE_METHODCALL;
  217. job.job.methodCall.method = (UA_ServerCallback)UA_MoniteredItem_SampleCallback;
  218. job.job.methodCall.data = mon;
  219. UA_StatusCode retval = UA_Server_addRepeatedJob(server, job,
  220. (UA_UInt32)mon->samplingInterval,
  221. &mon->sampleJobGuid);
  222. if(retval == UA_STATUSCODE_GOOD)
  223. mon->sampleJobIsRegistered = true;
  224. return retval;
  225. }
  226. UA_StatusCode MonitoredItem_unregisterSampleJob(UA_Server *server, UA_MonitoredItem *mon) {
  227. if(!mon->sampleJobIsRegistered)
  228. return UA_STATUSCODE_GOOD;
  229. mon->sampleJobIsRegistered = false;
  230. return UA_Server_removeRepeatedJob(server, mon->sampleJobGuid);
  231. }
  232. /****************/
  233. /* Subscription */
  234. /****************/
  235. UA_Subscription * UA_Subscription_new(UA_Session *session, UA_UInt32 subscriptionID) {
  236. UA_Subscription *newItem = (UA_Subscription *)UA_malloc(sizeof(UA_Subscription));
  237. if(!newItem)
  238. return NULL;
  239. newItem->session = session;
  240. newItem->subscriptionID = subscriptionID;
  241. newItem->sequenceNumber = 0;
  242. newItem->maxKeepAliveCount = 0;
  243. newItem->publishingEnabled = false;
  244. memset(&newItem->publishJobGuid, 0, sizeof(UA_Guid));
  245. newItem->publishJobIsRegistered = false;
  246. newItem->currentKeepAliveCount = 0;
  247. newItem->currentLifetimeCount = 0;
  248. newItem->lastMonitoredItemId = 0;
  249. newItem->state = UA_SUBSCRIPTIONSTATE_NORMAL; /* The first publish response is sent immediately */
  250. LIST_INIT(&newItem->monitoredItems);
  251. TAILQ_INIT(&newItem->retransmissionQueue);
  252. newItem->retransmissionQueueSize = 0;
  253. return newItem;
  254. }
  255. void UA_Subscription_deleteMembers(UA_Subscription *subscription, UA_Server *server) {
  256. Subscription_unregisterPublishJob(server, subscription);
  257. /* Delete monitored Items */
  258. UA_MonitoredItem *mon, *tmp_mon;
  259. LIST_FOREACH_SAFE(mon, &subscription->monitoredItems, listEntry, tmp_mon) {
  260. LIST_REMOVE(mon, listEntry);
  261. MonitoredItem_delete(server, mon);
  262. }
  263. /* Delete Retransmission Queue */
  264. UA_NotificationMessageEntry *nme, *nme_tmp;
  265. TAILQ_FOREACH_SAFE(nme, &subscription->retransmissionQueue, listEntry, nme_tmp) {
  266. TAILQ_REMOVE(&subscription->retransmissionQueue, nme, listEntry);
  267. UA_NotificationMessage_deleteMembers(&nme->message);
  268. UA_free(nme);
  269. }
  270. subscription->retransmissionQueueSize = 0;
  271. }
  272. UA_MonitoredItem *
  273. UA_Subscription_getMonitoredItem(UA_Subscription *sub, UA_UInt32 monitoredItemID) {
  274. UA_MonitoredItem *mon;
  275. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  276. if(mon->itemId == monitoredItemID)
  277. break;
  278. }
  279. return mon;
  280. }
  281. UA_StatusCode
  282. UA_Subscription_deleteMonitoredItem(UA_Server *server, UA_Subscription *sub,
  283. UA_UInt32 monitoredItemID) {
  284. UA_MonitoredItem *mon;
  285. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  286. if(mon->itemId == monitoredItemID) {
  287. LIST_REMOVE(mon, listEntry);
  288. MonitoredItem_delete(server, mon);
  289. return UA_STATUSCODE_GOOD;
  290. }
  291. }
  292. return UA_STATUSCODE_BADMONITOREDITEMIDINVALID;
  293. }
  294. static size_t
  295. countQueuedNotifications(UA_Subscription *sub, UA_Boolean *moreNotifications) {
  296. size_t notifications = 0;
  297. if(sub->publishingEnabled) {
  298. UA_MonitoredItem *mon;
  299. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  300. MonitoredItem_queuedValue *qv;
  301. TAILQ_FOREACH(qv, &mon->queue, listEntry) {
  302. if(notifications >= sub->notificationsPerPublish) {
  303. *moreNotifications = true;
  304. break;
  305. }
  306. ++notifications;
  307. }
  308. }
  309. }
  310. return notifications;
  311. }
  312. static void
  313. UA_Subscription_addRetransmissionMessage(UA_Server *server, UA_Subscription *sub,
  314. UA_NotificationMessageEntry *entry) {
  315. /* Release the oldest entry if there is not enough space */
  316. if(server->config.maxRetransmissionQueueSize > 0 &&
  317. sub->retransmissionQueueSize >= server->config.maxRetransmissionQueueSize) {
  318. UA_NotificationMessageEntry *lastentry =
  319. TAILQ_LAST(&sub->retransmissionQueue,
  320. memberstruct(UA_Subscription,UA_ListOfNotificationMessages));
  321. TAILQ_REMOVE(&sub->retransmissionQueue, lastentry, listEntry);
  322. --sub->retransmissionQueueSize;
  323. UA_NotificationMessage_deleteMembers(&lastentry->message);
  324. UA_free(lastentry);
  325. }
  326. /* Add entry */
  327. TAILQ_INSERT_HEAD(&sub->retransmissionQueue, entry, listEntry);
  328. ++sub->retransmissionQueueSize;
  329. }
  330. UA_StatusCode
  331. UA_Subscription_removeRetransmissionMessage(UA_Subscription *sub, UA_UInt32 sequenceNumber) {
  332. UA_NotificationMessageEntry *entry, *entry_tmp;
  333. TAILQ_FOREACH_SAFE(entry, &sub->retransmissionQueue, listEntry, entry_tmp) {
  334. if(entry->message.sequenceNumber != sequenceNumber)
  335. continue;
  336. TAILQ_REMOVE(&sub->retransmissionQueue, entry, listEntry);
  337. --sub->retransmissionQueueSize;
  338. UA_NotificationMessage_deleteMembers(&entry->message);
  339. UA_free(entry);
  340. return UA_STATUSCODE_GOOD;
  341. }
  342. return UA_STATUSCODE_BADSEQUENCENUMBERUNKNOWN;
  343. }
  344. static UA_StatusCode
  345. prepareNotificationMessage(UA_Subscription *sub, UA_NotificationMessage *message,
  346. size_t notifications) {
  347. /* Array of ExtensionObject to hold different kinds of notifications
  348. (currently only DataChangeNotifications) */
  349. message->notificationData = UA_ExtensionObject_new();
  350. if(!message->notificationData)
  351. return UA_STATUSCODE_BADOUTOFMEMORY;
  352. message->notificationDataSize = 1;
  353. /* Allocate Notification */
  354. UA_DataChangeNotification *dcn = UA_DataChangeNotification_new();
  355. if(!dcn) {
  356. UA_NotificationMessage_deleteMembers(message);
  357. return UA_STATUSCODE_BADOUTOFMEMORY;
  358. }
  359. UA_ExtensionObject *data = message->notificationData;
  360. data->encoding = UA_EXTENSIONOBJECT_DECODED;
  361. data->content.decoded.data = dcn;
  362. data->content.decoded.type = &UA_TYPES[UA_TYPES_DATACHANGENOTIFICATION];
  363. /* Allocate array of notifications */
  364. dcn->monitoredItems = (UA_MonitoredItemNotification *)
  365. UA_Array_new(notifications, &UA_TYPES[UA_TYPES_MONITOREDITEMNOTIFICATION]);
  366. if(!dcn->monitoredItems) {
  367. UA_NotificationMessage_deleteMembers(message);
  368. return UA_STATUSCODE_BADOUTOFMEMORY;
  369. }
  370. dcn->monitoredItemsSize = notifications;
  371. /* Move notifications into the response .. the point of no return */
  372. size_t l = 0;
  373. UA_MonitoredItem *mon;
  374. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  375. MonitoredItem_queuedValue *qv, *qv_tmp;
  376. TAILQ_FOREACH_SAFE(qv, &mon->queue, listEntry, qv_tmp) {
  377. if(l >= notifications)
  378. return UA_STATUSCODE_GOOD;
  379. UA_MonitoredItemNotification *min = &dcn->monitoredItems[l];
  380. min->clientHandle = qv->clientHandle;
  381. min->value = qv->value;
  382. TAILQ_REMOVE(&mon->queue, qv, listEntry);
  383. UA_free(qv);
  384. --mon->currentQueueSize;
  385. ++l;
  386. }
  387. }
  388. return UA_STATUSCODE_GOOD;
  389. }
  390. void UA_Subscription_publishCallback(UA_Server *server, UA_Subscription *sub) {
  391. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  392. "Publish Callback", sub->subscriptionID);
  393. /* Count the available notifications */
  394. UA_Boolean moreNotifications = false;
  395. size_t notifications = countQueuedNotifications(sub, &moreNotifications);
  396. /* Return if nothing to do */
  397. if(notifications == 0) {
  398. ++sub->currentKeepAliveCount;
  399. if(sub->currentKeepAliveCount < sub->maxKeepAliveCount)
  400. return;
  401. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  402. "Subscription %u | Sending a KeepAlive",
  403. sub->subscriptionID)
  404. }
  405. /* Check if the securechannel is valid */
  406. UA_SecureChannel *channel = sub->session->channel;
  407. if(!channel)
  408. return;
  409. /* Dequeue a response */
  410. UA_PublishResponseEntry *pre = SIMPLEQ_FIRST(&sub->session->responseQueue);
  411. /* Cannot publish without a response */
  412. if(!pre) {
  413. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  414. "Subscription %u | Cannot send a publish response "
  415. "since the publish queue is empty", sub->subscriptionID)
  416. if(sub->state != UA_SUBSCRIPTIONSTATE_LATE) {
  417. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  418. } else {
  419. ++sub->currentLifetimeCount;
  420. if(sub->currentLifetimeCount > sub->lifeTimeCount) {
  421. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  422. "End of lifetime for subscription", sub->subscriptionID);
  423. UA_Session_deleteSubscription(server, sub->session, sub->subscriptionID);
  424. }
  425. }
  426. return;
  427. }
  428. UA_PublishResponse *response = &pre->response;
  429. UA_NotificationMessage *message = &response->notificationMessage;
  430. UA_NotificationMessageEntry *retransmission = NULL;
  431. if(notifications > 0) {
  432. /* Allocate the retransmission entry */
  433. retransmission = (UA_NotificationMessageEntry*)UA_malloc(sizeof(UA_NotificationMessageEntry));
  434. if(!retransmission) {
  435. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  436. "Subscription %u | Could not allocate memory "
  437. "for retransmission", sub->subscriptionID);
  438. return;
  439. }
  440. /* Prepare the response */
  441. UA_StatusCode retval =
  442. prepareNotificationMessage(sub, message, notifications);
  443. if(retval != UA_STATUSCODE_GOOD) {
  444. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  445. "Subscription %u | Could not prepare the "
  446. "notification message", sub->subscriptionID);
  447. UA_free(retransmission);
  448. return;
  449. }
  450. }
  451. /* <-- The point of no return --> */
  452. /* Remove the response from the response queue */
  453. SIMPLEQ_REMOVE_HEAD(&sub->session->responseQueue, listEntry);
  454. /* Set up the response */
  455. response->responseHeader.timestamp = UA_DateTime_now();
  456. response->subscriptionId = sub->subscriptionID;
  457. response->moreNotifications = moreNotifications;
  458. message->publishTime = response->responseHeader.timestamp;
  459. if(notifications == 0) {
  460. /* Send sequence number for the next notification */
  461. message->sequenceNumber = sub->sequenceNumber + 1;
  462. } else {
  463. /* Increase the sequence number */
  464. message->sequenceNumber = ++sub->sequenceNumber;
  465. /* Put the notification message into the retransmission queue. This needs to
  466. * be done here, so that the message itself is included in the available
  467. * sequence numbers for acknowledgement. */
  468. retransmission->message = response->notificationMessage;
  469. UA_Subscription_addRetransmissionMessage(server, sub, retransmission);
  470. }
  471. /* Get the available sequence numbers from the retransmission queue */
  472. size_t available = sub->retransmissionQueueSize;
  473. if(available > 0) {
  474. response->availableSequenceNumbers = (UA_UInt32 *)UA_alloca(available * sizeof(UA_UInt32));
  475. response->availableSequenceNumbersSize = available;
  476. size_t i = 0;
  477. UA_NotificationMessageEntry *nme;
  478. TAILQ_FOREACH(nme, &sub->retransmissionQueue, listEntry) {
  479. response->availableSequenceNumbers[i] = nme->message.sequenceNumber;
  480. ++i;
  481. }
  482. }
  483. /* Send the response */
  484. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  485. "Subscription %u | Sending out a publish response with %u "
  486. "notifications", sub->subscriptionID, (UA_UInt32)notifications);
  487. UA_SecureChannel_sendBinaryMessage(sub->session->channel, pre->requestId, response,
  488. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  489. /* Reset subscription state to normal. */
  490. sub->state = UA_SUBSCRIPTIONSTATE_NORMAL;
  491. sub->currentKeepAliveCount = 0;
  492. sub->currentLifetimeCount = 0;
  493. /* Free the response */
  494. UA_Array_delete(response->results, response->resultsSize,
  495. &UA_TYPES[UA_TYPES_UINT32]);
  496. UA_free(pre); /* no need for UA_PublishResponse_deleteMembers */
  497. /* Repeat if there are more notifications to send */
  498. if(moreNotifications)
  499. UA_Subscription_publishCallback(server, sub);
  500. }
  501. UA_StatusCode
  502. Subscription_registerPublishJob(UA_Server *server, UA_Subscription *sub) {
  503. if(sub->publishJobIsRegistered)
  504. return UA_STATUSCODE_GOOD;
  505. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  506. "Subscription %u | Register subscription publishing callback",
  507. sub->subscriptionID);
  508. UA_Job job;
  509. job.type = UA_JOBTYPE_METHODCALL;
  510. job.job.methodCall.method = (UA_ServerCallback)UA_Subscription_publishCallback;
  511. job.job.methodCall.data = sub;
  512. UA_StatusCode retval =
  513. UA_Server_addRepeatedJob(server, job, (UA_UInt32)sub->publishingInterval,
  514. &sub->publishJobGuid);
  515. if(retval == UA_STATUSCODE_GOOD)
  516. sub->publishJobIsRegistered = true;
  517. return retval;
  518. }
  519. UA_StatusCode
  520. Subscription_unregisterPublishJob(UA_Server *server, UA_Subscription *sub) {
  521. if(!sub->publishJobIsRegistered)
  522. return UA_STATUSCODE_GOOD;
  523. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  524. "Subscription %u | Unregister subscription publishing callback",
  525. sub->subscriptionID);
  526. sub->publishJobIsRegistered = false;
  527. return UA_Server_removeRepeatedJob(server, sub->publishJobGuid);
  528. }
  529. /* When the session has publish requests stored but the last subscription is
  530. deleted... Send out empty responses */
  531. void
  532. UA_Subscription_answerPublishRequestsNoSubscription(UA_Server *server, UA_NodeId *sessionToken) {
  533. /* Get session */
  534. UA_Session *session = UA_SessionManager_getSession(&server->sessionManager, sessionToken);
  535. UA_NodeId_delete(sessionToken);
  536. /* No session or there are remaining subscriptions */
  537. if(!session || LIST_FIRST(&session->serverSubscriptions))
  538. return;
  539. /* Send a response for every queued request */
  540. UA_PublishResponseEntry *pre;
  541. while((pre = SIMPLEQ_FIRST(&session->responseQueue))) {
  542. SIMPLEQ_REMOVE_HEAD(&session->responseQueue, listEntry);
  543. UA_PublishResponse *response = &pre->response;
  544. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOSUBSCRIPTION;
  545. response->responseHeader.timestamp = UA_DateTime_now();
  546. UA_SecureChannel_sendBinaryMessage(session->channel, pre->requestId, response,
  547. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  548. UA_PublishResponse_deleteMembers(response);
  549. UA_free(pre);
  550. }
  551. }
  552. #endif /* UA_ENABLE_SUBSCRIPTIONS */