server_certificate.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #ifdef _MSC_VER
  4. #define _CRT_SECURE_NO_WARNINGS //disable fopen deprication warning in msvs
  5. #endif
  6. #ifdef UA_NO_AMALGAMATION
  7. #include "ua_types.h"
  8. #include "ua_server.h"
  9. #include "ua_config_standard.h"
  10. #include "ua_network_tcp.h"
  11. #include "ua_log_stdout.h"
  12. #else
  13. #include "open62541.h"
  14. #endif
  15. #include <errno.h> // errno, EINTR
  16. #include <stdio.h>
  17. #include <signal.h>
  18. #include <stdlib.h>
  19. UA_Boolean running = true;
  20. UA_Logger logger = UA_Log_Stdout;
  21. static UA_ByteString loadCertificate(void) {
  22. UA_ByteString certificate = UA_STRING_NULL;
  23. FILE *fp = NULL;
  24. //FIXME: a potiential bug of locating the certificate, we need to get the path from the server's config
  25. fp=fopen("server_cert.der", "rb");
  26. if(!fp) {
  27. errno = 0; // we read errno also from the tcp layer...
  28. UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER, "Could not open certificate file");
  29. return certificate;
  30. }
  31. fseek(fp, 0, SEEK_END);
  32. certificate.length = (size_t)ftell(fp);
  33. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  34. if(!certificate.data)
  35. return certificate;
  36. fseek(fp, 0, SEEK_SET);
  37. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  38. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  39. fclose(fp);
  40. return certificate;
  41. }
  42. static void stopHandler(int sign) {
  43. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  44. running = false;
  45. }
  46. int main(int argc, char** argv) {
  47. signal(SIGINT, stopHandler); /* catches ctrl-c */
  48. UA_ServerConfig config = UA_ServerConfig_standard;
  49. UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664);
  50. config.networkLayers = &nl;
  51. config.networkLayersSize = 1;
  52. /* load certificate */
  53. config.serverCertificate = loadCertificate();
  54. if(config.serverCertificate.length > 0)
  55. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Certificate loaded");
  56. UA_Server *server = UA_Server_new(config);
  57. UA_StatusCode retval = UA_Server_run(server, &running);
  58. /* deallocate certificate's memory */
  59. UA_ByteString_deleteMembers(&config.serverCertificate);
  60. UA_Server_delete(server);
  61. nl.deleteMembers(&nl);
  62. return (int)retval;
  63. }