server_multicast.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. /*
  4. * A simple server instance which registers with the discovery server.
  5. * Compared to server_register.c this example waits until the LDS server announces
  6. * itself through mDNS. Therefore the LDS server needs to support multicast extension
  7. * (i.e., LDS-ME).
  8. */
  9. #include <ua_server.h>
  10. #include <ua_config_default.h>
  11. #include <ua_types.h>
  12. #include <ua_log_stdout.h>
  13. #include <ua_securitypolicies.h>
  14. #include <signal.h>
  15. UA_Boolean running = true;
  16. const UA_ByteString UA_SECURITY_POLICY_BASIC128_URI =
  17. {56, (UA_Byte *)"http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15"};
  18. static void stopHandler(int sign) {
  19. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  20. running = false;
  21. }
  22. static UA_StatusCode
  23. readInteger(UA_Server *server, const UA_NodeId *sessionId,
  24. void *sessionContext, const UA_NodeId *nodeId,
  25. void *nodeContext, UA_Boolean includeSourceTimeStamp,
  26. const UA_NumericRange *range, UA_DataValue *value) {
  27. UA_Int32 *myInteger = (UA_Int32*)nodeContext;
  28. value->hasValue = true;
  29. UA_Variant_setScalarCopy(&value->value, myInteger, &UA_TYPES[UA_TYPES_INT32]);
  30. // we know the nodeid is a string
  31. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Node read %.*s",
  32. (int)nodeId->identifier.string.length,
  33. nodeId->identifier.string.data);
  34. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  35. "read value %i", *(UA_UInt32 *)myInteger);
  36. return UA_STATUSCODE_GOOD;
  37. }
  38. static UA_StatusCode
  39. writeInteger(UA_Server *server, const UA_NodeId *sessionId,
  40. void *sessionContext, const UA_NodeId *nodeId,
  41. void *nodeContext, const UA_NumericRange *range,
  42. const UA_DataValue *value) {
  43. UA_Int32 *myInteger = (UA_Int32*)nodeContext;
  44. if(value->hasValue && UA_Variant_isScalar(&value->value) &&
  45. value->value.type == &UA_TYPES[UA_TYPES_INT32] && value->value.data)
  46. *myInteger = *(UA_Int32 *)value->value.data;
  47. // we know the nodeid is a string
  48. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Node written %.*s",
  49. (int)nodeId->identifier.string.length,
  50. nodeId->identifier.string.data);
  51. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  52. "written value %i", *(UA_UInt32 *)myInteger);
  53. return UA_STATUSCODE_GOOD;
  54. }
  55. char *discovery_url = NULL;
  56. static void
  57. serverOnNetworkCallback(const UA_ServerOnNetwork *serverOnNetwork, UA_Boolean isServerAnnounce,
  58. UA_Boolean isTxtReceived, void *data) {
  59. if(discovery_url != NULL || !isServerAnnounce) {
  60. UA_LOG_DEBUG(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  61. "serverOnNetworkCallback called, but discovery URL "
  62. "already initialized or is not announcing. Ignoring.");
  63. return; // we already have everything we need or we only want server announces
  64. }
  65. if(!isTxtReceived)
  66. return; // we wait until the corresponding TXT record is announced.
  67. // Problem: how to handle if a Server does not announce the
  68. // optional TXT?
  69. // here you can filter for a specific LDS server, e.g. call FindServers on
  70. // the serverOnNetwork to make sure you are registering with the correct
  71. // LDS. We will ignore this for now
  72. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "Another server announced itself on %.*s",
  73. (int)serverOnNetwork->discoveryUrl.length, serverOnNetwork->discoveryUrl.data);
  74. if(discovery_url != NULL)
  75. UA_free(discovery_url);
  76. discovery_url = (char*)UA_malloc(serverOnNetwork->discoveryUrl.length + 1);
  77. memcpy(discovery_url, serverOnNetwork->discoveryUrl.data, serverOnNetwork->discoveryUrl.length);
  78. discovery_url[serverOnNetwork->discoveryUrl.length] = 0;
  79. }
  80. /*
  81. * Get the endpoint from the server, where we can call RegisterServer2 (or RegisterServer).
  82. * This is normally the endpoint with highest supported encryption mode.
  83. *
  84. * @param discoveryServerUrl The discovery url from the remote server
  85. * @return The endpoint description (which needs to be freed) or NULL
  86. */
  87. static
  88. UA_EndpointDescription *getRegisterEndpointFromServer(const char *discoveryServerUrl) {
  89. UA_Client *client = UA_Client_new(UA_ClientConfig_default);
  90. UA_EndpointDescription *endpointArray = NULL;
  91. size_t endpointArraySize = 0;
  92. UA_StatusCode retval = UA_Client_getEndpoints(client, discoveryServerUrl,
  93. &endpointArraySize, &endpointArray);
  94. if (retval != UA_STATUSCODE_GOOD) {
  95. UA_Array_delete(endpointArray, endpointArraySize,
  96. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  97. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  98. "GetEndpoints failed with %s", UA_StatusCode_name(retval));
  99. UA_Client_delete(client);
  100. return NULL;
  101. }
  102. UA_LOG_DEBUG(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "Server has %lu endpoints", (unsigned long)endpointArraySize);
  103. UA_EndpointDescription *foundEndpoint = NULL;
  104. for (size_t i = 0; i < endpointArraySize; i++) {
  105. UA_LOG_DEBUG(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "\tURL = %.*s, SecurityMode = %s",
  106. (int) endpointArray[i].endpointUrl.length,
  107. endpointArray[i].endpointUrl.data,
  108. endpointArray[i].securityMode == UA_MESSAGESECURITYMODE_NONE ? "None" :
  109. endpointArray[i].securityMode == UA_MESSAGESECURITYMODE_SIGN ? "Sign" :
  110. endpointArray[i].securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ? "SignAndEncrypt" :
  111. "Invalid"
  112. );
  113. // find the endpoint with highest supported security mode
  114. if ((UA_String_equal(&endpointArray[i].securityPolicyUri, &UA_SECURITY_POLICY_NONE_URI) ||
  115. UA_String_equal(&endpointArray[i].securityPolicyUri, &UA_SECURITY_POLICY_BASIC128_URI)) && (
  116. foundEndpoint == NULL || foundEndpoint->securityMode < endpointArray[i].securityMode))
  117. foundEndpoint = &endpointArray[i];
  118. }
  119. UA_EndpointDescription *returnEndpoint = NULL;
  120. if (foundEndpoint != NULL) {
  121. returnEndpoint = UA_EndpointDescription_new();
  122. UA_EndpointDescription_copy(foundEndpoint, returnEndpoint);
  123. }
  124. UA_Array_delete(endpointArray, endpointArraySize,
  125. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  126. return returnEndpoint;
  127. }
  128. #ifdef UA_ENABLE_ENCRYPTION
  129. /* loadFile parses the certificate file.
  130. *
  131. * @param path specifies the file name given in argv[]
  132. * @return Returns the file content after parsing */
  133. static UA_ByteString loadFile(const char *const path) {
  134. UA_ByteString fileContents = UA_BYTESTRING_NULL;
  135. if (path == NULL)
  136. return fileContents;
  137. /* Open the file */
  138. FILE *fp = fopen(path, "rb");
  139. if (!fp) {
  140. errno = 0; /* We read errno also from the tcp layer */
  141. return fileContents;
  142. }
  143. /* Get the file length, allocate the data and read */
  144. fseek(fp, 0, SEEK_END);
  145. fileContents.length = (size_t) ftell(fp);
  146. fileContents.data = (UA_Byte *) UA_malloc(fileContents.length * sizeof(UA_Byte));
  147. if (fileContents.data) {
  148. fseek(fp, 0, SEEK_SET);
  149. size_t read = fread(fileContents.data, sizeof(UA_Byte), fileContents.length, fp);
  150. if (read != fileContents.length)
  151. UA_ByteString_clear(&fileContents);
  152. } else {
  153. fileContents.length = 0;
  154. }
  155. fclose(fp);
  156. return fileContents;
  157. }
  158. #endif
  159. /**
  160. * Initialize a client instance which is used for calling the registerServer service.
  161. * If the given endpoint has securityMode NONE, a client with default configuration
  162. * is returned.
  163. * If it is using SignAndEncrypt, the client certificates must be provided as a
  164. * command line argument and then the client is initialized using these certificates.
  165. * @param endpointRegister The remote endpoint where this server should register
  166. * @param argc from the main method
  167. * @param argv from the main method
  168. * @return NULL or the initialized non-connected client
  169. */
  170. static
  171. UA_Client *getRegisterClient(UA_EndpointDescription *endpointRegister, int argc, char **argv) {
  172. if (endpointRegister->securityMode == UA_MESSAGESECURITYMODE_NONE) {
  173. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "Using LDS endpoint with security None");
  174. return UA_Client_new(UA_ClientConfig_default);
  175. }
  176. #ifdef UA_ENABLE_ENCRYPTION
  177. if (endpointRegister->securityMode == UA_MESSAGESECURITYMODE_SIGN) {
  178. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  179. "LDS endpoint which only supports Sign is currently not supported");
  180. return NULL;
  181. }
  182. UA_Client *clientRegister;
  183. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  184. "Using LDS endpoint with security SignAndEncrypt");
  185. UA_ByteString certificate = UA_BYTESTRING_NULL;
  186. UA_ByteString privateKey = UA_BYTESTRING_NULL;
  187. UA_ByteString *trustList = NULL;
  188. size_t trustListSize = 0;
  189. UA_ByteString *revocationList = NULL;
  190. size_t revocationListSize = 0;
  191. if (argc < 3) {
  192. UA_LOG_FATAL(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  193. "The Certificate and key is missing."
  194. "The required arguments are "
  195. "<client-certificate.der> <client-private-key.der> "
  196. "[<trustlist1.crl>, ...]");
  197. return NULL;
  198. }
  199. certificate = loadFile(argv[1]);
  200. privateKey = loadFile(argv[2]);
  201. /* Load the trustList. Load revocationList is not supported now */
  202. if (argc > 3) {
  203. trustListSize = (size_t) argc - 3;
  204. UA_StatusCode retval = UA_ByteString_allocBuffer(trustList, trustListSize);
  205. if (retval != UA_STATUSCODE_GOOD) {
  206. UA_ByteString_clear(&certificate);
  207. UA_ByteString_clear(&privateKey);
  208. return NULL;
  209. }
  210. for (size_t trustListCount = 0; trustListCount < trustListSize; trustListCount++) {
  211. trustList[trustListCount] = loadFile(argv[trustListCount + 3]);
  212. }
  213. }
  214. /* Secure client initialization */
  215. clientRegister = UA_Client_secure_new(UA_ClientConfig_default,
  216. certificate, privateKey,
  217. &endpointRegister->serverCertificate,
  218. trustList, trustListSize,
  219. revocationList, revocationListSize,
  220. UA_SecurityPolicy_Basic128Rsa15);
  221. UA_ByteString_clear(&certificate);
  222. UA_ByteString_clear(&privateKey);
  223. for (size_t deleteCount = 0; deleteCount < trustListSize; deleteCount++) {
  224. UA_ByteString_clear(&trustList[deleteCount]);
  225. }
  226. return clientRegister;
  227. #else
  228. return NULL;
  229. #endif
  230. }
  231. int main(int argc, char **argv) {
  232. signal(SIGINT, stopHandler); /* catches ctrl-c */
  233. signal(SIGTERM, stopHandler);
  234. UA_ServerConfig *config = UA_ServerConfig_new_minimal(16600, NULL);
  235. // To enable mDNS discovery, set application type to discovery server.
  236. config->applicationDescription.applicationType = UA_APPLICATIONTYPE_DISCOVERYSERVER;
  237. UA_String_clear(&config->applicationDescription.applicationUri);
  238. config->applicationDescription.applicationUri =
  239. UA_String_fromChars("urn:open62541.example.server_multicast");
  240. config->mdnsServerName = UA_String_fromChars("Sample Multicast Server");
  241. // See http://www.opcfoundation.org/UA/schemas/1.03/ServerCapabilities.csv
  242. //config.serverCapabilitiesSize = 1;
  243. //UA_String caps = UA_String_fromChars("LDS");
  244. //config.serverCapabilities = &caps;
  245. UA_Server *server = UA_Server_new(config);
  246. /* add a variable node to the address space */
  247. UA_Int32 myInteger = 42;
  248. UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  249. UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  250. UA_DataSource dateDataSource;
  251. dateDataSource.read = readInteger;
  252. dateDataSource.write = writeInteger;
  253. UA_VariableAttributes attr = UA_VariableAttributes_default;
  254. attr.description = UA_LOCALIZEDTEXT("en-US", "the answer");
  255. attr.displayName = UA_LOCALIZEDTEXT("en-US", "the answer");
  256. UA_Server_addDataSourceVariableNode(server, myIntegerNodeId,
  257. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  258. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  259. myIntegerName, UA_NODEID_NULL, attr, dateDataSource,
  260. &myInteger, NULL);
  261. // callback which is called when a new server is detected through mDNS
  262. UA_Server_setServerOnNetworkCallback(server, serverOnNetworkCallback, NULL);
  263. // Start the server and call iterate to wait for the multicast discovery of the LDS
  264. UA_StatusCode retval = UA_Server_run_startup(server);
  265. if(retval != UA_STATUSCODE_GOOD) {
  266. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  267. "Could not start the server. StatusCode %s",
  268. UA_StatusCode_name(retval));
  269. UA_Server_delete(server);
  270. UA_ServerConfig_delete(config);
  271. UA_free(discovery_url);
  272. return 1;
  273. }
  274. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  275. "Server started. Waiting for announce of LDS Server.");
  276. while (running && discovery_url == NULL)
  277. UA_Server_run_iterate(server, true);
  278. if(!running) {
  279. UA_Server_delete(server);
  280. UA_ServerConfig_delete(config);
  281. UA_free(discovery_url);
  282. return 1;
  283. }
  284. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "LDS-ME server found on %s", discovery_url);
  285. /* Check if the server supports sign and encrypt. OPC Foundation LDS requires an encrypted session for
  286. * RegisterServer call, our server currently uses encrpytion optionally */
  287. UA_EndpointDescription *endpointRegister = getRegisterEndpointFromServer(discovery_url);
  288. UA_free(discovery_url);
  289. if (endpointRegister == NULL || endpointRegister->securityMode == UA_MESSAGESECURITYMODE_INVALID) {
  290. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  291. "Could not find any suitable endpoints on discovery server");
  292. UA_Server_delete(server);
  293. UA_ServerConfig_delete(config);
  294. return 1;
  295. }
  296. UA_Client *clientRegister = getRegisterClient(endpointRegister, argc, argv);
  297. if (!clientRegister) {
  298. UA_LOG_FATAL(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  299. "Could not create the client for remote registering");
  300. UA_Server_delete(server);
  301. UA_ServerConfig_delete(config);
  302. return 1;
  303. }
  304. /* Connect the client */
  305. char *endpointUrl = (char*)UA_malloc(endpointRegister->endpointUrl.length + 1);
  306. memcpy(endpointUrl, endpointRegister->endpointUrl.data, endpointRegister->endpointUrl.length);
  307. endpointUrl[endpointRegister->endpointUrl.length] = 0;
  308. retval = UA_Server_addPeriodicServerRegisterCallback(server, clientRegister, endpointUrl,
  309. 10 * 60 * 1000, 500, NULL);
  310. if(retval != UA_STATUSCODE_GOOD) {
  311. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  312. "Could not create periodic job for server register. StatusCode %s",
  313. UA_StatusCode_name(retval));
  314. UA_free(endpointUrl);
  315. UA_Client_disconnect(clientRegister);
  316. UA_Client_delete(clientRegister);
  317. UA_Server_delete(server);
  318. UA_ServerConfig_delete(config);
  319. return 1;
  320. }
  321. while (running)
  322. UA_Server_run_iterate(server, true);
  323. UA_Server_run_shutdown(server);
  324. // UNregister the server from the discovery server.
  325. retval = UA_Server_unregister_discovery(server, clientRegister);
  326. if (retval != UA_STATUSCODE_GOOD)
  327. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  328. "Could not unregister server from discovery server. "
  329. "StatusCode %s", UA_StatusCode_name(retval));
  330. UA_free(endpointUrl);
  331. UA_Client_disconnect(clientRegister);
  332. UA_Client_delete(clientRegister);
  333. UA_Server_delete(server);
  334. UA_ServerConfig_delete(config);
  335. return (int)retval;
  336. }