ua_services_subscription.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2016-2017 (c) Florian Palm
  7. * Copyright 2015 (c) Chris Iatrou
  8. * Copyright 2015-2016 (c) Sten Grüner
  9. * Copyright 2015-2016 (c) Oleksiy Vasylyev
  10. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  11. * Copyright 2018 (c) Ari Breitkreuz, fortiss GmbH
  12. * Copyright 2017 (c) Mattias Bornhager
  13. * Copyright 2017 (c) Henrik Norrman
  14. * Copyright 2017-2018 (c) Thomas Stalder, Blue Time Concept SA
  15. * Copyright 2018 (c) Fabian Arndt, Root-Core
  16. */
  17. #include "ua_server_internal.h"
  18. #include "ua_services.h"
  19. #include "ua_subscription.h"
  20. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  21. static UA_StatusCode
  22. setSubscriptionSettings(UA_Server *server, UA_Subscription *subscription,
  23. UA_Double requestedPublishingInterval,
  24. UA_UInt32 requestedLifetimeCount,
  25. UA_UInt32 requestedMaxKeepAliveCount,
  26. UA_UInt32 maxNotificationsPerPublish, UA_Byte priority) {
  27. /* deregister the callback if required */
  28. Subscription_unregisterPublishCallback(server, subscription);
  29. /* re-parameterize the subscription */
  30. UA_BOUNDEDVALUE_SETWBOUNDS(server->config.publishingIntervalLimits,
  31. requestedPublishingInterval, subscription->publishingInterval);
  32. /* check for nan*/
  33. if(requestedPublishingInterval != requestedPublishingInterval)
  34. subscription->publishingInterval = server->config.publishingIntervalLimits.min;
  35. UA_BOUNDEDVALUE_SETWBOUNDS(server->config.keepAliveCountLimits,
  36. requestedMaxKeepAliveCount, subscription->maxKeepAliveCount);
  37. UA_BOUNDEDVALUE_SETWBOUNDS(server->config.lifeTimeCountLimits,
  38. requestedLifetimeCount, subscription->lifeTimeCount);
  39. if(subscription->lifeTimeCount < 3 * subscription->maxKeepAliveCount)
  40. subscription->lifeTimeCount = 3 * subscription->maxKeepAliveCount;
  41. subscription->notificationsPerPublish = maxNotificationsPerPublish;
  42. if(maxNotificationsPerPublish == 0 ||
  43. maxNotificationsPerPublish > server->config.maxNotificationsPerPublish)
  44. subscription->notificationsPerPublish = server->config.maxNotificationsPerPublish;
  45. subscription->priority = priority;
  46. UA_StatusCode retval = Subscription_registerPublishCallback(server, subscription);
  47. if(retval != UA_STATUSCODE_GOOD) {
  48. UA_LOG_DEBUG_SESSION(&server->config.logger, subscription->session,
  49. "Subscription %u | Could not register publish callback with error code %s",
  50. subscription->subscriptionId, UA_StatusCode_name(retval));
  51. }
  52. return retval;
  53. }
  54. void
  55. Service_CreateSubscription(UA_Server *server, UA_Session *session,
  56. const UA_CreateSubscriptionRequest *request,
  57. UA_CreateSubscriptionResponse *response) {
  58. /* Check limits for the number of subscriptions */
  59. if(((server->config.maxSubscriptions != 0) &&
  60. (server->numSubscriptions >= server->config.maxSubscriptions)) ||
  61. ((server->config.maxSubscriptionsPerSession != 0) &&
  62. (session->numSubscriptions >= server->config.maxSubscriptionsPerSession))) {
  63. response->responseHeader.serviceResult = UA_STATUSCODE_BADTOOMANYSUBSCRIPTIONS;
  64. return;
  65. }
  66. /* Create the subscription */
  67. UA_Subscription *newSubscription = UA_Subscription_new(session, response->subscriptionId);
  68. if(!newSubscription) {
  69. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  70. "Processing CreateSubscriptionRequest failed");
  71. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  72. return;
  73. }
  74. UA_Session_addSubscription(server, session, newSubscription); /* Also assigns the subscription id */
  75. /* Set the subscription parameters */
  76. newSubscription->publishingEnabled = request->publishingEnabled;
  77. UA_StatusCode retval = setSubscriptionSettings(server, newSubscription, request->requestedPublishingInterval,
  78. request->requestedLifetimeCount, request->requestedMaxKeepAliveCount,
  79. request->maxNotificationsPerPublish, request->priority);
  80. if(retval != UA_STATUSCODE_GOOD) {
  81. response->responseHeader.serviceResult = retval;
  82. return;
  83. }
  84. newSubscription->currentKeepAliveCount = newSubscription->maxKeepAliveCount; /* set settings first */
  85. /* Prepare the response */
  86. response->subscriptionId = newSubscription->subscriptionId;
  87. response->revisedPublishingInterval = newSubscription->publishingInterval;
  88. response->revisedLifetimeCount = newSubscription->lifeTimeCount;
  89. response->revisedMaxKeepAliveCount = newSubscription->maxKeepAliveCount;
  90. UA_LOG_INFO_SESSION(&server->config.logger, session, "Subscription %u | "
  91. "Created the Subscription with a publishing interval of %.2f ms",
  92. response->subscriptionId, newSubscription->publishingInterval);
  93. }
  94. void
  95. Service_ModifySubscription(UA_Server *server, UA_Session *session,
  96. const UA_ModifySubscriptionRequest *request,
  97. UA_ModifySubscriptionResponse *response) {
  98. UA_LOG_DEBUG_SESSION(&server->config.logger, session, "Processing ModifySubscriptionRequest");
  99. UA_Subscription *sub = UA_Session_getSubscriptionById(session, request->subscriptionId);
  100. if(!sub) {
  101. response->responseHeader.serviceResult = UA_STATUSCODE_BADSUBSCRIPTIONIDINVALID;
  102. return;
  103. }
  104. UA_StatusCode retval = setSubscriptionSettings(server, sub, request->requestedPublishingInterval,
  105. request->requestedLifetimeCount, request->requestedMaxKeepAliveCount,
  106. request->maxNotificationsPerPublish, request->priority);
  107. if(retval != UA_STATUSCODE_GOOD) {
  108. response->responseHeader.serviceResult = retval;
  109. return;
  110. }
  111. sub->currentLifetimeCount = 0; /* Reset the subscription lifetime */
  112. response->revisedPublishingInterval = sub->publishingInterval;
  113. response->revisedLifetimeCount = sub->lifeTimeCount;
  114. response->revisedMaxKeepAliveCount = sub->maxKeepAliveCount;
  115. }
  116. static void
  117. Operation_SetPublishingMode(UA_Server *Server, UA_Session *session,
  118. const UA_Boolean *publishingEnabled, const UA_UInt32 *subscriptionId,
  119. UA_StatusCode *result) {
  120. UA_Subscription *sub = UA_Session_getSubscriptionById(session, *subscriptionId);
  121. if(!sub) {
  122. *result = UA_STATUSCODE_BADSUBSCRIPTIONIDINVALID;
  123. return;
  124. }
  125. sub->currentLifetimeCount = 0; /* Reset the subscription lifetime */
  126. sub->publishingEnabled = *publishingEnabled; /* Set the publishing mode */
  127. }
  128. void
  129. Service_SetPublishingMode(UA_Server *server, UA_Session *session,
  130. const UA_SetPublishingModeRequest *request,
  131. UA_SetPublishingModeResponse *response) {
  132. UA_LOG_DEBUG_SESSION(&server->config.logger, session, "Processing SetPublishingModeRequest");
  133. UA_Boolean publishingEnabled = request->publishingEnabled; /* request is const */
  134. response->responseHeader.serviceResult =
  135. UA_Server_processServiceOperations(server, session, (UA_ServiceOperation)Operation_SetPublishingMode,
  136. &publishingEnabled,
  137. &request->subscriptionIdsSize, &UA_TYPES[UA_TYPES_UINT32],
  138. &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);
  139. }
  140. /* TODO: Unify with senderror in ua_server_binary.c */
  141. static void
  142. subscriptionSendError(UA_SecureChannel *channel, UA_UInt32 requestHandle,
  143. UA_UInt32 requestId, UA_StatusCode error) {
  144. UA_PublishResponse err_response;
  145. UA_PublishResponse_init(&err_response);
  146. err_response.responseHeader.requestHandle = requestHandle;
  147. err_response.responseHeader.timestamp = UA_DateTime_now();
  148. err_response.responseHeader.serviceResult = error;
  149. UA_SecureChannel_sendSymmetricMessage(channel, requestId, UA_MESSAGETYPE_MSG,
  150. &err_response, &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  151. }
  152. void
  153. Service_Publish(UA_Server *server, UA_Session *session,
  154. const UA_PublishRequest *request, UA_UInt32 requestId) {
  155. UA_LOG_DEBUG_SESSION(&server->config.logger, session, "Processing PublishRequest");
  156. /* Return an error if the session has no subscription */
  157. if(LIST_EMPTY(&session->serverSubscriptions)) {
  158. subscriptionSendError(session->header.channel, request->requestHeader.requestHandle,
  159. requestId, UA_STATUSCODE_BADNOSUBSCRIPTION);
  160. return;
  161. }
  162. /* Handle too many subscriptions to free resources before trying to allocate
  163. * resources for the new publish request. If the limit has been reached the
  164. * oldest publish request shall be responded */
  165. if((server->config.maxPublishReqPerSession != 0) &&
  166. (session->numPublishReq >= server->config.maxPublishReqPerSession)) {
  167. if(!UA_Subscription_reachedPublishReqLimit(server, session)) {
  168. subscriptionSendError(session->header.channel, requestId,
  169. request->requestHeader.requestHandle,
  170. UA_STATUSCODE_BADINTERNALERROR);
  171. return;
  172. }
  173. }
  174. /* Allocate the response to store it in the retransmission queue */
  175. UA_PublishResponseEntry *entry = (UA_PublishResponseEntry *)
  176. UA_malloc(sizeof(UA_PublishResponseEntry));
  177. if(!entry) {
  178. subscriptionSendError(session->header.channel, requestId,
  179. request->requestHeader.requestHandle,
  180. UA_STATUSCODE_BADOUTOFMEMORY);
  181. return;
  182. }
  183. /* Prepare the response */
  184. entry->requestId = requestId;
  185. UA_PublishResponse *response = &entry->response;
  186. UA_PublishResponse_init(response);
  187. response->responseHeader.requestHandle = request->requestHeader.requestHandle;
  188. /* Allocate the results array to acknowledge the acknowledge */
  189. if(request->subscriptionAcknowledgementsSize > 0) {
  190. response->results = (UA_StatusCode *)
  191. UA_Array_new(request->subscriptionAcknowledgementsSize,
  192. &UA_TYPES[UA_TYPES_STATUSCODE]);
  193. if(!response->results) {
  194. UA_free(entry);
  195. subscriptionSendError(session->header.channel, requestId,
  196. request->requestHeader.requestHandle,
  197. UA_STATUSCODE_BADOUTOFMEMORY);
  198. return;
  199. }
  200. response->resultsSize = request->subscriptionAcknowledgementsSize;
  201. }
  202. /* Delete Acknowledged Subscription Messages */
  203. for(size_t i = 0; i < request->subscriptionAcknowledgementsSize; ++i) {
  204. UA_SubscriptionAcknowledgement *ack = &request->subscriptionAcknowledgements[i];
  205. UA_Subscription *sub = UA_Session_getSubscriptionById(session, ack->subscriptionId);
  206. if(!sub) {
  207. response->results[i] = UA_STATUSCODE_BADSUBSCRIPTIONIDINVALID;
  208. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  209. "Cannot process acknowledgements subscription %u",
  210. ack->subscriptionId);
  211. continue;
  212. }
  213. /* Remove the acked transmission from the retransmission queue */
  214. response->results[i] = UA_Subscription_removeRetransmissionMessage(sub, ack->sequenceNumber);
  215. }
  216. /* Queue the publish response. It will be dequeued in a repeated publish
  217. * callback. This can also be triggered right now for a late
  218. * subscription. */
  219. UA_Session_queuePublishReq(session, entry, false);
  220. UA_LOG_DEBUG_SESSION(&server->config.logger, session, "Queued a publication message");
  221. /* If there are late subscriptions, the new publish request is used to
  222. * answer them immediately. However, a single subscription that generates
  223. * many notifications must not "starve" other late subscriptions. Therefore
  224. * we keep track of the last subscription that got preferential treatment.
  225. * We start searching for late subscriptions **after** the last one. */
  226. UA_Subscription *immediate = NULL;
  227. if(session->lastSeenSubscriptionId > 0) {
  228. LIST_FOREACH(immediate, &session->serverSubscriptions, listEntry) {
  229. if(immediate->subscriptionId == session->lastSeenSubscriptionId) {
  230. immediate = LIST_NEXT(immediate, listEntry);
  231. break;
  232. }
  233. }
  234. }
  235. /* If no entry was found, start at the beginning and don't restart */
  236. UA_Boolean found = false;
  237. if(!immediate)
  238. immediate = LIST_FIRST(&session->serverSubscriptions);
  239. else
  240. found = true;
  241. repeat:
  242. while(immediate) {
  243. if(immediate->state == UA_SUBSCRIPTIONSTATE_LATE) {
  244. session->lastSeenSubscriptionId = immediate->subscriptionId;
  245. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  246. "Subscription %u | Response on a late subscription",
  247. immediate->subscriptionId);
  248. UA_Subscription_publish(server, immediate);
  249. return;
  250. }
  251. immediate = LIST_NEXT(immediate, listEntry);
  252. }
  253. /* Restart at the beginning of the list */
  254. if(found) {
  255. immediate = LIST_FIRST(&session->serverSubscriptions);
  256. found = false;
  257. goto repeat;
  258. }
  259. /* No late subscription this time */
  260. session->lastSeenSubscriptionId = 0;
  261. }
  262. static void
  263. Operation_DeleteSubscription(UA_Server *server, UA_Session *session, void *_,
  264. const UA_UInt32 *subscriptionId, UA_StatusCode *result) {
  265. *result = UA_Session_deleteSubscription(server, session, *subscriptionId);
  266. if(*result == UA_STATUSCODE_GOOD) {
  267. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  268. "Subscription %u | Subscription deleted",
  269. *subscriptionId);
  270. } else {
  271. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  272. "Deleting Subscription with Id %u failed with error code %s",
  273. *subscriptionId, UA_StatusCode_name(*result));
  274. }
  275. }
  276. void
  277. Service_DeleteSubscriptions(UA_Server *server, UA_Session *session,
  278. const UA_DeleteSubscriptionsRequest *request,
  279. UA_DeleteSubscriptionsResponse *response) {
  280. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  281. "Processing DeleteSubscriptionsRequest");
  282. response->responseHeader.serviceResult =
  283. UA_Server_processServiceOperations(server, session,
  284. (UA_ServiceOperation)Operation_DeleteSubscription, NULL,
  285. &request->subscriptionIdsSize, &UA_TYPES[UA_TYPES_UINT32],
  286. &response->resultsSize, &UA_TYPES[UA_TYPES_STATUSCODE]);
  287. /* The session has at least one subscription */
  288. if(LIST_FIRST(&session->serverSubscriptions))
  289. return;
  290. /* Send remaining publish responses if the last subscription was removed */
  291. UA_Subscription_answerPublishRequestsNoSubscription(server, session);
  292. }
  293. void
  294. Service_Republish(UA_Server *server, UA_Session *session,
  295. const UA_RepublishRequest *request,
  296. UA_RepublishResponse *response) {
  297. UA_LOG_DEBUG_SESSION(&server->config.logger, session,
  298. "Processing RepublishRequest");
  299. /* Get the subscription */
  300. UA_Subscription *sub = UA_Session_getSubscriptionById(session, request->subscriptionId);
  301. if(!sub) {
  302. response->responseHeader.serviceResult = UA_STATUSCODE_BADSUBSCRIPTIONIDINVALID;
  303. return;
  304. }
  305. /* Reset the subscription lifetime */
  306. sub->currentLifetimeCount = 0;
  307. /* Find the notification in the retransmission queue */
  308. UA_NotificationMessageEntry *entry;
  309. TAILQ_FOREACH(entry, &sub->retransmissionQueue, listEntry) {
  310. if(entry->message.sequenceNumber == request->retransmitSequenceNumber)
  311. break;
  312. }
  313. if(!entry) {
  314. response->responseHeader.serviceResult = UA_STATUSCODE_BADMESSAGENOTAVAILABLE;
  315. return;
  316. }
  317. response->responseHeader.serviceResult =
  318. UA_NotificationMessage_copy(&entry->message, &response->notificationMessage);
  319. }
  320. #endif /* UA_ENABLE_SUBSCRIPTIONS */