server_multicast.c 16 KB

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