server_multicast.c 16 KB

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