ua_subscription.c 24 KB

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