Coverage Report

Created: 2026-07-16 06:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541/include/open62541/server.h
Line
Count
Source
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-2025 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
6
 *    Copyright 2015-2016 (c) Sten GrĂ¼ner
7
 *    Copyright 2014-2015, 2017 (c) Florian Palm
8
 *    Copyright 2015-2016 (c) Chris Iatrou
9
 *    Copyright 2015-2016 (c) Oleksiy Vasylyev
10
 *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
11
 *    Copyright 2017 (c) Henrik Norrman
12
 *    Copyright 2018 (c) Fabian Arndt, Root-Core
13
 *    Copyright 2017-2020 (c) HMS Industrial Networks AB (Author: Jonas Green)
14
 *    Copyright 2020-2022 (c) Christian von Arnim, ISW University of Stuttgart  (for VDW and umati)
15
 *    Copyright 2025 (c) o6 Automation GmbH (Author: Julius Pfrommer)
16
 *    Copyright 2025-2026 (c) o6 Automation GmbH (Author: Andreas Ebner)
17
 */
18
19
#ifndef UA_SERVER_H_
20
#define UA_SERVER_H_
21
22
#include <open62541/common.h>
23
#include <open62541/util.h>
24
#include <open62541/types.h>
25
#ifdef UA_ENABLE_DISCOVERY
26
#include <open62541/client.h>
27
#endif
28
29
#include <open62541/plugin/log.h>
30
#include <open62541/plugin/certificategroup.h>
31
#include <open62541/plugin/eventloop.h>
32
#include <open62541/plugin/accesscontrol.h>
33
#include <open62541/plugin/securitypolicy.h>
34
35
#ifdef UA_ENABLE_HISTORIZING
36
#include <open62541/plugin/historydatabase.h>
37
#endif
38
39
#ifdef UA_ENABLE_PUBSUB
40
#include <open62541/server_pubsub.h>
41
#endif
42
43
/* Forward Declarations */
44
struct UA_Nodestore;
45
typedef struct UA_Nodestore UA_Nodestore;
46
47
struct UA_ServerConfig;
48
typedef struct UA_ServerConfig UA_ServerConfig;
49
50
_UA_BEGIN_DECLS
51
52
/**
53
 * .. _server:
54
 *
55
 * Server
56
 * ======
57
 * An OPC UA server contains an object-oriented information model and makes it
58
 * accessible to clients over the network via the OPC UA :ref:`services`. The
59
 * information model can be used either used to store "passive data" or as an
60
 * "active database" that integrates with data-sources and devices. For the
61
 * latter, user-defined callbacks can be attached to VariableNodes and
62
 * MethodNodes.
63
 *
64
 * .. _server-lifecycle:
65
 *
66
 * Server Lifecycle
67
 * ----------------
68
 * This section describes the API for creating, running and deleting a server.
69
 * At runtime, the server continuously listens on the network, acceppts incoming
70
 * connections and processes received messages. Furthermore, timed (cyclic)
71
 * callbacks are executed. */
72
73
/* Create a new server with a default configuration that adds plugins for
74
 * networking, security, logging and so on. See the "server_config_default.h"
75
 * for more detailed options.
76
 *
77
 * The default configuration can be used as the starting point to adjust the
78
 * server configuration to individual needs. UA_Server_new is implemented in the
79
 * /plugins folder under the CC0 license. Furthermore the server confiugration
80
 * only uses the public server API.
81
 *
82
 * Returns the configured server or NULL if an error occurs. */
83
UA_EXPORT UA_Server *
84
UA_Server_new(void);
85
86
/* Creates a new server. Moves the config into the server with a shallow copy.
87
 * The config content is cleared together with the server. */
88
UA_EXPORT UA_Server *
89
UA_Server_newWithConfig(UA_ServerConfig *config);
90
91
/* Delete the server and its configuration */
92
UA_EXPORT UA_StatusCode
93
UA_Server_delete(UA_Server *server);
94
95
/* Get the configuration. Always succeeds as this simplfy resolves a pointer.
96
 * Attention! Do not adjust the configuration while the server is running! */
97
UA_EXPORT UA_ServerConfig *
98
UA_Server_getConfig(UA_Server *server);
99
100
/* Get the current server lifecycle state */
101
UA_EXPORT UA_LifecycleState
102
UA_Server_getLifecycleState(UA_Server *server);
103
104
/* Runs the server until until "running" is set to false. The logical sequence
105
 * is as follows:
106
 *
107
 * - UA_Server_run_startup
108
 * - Loop UA_Server_run_iterate while "running" is true
109
 * - UA_Server_run_shutdown */
110
UA_EXPORT UA_StatusCode
111
UA_Server_run(UA_Server *server, const volatile UA_Boolean *running);
112
113
/* Runs the server until interrupted. On Unix/Windows this registers an
114
 * interrupt for SIGINT (ctrl-c). The method only returns after having received
115
 * the interrupt or upon an error condition. The logical sequence is as follows:
116
 *
117
 * - Register the interrupt
118
 * - UA_Server_run_startup
119
 * - Loop until interrupt: UA_Server_run_iterate
120
 * - UA_Server_run_shutdown
121
 * - Deregister the interrupt
122
 *
123
 * Attention! This method is implemented individually for the different
124
 * platforms (POSIX/Win32/etc.). The default implementation is in
125
 * /plugins/ua_config_default.c under the CC0 license. Adjust as needed. */
126
UA_EXPORT UA_StatusCode
127
UA_Server_runUntilInterrupt(UA_Server *server);
128
129
/* The prologue part of UA_Server_run (no need to use if you call
130
 * UA_Server_run or UA_Server_runUntilInterrupt) */
131
UA_EXPORT UA_StatusCode
132
UA_Server_run_startup(UA_Server *server);
133
134
/* Executes a single iteration of the server's main loop.
135
 *
136
 * @param server The server object.
137
 * @param waitInternal Should we wait for messages in the networklayer?
138
 *        Otherwise, the timeouts for the networklayers are set to zero.
139
 *        The default max wait time is 200ms.
140
 * @return Returns how long we can wait until the next scheduled
141
 *         callback (in ms) */
142
UA_EXPORT UA_UInt16
143
UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal);
144
145
/* The epilogue part of UA_Server_run (no need to use if you call
146
 * UA_Server_run or UA_Server_runUntilInterrupt) */
147
UA_EXPORT UA_StatusCode
148
UA_Server_run_shutdown(UA_Server *server);
149
150
/**
151
 * Timed Callbacks
152
 * ---------------
153
 * Timed callback are executed at their defined timestamp. The callback can also
154
 * be registered with a cyclic repetition interval. */
155
156
typedef void (*UA_ServerCallback)(UA_Server *server, void *data);
157
158
/* Add a callback for execution at a specified time. If the indicated time lies
159
 * in the past, then the callback is executed at the next iteration of the
160
 * server's main loop.
161
 *
162
 * @param server The server object.
163
 * @param callback The callback that shall be added.
164
 * @param data Data that is forwarded to the callback.
165
 * @param date The timestamp for the execution time.
166
 * @param callbackId Set to the identifier of the repeated callback . This can
167
 *        be used to cancel the callback later on. If the pointer is null, the
168
 *        identifier is not set.
169
 * @return Upon success, ``UA_STATUSCODE_GOOD`` is returned. An error code
170
 *         otherwise. */
171
UA_StatusCode UA_EXPORT UA_THREADSAFE
172
UA_Server_addTimedCallback(UA_Server *server, UA_ServerCallback callback,
173
                           void *data, UA_DateTime date, UA_UInt64 *callbackId);
174
175
/* Add a callback for cyclic repetition to the server.
176
 *
177
 * @param server The server object.
178
 * @param callback The callback that shall be added.
179
 * @param data Data that is forwarded to the callback.
180
 * @param interval_ms The callback shall be repeatedly executed with the given
181
 *        interval (in ms). The interval must be positive. The first execution
182
 *        occurs at now() + interval at the latest.
183
 * @param callbackId Set to the identifier of the repeated callback . This can
184
 *        be used to cancel the callback later on. If the pointer is null, the
185
 *        identifier is not set.
186
 * @return Upon success, ``UA_STATUSCODE_GOOD`` is returned. An error code
187
 *         otherwise. */
188
UA_StatusCode UA_EXPORT UA_THREADSAFE
189
UA_Server_addRepeatedCallback(UA_Server *server, UA_ServerCallback callback,
190
                              void *data, UA_Double interval_ms,
191
                              UA_UInt64 *callbackId);
192
193
UA_StatusCode UA_EXPORT UA_THREADSAFE
194
UA_Server_changeRepeatedCallbackInterval(UA_Server *server, UA_UInt64 callbackId,
195
                                         UA_Double interval_ms);
196
197
/* Remove a repeated callback. Does nothing if the callback is not found. */
198
void UA_EXPORT UA_THREADSAFE
199
UA_Server_removeCallback(UA_Server *server, UA_UInt64 callbackId);
200
201
#define UA_Server_removeRepeatedCallback(server, callbackId) \
202
0
    UA_Server_removeCallback(server, callbackId)
203
204
/**
205
 * Application Notification
206
 * ------------------------
207
 * The server defines callbacks to notify the application on defined triggering
208
 * points. These callbacks are executed with the (re-entrant) server-mutex held.
209
 *
210
 * The different types of callback are disambiguated by their type enum. Besides
211
 * the global notification callback (which is always triggered), the server
212
 * configuration contains specialized callbacks that trigger only for specific
213
 * notifications. This can reduce the burden of high-frequency notifications.
214
 *
215
 * If a specialized notification callback is set, it always gets called before
216
 * the global notification callback for the same triggering point.
217
 *
218
 * See the section on the :ref:`Application Notification` enum for more
219
 * documentation on the notifications and their defined payload. */
220
221
typedef void (*UA_ServerNotificationCallback)(UA_Server *server,
222
                                              UA_ApplicationNotificationType type,
223
                                              const UA_KeyValueMap payload);
224
225
/**
226
 * SecureChannel Handling
227
 * ----------------------
228
 * The server opens new SecureChannels internally when a server socket is
229
 * active. Information about SecureChannels and their state is notified with
230
 * UA_APPLICATIONNOTIFICATIONTYPE_SECURECHANNEL. SecureChannels can be manually
231
 * closed. This leaves any attached session alive so that it can potentially
232
 * reconnect. */
233
234
UA_EXPORT UA_StatusCode UA_THREADSAFE
235
UA_Server_closeSecureChannel(UA_Server *server, UA_UInt32 channelId,
236
                             UA_ShutdownReason reason);
237
238
/**
239
 * .. _server-session-handling:
240
 *
241
 * Session Handling
242
 * ----------------
243
 * Sessions are managed via the OPC UA Session Service Set (CreateSession,
244
 * ActivateSession, CloseSession). The identifier of sessions is generated
245
 * internally in the server and is always a Guid-NodeId.
246
 *
247
 * The creation of sessions is passed to the :ref:`access-control`. There, the
248
 * authentication information is evaluated and a context-pointer is attached to
249
 * the new session. The context pointer (and the session identifier) are then
250
 * forwarded to all user-defined callbacks that can be triggere by a session.
251
 *
252
 * When the operations from the OPC UA Services are invoked locally via the
253
 * C-API, this implies that the operations are executed with the access rights
254
 * of the "admin-session" that is always present in a server. Any AccessControl
255
 * checks are omitted for the admin-session.
256
 *
257
 * The admin-session has the identifier
258
 * ``g=00000001-0000-0000-0000-000000000000``. Its session context pointer needs
259
 * to be manually set (NULL by default). */
260
261
void UA_EXPORT
262
UA_Server_setAdminSessionContext(UA_Server *server, void *context);
263
264
/* Manually close a session */
265
UA_EXPORT UA_StatusCode UA_THREADSAFE
266
UA_Server_closeSession(UA_Server *server, const UA_NodeId *sessionId);
267
268
/**
269
 * Besides the session context pointer from the AccessControl plugin, a session
270
 * carries attributes in a key-value map. Always defined (and read-only) session
271
 * attributes are:
272
 *
273
 * - ``0:localeIds`` (``UA_String``): List of preferred languages
274
 * - ``0:clientDescription`` (``UA_ApplicationDescription``): Client description
275
 * - ``0:sessionName`` (``String``): Client-defined name of the session
276
 * - ``0:clientUserId`` (``String``): User identifier used to activate the session
277
 *
278
 * Additional attributes can be set manually with the API below. */
279
280
/* Returns a shallow copy of the attribute (don't _clear or _delete manually).
281
 * While the method is thread-safe, the returned value is not protected. Only
282
 * use it in a (callback) context where the server is locked for the current
283
 * thread. */
284
UA_EXPORT UA_StatusCode UA_THREADSAFE
285
UA_Server_getSessionAttribute(UA_Server *server, const UA_NodeId *sessionId,
286
                              const UA_QualifiedName key, UA_Variant *outValue);
287
288
/* Return a deep copy of the attribute */
289
UA_EXPORT UA_StatusCode UA_THREADSAFE
290
UA_Server_getSessionAttributeCopy(UA_Server *server, const UA_NodeId *sessionId,
291
                                  const UA_QualifiedName key, UA_Variant *outValue);
292
293
/* Returns NULL if the attribute is not defined or not a scalar or not of the
294
 * right datatype. Otherwise a shallow copy of the scalar value is created at
295
 * the target location of the void pointer (don't _clear or _delete manually).
296
 * While the method is thread-safe, the returned value is not protected. Only
297
 * use it in a (callback) context where the server is locked for the current
298
 * thread. */
299
UA_EXPORT UA_StatusCode UA_THREADSAFE
300
UA_Server_getSessionAttribute_scalar(UA_Server *server,
301
                                     const UA_NodeId *sessionId,
302
                                     const UA_QualifiedName key,
303
                                     const UA_DataType *type,
304
                                     void *outValue);
305
306
UA_EXPORT UA_StatusCode UA_THREADSAFE
307
UA_Server_setSessionAttribute(UA_Server *server, const UA_NodeId *sessionId,
308
                              const UA_QualifiedName key,
309
                              const UA_Variant *value);
310
311
UA_EXPORT UA_StatusCode UA_THREADSAFE
312
UA_Server_deleteSessionAttribute(UA_Server *server, const UA_NodeId *sessionId,
313
                                 const UA_QualifiedName key);
314
315
/**
316
 * Attribute Service Set
317
 * ---------------------
318
 * The functions for reading and writing node attributes call the regular read
319
 * and write service in the background that are also used over the network.
320
 *
321
 * The following attributes cannot be read, since the local "admin" user always
322
 * has full rights.
323
 *
324
 * - UserWriteMask
325
 * - UserAccessLevel
326
 * - UserExecutable */
327
328
/* Read an attribute of a node. Returns a deep copy. */
329
UA_DataValue UA_EXPORT UA_THREADSAFE
330
UA_Server_read(UA_Server *server, const UA_ReadValueId *item,
331
               UA_TimestampsToReturn timestamps);
332
333
/**
334
 * The following specialized read methods are a shorthand for the regular read
335
 * and set a deep copy of the attribute to the ``out`` pointer (when
336
 * successful). */
337
338
UA_EXPORT UA_THREADSAFE UA_StatusCode
339
UA_Server_readNodeId(UA_Server *server, const UA_NodeId nodeId,
340
                     UA_NodeId *out);
341
342
UA_EXPORT UA_THREADSAFE UA_StatusCode
343
UA_Server_readNodeClass(UA_Server *server, const UA_NodeId nodeId,
344
                        UA_NodeClass *out);
345
346
UA_EXPORT UA_THREADSAFE UA_StatusCode
347
UA_Server_readBrowseName(UA_Server *server, const UA_NodeId nodeId,
348
                         UA_QualifiedName *out);
349
350
UA_EXPORT UA_THREADSAFE UA_StatusCode
351
UA_Server_readDisplayName(UA_Server *server, const UA_NodeId nodeId,
352
                          UA_LocalizedText *out);
353
354
UA_EXPORT UA_THREADSAFE UA_StatusCode
355
UA_Server_readDescription(UA_Server *server, const UA_NodeId nodeId,
356
                          UA_LocalizedText *out);
357
358
UA_EXPORT UA_THREADSAFE UA_StatusCode
359
UA_Server_readWriteMask(UA_Server *server, const UA_NodeId nodeId,
360
                        UA_UInt32 *out);
361
362
UA_EXPORT UA_THREADSAFE UA_StatusCode
363
UA_Server_readIsAbstract(UA_Server *server, const UA_NodeId nodeId,
364
                         UA_Boolean *out);
365
366
UA_EXPORT UA_THREADSAFE UA_StatusCode
367
UA_Server_readSymmetric(UA_Server *server, const UA_NodeId nodeId,
368
                        UA_Boolean *out);
369
370
UA_EXPORT UA_THREADSAFE UA_StatusCode
371
UA_Server_readInverseName(UA_Server *server, const UA_NodeId nodeId,
372
                          UA_LocalizedText *out);
373
374
UA_EXPORT UA_THREADSAFE UA_StatusCode
375
UA_Server_readContainsNoLoops(UA_Server *server, const UA_NodeId nodeId,
376
                              UA_Boolean *out);
377
378
UA_EXPORT UA_THREADSAFE UA_StatusCode
379
UA_Server_readEventNotifier(UA_Server *server, const UA_NodeId nodeId,
380
                            UA_Byte *out);
381
382
UA_EXPORT UA_THREADSAFE UA_StatusCode
383
UA_Server_readValue(UA_Server *server, const UA_NodeId nodeId,
384
                    UA_Variant *out);
385
386
UA_EXPORT UA_THREADSAFE UA_StatusCode
387
UA_Server_readDataType(UA_Server *server, const UA_NodeId nodeId,
388
                       UA_NodeId *out);
389
390
UA_EXPORT UA_THREADSAFE UA_StatusCode
391
UA_Server_readValueRank(UA_Server *server, const UA_NodeId nodeId,
392
                        UA_Int32 *out);
393
394
/* Returns a variant with an uint32 array */
395
UA_EXPORT UA_THREADSAFE UA_StatusCode
396
UA_Server_readArrayDimensions(UA_Server *server, const UA_NodeId nodeId,
397
                              UA_Variant *out);
398
399
UA_EXPORT UA_THREADSAFE UA_StatusCode
400
UA_Server_readAccessLevel(UA_Server *server, const UA_NodeId nodeId,
401
                          UA_Byte *out);
402
403
UA_EXPORT UA_THREADSAFE UA_StatusCode
404
UA_Server_readAccessLevelEx(UA_Server *server, const UA_NodeId nodeId,
405
                            UA_UInt32 *out);
406
407
UA_EXPORT UA_THREADSAFE UA_StatusCode
408
UA_Server_readMinimumSamplingInterval(UA_Server *server, const UA_NodeId nodeId,
409
                                      UA_Double *out);
410
411
UA_EXPORT UA_THREADSAFE UA_StatusCode
412
UA_Server_readHistorizing(UA_Server *server, const UA_NodeId nodeId,
413
                          UA_Boolean *out);
414
415
UA_EXPORT UA_THREADSAFE UA_StatusCode
416
UA_Server_readExecutable(UA_Server *server, const UA_NodeId nodeId,
417
                         UA_Boolean *out);
418
419
/**
420
 * The following node attributes cannot be written once a node has been created:
421
 *
422
 * - NodeClass
423
 * - NodeId
424
 * - Symmetric
425
 * - ContainsNoLoops
426
 *
427
 * The following attributes cannot be written from C-API, as they are specific
428
 * to the session (context set by the access control callback):
429
 *
430
 * - UserWriteMask
431
 * - UserAccessLevel
432
 * - UserExecutable
433
 */
434
435
UA_EXPORT UA_THREADSAFE UA_StatusCode
436
UA_Server_write(UA_Server *server, const UA_WriteValue *value);
437
438
UA_EXPORT UA_THREADSAFE UA_StatusCode
439
UA_Server_writeBrowseName(UA_Server *server, const UA_NodeId nodeId,
440
                          const UA_QualifiedName browseName);
441
442
UA_EXPORT UA_THREADSAFE UA_StatusCode
443
UA_Server_writeDisplayName(UA_Server *server, const UA_NodeId nodeId,
444
                           const UA_LocalizedText displayName);
445
446
UA_EXPORT UA_THREADSAFE UA_StatusCode
447
UA_Server_writeDescription(UA_Server *server, const UA_NodeId nodeId,
448
                           const UA_LocalizedText description);
449
450
UA_EXPORT UA_THREADSAFE UA_StatusCode
451
UA_Server_writeWriteMask(UA_Server *server, const UA_NodeId nodeId,
452
                         const UA_UInt32 writeMask);
453
454
UA_EXPORT UA_THREADSAFE UA_StatusCode
455
UA_Server_writeIsAbstract(UA_Server *server, const UA_NodeId nodeId,
456
                          const UA_Boolean isAbstract);
457
458
UA_EXPORT UA_THREADSAFE UA_StatusCode
459
UA_Server_writeInverseName(UA_Server *server, const UA_NodeId nodeId,
460
                           const UA_LocalizedText inverseName);
461
462
UA_EXPORT UA_THREADSAFE UA_StatusCode
463
UA_Server_writeEventNotifier(UA_Server *server, const UA_NodeId nodeId,
464
                             const UA_Byte eventNotifier);
465
466
/* The value attribute is a DataValue. Here only a variant is provided. The
467
 * StatusCode is set to UA_STATUSCODE_GOOD, sourceTimestamp and serverTimestamp
468
 * are set to UA_DateTime_now(). See below for setting the full DataValue. */
469
UA_EXPORT UA_THREADSAFE UA_StatusCode
470
UA_Server_writeValue(UA_Server *server, const UA_NodeId nodeId,
471
                     const UA_Variant value);
472
473
UA_EXPORT UA_THREADSAFE UA_StatusCode
474
UA_Server_writeDataValue(UA_Server *server, const UA_NodeId nodeId,
475
                         const UA_DataValue value);
476
477
UA_EXPORT UA_THREADSAFE UA_StatusCode
478
UA_Server_writeDataType(UA_Server *server, const UA_NodeId nodeId,
479
                        const UA_NodeId dataType);
480
481
UA_EXPORT UA_THREADSAFE UA_StatusCode
482
UA_Server_writeValueRank(UA_Server *server, const UA_NodeId nodeId,
483
                         const UA_Int32 valueRank);
484
485
UA_EXPORT UA_THREADSAFE UA_StatusCode
486
UA_Server_writeArrayDimensions(UA_Server *server, const UA_NodeId nodeId,
487
                               const UA_Variant arrayDimensions);
488
489
UA_EXPORT UA_THREADSAFE UA_StatusCode
490
UA_Server_writeAccessLevel(UA_Server *server, const UA_NodeId nodeId,
491
                           const UA_Byte accessLevel);
492
493
UA_EXPORT UA_THREADSAFE UA_StatusCode
494
UA_Server_writeAccessLevelEx(UA_Server *server, const UA_NodeId nodeId,
495
                             const UA_UInt32 accessLevelEx);
496
497
UA_EXPORT UA_THREADSAFE UA_StatusCode
498
UA_Server_writeMinimumSamplingInterval(UA_Server *server, const UA_NodeId nodeId,
499
                                       const UA_Double miniumSamplingInterval);
500
501
UA_EXPORT UA_THREADSAFE UA_StatusCode
502
UA_Server_writeHistorizing(UA_Server *server, const UA_NodeId nodeId,
503
                           const UA_Boolean historizing);
504
505
UA_EXPORT UA_THREADSAFE UA_StatusCode
506
UA_Server_writeExecutable(UA_Server *server, const UA_NodeId nodeId,
507
                          const UA_Boolean executable);
508
509
/**
510
 * .. _server-method-call:
511
 *
512
 * Method Service Set
513
 * ------------------
514
 *
515
 * The Method Service Set defines the means to invoke methods. A MethodNode is a
516
 * component of an ObjectNode or of an ObjectTypeNode. The input and output
517
 * arguments of a method are a list of ``UA_Variant``. The type- and
518
 * size-requirements of the arguments can be retrieved from the
519
 * **InputArguments** and **OutputArguments** variable below the MethodNode.
520
 *
521
 * For calling a method, both ``methodId`` and ``objectId`` need to be defined
522
 * by their NodeId. This is required because the same MethodNode can be
523
 * referenced from multiple objects.
524
 *
525
 * In this server implementation, when an object is instantiated from a an
526
 * ObjectType, all (mandatory) methods are automatically added to the new object
527
 * instance. This is done by adding an additional reference to the original
528
 * MethodNode. It is however possible to add a custom MethodNode directly to the
529
 * object instance. It is also possible to remove a (optional) MethodNode that
530
 * exists in the ObjectType from an instance.
531
 *
532
 * The ``methodId`` can point to a MethodNode that exists in the ObjectType but
533
 * not in the object instance. It is resolved to the actual MethodNode of the
534
 * object instance by taking the *BrowseName* attribute of the
535
 * ``methodId``-MethodNode and looking up the member of the ``objectId`` object
536
 * with the same BrowseName.
537
 *
538
 * The resolved MethodNode then is used to
539
 *
540
 * - Check permissions for the current Session to call the method
541
 * - Obtain the ``UA_MethodCallback`` to execute
542
 * - Forwarded as ``methodId`` to said callback
543
 *
544
 * To showcase the resolution of the MethodNode with an example, consider this
545
 * information model::
546
 *
547
 *      ObjectType                      ObjectType                     Object
548
 *    Creature (i=10)  <-isSubTypeOf-  Insect (i=20)  <-hasTypeDef-   Ant (i=30)
549
 *          |                               |                            |
550
 *     hasComponent                    hasComponent                 hasComponent
551
 *          |                               |                            |
552
 *          v                               v                            v
553
 *       Methods                         Methods                      Methods
554
 *    - Walk (i=11)                   - Walk (i=21)                - Walk (i=31)
555
 *    - Fly (i=12)                    - Fly (i=22)                 - Amount (i=33)
556
 *    - Amount (i=13)                 - Amount (i=23)
557
 *
558
 * The following table shows what ``methodId`` - ``objectId`` combinations are
559
 * allowed to be used as parameters for the Call service and the resolved
560
 * ``methodId``.
561
 *
562
 * ========  ========  ====================================  =================
563
 * objectId  methodId  Corresponds to in OO-languages        Resolved methodId
564
 * ========  ========  ====================================  =================
565
 * i=30      i=31      ``Ant a; a.Walk();``                  i=31
566
 * i=30      i=21      ``Ant a; Insect i = a; i.Walk();``    i=31
567
 * i=30      i=11      ``Ant a; Creature c = a; c.Walk();``  i=31
568
 * i=20      i=23      ``Insect::Amount();``                 i=23
569
 * i=10      i=13      ``Creature::Amount();``               i=13
570
 * ========  ========  ====================================  =================
571
 *
572
 * The next table shows ``methodId`` - ``objectId`` combinations that are not
573
 * allowed. Note that an ObjecType cannot execute a methodId from a subtype or
574
 * instance.
575
 *
576
 * ========  ========  =====================================================
577
 * objectId  methodId  Reason
578
 * ========  ========  =====================================================
579
 * i=30      i=22      Object "Ant" does not own a method "Fly"
580
 * i=30      i=12      Object "Ant" does not own a method "Fly"
581
 * i=10      i=23      The method is not owned by the object type "Creature"
582
 * i=20      i=13      The method is not owned by the object type "Insect"
583
 * ========  ========  ===================================================== */
584
585
#ifdef UA_ENABLE_METHODCALLS
586
UA_CallMethodResult UA_EXPORT UA_THREADSAFE
587
UA_Server_call(UA_Server *server, const UA_CallMethodRequest *request);
588
#endif
589
590
/**
591
 * View Service Set
592
 * ----------------
593
 * The View Service Set allows Clients to discover Nodes by browsing the
594
 * information model. */
595
596
/* Browse the references of a particular node. See the definition of
597
 * BrowseDescription structure for details. */
598
UA_BrowseResult UA_EXPORT UA_THREADSAFE
599
UA_Server_browse(UA_Server *server, UA_UInt32 maxReferences,
600
                 const UA_BrowseDescription *bd);
601
602
UA_BrowseResult UA_EXPORT UA_THREADSAFE
603
UA_Server_browseNext(UA_Server *server, UA_Boolean releaseContinuationPoint,
604
                     const UA_ByteString *continuationPoint);
605
606
/* Non-standard version of the Browse service that recurses into child nodes.
607
 *
608
 * Possible loops (that can occur for non-hierarchical references) are handled
609
 * internally. Every node is added at most once to the results array.
610
 *
611
 * Nodes are only added if they match the NodeClassMask in the
612
 * BrowseDescription. However, child nodes are still recursed into if the
613
 * NodeClass does not match. So it is possible, for example, to get all
614
 * VariableNodes below a certain ObjectNode, with additional objects in the
615
 * hierarchy below. */
616
UA_StatusCode UA_EXPORT UA_THREADSAFE
617
UA_Server_browseRecursive(UA_Server *server, const UA_BrowseDescription *bd,
618
                          size_t *resultsSize, UA_ExpandedNodeId **results);
619
620
/* Translate abrowse path to (potentially several) NodeIds. Each browse path is
621
 * constructed of a starting Node and a RelativePath. The specified starting
622
 * Node identifies the Node from which the RelativePath is based. The
623
 * RelativePath contains a sequence of ReferenceTypes and BrowseNames. */
624
UA_BrowsePathResult UA_EXPORT UA_THREADSAFE
625
UA_Server_translateBrowsePathToNodeIds(UA_Server *server,
626
                                       const UA_BrowsePath *browsePath);
627
628
/* A simplified TranslateBrowsePathsToNodeIds based on the
629
 * SimpleAttributeOperand type (Part 4, 7.4.4.5).
630
 *
631
 * This specifies a relative path using a list of BrowseNames instead of the
632
 * RelativePath structure. The list of BrowseNames is equivalent to a
633
 * RelativePath that specifies forward references which are subtypes of the
634
 * HierarchicalReferences ReferenceType. All Nodes followed by the browsePath
635
 * shall be of the NodeClass Object or Variable. */
636
UA_BrowsePathResult UA_EXPORT UA_THREADSAFE
637
UA_Server_browseSimplifiedBrowsePath(UA_Server *server, const UA_NodeId origin,
638
                                     size_t browsePathSize,
639
                                     const UA_QualifiedName *browsePath);
640
641
/* Returns the target of a "HasTypeDefinition" reference (or inverse
642
 * "HasSubtype" reference for type nodes) */
643
UA_StatusCode UA_EXPORT UA_THREADSAFE
644
UA_Server_getNodeType(UA_Server *server, const UA_NodeId nodeId,
645
                      UA_NodeId *outTypeId);
646
647
/* Iterate over all nodes referenced by parentNodeId by calling the callback
648
 * function for each child node (in ifdef because GCC/CLANG handle include order
649
 * differently) */
650
typedef UA_StatusCode
651
(*UA_ServerNodeIteratorCallback)(UA_NodeId childId, UA_Boolean isInverse,
652
                           UA_NodeId referenceTypeId, void *handle);
653
654
UA_StatusCode UA_EXPORT UA_THREADSAFE
655
UA_Server_forEachChildNodeCall(UA_Server *server, UA_NodeId parentNodeId,
656
                               UA_ServerNodeIteratorCallback callback,
657
                               void *handle);
658
659
/**
660
 * .. _local-monitoreditems:
661
 *
662
 * MonitoredItem Service Set
663
 * -------------------------
664
 * MonitoredItems are used with the Subscription mechanism of OPC UA to
665
 * transported notifications for data changes and events. MonitoredItems can
666
 * also be registered locally. Notifications are then forwarded to a
667
 * user-defined callback instead of a remote client.
668
 *
669
 * Local MonitoredItems are delivered asynchronously. That is, the notification
670
 * is inserted as a *Delayed Callback* for the EventLoop. The callback is then
671
 * triggered when the control flow next returns to the EventLoop. */
672
673
#ifdef UA_ENABLE_SUBSCRIPTIONS
674
675
/* Delete a local MonitoredItem. Used for both DataChange- and
676
 * Event-MonitoredItems. */
677
UA_StatusCode UA_EXPORT UA_THREADSAFE
678
UA_Server_deleteMonitoredItem(UA_Server *server, UA_UInt32 monitoredItemId);
679
680
typedef void (*UA_Server_DataChangeNotificationCallback)
681
    (UA_Server *server, UA_UInt32 monitoredItemId, void *monitoredItemContext,
682
     const UA_NodeId *nodeId, void *nodeContext, UA_UInt32 attributeId,
683
     const UA_DataValue *value);
684
685
/**
686
 * DataChange MonitoredItem use a sampling interval and filter criteria to
687
 * notify the userland about value changes. Note that the sampling interval can
688
 * also be zero to be notified about changes "right away". For this we hook the
689
 * MonitoredItem into the observed Node and check the filter after every call of
690
 * the Write-Service. */
691
692
/* Create a local MonitoredItem to detect data changes.
693
 *
694
 * @param server The server executing the MonitoredItem
695
 * @param timestampsToReturn Shall timestamps be added to the value for the
696
 *        callback?
697
 * @param item The parameters of the new MonitoredItem. Note that the attribute
698
 *        of the ReadValueId (the node that is monitored) can not be
699
 *        ``UA_ATTRIBUTEID_EVENTNOTIFIER``. See below for event notifications.
700
 * @param monitoredItemContext A pointer that is forwarded with the callback
701
 * @param callback The callback that is executed on detected data changes
702
 * @return Returns a description of the created MonitoredItem. The structure
703
 *         also contains a StatusCode (in case of an error) and the identifier
704
 *         of the new MonitoredItem. */
705
UA_MonitoredItemCreateResult UA_EXPORT UA_THREADSAFE
706
UA_Server_createDataChangeMonitoredItem(UA_Server *server,
707
          UA_TimestampsToReturn timestampsToReturn,
708
          const UA_MonitoredItemCreateRequest item,
709
          void *monitoredItemContext,
710
          UA_Server_DataChangeNotificationCallback callback);
711
712
/**
713
 * See the section on :ref`events` for how to emit events in the server.
714
 *
715
 * Event-MonitoredItems emit notifications with a list of "fields" (variants).
716
 * The fields are specified as *SimpleAttributeOperands* in the select-clause of
717
 * the MonitoredItem's event filter. For the local event callback, instead of
718
 * using a list of variants, we use a key-value map for the event fields. They
719
 * key names are generated with ``UA_SimpleAttributeOperand_print`` to get a
720
 * human-readable representation.
721
 *
722
 * The received event-fields map could look like this::
723
 *
724
 *   /Severity   => UInt16(1000)
725
 *   /Message    => LocalizedText("en-US", "My Event Message")
726
 *   /EventType  => NodeId(i=50831)
727
 *   /SourceNode => NodeId(i=2253)
728
 *
729
 * The order of the keys is identical to the order of SimpleAttributeOperands in
730
 * the select-clause. */
731
732
#ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
733
734
typedef void (*UA_Server_EventNotificationCallback)
735
    (UA_Server *server, UA_UInt32 monitoredItemId, void *monitoredItemContext,
736
     const UA_KeyValueMap eventFields);
737
738
/* Create a local MonitoredItem for Events. The API is simplifed compared to a
739
 * UA_MonitoredItemCreateRequest. The unavailable options are not relevant for
740
 * local MonitoredItems (e.g. the queue size) or not relevant for Event
741
 * MonitoredItems (e.g. the sampling interval).
742
 *
743
 * @param server The server executing the MonitoredItem
744
 * @param nodeId The node where events are collected. Note that events "bubble
745
 *        up" to their parents (via hierarchical references).
746
 * @param filter The filter defined which event fields are selected (select
747
 *        clauses) and which events are considered for this particular
748
 *        MonitoredItem (where clause).
749
 * @param monitoredItemContext A pointer that is forwarded with the callback
750
 * @param callback The callback that is executed for each event
751
 * @return Returns a description of the created MonitoredItem. The structure
752
 *         also contains a StatusCode (in case of an error) and the identifier
753
 *         of the new MonitoredItem. */
754
UA_MonitoredItemCreateResult UA_EXPORT UA_THREADSAFE
755
UA_Server_createEventMonitoredItem(UA_Server *server, const UA_NodeId nodeId,
756
                                   const UA_EventFilter filter,
757
                                   void *monitoredItemContext,
758
                                   UA_Server_EventNotificationCallback callback);
759
760
/* Extended version UA_Server_createEventMonitoredItem that allows setting of
761
 * uncommon parameters (for local MonitoredItems) like the MonitoringMode and
762
 * queue sizes.
763
 *
764
 * @param server The server executing the MonitoredItem
765
 * @param item The description of the MonitoredItem. Must use
766
 *        UA_ATTRIBUTEID_EVENTNOTIFIER and an EventFilter.
767
 * @param monitoredItemContext A pointer that is forwarded with the callback
768
 * @param callback The callback that is executed for each event
769
 * @return Returns a description of the created MonitoredItem. The structure
770
 *         also contains a StatusCode (in case of an error) and the identifier
771
 *         of the new MonitoredItem. */
772
UA_MonitoredItemCreateResult UA_EXPORT UA_THREADSAFE
773
UA_Server_createEventMonitoredItemEx(UA_Server *server,
774
                                     const UA_MonitoredItemCreateRequest item,
775
                                     void *monitoredItemContext,
776
                                     UA_Server_EventNotificationCallback callback);
777
778
#endif /* UA_ENABLE_SUBSCRIPTIONS_EVENTS */
779
780
#endif /* UA_ENABLE_SUBSCRIPTIONS */
781
782
/**
783
 * .. _server-node-management:
784
 *
785
 * Node Management Service Set
786
 * ---------------------------
787
 * When creating dynamic node instances at runtime, chances are that you will
788
 * not care about the specific NodeId of the new node, as long as you can
789
 * reference it later. When passing numeric NodeIds with a numeric identifier 0,
790
 * the stack evaluates this as "select a random unassigned numeric NodeId in
791
 * that namespace". To find out which NodeId was actually assigned to the new
792
 * node, you may pass a pointer `outNewNodeId`, which will (after a successful
793
 * node insertion) contain the nodeId of the new node. You may also pass a
794
 * ``NULL`` pointer if this result is not needed.
795
 *
796
 * See the Section :ref:`node-lifecycle` on constructors and on attaching
797
 * user-defined data to nodes.
798
 *
799
 * The Section :ref:`default-node-attributes` contains useful starting points
800
 * for defining node attributes. Forgetting to set the ValueRank or the
801
 * AccessLevel leads to errors that can be hard to track down for new users. The
802
 * default attributes have a high likelihood to "do the right thing".
803
 *
804
 * The methods for node addition and deletion take mostly const arguments that
805
 * are not modified. When creating a node, a deep copy of the node identifier,
806
 * node attributes, etc. is created. Therefore, it is possible to call for
807
 * example ``UA_Server_addVariablenode`` with a value attribute (a
808
 * :ref:`variant`) pointing to a memory location on the stack.
809
 *
810
 * .. _variable-node:
811
 *
812
 * VariableNode
813
 * ~~~~~~~~~~~~
814
 * Variables store values as well as contraints for possible values. There are
815
 * three options for storing the value: Internal in the VariableNode data
816
 * structure itself, external with a double-pointer (to switch to an updated
817
 * value with an atomic pointer-replacing operation) or with a callback
818
 * registered by the application. */
819
820
typedef enum {
821
    UA_VALUESOURCETYPE_INTERNAL = 0,
822
    UA_VALUESOURCETYPE_EXTERNAL = 1,
823
    UA_VALUESOURCETYPE_CALLBACK = 2
824
} UA_ValueSourceType;
825
826
typedef struct {
827
    /* Notify the application before the value attribute is read. Ignored if
828
     * NULL. It is possible to write into the value attribute during onRead
829
     * (using the write service). The node is re-retrieved from the Nodestore
830
     * afterwards so that changes are considered in the following read
831
     * operation.
832
     *
833
     * @param handle Points to user-provided data for the callback.
834
     * @param nodeid The identifier of the node.
835
     * @param data Points to the current node value.
836
     * @param range Points to the numeric range the client wants to read from
837
     *        (or NULL). */
838
    void (*onRead)(UA_Server *server, const UA_NodeId *sessionId,
839
                   void *sessionContext, const UA_NodeId *nodeid,
840
                   void *nodeContext, const UA_NumericRange *range,
841
                   const UA_DataValue *value);
842
843
    /* Notify the application after writing the value attribute. Ignored if
844
     * NULL. The node is re-retrieved after writing, so that the new value is
845
     * visible in the callback.
846
     *
847
     * @param server The server executing the callback
848
     * @sessionId The identifier of the session
849
     * @sessionContext Additional data attached to the session
850
     *                 in the access control layer
851
     * @param nodeid The identifier of the node.
852
     * @param nodeUserContext Additional data attached to the node by
853
     *        the user.
854
     * @param nodeConstructorContext Additional data attached to the node
855
     *        by the type constructor(s).
856
     * @param range Points to the numeric range the client wants to write to (or
857
     *        NULL). */
858
    void (*onWrite)(UA_Server *server, const UA_NodeId *sessionId,
859
                    void *sessionContext, const UA_NodeId *nodeId,
860
                    void *nodeContext, const UA_NumericRange *range,
861
                    const UA_DataValue *data);
862
} UA_ValueSourceNotifications;
863
864
typedef struct {
865
    /* Copies the data from the source into the provided value.
866
     *
867
     * !! ZERO-COPY OPERATIONS POSSIBLE !!
868
     * It is not required to return a copy of the actual content data. You can
869
     * return a pointer to memory owned by the user. Memory can be reused
870
     * between read callbacks of a DataSource, as the result is already encoded
871
     * on the network buffer between each read operation.
872
     *
873
     * To use zero-copy reads, set the value of the `value->value` Variant
874
     * without copying, e.g. with `UA_Variant_setScalar`. Then, also set
875
     * `value->value.storageType` to `UA_VARIANT_DATA_NODELETE` to prevent the
876
     * memory being cleaned up. Don't forget to also set `value->hasValue` to
877
     * true to indicate the presence of a value.
878
     *
879
     * To make an async read, return UA_STATUSCODE_GOODCOMPLETESASYNCHRONOUSLY.
880
     * The result can then be set at a later time using
881
     * UA_Server_setAsyncReadResult. Note that the server might cancel the async
882
     * read by calling serverConfig->asyncOperationCancelCallback.
883
     *
884
     * @param server The server executing the callback
885
     * @param sessionId The identifier of the session
886
     * @param sessionContext Additional data attached to the session in the
887
     *        access control layer
888
     * @param nodeId The identifier of the node being read from
889
     * @param nodeContext Additional data attached to the node by the user
890
     * @param includeSourceTimeStamp If true, then the datasource is expected to
891
     *        set the source timestamp in the returned value
892
     * @param range If not null, then the datasource shall return only a
893
     *        selection of the (nonscalar) data. Set
894
     *        UA_STATUSCODE_BADINDEXRANGEINVALID in the value if this does not
895
     *        apply
896
     * @param value The (non-null) DataValue that is returned to the client. The
897
     *        data source sets the read data, the result status and optionally a
898
     *        sourcetimestamp.
899
     * @return Returns a status code for logging. Error codes intended for the
900
     *         original caller are set in the value. If an error is returned,
901
     *         then no releasing of the value is done. */
902
    UA_StatusCode (*read)(UA_Server *server, const UA_NodeId *sessionId,
903
                          void *sessionContext, const UA_NodeId *nodeId,
904
                          void *nodeContext, UA_Boolean includeSourceTimeStamp,
905
                          const UA_NumericRange *range, UA_DataValue *value);
906
907
    /* Write into a data source. This method pointer can be NULL if the
908
     * operation is unsupported.
909
     *
910
     * To make an async write, return UA_STATUSCODE_GOODCOMPLETESASYNCHRONOUSLY.
911
     * The result can then be set at a later time using
912
     * UA_Server_setAsyncWriteResult. Note that the server might cancel the
913
     * async read by calling serverConfig->asyncOperationCancelCallback.
914
     *
915
     * @param server The server executing the callback
916
     * @param sessionId The identifier of the session
917
     * @param sessionContext Additional data attached to the session in the
918
     *        access control layer
919
     * @param nodeId The identifier of the node being written to
920
     * @param nodeContext Additional data attached to the node by the user
921
     * @param range If not NULL, then the datasource shall return only a
922
     *        selection of the (nonscalar) data. Set
923
     *        UA_STATUSCODE_BADINDEXRANGEINVALID in the value if this does not
924
     *        apply
925
     * @param value The (non-NULL) DataValue that has been written by the client.
926
     *        The data source contains the written data, the result status and
927
     *        optionally a sourcetimestamp
928
     * @return Returns a status code for logging. Error codes intended for the
929
     *         original caller are set in the value. If an error is returned,
930
     *         then no releasing of the value is done. */
931
    UA_StatusCode (*write)(UA_Server *server, const UA_NodeId *sessionId,
932
                           void *sessionContext, const UA_NodeId *nodeId,
933
                           void *nodeContext, const UA_NumericRange *range,
934
                           const UA_DataValue *value);
935
} UA_CallbackValueSource;
936
937
/**
938
 * By default, when adding a VariableNode, the value from the
939
 * ``UA_VariableAttributes`` is used. The methods following afterwards can be
940
 * used to override the value source. */
941
942
UA_EXPORT UA_THREADSAFE UA_StatusCode
943
UA_Server_addVariableNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
944
                          const UA_NodeId parentNodeId,
945
                          const UA_NodeId referenceTypeId,
946
                          const UA_QualifiedName browseName,
947
                          const UA_NodeId typeDefinition,
948
                          const UA_VariableAttributes attr,
949
                          void *nodeContext, UA_NodeId *outNewNodeId);
950
951
/* Add a VariableNode with a callback value-source */
952
UA_StatusCode UA_EXPORT UA_THREADSAFE
953
UA_Server_addCallbackValueSourceVariableNode(UA_Server *server,
954
                                             const UA_NodeId requestedNewNodeId,
955
                                             const UA_NodeId parentNodeId,
956
                                             const UA_NodeId referenceTypeId,
957
                                             const UA_QualifiedName browseName,
958
                                             const UA_NodeId typeDefinition,
959
                                             const UA_VariableAttributes attr,
960
                                             const UA_CallbackValueSource evs,
961
                                             void *nodeContext, UA_NodeId *outNewNodeId);
962
963
/* Legacy API */
964
#define UA_Server_addDataSourceVariableNode(server, requestedNewNodeId, parentNodeId,    \
965
                                            referenceTypeId, browseName, typeDefinition, \
966
                                            attr, dataSource, nodeContext, outNewNodeId) \
967
    UA_Server_addCallbackValueSourceVariableNode(server, requestedNewNodeId,             \
968
                                                 parentNodeId, referenceTypeId,          \
969
                                                 browseName, typeDefinition,             \
970
                                                 attr, dataSource, nodeContext,          \
971
                                                 outNewNodeId)
972
973
/* Set an internal value source. Both the value argument and the notifications
974
 * argument can be NULL. If value is NULL, the Read service is used to get the
975
 * latest value before switching from a callback to an internal value source. If
976
 * notifications is NULL, then all onRead/onWrite notifications are disabled. */
977
UA_StatusCode UA_EXPORT UA_THREADSAFE
978
UA_Server_setVariableNode_internalValueSource(UA_Server *server,
979
    const UA_NodeId nodeId, const UA_DataValue *value,
980
    const UA_ValueSourceNotifications *notifications);
981
982
/* For the external value, no initial copy is made. The node "just" points to
983
 * the provided double-pointer. Otherwise identical to the internal data
984
 * source. */
985
UA_StatusCode UA_EXPORT UA_THREADSAFE
986
UA_Server_setVariableNode_externalValueSource(UA_Server *server,
987
    const UA_NodeId nodeId, UA_DataValue** value,
988
    const UA_ValueSourceNotifications *notifications);
989
990
/* It is expected that the read callback is implemented. Whenever the value
991
 * attribute is read, the function will be called and asked to fill a
992
 * UA_DataValue structure that contains the value content and additional
993
 * metadata like timestamps.
994
 *
995
 * The write callback can be set to a null-pointer. Then writing into the value
996
 * is disabled. */
997
UA_StatusCode UA_EXPORT UA_THREADSAFE
998
UA_Server_setVariableNode_callbackValueSource(UA_Server *server,
999
    const UA_NodeId nodeId, const UA_CallbackValueSource evs);
1000
1001
/* Deprecated API */
1002
typedef UA_CallbackValueSource UA_DataSource;
1003
#define UA_Server_setVariableNode_dataSource(server, nodeId, dataSource) \
1004
0
    UA_Server_setVariableNode_callbackValueSource(server, nodeId, dataSource)
1005
1006
/* Deprecated API */
1007
typedef UA_ValueSourceNotifications UA_ValueCallback;
1008
#define UA_Server_setVariableNode_valueCallback(server, nodeId, callback) \
1009
    UA_Server_setVariableNode_internalValueSource(server, nodeId, NULL, &callback)
1010
1011
/* VariableNodes that are "dynamic" (default for user-created variables) receive
1012
 * and store a SourceTimestamp. For non-dynamic VariableNodes the current time
1013
 * is used for the SourceTimestamp. */
1014
UA_StatusCode UA_EXPORT UA_THREADSAFE
1015
UA_Server_setVariableNodeDynamic(UA_Server *server, const UA_NodeId nodeId,
1016
                                 UA_Boolean isDynamic);
1017
1018
/**
1019
 * VariableTypeNode
1020
 * ~~~~~~~~~~~~~~~~ */
1021
1022
UA_EXPORT UA_THREADSAFE UA_StatusCode
1023
UA_Server_addVariableTypeNode(UA_Server *server,
1024
                              const UA_NodeId requestedNewNodeId,
1025
                              const UA_NodeId parentNodeId,
1026
                              const UA_NodeId referenceTypeId,
1027
                              const UA_QualifiedName browseName,
1028
                              const UA_NodeId typeDefinition,
1029
                              const UA_VariableTypeAttributes attr,
1030
                              void *nodeContext, UA_NodeId *outNewNodeId);
1031
1032
/**
1033
 * MethodNode
1034
 * ~~~~~~~~~~
1035
 * Please refer to the :ref:`Method Service Set <server-method-call>` to get
1036
 * information about which MethodNodes may get executed and would thus require
1037
 * callbacks to be registered. */
1038
1039
typedef UA_StatusCode
1040
(*UA_MethodCallback)(UA_Server *server,
1041
                     const UA_NodeId *sessionId, void *sessionContext,
1042
                     const UA_NodeId *methodId, void *methodContext,
1043
                     const UA_NodeId *objectId, void *objectContext,
1044
                     size_t inputSize, const UA_Variant *input,
1045
                     size_t outputSize, UA_Variant *output);
1046
1047
#ifdef UA_ENABLE_METHODCALLS
1048
1049
UA_EXPORT UA_THREADSAFE UA_StatusCode
1050
UA_Server_addMethodNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1051
                        const UA_NodeId parentNodeId, const UA_NodeId referenceTypeId,
1052
                        const UA_QualifiedName browseName, const UA_MethodAttributes attr,
1053
                        UA_MethodCallback method,
1054
                        size_t inputArgumentsSize, const UA_Argument *inputArguments,
1055
                        size_t outputArgumentsSize, const UA_Argument *outputArguments,
1056
                        void *nodeContext, UA_NodeId *outNewNodeId);
1057
1058
/* Extended version, allows the additional definition of fixed NodeIds for the
1059
 * InputArgument/OutputArgument child variables */
1060
UA_StatusCode UA_EXPORT UA_THREADSAFE
1061
UA_Server_addMethodNodeEx(UA_Server *server, const UA_NodeId requestedNewNodeId,
1062
                          const UA_NodeId parentNodeId,
1063
                          const UA_NodeId referenceTypeId,
1064
                          const UA_QualifiedName browseName,
1065
                          const UA_MethodAttributes attr, UA_MethodCallback method,
1066
                          size_t inputArgumentsSize, const UA_Argument *inputArguments,
1067
                          const UA_NodeId inputArgumentsRequestedNewNodeId,
1068
                          UA_NodeId *inputArgumentsOutNewNodeId,
1069
                          size_t outputArgumentsSize, const UA_Argument *outputArguments,
1070
                          const UA_NodeId outputArgumentsRequestedNewNodeId,
1071
                          UA_NodeId *outputArgumentsOutNewNodeId,
1072
                          void *nodeContext, UA_NodeId *outNewNodeId);
1073
1074
UA_StatusCode UA_EXPORT UA_THREADSAFE
1075
UA_Server_setMethodNodeCallback(UA_Server *server,
1076
                                const UA_NodeId methodNodeId,
1077
                                UA_MethodCallback methodCallback);
1078
1079
/* Backwards compatibility definition */
1080
#define UA_Server_setMethodNode_callback(server, methodNodeId, methodCallback) \
1081
    UA_Server_setMethodNodeCallback(server, methodNodeId, methodCallback)
1082
1083
UA_StatusCode UA_EXPORT UA_THREADSAFE
1084
UA_Server_getMethodNodeCallback(UA_Server *server,
1085
                                const UA_NodeId methodNodeId,
1086
                                UA_MethodCallback *outMethodCallback);
1087
1088
#endif
1089
1090
/**
1091
 * ObjectNode
1092
 * ~~~~~~~~~~ */
1093
1094
UA_EXPORT UA_THREADSAFE UA_StatusCode
1095
UA_Server_addObjectNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1096
                        const UA_NodeId parentNodeId,
1097
                        const UA_NodeId referenceTypeId,
1098
                        const UA_QualifiedName browseName,
1099
                        const UA_NodeId typeDefinition,
1100
                        const UA_ObjectAttributes attr,
1101
                        void *nodeContext, UA_NodeId *outNewNodeId);
1102
1103
/**
1104
 * ObjectTypeNode
1105
 * ~~~~~~~~~~~~~~ */
1106
1107
UA_EXPORT UA_THREADSAFE UA_StatusCode
1108
UA_Server_addObjectTypeNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1109
                            const UA_NodeId parentNodeId,
1110
                            const UA_NodeId referenceTypeId,
1111
                            const UA_QualifiedName browseName,
1112
                            const UA_ObjectTypeAttributes attr,
1113
                            void *nodeContext, UA_NodeId *outNewNodeId);
1114
1115
/**
1116
 * ReferenceTypeNode
1117
 * ~~~~~~~~~~~~~~~~~ */
1118
1119
UA_EXPORT UA_THREADSAFE UA_StatusCode
1120
UA_Server_addReferenceTypeNode(UA_Server *server,
1121
                               const UA_NodeId requestedNewNodeId,
1122
                               const UA_NodeId parentNodeId,
1123
                               const UA_NodeId referenceTypeId,
1124
                               const UA_QualifiedName browseName,
1125
                               const UA_ReferenceTypeAttributes attr,
1126
                               void *nodeContext, UA_NodeId *outNewNodeId);
1127
1128
/**
1129
 * DataTypeNode
1130
 * ~~~~~~~~~~~~ */
1131
1132
UA_EXPORT UA_THREADSAFE UA_StatusCode
1133
UA_Server_addDataTypeNode(UA_Server *server,
1134
                          const UA_NodeId requestedNewNodeId,
1135
                          const UA_NodeId parentNodeId,
1136
                          const UA_NodeId referenceTypeId,
1137
                          const UA_QualifiedName browseName,
1138
                          const UA_DataTypeAttributes attr,
1139
                          void *nodeContext, UA_NodeId *outNewNodeId);
1140
1141
/**
1142
 * Due to the history of development, the DataTypeAttributes structure used in
1143
 * the AddNodes Service does not describe the layout of the DataType. But the
1144
 * (newer) structures for describing DataTypes do:
1145
 *
1146
 * - SimpleTypeDescription
1147
 * - EnumDescription
1148
 * - StructureDescription
1149
 *
1150
 * The ``UA_Server_addDataTypeFromDescription`` function translates the
1151
 * DataTypeDescription into a UA_DataType structure and adds it to an internal
1152
 * array of the server. Then the DataType is automatically decoded in messages
1153
 * received by the server. Also the ``DataTypeDefinition`` attribute of the
1154
 * corresponding DataTypeNode can then be read via the Read service.
1155
 *
1156
 * The memory layout of the internally generated ``UA_DataType`` corresponds to
1157
 * the matching C-structure including padding.
1158
 *
1159
 * Note that a DataTypeDescription can be added only once during the lifetime of
1160
 * the server. This protects against existing instances of the DataType to
1161
 * having their layout changed. */
1162
1163
/* Use the DataType description to create an internal UA_DataType entry in the
1164
 * server */
1165
UA_EXPORT UA_THREADSAFE UA_StatusCode
1166
UA_Server_addDataTypeFromDescription(UA_Server *server,
1167
                                     const UA_ExtensionObject *description);
1168
1169
/* The same as UA_Server_addDataTypeFromDescription, but with the description
1170
 * already converted into a UA_DataType. Makes a copy of the UA_DataType
1171
 * internally. */
1172
UA_EXPORT UA_THREADSAFE UA_StatusCode
1173
UA_Server_addDataType(UA_Server *server, const UA_NodeId parentNodeId,
1174
                      const UA_DataType *type);
1175
1176
/* Get the entry to the linked list of custom datatypes. This includes both the
1177
 * datatypes from serverConfig->customDataTypes and the internal custom data
1178
 * types from UA_Server_addDataType.
1179
 *
1180
 * Attention! The output pointer is only valid until the next call to
1181
 * UA_Server_addDataType. */
1182
UA_EXPORT UA_THREADSAFE const UA_DataTypeArray *
1183
UA_Server_getDataTypes(UA_Server *server);
1184
1185
/**
1186
 * ViewNode
1187
 * ~~~~~~~~ */
1188
1189
UA_EXPORT UA_THREADSAFE UA_StatusCode
1190
UA_Server_addViewNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1191
                      const UA_NodeId parentNodeId,
1192
                      const UA_NodeId referenceTypeId,
1193
                      const UA_QualifiedName browseName,
1194
                      const UA_ViewAttributes attr,
1195
                      void *nodeContext, UA_NodeId *outNewNodeId);
1196
1197
/**
1198
 * .. _node-lifecycle:
1199
 *
1200
 * Node Lifecycle: Constructors, Destructors and Node Contexts
1201
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1202
 * To finalize the instantiation of a node, a (user-defined) constructor
1203
 * callback is executed. There can be both a global constructor for all nodes
1204
 * and node-type constructor specific to the TypeDefinition of the new node
1205
 * (attached to an ObjectTypeNode or VariableTypeNode).
1206
 *
1207
 * In the hierarchy of ObjectTypes and VariableTypes, only the constructor of
1208
 * the (lowest) type defined for the new node is executed. Note that every
1209
 * Object and Variable can have only one ``isTypeOf`` reference. But type-nodes
1210
 * can technically have several ``hasSubType`` references to implement multiple
1211
 * inheritance. Issues of (multiple) inheritance in the constructor need to be
1212
 * solved by the user.
1213
 *
1214
 * When a node is destroyed, the node-type destructor is called before the
1215
 * global destructor. So the overall node lifecycle is as follows:
1216
 *
1217
 * 1. Global Constructor (set in the server config)
1218
 * 2. Node-Type Constructor (for VariableType or ObjectTypes)
1219
 * 3. (Usage-period of the Node)
1220
 * 4. Node-Type Destructor
1221
 * 5. Global Destructor
1222
 *
1223
 * The constructor and destructor callbacks can be set to ``NULL`` and are not
1224
 * used in that case. If the node-type constructor fails, the global destructor
1225
 * will be called before removing the node. The destructors are assumed to never
1226
 * fail.
1227
 *
1228
 * Every node carries a user-context and a constructor-context pointer. The
1229
 * user-context is used to attach custom data to a node. But the (user-defined)
1230
 * constructors and destructors may replace the user-context pointer if they
1231
 * wish to do so. The initial value for the constructor-context is ``NULL``.
1232
 * When the ``AddNodes`` service is used over the network, the user-context
1233
 * pointer of the new node is also initially set to ``NULL``. */
1234
1235
UA_StatusCode UA_EXPORT UA_THREADSAFE
1236
UA_Server_getNodeContext(UA_Server *server, UA_NodeId nodeId, void **nodeContext);
1237
1238
/* Careful! The user has to ensure that the destructor callbacks still work. */
1239
UA_StatusCode UA_EXPORT UA_THREADSAFE
1240
UA_Server_setNodeContext(UA_Server *server, UA_NodeId nodeId, void *nodeContext);
1241
1242
/**
1243
 * Global constructor and destructor callbacks used for every node type.
1244
 * It gets set in the server config. */
1245
1246
typedef struct {
1247
    /* Can be NULL. May replace the nodeContext */
1248
    UA_StatusCode (*constructor)(UA_Server *server,
1249
                                 const UA_NodeId *sessionId, void *sessionContext,
1250
                                 const UA_NodeId *nodeId, void **nodeContext);
1251
1252
    /* Can be NULL. The context cannot be replaced since the node is destroyed
1253
     * immediately afterwards anyway. */
1254
    void (*destructor)(UA_Server *server,
1255
                       const UA_NodeId *sessionId, void *sessionContext,
1256
                       const UA_NodeId *nodeId, void *nodeContext);
1257
1258
    /* Can be NULL. Called during recursive node instantiation. While mandatory
1259
     * child nodes are automatically created if not already present, optional child
1260
     * nodes are not. This callback can be used to define whether an optional child
1261
     * node should be created.
1262
     *
1263
     * @param server The server executing the callback
1264
     * @param sessionId The identifier of the session
1265
     * @param sessionContext Additional data attached to the session in the
1266
     *        access control layer
1267
     * @param sourceNodeId Source node from the type definition. If the new node
1268
     *        shall be created, it will be a copy of this node.
1269
     * @param targetParentNodeId Parent of the potential new child node
1270
     * @param referenceTypeId Identifies the reference type which that the parent
1271
     *        node has to the new node.
1272
     * @return Return UA_TRUE if the child node shall be instantiated,
1273
     *         UA_FALSE otherwise. */
1274
    UA_Boolean (*createOptionalChild)(UA_Server *server,
1275
                                      const UA_NodeId *sessionId,
1276
                                      void *sessionContext,
1277
                                      const UA_NodeId *sourceNodeId,
1278
                                      const UA_NodeId *targetParentNodeId,
1279
                                      const UA_NodeId *referenceTypeId);
1280
1281
    /* Can be NULL. Called when a node is to be copied during recursive
1282
     * node instantiation. Allows definition of the NodeId for the new node.
1283
     * If the callback is set to NULL or the resulting NodeId is UA_NODEID_NUMERIC(X,0)
1284
     * an unused nodeid in namespace X will be used. E.g. passing UA_NODEID_NULL will
1285
     * result in a NodeId in namespace 0.
1286
     *
1287
     * @param server The server executing the callback
1288
     * @param sessionId The identifier of the session
1289
     * @param sessionContext Additional data attached to the session in the
1290
     *        access control layer
1291
     * @param sourceNodeId Source node of the copy operation
1292
     * @param targetParentNodeId Parent node of the new node
1293
     * @param referenceTypeId Identifies the reference type which that the parent
1294
     *        node has to the new node. */
1295
    UA_StatusCode (*generateChildNodeId)(UA_Server *server,
1296
                                         const UA_NodeId *sessionId, void *sessionContext,
1297
                                         const UA_NodeId *sourceNodeId,
1298
                                         const UA_NodeId *targetParentNodeId,
1299
                                         const UA_NodeId *referenceTypeId,
1300
                                         UA_NodeId *targetNodeId);
1301
} UA_GlobalNodeLifecycle;
1302
1303
/**
1304
 * The following node-type lifecycle can be set for VariableTypeNodes and
1305
 * ObjectTypeNodes. It gets called for instances of this node-type. */
1306
1307
typedef struct {
1308
    /* Can be NULL. May replace the nodeContext */
1309
    UA_StatusCode (*constructor)(UA_Server *server,
1310
                                 const UA_NodeId *sessionId, void *sessionContext,
1311
                                 const UA_NodeId *typeNodeId, void *typeNodeContext,
1312
                                 const UA_NodeId *nodeId, void **nodeContext);
1313
1314
    /* Can be NULL. May replace the nodeContext. */
1315
    void (*destructor)(UA_Server *server,
1316
                       const UA_NodeId *sessionId, void *sessionContext,
1317
                       const UA_NodeId *typeNodeId, void *typeNodeContext,
1318
                       const UA_NodeId *nodeId, void **nodeContext);
1319
} UA_NodeTypeLifecycle;
1320
1321
UA_StatusCode UA_EXPORT UA_THREADSAFE
1322
UA_Server_setNodeTypeLifecycle(UA_Server *server, UA_NodeId nodeId,
1323
                               UA_NodeTypeLifecycle lifecycle);
1324
1325
/**
1326
 * Detailed Node Construction
1327
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~
1328
 * The method pair UA_Server_addNode_begin and _finish splits the AddNodes
1329
 * service in two parts. This is useful if the node shall be modified before
1330
 * finish the instantiation. For example to add children with specific NodeIds.
1331
 * Otherwise, mandatory children (e.g. of an ObjectType) are added with
1332
 * pseudo-random unique NodeIds. Existing children are detected during the
1333
 * _finish part via their matching BrowseName.
1334
 *
1335
 * The _begin method:
1336
 *  - prepares the node and adds it to the nodestore
1337
 *  - copies some unassigned attributes from the TypeDefinition node internally
1338
 *  - adds the references to the parent (and the TypeDefinition if applicable)
1339
 *  - performs type-checking of variables.
1340
 *
1341
 * You can add an object node without a parent if you set the parentNodeId and
1342
 * referenceTypeId to UA_NODE_ID_NULL. Then you need to add the parent reference
1343
 * and hasTypeDef reference yourself before calling the _finish method.
1344
 * Not that this is only allowed for object nodes.
1345
 *
1346
 * The _finish method:
1347
 *  - copies mandatory children
1348
 *  - calls the node constructor(s) at the end
1349
 *  - may remove the node if it encounters an error.
1350
 *
1351
 * The special UA_Server_addMethodNode_finish method needs to be used for method
1352
 * nodes, since there you need to explicitly specifiy the input and output
1353
 * arguments which are added in the finish step (if not yet already there) */
1354
1355
/* The ``attr`` argument must have a type according to the NodeClass.
1356
 * ``VariableAttributes`` for variables, ``ObjectAttributes`` for objects, and
1357
 * so on. Missing attributes are taken from the TypeDefinition node if
1358
 * applicable. */
1359
UA_StatusCode UA_EXPORT UA_THREADSAFE
1360
UA_Server_addNode_begin(UA_Server *server, const UA_NodeClass nodeClass,
1361
                        const UA_NodeId requestedNewNodeId,
1362
                        const UA_NodeId parentNodeId,
1363
                        const UA_NodeId referenceTypeId,
1364
                        const UA_QualifiedName browseName,
1365
                        const UA_NodeId typeDefinition,
1366
                        const void *attr, const UA_DataType *attributeType,
1367
                        void *nodeContext, UA_NodeId *outNewNodeId);
1368
1369
UA_StatusCode UA_EXPORT UA_THREADSAFE
1370
UA_Server_addNode_finish(UA_Server *server, const UA_NodeId nodeId);
1371
1372
#ifdef UA_ENABLE_METHODCALLS
1373
1374
UA_StatusCode UA_EXPORT UA_THREADSAFE
1375
UA_Server_addMethodNode_finish(UA_Server *server, const UA_NodeId nodeId,
1376
                         UA_MethodCallback method,
1377
                         size_t inputArgumentsSize, const UA_Argument *inputArguments,
1378
                         size_t outputArgumentsSize, const UA_Argument *outputArguments);
1379
1380
#endif
1381
1382
/* Deletes a node and optionally all references leading to the node. */
1383
UA_StatusCode UA_EXPORT UA_THREADSAFE
1384
UA_Server_deleteNode(UA_Server *server, const UA_NodeId nodeId,
1385
                     UA_Boolean deleteReferences);
1386
1387
/**
1388
 * Reference Management
1389
 * ~~~~~~~~~~~~~~~~~~~~ */
1390
1391
UA_StatusCode UA_EXPORT UA_THREADSAFE
1392
UA_Server_addReference(UA_Server *server, const UA_NodeId sourceId,
1393
                       const UA_NodeId refTypeId,
1394
                       const UA_ExpandedNodeId targetId, UA_Boolean isForward);
1395
1396
UA_StatusCode UA_EXPORT UA_THREADSAFE
1397
UA_Server_deleteReference(UA_Server *server, const UA_NodeId sourceNodeId,
1398
                          const UA_NodeId referenceTypeId, UA_Boolean isForward,
1399
                          const UA_ExpandedNodeId targetNodeId,
1400
                          UA_Boolean deleteBidirectional);
1401
1402
/**
1403
 * .. _async-operations:
1404
 *
1405
 * Async Operations
1406
 * ----------------
1407
 * Some operations can take time, such as reading a sensor that needs to warm up
1408
 * first. In order not to block the server, a long-running operation can be
1409
 * handled asynchronously and the result returned at a later time. The core idea
1410
 * is that a userland callback can return
1411
 * UA_STATUSCODE_GOODCOMPLETESASYNCHRONOUSLY as the statuscode to signal that it
1412
 * wishes to complete the operation later.
1413
 *
1414
 * Currently, async operations are supported for the services
1415
 *
1416
 * - Read
1417
 * - Write
1418
 * - Call
1419
 *
1420
 * with the caveat that read/write need a CallbackValueSource registered for the
1421
 * variable. Values that are stored directly in a VariableNode are written and
1422
 * read immediately.
1423
 *
1424
 * Note that an async operation can be cancelled (e.g. after a timeout period or
1425
 * if the caller cannot wait for the result). This is signaled in the configured
1426
 * ``asyncOperationCancelCallback``. The provided memory locations to store the
1427
 * operation output are then no longer valid. */
1428
1429
/* When the UA_MethodCallback returns UA_STATUSCODE_GOODCOMPLETESASYNCHRONOUSLY,
1430
 * then an async operation is created in the server for later completion. The
1431
 * output pointer from the method callback is used to identify the async
1432
 * operation. Do not access the output pointer after the operation has been
1433
 * cancelled or after setting the result. */
1434
UA_EXPORT UA_THREADSAFE UA_StatusCode
1435
UA_Server_setAsyncCallMethodResult(UA_Server *server, UA_Variant *output,
1436
                                   UA_StatusCode result);
1437
1438
/* See the UA_CallbackValueSource documentation */
1439
UA_EXPORT UA_THREADSAFE UA_StatusCode
1440
UA_Server_setAsyncReadResult(UA_Server *server, UA_DataValue *result);
1441
1442
/* See the UA_CallbackValueSource documentation. The value needs to be the
1443
 * pointer used in the write callback. The statuscode is the result signal to be
1444
 * returned asynchronously. */
1445
UA_EXPORT UA_THREADSAFE UA_StatusCode
1446
UA_Server_setAsyncWriteResult(UA_Server *server, const UA_DataValue *value,
1447
                              UA_StatusCode result);
1448
1449
/**
1450
 * The server supports asynchronous "local" read/write/call operations. The user
1451
 * supplies a result-callback that gets called either synchronously (if the
1452
 * operation terminates right away) or asynchronously at a later time. The
1453
 * result-callback is called exactly one time for each operation, also if the
1454
 * operation is cancelled. In this case a StatusCode like
1455
 * ``UA_STATUSCODE_BADTIMEOUT`` or ``UA_STATUSCODE_BADSHUTDOWN`` is set.
1456
 *
1457
 * If an operation returns asynchronously, then the result-callback is executed
1458
 * only in the next iteration of the Eventloop. An exception to this is
1459
 * UA_Server_cancelAsync, which can optionally call the result-callback right
1460
 * away (e.g. as part of a cleanup where the context of the result-callback gets
1461
 * removed).
1462
 *
1463
 * Async operations incur a small overhead since memory is allocated to persist
1464
 * the operation over time.
1465
 *
1466
 * The operation timeout is defined in milliseconds. A timeout of zero means
1467
 * infinite. */
1468
1469
typedef void(*UA_ServerAsyncReadResultCallback)
1470
    (UA_Server *server, void *asyncOpContext, const UA_DataValue *result);
1471
typedef void(*UA_ServerAsyncWriteResultCallback)
1472
    (UA_Server *server, void *asyncOpContext, UA_StatusCode result);
1473
typedef void(*UA_ServerAsyncMethodResultCallback)
1474
    (UA_Server *server, void *asyncOpContext, const UA_CallMethodResult *result);
1475
1476
UA_StatusCode UA_EXPORT UA_THREADSAFE
1477
UA_Server_read_async(UA_Server *server, const UA_ReadValueId *operation,
1478
                     UA_TimestampsToReturn timestamps,
1479
                     UA_ServerAsyncReadResultCallback callback,
1480
                     void *asyncOpContext, UA_UInt32 timeout);
1481
1482
UA_StatusCode UA_EXPORT UA_THREADSAFE
1483
UA_Server_write_async(UA_Server *server, const UA_WriteValue *operation,
1484
                      UA_ServerAsyncWriteResultCallback callback,
1485
                      void *asyncOpContext, UA_UInt32 timeout);
1486
1487
#ifdef UA_ENABLE_METHODCALLS
1488
UA_StatusCode UA_EXPORT UA_THREADSAFE
1489
UA_Server_call_async(UA_Server *server, const UA_CallMethodRequest *operation,
1490
                     UA_ServerAsyncMethodResultCallback callback,
1491
                     void *asyncOpContext, UA_UInt32 timeout);
1492
#endif
1493
1494
/**
1495
 * Local async operations can be manually cancelled (besides an internal cancel
1496
 * due to a timeout or server shutdown). The local async operations to be
1497
 * cancelled are selected by matching their asyncOpContext pointer. This can
1498
 * cancel multiple operations that use the same context pointer.
1499
 *
1500
 * For operations where the async result was not yet set, the
1501
 * asyncOperationCancelCallback from the server-config gets called and the
1502
 * cancel-status is set in the operation result.
1503
 *
1504
 * For async operations where the result has already been set, but not yet
1505
 * notified with the result-callback (to be done in the next EventLoop
1506
 * iteration), the asyncOperationCancelCallback is not called and no cancel
1507
 * status is set in the result.
1508
 *
1509
 * Each operation's result-callback gets called exactly once. When the operation
1510
 * is cancelled, the result-callback can be called synchronously using the
1511
 * synchronousResultCallback flag. Otherwise the result gets returned "normally"
1512
 * in the next EventLoop iteration. The synchronous option ensures that all
1513
 * (matching) async operations are fully cancelled right away. This can be
1514
 * important in a cleanup situation where the asyncOpContext is no longer valid
1515
 * in the future. */
1516
1517
void UA_EXPORT UA_THREADSAFE
1518
UA_Server_cancelAsync(UA_Server *server, void *asyncOpContext,
1519
                      UA_StatusCode status,
1520
                      UA_Boolean synchronousResultCallback);
1521
1522
/**
1523
 * .. _events:
1524
 *
1525
 * Events
1526
 * ------
1527
 * Events are emitted by objects in the OPC UA information model. Starting at
1528
 * the source-node, the events "bubble up" in the hierarchy of objects and are
1529
 * caught by MonitoredItems listening for them.
1530
 *
1531
 * EventTypes are special ObjectTypeNodes that describe the (data) fields of an
1532
 * event instance. An EventType can simply contain a flat list of VariableNodes.
1533
 * But (deep) nesting of objects and variables is also allowed. The individual
1534
 * MonitoredItems then contain an EventFilter (with a select-clause) that
1535
 * defines the event fields to be transmitted to a particular client.
1536
 *
1537
 * In open62541, there are three possible sources for the event fields. When the
1538
 * select-clause of an EventFilter is resolved, the sources are evaluated in the
1539
 * following order:
1540
 *
1541
 * 1. An key-value map that defines event fields. The key of its entries is a
1542
 *    "path-string", a :ref:``human-readable encoding of a
1543
 *    SimpleAttributeOperand<parse-sao>`. For example ``/SourceNode`` or
1544
 *    ``/EventType``.
1545
 * 2. A NodeId pointing to an ObjectNode that instantiates an EventType. The
1546
 *    ``SimpleAttributeOperands`` from the EventFilter are resolved in its
1547
 *    context.
1548
 * 3. The event fields defined as mandatory for the *BaseEventType* have a
1549
 *    default that gets used if they are not defined otherwise:
1550
 *
1551
 *    /EventId
1552
 *       ByteString to uniquely identify the event instance
1553
 *       (default: random 16-byte ByteString)
1554
 *
1555
 *    /EventType
1556
 *       NodeId of the EventType (default: argument of ``_createEvent``)
1557
 *
1558
 *    /SourceNode
1559
 *       NodeId of the emitting node (default: argument of ``_createEvent``)
1560
 *
1561
 *    /SourceName
1562
 *       LocalizedText with the DisplayName of the source node
1563
 *       (default: read from the information model)
1564
 *
1565
 *    /Time
1566
 *       DateTime with the timestamp when the event occurred
1567
 *       (default: current time)
1568
 *
1569
 *    /ReceiveTime
1570
 *       DateTime when the server received the information about the event from an
1571
 *       underlying device (default: current time)
1572
 *
1573
 *    /Message
1574
 *       LocalizedText with a human-readable description of the event (default:
1575
 *       argument of ``_createEvent``)
1576
 *
1577
 *    /Severity
1578
 *       UInt16 for the urgency of the event defined to be between 1 (lowest) and
1579
 *       1000 (catastrophic) (default: argument of ``_createEvent``)
1580
 *
1581
 * The "path-string" (SimpleAttributeOperand expression) can use
1582
 * namespace-indices and point into nested objects and variables. For example
1583
 * ``/1:Truck/2:Wheel``.
1584
 *
1585
 * The key-value map source for the event-fields uses a QualifiedName for the
1586
 * key. The NamespaceIndex from the key is used as the default NamespaceIndex
1587
 * for the path elements that do not define it explicitly. So the key
1588
 * ``2:"/1:Truck/Wheel"`` becomes ``/1:Truck/2:Wheel``.
1589
 *
1590
 * An event field that is missing from all sources resolves to an empty variant.
1591
 *
1592
 * It is typically faster to define event-fields in the key-value map than to
1593
 * look them up from an event instance in the information model. This is
1594
 * particularly important for events emitted at a high frequency. */
1595
1596
#ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
1597
1598
/* Create an event in the server. The eventFields and eventInstance pointer can
1599
 * be NULL and are then not considered as a source of event fields. The
1600
 * outEventId pointer can be NULL. If set, the EventId of a successfully created
1601
 * Event gets copied into the argument. */
1602
UA_StatusCode UA_EXPORT UA_THREADSAFE
1603
UA_Server_createEvent(UA_Server *server, const UA_NodeId sourceNode,
1604
                      const UA_NodeId eventType, UA_UInt16 severity,
1605
                      const UA_LocalizedText message,
1606
                      const UA_KeyValueMap *eventFields,
1607
                      const UA_NodeId *eventInstance,
1608
                      UA_ByteString *outEventId);
1609
1610
/* Extended version of the _createEvent API. The members of the
1611
 * UA_EventDescription structure have the same meaning as above.
1612
 *
1613
 * In addition, the extended version allows the filtering of Events to be only
1614
 * transmitted to a particular Session/Subscription/MonitoredItem. The filtering
1615
 * criteria can be NULL. But the subscriptionId requires a sessionId and the
1616
 * monitoredItemId requires a subscriptionId as context. */
1617
1618
typedef struct {
1619
    /* Event fields */
1620
    UA_NodeId sourceNode;
1621
    UA_NodeId eventType;
1622
    UA_UInt16 severity;
1623
    UA_LocalizedText message;
1624
    const UA_KeyValueMap *eventFields;
1625
    const UA_NodeId *eventInstance;
1626
1627
    /* Restrict who can receive the event */
1628
    const UA_NodeId *sessionId;
1629
    const UA_UInt32 *subscriptionId;
1630
    const UA_UInt32 *monitoredItemId;
1631
} UA_EventDescription;
1632
1633
UA_StatusCode UA_EXPORT UA_THREADSAFE
1634
UA_Server_createEventEx(UA_Server *server,
1635
                        const UA_EventDescription *ed,
1636
                        UA_ByteString *outEventId);
1637
1638
#endif /* UA_ENABLE_SUBSCRIPTIONS_EVENTS */
1639
1640
#ifdef UA_ENABLE_DISCOVERY
1641
1642
/**
1643
 * Remote Discovery Server Registration
1644
 * ------------------------------------
1645
 * The current server can register itself at a discovery. For that it requires
1646
 * to open a client connection. */
1647
1648
/* Register the given server instance at a discovery server. This should be
1649
 * called periodically, for example every 10 minutes, depending on the
1650
 * configuration of the discovery server.
1651
 *
1652
 * The supplied client configuration is used to create a new client to connect
1653
 * to the discovery server. The client configuration is moved over to the server
1654
 * and eventually cleaned up internally. The structure pointed at by `cc` is
1655
 * zeroed to avoid accessing outdated information.
1656
 *
1657
 * The eventloop and logging plugins in the client configuration are replaced by
1658
 * those configured in the server. */
1659
UA_StatusCode UA_EXPORT UA_THREADSAFE
1660
UA_Server_registerDiscovery(UA_Server *server, UA_ClientConfig *cc,
1661
                            const UA_String discoveryServerUrl,
1662
                            const UA_String semaphoreFilePath);
1663
1664
/* Deregister the given server instance from the discovery server.
1665
 * This should be called when the server is shutting down. */
1666
UA_StatusCode UA_EXPORT UA_THREADSAFE
1667
UA_Server_deregisterDiscovery(UA_Server *server, UA_ClientConfig *cc,
1668
                              const UA_String discoveryServerUrl);
1669
1670
/**
1671
 * Local Discovery Server Records
1672
 * ------------------------------
1673
 * The Discovery Service-Set allows the registering of local (for FindServers)
1674
 * and also remote servers (for FindServersOnNetwork).
1675
 *
1676
 * We uniquely identify records by their combination of ServerUri + one matching
1677
 * DiscoveryUrl. */
1678
1679
UA_StatusCode UA_EXPORT UA_THREADSAFE
1680
UA_Server_findServers(UA_Server *server, UA_String endpointUrl,
1681
                      size_t localeIdsSize, UA_LocaleId *localeIds,
1682
                      size_t serverUrisSize, UA_String *serverUris,
1683
                      size_t *outServersSize,
1684
                      UA_ApplicationDescription **outServers);
1685
1686
/* Local API for the RegisterServer2 service. If configurationResults is
1687
 * non-Null, then it must point to an array of discoveryConfigurationSize
1688
 * length. */
1689
UA_StatusCode UA_EXPORT UA_THREADSAFE
1690
UA_Server_registerServer(UA_Server *server,
1691
                         const UA_RegisteredServer *registeredServer,
1692
                         const size_t discoveryConfigurationSize,
1693
                         const UA_ExtensionObject *discoveryConfiguration,
1694
                         UA_StatusCode *configurationResults);
1695
1696
/* Remove the servers matching the ServerUri and at least one of the
1697
 * provided DiscoveryUrls */
1698
UA_StatusCode UA_EXPORT UA_THREADSAFE
1699
UA_Server_deregisterServer(UA_Server *server, const UA_String serverUri,
1700
                           size_t discoveryUrlsSize,
1701
                           const UA_String *discoveryUrls);
1702
1703
/**
1704
 * The server internally manages the ServersOnNetwork list. Multicast discovery
1705
 * is implemented on top in a driver outside of the core library. */
1706
1707
UA_StatusCode UA_EXPORT UA_THREADSAFE
1708
UA_Server_findServersOnNetwork(UA_Server *server, UA_String endpointUrl,
1709
                               UA_UInt32 startingRecordId,
1710
                               UA_UInt32 maxRecordsToReturn,
1711
                               size_t serverCapabilityFilterSize,
1712
                               const UA_String *serverCapabilityFilter,
1713
                               UA_DateTime *outLastCounterResetTime,
1714
                               size_t *outServersSize,
1715
                               UA_ServerOnNetwork **outServers);
1716
1717
/* Register a remote server. If the server name was previously known, the
1718
 * existing entry gets updated. The parameter kv-map can be extended with
1719
 * additional parameters in the future. Currently supported are:
1720
 *
1721
 * 0:remote-address [String]
1722
 *    IP-address or other host identifier from which the information
1723
 *    was received.
1724
 * 0:ttl [UInt32]
1725
 *    Time-to-live of DNS information. Zero means infinite. */
1726
UA_StatusCode UA_EXPORT UA_THREADSAFE
1727
UA_Server_registerServerOnNetwork(UA_Server *server,
1728
                                  const UA_ServerOnNetwork *son,
1729
                                  const UA_KeyValueMap params);
1730
1731
/* Remove the entry of the remote server with the matching ServerName */
1732
UA_StatusCode UA_EXPORT UA_THREADSAFE
1733
UA_Server_deregisterServerOnNetwork(UA_Server *server,
1734
                                    UA_String serverName);
1735
1736
#endif /* UA_ENABLE_DISCOVERY */
1737
1738
/**
1739
 * .. _drivers:
1740
 *
1741
 * Drivers
1742
 * -------
1743
 * Drivers are different from other "plugins" in that they have an explicit
1744
 * stateful lifecycle and can be started/stopped at runtime. Their lifecycle is
1745
 * however dependent on the server into which the drivers are embedded. When the
1746
 * server shuts down, the drivers are also stopped.
1747
 *
1748
 * Drivers can use the server's public API to the full extent. For example
1749
 * add/remove nodes, or register connections and timers in the server's
1750
 * EventLoop.
1751
 *
1752
 * Some drivers define core functionality and are added internally in the server
1753
 * implementation. */
1754
1755
typedef enum {
1756
    UA_DRIVERTYPE_GENERIC = 0
1757
} UA_DriverType;
1758
1759
struct UA_Driver;
1760
typedef struct UA_Driver UA_Driver;
1761
1762
/* Callback through which the server notifies the driver
1763
 * about runtime changes and internal events. */
1764
typedef void
1765
(*UA_DriverNotificationCallback)(UA_Driver *drv,
1766
                                 UA_ApplicationNotificationType type,
1767
                                 const UA_KeyValueMap payload);
1768
1769
struct UA_Driver {
1770
    UA_Driver *next; /* linked-list */
1771
1772
    /*
1773
     * Configuration
1774
     */
1775
1776
    UA_DriverType driverType;
1777
    UA_String name;
1778
1779
    /* See the driver-specific documentation for possible parameters.
1780
     * The params need to be cleaned up within the _free method. */
1781
    UA_KeyValueMap params;
1782
1783
    /* Backpointer to the server. Must be set before _start is called. If NULL
1784
     * this is set by the server during registering. Generally the server must
1785
     * not be switched out once the driver has been started. */
1786
    UA_Server *server;
1787
1788
    /* The server forwards its internal notifications to all drivers. In order
1789
     * to avoid overload, the filter must be set. The top 32bit are ANDed with
1790
     * the notification type to see if the driver is interested in the
1791
     * notification. See the common.h for details on the notification types and
1792
     * their payload. */
1793
    UA_DriverNotificationCallback notificationCallback;
1794
    UA_ApplicationNotificationType notificationFilter;
1795
1796
    /*
1797
     * Lifecycle management
1798
     */
1799
1800
    UA_LifecycleState state;
1801
1802
    /* Start the Driver. It will typically register timers/connections in the
1803
     * EventLoop and may add nodes in the server's information model. Starting
1804
     * can fail if the server is not already started also.
1805
     *
1806
     * During startup, the server calls start on all registered drivers. */
1807
    UA_StatusCode (*start)(UA_Driver *sc);
1808
1809
    /* Stopping is asynchronous and might need a few iterations of the eventloop
1810
     * to succeed. All Drivers are stopped during the shutdown of the server.
1811
     * Once fully stopped, the Driver must no longer rely on the server
1812
     * backpointer. So it can be detached and _free'd at runtime of the
1813
     * server. */
1814
    void (*stop)(UA_Driver *sc);
1815
1816
    /* Clean up and delete the Driver. Can fail if it is not fully stopped. When
1817
     * successfully removed, the Driver must no longer be accessed from the
1818
     * server.
1819
     *
1820
     * Drivers are all free'd when the server is deleted. If a Driver is
1821
     * manually removed before, then it needs to be unlinked from the server's
1822
     * internal linked-list before. */
1823
    UA_StatusCode (*free)(UA_Driver *sc);
1824
};
1825
1826
/* Adds the Driver to the server. Starts the driver if the server is already
1827
 * started. */
1828
UA_StatusCode
1829
UA_Server_addDriver(UA_Server *server, UA_Driver *drv);
1830
1831
/* Remove the Driver from the server. This will fail if the driver is not fully
1832
 * stopped. */
1833
UA_StatusCode
1834
UA_Server_removeDriver(UA_Server *server, UA_Driver *drv);
1835
1836
/* Get the first entry of the server's driver linked list. */
1837
UA_Driver *
1838
UA_Server_getDrivers(UA_Server *server);
1839
1840
/**
1841
 * Statistics
1842
 * ----------
1843
 * Statistic counters keeping track of the current state of the stack. Counters
1844
 * are structured per OPC UA communication layer. */
1845
1846
typedef struct {
1847
   UA_SecureChannelStatistics scs;
1848
   UA_SessionStatistics ss;
1849
} UA_ServerStatistics;
1850
1851
UA_ServerStatistics UA_EXPORT UA_THREADSAFE
1852
UA_Server_getStatistics(UA_Server *server);
1853
1854
/**
1855
 * Reverse Connect
1856
 * ---------------
1857
 * The reverse connect feature of OPC UA permits the server instead of the
1858
 * client to establish the connection. The client must expose the listening port
1859
 * so the server is able to reach it. */
1860
1861
/* The reverse connect state change callback is called whenever the state of a
1862
 * reverse connect is changed by a connection attempt, a successful connection
1863
 * or a connection loss.
1864
 *
1865
 * The reverse connect states reflect the state of the secure channel currently
1866
 * associated with a reverse connect. The state will remain
1867
 * UA_SECURECHANNELSTATE_CONNECTING while the server attempts repeatedly to
1868
 * establish a connection. */
1869
typedef void (*UA_Server_ReverseConnectStateCallback)(UA_Server *server,
1870
                                                      UA_UInt64 handle,
1871
                                                      UA_SecureChannelState state,
1872
                                                      void *context);
1873
1874
/* Registers a reverse connect in the server. The server periodically attempts
1875
 * to establish a connection if the initial connect fails or if the connection
1876
 * breaks.
1877
 *
1878
 * @param server The server object
1879
 * @param url The URL of the remote client
1880
 * @param stateCallback The callback which will be called on state changes
1881
 * @param callbackContext The context for the state callback
1882
 * @param handle Is set to the handle of the reverse connect if not NULL
1883
 * @return Returns UA_STATUSCODE_GOOD if the reverse connect has been registered */
1884
UA_StatusCode UA_EXPORT
1885
UA_Server_addReverseConnect(UA_Server *server, UA_String url,
1886
                            UA_Server_ReverseConnectStateCallback stateCallback,
1887
                            void *callbackContext, UA_UInt64 *handle);
1888
1889
/* Removes a reverse connect from the server and closes the connection if it is
1890
 * currently open.
1891
 *
1892
 * @param server The server object
1893
 * @param handle The handle of the reverse connect to remove
1894
 * @return Returns UA_STATUSCODE_GOOD if the reverse connect has been
1895
 *         successfully removed */
1896
UA_StatusCode UA_EXPORT
1897
UA_Server_removeReverseConnect(UA_Server *server, UA_UInt64 handle);
1898
1899
/**
1900
 * Utility Functions
1901
 * ----------------- */
1902
1903
/* Lookup a datatype by its NodeId. Takes the custom types in the server
1904
 * configuration into account. Return NULL if none found. */
1905
UA_EXPORT const UA_DataType *
1906
UA_Server_findDataType(UA_Server *server, const UA_NodeId *typeId);
1907
1908
/* Add a new namespace to the server. Returns the index of the new namespace */
1909
UA_UInt16 UA_EXPORT UA_THREADSAFE
1910
UA_Server_addNamespace(UA_Server *server, const char* name);
1911
1912
/* Get namespace by name from the server. */
1913
UA_StatusCode UA_EXPORT UA_THREADSAFE
1914
UA_Server_getNamespaceByName(UA_Server *server, const UA_String namespaceUri,
1915
                             size_t* foundIndex);
1916
1917
/* Get namespace by id from the server. */
1918
UA_StatusCode UA_EXPORT UA_THREADSAFE
1919
UA_Server_getNamespaceByIndex(UA_Server *server, const size_t namespaceIndex,
1920
                              UA_String *foundUri);
1921
1922
/**
1923
 * Some convenience functions are provided to simplify the interaction with
1924
 * objects. */
1925
1926
/* Write an object property. The property is represented as a VariableNode with
1927
 * a ``HasProperty`` reference from the ObjectNode. The VariableNode is
1928
 * identified by its BrowseName. Writing the property sets the value attribute
1929
 * of the VariableNode.
1930
 *
1931
 * @param server The server object
1932
 * @param objectId The identifier of the object (node)
1933
 * @param propertyName The name of the property
1934
 * @param value The value to be set for the event attribute
1935
 * @return The StatusCode for setting the event attribute */
1936
UA_StatusCode UA_EXPORT UA_THREADSAFE
1937
UA_Server_writeObjectProperty(UA_Server *server, const UA_NodeId objectId,
1938
                              const UA_QualifiedName propertyName,
1939
                              const UA_Variant value);
1940
1941
/* Directly point to the scalar value instead of a variant */
1942
UA_StatusCode UA_EXPORT UA_THREADSAFE
1943
UA_Server_writeObjectProperty_scalar(UA_Server *server, const UA_NodeId objectId,
1944
                                     const UA_QualifiedName propertyName,
1945
                                     const void *value, const UA_DataType *type);
1946
1947
/* Read an object property.
1948
 *
1949
 * @param server The server object
1950
 * @param objectId The identifier of the object (node)
1951
 * @param propertyName The name of the property
1952
 * @param value Contains the property value after reading. Must not be NULL.
1953
 * @return The StatusCode for setting the event attribute */
1954
UA_StatusCode UA_EXPORT UA_THREADSAFE
1955
UA_Server_readObjectProperty(UA_Server *server, const UA_NodeId objectId,
1956
                             const UA_QualifiedName propertyName,
1957
                             UA_Variant *value);
1958
1959
/**
1960
 * Role-Based Access Control (RBAC)
1961
 * --------------------------------
1962
 *
1963
 * Role-Based Access Control implementation per OPC UA Part 18.
1964
 *
1965
 * **WARNING**: This feature is EXPERIMENTAL and NOT FOR PRODUCTION USE.
1966
 * The RBAC implementation is under active development and the API may change.
1967
 * Use only for testing and development purposes.
1968
 *
1969
 * RBAC allows fine-grained access control by assigning roles to sessions and
1970
 * defining permissions per role on individual nodes or entire namespaces.
1971
 *
1972
 * Type Definitions
1973
 * ~~~~~~~~~~~~~~~~
1974
 */
1975
1976
#ifdef UA_ENABLE_RBAC
1977
1978
/* UA_RolePermission
1979
 * Maps a single role to its permissions bitmask. Used in the server
1980
 * configuration to define presets and in the public API to set or query
1981
 * role permissions on nodes. */
1982
typedef struct {
1983
    UA_NodeId roleId;
1984
    UA_PermissionType permissions;
1985
} UA_RolePermission;
1986
1987
/* UA_RolePermissionSet
1988
 * A set of role-permission mappings. Used in the server configuration
1989
 * to define initial role-permission presets. */
1990
typedef struct {
1991
    size_t rolePermissionsSize;
1992
    UA_RolePermission *rolePermissions;
1993
} UA_RolePermissionSet;
1994
1995
/* UA_RolePermissionSet Type Management */
1996
void UA_EXPORT
1997
UA_RolePermissionSet_init(UA_RolePermissionSet *rps);
1998
1999
void UA_EXPORT
2000
UA_RolePermissionSet_clear(UA_RolePermissionSet *rps);
2001
2002
UA_StatusCode UA_EXPORT
2003
UA_RolePermissionSet_copy(const UA_RolePermissionSet *src,
2004
                          UA_RolePermissionSet *dst);
2005
2006
/* UA_Role
2007
 * Represents an OPC UA role with identity mapping rules and optional
2008
 * application/endpoint restrictions per OPC UA Part 18. */
2009
typedef struct {
2010
    UA_NodeId roleId;
2011
    UA_QualifiedName roleName;              /* BrowseName of the role */
2012
2013
    /* Identity Mapping Rules - determine which sessions get this role */
2014
    size_t identityMappingRulesSize;
2015
    UA_IdentityMappingRuleType *identityMappingRules;
2016
2017
    /* Application restrictions  (empty list = ignore) */
2018
    UA_Boolean applicationsExclude;
2019
    size_t applicationsSize;
2020
    UA_String *applications;
2021
2022
    /* Endpoint restrictions (empty list = ignore) */
2023
    UA_Boolean endpointsExclude;
2024
    size_t endpointsSize;
2025
    UA_EndpointType *endpoints;
2026
} UA_Role;
2027
2028
/* UA_Role Type Management */
2029
void UA_EXPORT
2030
UA_Role_init(UA_Role *role);
2031
2032
void UA_EXPORT
2033
UA_Role_clear(UA_Role *role);
2034
2035
UA_StatusCode UA_EXPORT
2036
UA_Role_copy(const UA_Role *src, UA_Role *dst);
2037
2038
UA_Boolean UA_EXPORT
2039
UA_Role_equal(const UA_Role *r1, const UA_Role *r2);
2040
2041
#endif /* UA_ENABLE_RBAC */
2042
2043
/**
2044
 * .. _server-configuration:
2045
 *
2046
 * Server Configuration
2047
 * --------------------
2048
 * The configuration structure is passed to the server during initialization.
2049
 * The server expects that the configuration is not modified during runtime.
2050
 * Currently, only one server can use a configuration at a time. During
2051
 * shutdown, the server will clean up the parts of the configuration that are
2052
 * modified at runtime through the provided API.
2053
 *
2054
 * Examples for configurations are provided in the ``/plugins`` folder.
2055
 * The usual usage is as follows:
2056
 *
2057
 * 1. Create a server configuration with default settings as a starting point
2058
 * 2. Modifiy the configuration, e.g. by adding a server certificate
2059
 * 3. Instantiate a server with it
2060
 * 4. After shutdown of the server, clean up the configuration (free memory)
2061
 *
2062
 * The :ref:`tutorials` provide a good starting point for this. */
2063
2064
struct UA_ServerConfig {
2065
    void *context; /* Used to attach custom data to a server config. This can
2066
                    * then be retrieved e.g. in a callback that forwards a
2067
                    * pointer to the server. */
2068
    UA_Logger *logging; /* Plugin for log output */
2069
2070
    /* Server Description
2071
     * ~~~~~~~~~~~~~~~~~~
2072
     * The description must be internally consistent. The ApplicationUri set in
2073
     * the ApplicationDescription must match the URI set in the server
2074
     * certificate.
2075
     * The applicationType is not just descriptive, it changes the actual
2076
     * functionality of the server. The RegisterServer service is available only
2077
     * if the server is a DiscoveryServer and the applicationType is set to the
2078
     * appropriate value.*/
2079
    UA_BuildInfo buildInfo;
2080
    UA_ApplicationDescription applicationDescription;
2081
2082
    /* Server Lifecycle
2083
     * ~~~~~~~~~~~~~~~~
2084
     * Delay in ms from the shutdown signal (ctrl-c) until the actual shutdown.
2085
     * Clients need to be able to get a notification ahead of time. */
2086
    UA_Double shutdownDelay;
2087
2088
    /* If an asynchronous server shutdown is used, this callback notifies about
2089
     * the current lifecycle state (notably the STOPPING -> STOPPED
2090
     * transition). */
2091
    void (*notifyLifecycleState)(UA_Server *server, UA_LifecycleState state);
2092
2093
    /* Rule Handling
2094
     * ~~~~~~~~~~~~~
2095
     * Override the handling of standard-defined behavior. These settings are
2096
     * used to balance the following contradicting requirements:
2097
     *
2098
     * - Strict conformance with the standard (for certification).
2099
     * - Ensure interoperability with old/non-conforming implementations
2100
     *   encountered in the wild.
2101
     *
2102
     * The defaults are set for compatibility with the largest number of OPC UA
2103
     * vendors (with log warnings activated). Cf. Postel's Law "be conservative
2104
     * in what you send, be liberal in what you accept".
2105
     *
2106
     * See the section :ref:`rule-handling` for the possible settings. */
2107
2108
    /* Verify that the server sends a timestamp in the request header */
2109
    UA_RuleHandling verifyRequestTimestamp;
2110
2111
    /* Variables (that don't have a DataType of BaseDataType) must not have an
2112
     * empty variant value. The default behaviour is to auto-create a matching
2113
     * zeroed-out value for empty VariableNodes when they are added. */
2114
    UA_RuleHandling allowEmptyVariables;
2115
2116
    UA_RuleHandling allowAllCertificateUris;
2117
2118
    /* Custom Data Types
2119
     * ~~~~~~~~~~~~~~~~~
2120
     * The following is a linked list of arrays with custom data types. All data
2121
     * types that are accessible from here are automatically considered for the
2122
     * decoding of received messages. Custom data types are not cleaned up
2123
     * together with the configuration. So it is possible to allocate them on
2124
     * ROM.
2125
     *
2126
     * See the section on :ref:`generic-types`. Examples for working with custom
2127
     * data types are provided in ``/examples/custom_datatype/``. */
2128
    UA_DataTypeArray *customDataTypes;
2129
2130
    /* EventLoop
2131
     * ~~~~~~~~~
2132
     * The sever can be plugged into an external EventLoop. Otherwise the
2133
     * EventLoop is considered to be attached to the server's lifecycle and will
2134
     * be destroyed when the config is cleaned up. */
2135
    UA_EventLoop *eventLoop;
2136
    UA_Boolean externalEventLoop; /* The EventLoop is not deleted with the config */
2137
2138
    /* Application Notification
2139
     * ~~~~~~~~~~~~~~~~~~~~~~~~
2140
     * The notification callbacks can be NULL. The global callback receives all
2141
     * notifications. The specialized callbacks receive only the subset
2142
     * indicated by their name. */
2143
    UA_ServerNotificationCallback globalNotificationCallback;
2144
    UA_ServerNotificationCallback lifecycleNotificationCallback;
2145
    UA_ServerNotificationCallback secureChannelNotificationCallback;
2146
    UA_ServerNotificationCallback sessionNotificationCallback;
2147
    UA_ServerNotificationCallback serviceNotificationCallback;
2148
    UA_ServerNotificationCallback subscriptionNotificationCallback;
2149
    UA_ServerNotificationCallback discoveryNotificationCallback;
2150
#ifdef UA_ENABLE_AUDITING
2151
    UA_ServerNotificationCallback auditNotificationCallback;
2152
#endif
2153
2154
    /* Networking
2155
     * ~~~~~~~~~~
2156
     * The `severUrls` array contains the server URLs like
2157
     * `opc.tcp://my-server:4840` or `opc.wss://localhost:443`. The URLs are
2158
     * used both for discovery and to set up the server sockets based on the
2159
     * defined hostnames (and ports).
2160
     *
2161
     * - If the list is empty: Listen on all network interfaces with TCP port 4840.
2162
     * - If the hostname of a URL is empty: Use the define protocol and port and
2163
     *   listen on all interfaces. */
2164
    UA_String *serverUrls;
2165
    size_t serverUrlsSize;
2166
2167
    /* The following settings are specific to OPC UA with TCP transport. */
2168
    UA_Boolean tcpEnabled;
2169
    UA_UInt32 tcpBufSize;    /* Max length of sent and received chunks (packets)
2170
                              * (default: 64kB) */
2171
    UA_UInt32 tcpMaxMsgSize; /* Max length of messages
2172
                              * (default: 0 -> unbounded) */
2173
    UA_UInt32 tcpMaxChunks;  /* Max number of chunks per message
2174
                              * (default: 0 -> unbounded) */
2175
    UA_Boolean tcpReuseAddr;
2176
2177
    /* Security and Encryption
2178
     * ~~~~~~~~~~~~~~~~~~~~~~~ */
2179
    size_t securityPoliciesSize;
2180
    UA_SecurityPolicy* securityPolicies;
2181
2182
    /* Endpoints with combinations of SecurityPolicy and SecurityMode. If the
2183
     * UserIdentityToken array of the Endpoint is not set, then it will be
2184
     * filled by the server for all UserTokenPolicies that are configured in the
2185
     * AccessControl plugin. */
2186
    size_t endpointsSize;
2187
    UA_EndpointDescription *endpoints;
2188
2189
    /* Only allow the following discovery services to be executed on a
2190
     * SecureChannel with SecurityPolicyNone: GetEndpointsRequest,
2191
     * FindServersRequest and FindServersOnNetworkRequest.
2192
     *
2193
     * Only enable this option if there is no endpoint with SecurityPolicy#None
2194
     * in the endpoints list. The SecurityPolicy#None must be present in the
2195
     * securityPolicies list. */
2196
    UA_Boolean securityPolicyNoneDiscoveryOnly;
2197
2198
    /* Allow clients without encryption support to connect with username and password.
2199
     * This requires to transmit the password in plain text over the network which is
2200
     * why this option is disabled by default.
2201
     * Make sure you really need this before enabling plain text passwords. */
2202
    UA_Boolean allowNonePolicyPassword;
2203
2204
    /* Different sets of certificates are trusted for SecureChannel / Session.
2205
     * They correspond to the CertificateGroups "DefaultApplicationGroup" and
2206
     * "DefaultUserTokenGroup" from Part 12.
2207
     *
2208
     * If the client authenticates with an X509IdentityToken (ActivateSession
2209
     * Service), then this certificate is validated with the sessionPKI before
2210
     * forwarding the token to the AccessControl plugin. */
2211
    UA_CertificateGroup secureChannelPKI;
2212
    UA_CertificateGroup sessionPKI;
2213
2214
    /* See the AccessControl Plugin API */
2215
    UA_AccessControl accessControl;
2216
2217
    /* Nodes and Node Lifecycle
2218
     * ~~~~~~~~~~~~~~~~~~~~~~~~
2219
     * See the section for :ref:`node lifecycle handling<node-lifecycle>`. */
2220
    UA_Nodestore *nodestore;
2221
    UA_GlobalNodeLifecycle *nodeLifecycle;
2222
2223
    /* Copy the HasModellingRule reference in instances from the type
2224
     * definition in UA_Server_addObjectNode and UA_Server_addVariableNode.
2225
     *
2226
     * Part 3 - 6.4.4: [...] it is not required that newly created or referenced
2227
     * instances based on InstanceDeclarations have a ModellingRule, however, it
2228
     * is allowed that they have any ModellingRule independent of the
2229
     * ModellingRule of their InstanceDeclaration */
2230
    UA_Boolean modellingRulesOnInstances;
2231
2232
    /* Limits
2233
     * ~~~~~~ */
2234
    /* Limits for SecureChannels */
2235
    UA_UInt16 maxSecureChannels;
2236
    UA_UInt32 maxSecurityTokenLifetime; /* in ms */
2237
2238
    /* Limits for Sessions */
2239
    UA_UInt16 maxSessions;
2240
    UA_Double maxSessionTimeout; /* in ms */
2241
2242
    /* Operation limits */
2243
    UA_UInt32 maxNodesPerRead;
2244
    UA_UInt32 maxNodesPerWrite;
2245
    UA_UInt32 maxNodesPerMethodCall;
2246
    UA_UInt32 maxNodesPerBrowse;
2247
    UA_UInt32 maxNodesPerRegisterNodes;
2248
    UA_UInt32 maxNodesPerTranslateBrowsePathsToNodeIds;
2249
    UA_UInt32 maxNodesPerNodeManagement;
2250
    UA_UInt32 maxMonitoredItemsPerCall;
2251
2252
    /* Limits for Requests */
2253
    UA_UInt32 maxReferencesPerNode;
2254
2255
    /* Reverse Connect
2256
     * ~~~~~~~~~~~~~~~ */
2257
    UA_UInt32 reverseReconnectInterval; /* Default is 15000 ms */
2258
2259
    /* Async Operations
2260
     * ~~~~~~~~~~~~~~~~
2261
     * See the section for :ref:`async operations<async-operations>`. */
2262
    UA_Double asyncOperationTimeout;   /* in ms, 0 => unlimited */
2263
    size_t maxAsyncOperationQueueSize; /* 0 => unlimited */
2264
2265
    /* Notifies the userland that an async operation has been canceled. The
2266
     * memory for setting the output value is then freed internally and should
2267
     * not be touched afterwards. */
2268
    void (*asyncOperationCancelCallback)(UA_Server *server, const void *out);
2269
2270
#ifdef UA_ENABLE_ENCRYPTION
2271
    /* Limits for TrustList */
2272
    UA_UInt32 maxTrustListSize; /* in bytes, 0 => unlimited */
2273
    UA_UInt32 maxRejectedListSize; /* 0 => unlimited */
2274
#endif
2275
2276
    /* Discovery
2277
     * ~~~~~~~~~ */
2278
#ifdef UA_ENABLE_DISCOVERY
2279
    /* Enable the internal management of RegisteredServers (besides the local
2280
     * server itself) via the RegisterServer and FindServer services. */
2281
    UA_Boolean registeredServersEnabled;
2282
2283
    /* Timeout in seconds when to automatically remove a registered server from
2284
     * the list, if it doesn't re-register within the given time frame. A value
2285
     * of 0 disables automatic removal. Default is 60 Minutes (60*60). Must be
2286
     * bigger than 10 seconds, because cleanup is only triggered approximately
2287
     * every 10 seconds. The server will still be removed depending on the
2288
     * state of the semaphore file. */
2289
    UA_UInt32 registeredServerCleanupTimeout;
2290
2291
    /* mDNS based Announcement and Discovery is implemented in a driver that
2292
     * attach to a server outside the main configuration. The
2293
     * FindServersOnNetwork Server is however implemented by the server itself.
2294
     * The drivers interact with the server via the Discovery API. For example
2295
     * to add/update/remove a ServerOnNetwork structure. */
2296
2297
    /* Enable the internal management of ServerOnNetwork entries and the
2298
     * FindServersOnNetwork Service. This is used in conjunction with mDNS to
2299
     * implement a Discovery Server that detects other servers on the
2300
     * network. */
2301
    UA_Boolean serversOnNetworkEnabled;
2302
#endif
2303
2304
    /* Subscriptions
2305
     * ~~~~~~~~~~~~~ */
2306
    UA_Boolean subscriptionsEnabled;
2307
#ifdef UA_ENABLE_SUBSCRIPTIONS
2308
    /* Limits for Subscriptions */
2309
    UA_UInt32 maxSubscriptions;
2310
    UA_UInt32 maxSubscriptionsPerSession;
2311
    UA_DurationRange publishingIntervalLimits; /* in ms (must not be less than 5) */
2312
    UA_UInt32Range lifeTimeCountLimits;
2313
    UA_UInt32Range keepAliveCountLimits;
2314
    UA_UInt32 maxNotificationsPerPublish;
2315
    UA_Boolean enableRetransmissionQueue;
2316
    UA_UInt32 maxRetransmissionQueueSize; /* 0 -> unlimited size */
2317
# ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
2318
    UA_UInt32 maxEventsPerNode; /* 0 -> unlimited size */
2319
# endif
2320
2321
    /* Limits for MonitoredItems */
2322
    UA_UInt32 maxMonitoredItems;
2323
    UA_UInt32 maxMonitoredItemsPerSubscription;
2324
    UA_DurationRange samplingIntervalLimits; /* in ms (must not be less than 5) */
2325
    UA_UInt32Range queueSizeLimits; /* Negotiated with the client */
2326
2327
    /* Limits for PublishRequests */
2328
    UA_UInt32 maxPublishReqPerSession;
2329
2330
    /* Register MonitoredItem in Userland.
2331
     * Deprecated now. Use the ServerNotificationCallback mechanism with
2332
     * UA_APPLICATIONNOTIFICATIONTYPE_MONITOREDITEM for the same feature.
2333
    void (*monitoredItemRegisterCallback)(UA_Server *server,
2334
                                          const UA_NodeId *sessionId,
2335
                                          void *sessionContext,
2336
                                          const UA_NodeId *nodeId,
2337
                                          void *nodeContext,
2338
                                          UA_UInt32 attibuteId,
2339
                                          UA_Boolean removed);
2340
    */
2341
#endif
2342
2343
    /* PubSub
2344
     * ~~~~~~ */
2345
#ifdef UA_ENABLE_PUBSUB
2346
    UA_Boolean pubsubEnabled;
2347
    UA_PubSubConfiguration pubSubConfig;
2348
#endif
2349
2350
    /* Auditing
2351
     * ~~~~~~~~
2352
     * Drops audit events into the auditNotificationCallback and generates
2353
     * the corresponding Audit Events (if Events are enabled). */
2354
    UA_Boolean auditingEnabled;
2355
#ifdef UA_ENABLE_AUDITING
2356
    UA_Boolean auditWriteUpdateEnabled;  /* Mind the runtime overhead */
2357
    UA_Boolean auditMethodUpdateEnabled; /* Mind the runtime overhead */
2358
#endif
2359
2360
    /* Historical Access
2361
     * ~~~~~~~~~~~~~~~~~ */
2362
    UA_Boolean historizingEnabled;
2363
#ifdef UA_ENABLE_HISTORIZING
2364
    UA_HistoryDatabase historyDatabase;
2365
2366
    UA_Boolean accessHistoryDataCapability;
2367
    UA_UInt32  maxReturnDataValues; /* 0 -> unlimited size */
2368
2369
    UA_Boolean accessHistoryEventsCapability;
2370
    UA_UInt32  maxReturnEventValues; /* 0 -> unlimited size */
2371
2372
    UA_Boolean insertDataCapability;
2373
    UA_Boolean insertEventCapability;
2374
    UA_Boolean insertAnnotationsCapability;
2375
2376
    UA_Boolean replaceDataCapability;
2377
    UA_Boolean replaceEventCapability;
2378
2379
    UA_Boolean updateDataCapability;
2380
    UA_Boolean updateEventCapability;
2381
2382
    UA_Boolean deleteRawCapability;
2383
    UA_Boolean deleteEventCapability;
2384
    UA_Boolean deleteAtTimeDataCapability;
2385
#endif
2386
2387
    /* Certificate Password Callback
2388
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2389
#ifdef UA_ENABLE_ENCRYPTION
2390
    /* If the private key is in PEM format and password protected, this callback
2391
     * is called during initialization to get the password to decrypt the
2392
     * private key. The memory containing the password is freed by the client
2393
     * after use. The callback should be set early, other parts of the client
2394
     * config setup may depend on it. */
2395
    UA_StatusCode (*privateKeyPasswordCallback)(UA_ServerConfig *sc,
2396
                                                UA_ByteString *password);
2397
#endif
2398
2399
#ifdef UA_ENABLE_RBAC
2400
    /* Initial Role-Permission Presets
2401
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2402
     * Array of initial role-permission presets. Each entry is a set of
2403
     * UA_RolePermission mappings that define which roles get which
2404
     * permissions on nodes that reference this preset.
2405
     *
2406
     * During server startup, these presets are copied into the server's
2407
     * internal role-permissions array. The preset entries form the initial
2408
     * configuration with the following guarantees:
2409
     *
2410
     * - Preset entries are **never deleted** during server runtime.
2411
     * - Their position (index) in the internal array is **kept stable**,
2412
     *   ensuring that nodes assigned to a preset continue to reference
2413
     *   the same configuration throughout the server's lifetime.
2414
     * - Custom nodestore implementations should be aware of these
2415
     *   index-stability guarantees when managing node permission storage.
2416
     *
2417
     * Additional role-permission sets can be added at runtime through
2418
     * the server API (UA_Server_setNodeRolePermissions). Runtime entries
2419
     * may be garbage-collected when no longer referenced by any node. */
2420
    size_t rolePermissionPresetsSize;
2421
    UA_RolePermissionSet *rolePermissionPresets;
2422
2423
    /* Initial Role Definitions
2424
     * ~~~~~~~~~~~~~~~~~~~~~~~~
2425
     * Array of initial role definitions. During server startup, these roles
2426
     * are copied into the server's internal role registry. Config roles are
2427
     * treated as **protected**: they cannot be removed at runtime via
2428
     * UA_Server_removeRole.
2429
     *
2430
     * Additional roles can be added at runtime through UA_Server_addRole.
2431
     * Runtime-added roles can be removed via UA_Server_removeRole. */
2432
    size_t rolesSize;
2433
    UA_Role *roles;
2434
2435
    /* If true, all permissions are granted regardless of roles.
2436
     * WARNING: Effectively disables authorization. Use for testing only. */
2437
    UA_Boolean allPermissionsForAnonymous;
2438
#endif
2439
};
2440
2441
void UA_EXPORT
2442
UA_ServerConfig_clear(UA_ServerConfig *config);
2443
2444
UA_DEPRECATED static UA_INLINE void
2445
0
UA_ServerConfig_clean(UA_ServerConfig *config) {
2446
0
    UA_ServerConfig_clear(config);
2447
0
}
Unexecuted instantiation: ua_util.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_session.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_nodes.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_ns0.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_ns0_diagnostics.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_gds_push.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_ns0_gds.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_config.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_binary.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_binary_reverse.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_utils.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_auditing.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_async.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription_datachange.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription_event.c:UA_ServerConfig_clean
Unexecuted instantiation: alarms_conditions.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_view.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_method.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_session.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_attribute.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_discovery.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_subscription.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_monitoreditem.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_securechannel.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_nodemanagement.c:UA_ServerConfig_clean
Unexecuted instantiation: namespace0_generated.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_connection.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_dataset.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_writer.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_writergroup.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_reader.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_readergroup.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_manager.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_ns0.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_ns0_sks.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_keystorage.c:UA_ServerConfig_clean
Unexecuted instantiation: discovery_mdns_mdnsd.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_discovery.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_accesscontrol_default.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_nodestore_ziptree.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_config_default.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_config_json.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_history_data_backend_memory.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_history_data_gathering_default.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_history_database_default.c:UA_ServerConfig_clean
2448
2449
/**
2450
 * Update the Server Certificate at Runtime
2451
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2452
 * If certificateGroupId is null the DefaultApplicationGroup is used.
2453
 */
2454
2455
UA_StatusCode UA_EXPORT UA_THREADSAFE
2456
UA_Server_updateCertificate(UA_Server *server,
2457
                            const UA_NodeId certificateGroupId,
2458
                            const UA_NodeId certificateTypeId,
2459
                            const UA_ByteString certificate,
2460
                            const UA_ByteString *privateKey);
2461
2462
/* Creates a PKCS #10 DER encoded certificate request signed with the server's
2463
 * private key.
2464
 * If certificateGroupId is null the DefaultApplicationGroup is used.
2465
 */
2466
UA_StatusCode UA_EXPORT UA_THREADSAFE
2467
UA_Server_createSigningRequest(UA_Server *server,
2468
                               const UA_NodeId certificateGroupId,
2469
                               const UA_NodeId certificateTypeId,
2470
                               const UA_String *subjectName,
2471
                               const UA_Boolean *regenerateKey,
2472
                               const UA_ByteString *nonce,
2473
                               UA_ByteString *csr);
2474
2475
/* Adds certificates and Certificate Revocation Lists (CRLs) to a specific
2476
 * certificate group on the server.
2477
 *
2478
 * @param server The server object
2479
 * @param certificateGroupId The NodeId of the certificate group where
2480
 *        certificates will be added
2481
 * @param certificates The certificates to be added
2482
 * @param certificatesSize The number of certificates
2483
 * @param crls The associated CRLs for the certificates, required when adding
2484
 *        issuer certificates
2485
 * @param crlsSize The number of CRLs
2486
 * @param isTrusted Indicates whether the certificates should be added to the
2487
 *        trusted list or the issuer list
2488
 * @param appendCertificates Indicates whether the certificates should be added
2489
 *        to the list or replace the existing list
2490
 * @return ``UA_STATUSCODE_GOOD`` on success */
2491
UA_StatusCode UA_EXPORT
2492
UA_Server_addCertificates(UA_Server *server,
2493
                          const UA_NodeId certificateGroupId,
2494
                          UA_ByteString *certificates,
2495
                          size_t certificatesSize,
2496
                          UA_ByteString *crls,
2497
                          size_t crlsSize,
2498
                          const UA_Boolean isTrusted,
2499
                          const UA_Boolean appendCertificates);
2500
2501
/* Removes certificates from a specific certificate group on the server. The
2502
 * corresponding CRLs are removed automatically.
2503
 *
2504
 * @param server The server object
2505
 * @param certificateGroupId The NodeId of the certificate group from which
2506
 *        certificates will be removed
2507
 * @param certificates The certificates to be removed
2508
 * @param certificatesSize The number of certificates
2509
 * @param isTrusted Indicates whether the certificates are being removed from
2510
 *        the trusted list or the issuer list
2511
 * @return ``UA_STATUSCODE_GOOD`` on success */
2512
UA_StatusCode UA_EXPORT
2513
UA_Server_removeCertificates(UA_Server *server,
2514
                             const UA_NodeId certificateGroupId,
2515
                             UA_ByteString *certificates,
2516
                             size_t certificatesSize,
2517
                             const UA_Boolean isTrusted);
2518
2519
/**
2520
 * RBAC API
2521
 * ~~~~~~~~
2522
 */
2523
2524
#ifdef UA_ENABLE_RBAC
2525
2526
/**
2527
 * Node Role-Permission Management
2528
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2529
 * Functions for managing role permissions on individual nodes. */
2530
2531
/* Set role permissions for a node.
2532
 *
2533
 * Assigns the given set of role-permission mappings to the specified node.
2534
 * If an identical permission configuration already exists internally, the
2535
 * node will reference the existing configuration (deduplication). Otherwise,
2536
 * a new internal entry is created.
2537
 *
2538
 * @param server The server instance
2539
 * @param nodeId The NodeId of the node
2540
 * @param rolePermissionsSize Number of role-permission entries
2541
 * @param rolePermissions Array of role-permission mappings
2542
 * @param recursive If true, also set for all hierarchically referenced
2543
 *        child nodes
2544
 * @param options Reserved for future use (e.g. to restrict the reference
2545
 *        type for recursive traversal). Pass NULL for now.
2546
 * @return UA_STATUSCODE_GOOD on success */
2547
UA_StatusCode UA_EXPORT UA_THREADSAFE
2548
UA_Server_setNodeRolePermissions(UA_Server *server,
2549
                                 const UA_NodeId nodeId,
2550
                                 size_t rolePermissionsSize,
2551
                                 const UA_RolePermission *rolePermissions,
2552
                                 UA_Boolean recursive,
2553
                                 const UA_KeyValueMap *options);
2554
2555
/* Get the role permissions of a node.
2556
 *
2557
 * Returns a copy of the role-permission mappings currently assigned to
2558
 * the node. The output array and its entries are allocated and must be
2559
 * freed by the caller.
2560
 *
2561
 * If the node has no specific role permissions assigned, the output size
2562
 * is set to 0 and the output pointer to NULL.
2563
 *
2564
 * @param server The server instance
2565
 * @param nodeId The NodeId of the node
2566
 * @param rolePermissionsSize Output: number of entries
2567
 * @param rolePermissions Output: deep-copy array of role-permission mappings
2568
 * @return UA_STATUSCODE_GOOD on success */
2569
UA_StatusCode UA_EXPORT UA_THREADSAFE
2570
UA_Server_getNodeRolePermissions(UA_Server *server,
2571
                                 const UA_NodeId nodeId,
2572
                                 size_t *rolePermissionsSize,
2573
                                 UA_RolePermission **rolePermissions);
2574
2575
/* Remove role permissions from a node.
2576
 *
2577
 * Resets the node to have no specific role permissions. Default access
2578
 * control behavior then applies. The internal reference count for the
2579
 * previously assigned permission configuration is decremented.
2580
 *
2581
 * @param server The server instance
2582
 * @param nodeId The NodeId of the node
2583
 * @param recursive If true, also remove from all hierarchically referenced
2584
 *        child nodes
2585
 * @return UA_STATUSCODE_GOOD on success */
2586
UA_StatusCode UA_EXPORT UA_THREADSAFE
2587
UA_Server_removeNodeRolePermissions(UA_Server *server,
2588
                                    const UA_NodeId nodeId,
2589
                                    UA_Boolean recursive);
2590
2591
/**
2592
 * Role Management
2593
 * ^^^^^^^^^^^^^^^
2594
 * Functions for managing the server's role registry. Roles define which
2595
 * sessions get which access rights. Config-provided roles are protected
2596
 * and cannot be removed at runtime. */
2597
2598
/* Add a role to the server's role registry.
2599
 *
2600
 * The role's BrowseName (roleName) is the primary unique identifier,
2601
 * per OPC UA Part 18 Section 4.2. A role with the same roleName or
2602
 * roleId must not already exist.
2603
 *
2604
 * If role->roleId is null, the server auto-assigns a random numeric
2605
 * NodeId in namespace 0. To control the namespace or identifier, set
2606
 * role->roleId before calling.
2607
 *
2608
 * @param server The server instance
2609
 * @param role The role definition to add (deep-copied)
2610
 * @param outRoleNodeId Output: the assigned NodeId (deep copy). May be NULL.
2611
 * @return UA_STATUSCODE_GOOD on success,
2612
 *         UA_STATUSCODE_BADALREADYEXISTS if a role with the same
2613
 *         roleName or roleId already exists */
2614
UA_StatusCode UA_EXPORT UA_THREADSAFE
2615
UA_Server_addRole(UA_Server *server, const UA_Role *role,
2616
                  UA_NodeId *outRoleNodeId);
2617
2618
/* Remove a role from the server's role registry.
2619
 *
2620
 * Config-provided (protected) roles cannot be removed.
2621
 *
2622
 * @param server The server instance
2623
 * @param roleName The BrowseName (QualifiedName) of the role to remove
2624
 * @return UA_STATUSCODE_GOOD on success,
2625
 *         UA_STATUSCODE_BADUSERACCESSDENIED if the role is protected,
2626
 *         UA_STATUSCODE_BADNOTFOUND if the role does not exist */
2627
UA_StatusCode UA_EXPORT UA_THREADSAFE
2628
UA_Server_removeRole(UA_Server *server,
2629
                     const UA_QualifiedName roleName);
2630
2631
/* Get a copy of a role by its BrowseName.
2632
 *
2633
 * @param server The server instance
2634
 * @param roleName The BrowseName (QualifiedName) of the role
2635
 * @param outRole Output: deep copy of the role (caller must clear)
2636
 * @return UA_STATUSCODE_GOOD on success,
2637
 *         UA_STATUSCODE_BADNOTFOUND if the role does not exist */
2638
UA_StatusCode UA_EXPORT UA_THREADSAFE
2639
UA_Server_getRole(UA_Server *server,
2640
                  const UA_QualifiedName roleName,
2641
                  UA_Role *outRole);
2642
2643
/* Get a copy of a role by its NodeId.
2644
 *
2645
 * @param server The server instance
2646
 * @param roleId The NodeId of the role
2647
 * @param outRole Output: deep copy of the role (caller must clear)
2648
 * @return UA_STATUSCODE_GOOD on success,
2649
 *         UA_STATUSCODE_BADNOTFOUND if the role does not exist */
2650
UA_StatusCode UA_EXPORT UA_THREADSAFE
2651
UA_Server_getRoleById(UA_Server *server, UA_NodeId roleId,
2652
                      UA_Role *outRole);
2653
2654
/* Get the BrowseNames of all registered roles.
2655
 *
2656
 * @param server The server instance
2657
 * @param rolesSize Output: number of roles
2658
 * @param roleNames Output: array of role BrowseNames (caller must
2659
 *        clear each entry and free the array)
2660
 * @return UA_STATUSCODE_GOOD on success */
2661
UA_StatusCode UA_EXPORT UA_THREADSAFE
2662
UA_Server_getRoles(UA_Server *server, size_t *rolesSize,
2663
                   UA_QualifiedName **roleNames);
2664
2665
/* Update a role in the server's role registry.
2666
 *
2667
 * The existing role is matched by roleId, roleName (QualifiedName) or
2668
 * both. At least one must be set. If both are provided they must
2669
 * identify the same role. Replaces all mutable fields (identityMappingRules,
2670
 * applications, endpoints and their exclude flags) with deep copies
2671
 * from the provided role. The roleId and roleName of the stored role
2672
 * are not changed.
2673
 *
2674
 * Anonymous and AuthenticatedUser are well-known roles defined by the
2675
 * OPC UA specification and cannot be modified.
2676
 *
2677
 * @param server The server instance
2678
 * @param role The role with updated fields
2679
 * @return UA_STATUSCODE_GOOD on success,
2680
 *         UA_STATUSCODE_BADINVALIDARGUMENT if neither roleId nor
2681
 *         roleName is set,
2682
 *         UA_STATUSCODE_BADNOTFOUND if no matching role exists,
2683
 *         UA_STATUSCODE_BADUSERACCESSDENIED if the matched role is
2684
 *         Anonymous or AuthenticatedUser */
2685
UA_StatusCode UA_EXPORT UA_THREADSAFE
2686
UA_Server_updateRole(UA_Server *server, const UA_Role *role);
2687
2688
/**
2689
 * Session Role Management
2690
 * ^^^^^^^^^^^^^^^^^^^^^^^
2691
 * Session roles are managed via the generic session attribute API using the
2692
 * key ``UA_QUALIFIEDNAME(0, "roles")``. The value is a ``UA_NodeId[]``
2693
 * array of the roles assigned to the session.
2694
 *
2695
 * All role NodeIds are validated against the server's role registry on write.
2696
 *
2697
 * **Set roles:**
2698
 *
2699
 * .. code-block:: c
2700
 *
2701
 *    UA_NodeId roles[2] = { role1Id, role2Id };
2702
 *    UA_Variant v;
2703
 *    UA_Variant_setArray(&v, roles, 2, &UA_TYPES[UA_TYPES_NODEID]);
2704
 *    UA_Server_setSessionAttribute(server, &sessionId,
2705
 *                                  UA_QUALIFIEDNAME(0, "roles"), &v);
2706
 *
2707
 * **Get roles (deep copy):**
2708
 *
2709
 * .. code-block:: c
2710
 *
2711
 *    UA_Variant out;
2712
 *    UA_Server_getSessionAttributeCopy(server, &sessionId,
2713
 *                                      UA_QUALIFIEDNAME(0, "roles"), &out);
2714
 *    UA_NodeId *roles = (UA_NodeId *)out.data;
2715
 *    size_t count = out.arrayLength;
2716
 *    // ... use roles ...
2717
 *    UA_Variant_clear(&out);
2718
 *
2719
 * **Clear roles:**
2720
 *
2721
 * .. code-block:: c
2722
 *
2723
 *    UA_Server_deleteSessionAttribute(server, &sessionId,
2724
 *                                     UA_QUALIFIEDNAME(0, "roles")); */
2725
2726
/* Convenience: Get role QualifiedNames assigned to a session.
2727
 * Returns a deep copy of the role names. Free the result with
2728
 * UA_Array_delete(roleNames, count, &UA_TYPES[UA_TYPES_QUALIFIEDNAME]).
2729
 *
2730
 * @param server The server instance
2731
 * @param sessionId The session to query
2732
 * @param outSize Output: number of roles
2733
 * @param outRoleNames Output: deep-copy array of QualifiedNames
2734
 * @return UA_STATUSCODE_GOOD on success */
2735
UA_StatusCode UA_EXPORT UA_THREADSAFE
2736
UA_Server_getSessionRoleNames(UA_Server *server, const UA_NodeId sessionId,
2737
                              size_t *outSize, UA_QualifiedName **outRoleNames);
2738
2739
/* Convenience bitmask: all permission bits set */
2740
#define UA_PERMISSIONTYPE_ALL ((UA_PermissionType)0xFFFFFFFF)
2741
2742
/**
2743
 * Per-Role Node Permission Management
2744
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2745
 * Functions that add or remove permissions for a specific role on a node.
2746
 * Unlike setNodeRolePermissions (which replaces the entire set), these
2747
 * functions modify individual role entries within the node's permission
2748
 * configuration. */
2749
2750
/* Add role permissions to a node for a specific role.
2751
 *
2752
 * @param server The server instance
2753
 * @param nodeId The node to modify
2754
 * @param roleId The role to add permissions for
2755
 * @param permissions Permission bitmask to set
2756
 * @param overwriteExisting If true, replace the role's existing permission
2757
 *        bitmask entirely; if false, OR (merge) the new bits into the
2758
 *        existing bitmask
2759
 * @param recursive If true, apply recursively to child nodes
2760
 * @return UA_STATUSCODE_GOOD on success */
2761
UA_StatusCode UA_EXPORT UA_THREADSAFE
2762
UA_Server_addRolePermissions(UA_Server *server, const UA_NodeId nodeId,
2763
                             const UA_NodeId roleId,
2764
                             UA_PermissionType permissions,
2765
                             UA_Boolean overwriteExisting,
2766
                             UA_Boolean recursive);
2767
2768
/* Remove role permissions from a node for a specific role.
2769
 *
2770
 * @param server The server instance
2771
 * @param nodeId The node to modify
2772
 * @param roleId The role to remove permissions for
2773
 * @param permissions Permission bitmask to clear
2774
 * @param recursive If true, apply recursively to child nodes
2775
 * @return UA_STATUSCODE_GOOD on success */
2776
UA_StatusCode UA_EXPORT UA_THREADSAFE
2777
UA_Server_removeRolePermissions(UA_Server *server, const UA_NodeId nodeId,
2778
                                const UA_NodeId roleId,
2779
                                UA_PermissionType permissions,
2780
                                UA_Boolean recursive);
2781
2782
/**
2783
 * Namespace Default Role Permissions
2784
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2785
 * Per OPC UA Part 5: if a node has no explicit RolePermissions,
2786
 * the DefaultRolePermissions from the NamespaceMetadata apply.
2787
 *
2788
 * Permission resolution order:
2789
 *  1. Explicit node RolePermissions (set via addRolePermissions)
2790
 *  2. Namespace default RolePermissions (set via this API) */
2791
2792
/* Set default role permissions for a namespace.
2793
 * Overwrites any previously set defaults for the given namespace.
2794
 *
2795
 * @param server The server instance
2796
 * @param namespaceIndex The namespace index
2797
 * @param entriesSize Number of role-permission entries
2798
 * @param entries Array of role-permission entries (deep-copied)
2799
 * @return UA_STATUSCODE_GOOD on success */
2800
UA_StatusCode UA_EXPORT UA_THREADSAFE
2801
UA_Server_setNamespaceDefaultRolePermissions(UA_Server *server,
2802
                                             UA_UInt16 namespaceIndex,
2803
                                             size_t entriesSize,
2804
                                             const UA_RolePermission *entries);
2805
2806
/* Get default role permissions for a namespace.
2807
 * Returns a deep copy. The caller must free each entry's roleId
2808
 * with UA_NodeId_clear and the array with UA_free.
2809
 *
2810
 * @param server The server instance
2811
 * @param namespaceIndex The namespace index
2812
 * @param entriesSize Output: number of entries
2813
 * @param entries Output: deep-copied array (caller must free)
2814
 * @return UA_STATUSCODE_GOOD on success */
2815
UA_StatusCode UA_EXPORT UA_THREADSAFE
2816
UA_Server_getNamespaceDefaultRolePermissions(UA_Server *server,
2817
                                             UA_UInt16 namespaceIndex,
2818
                                             size_t *entriesSize,
2819
                                             UA_RolePermission **entries);
2820
2821
#endif /* UA_ENABLE_RBAC */
2822
2823
/**
2824
 * .. _server-json-config:
2825
 *
2826
 * Configuration from File
2827
 * -----------------------
2828
 *
2829
 * The server can be configured from JSON5-formatted content stored in a
2830
 * ``UA_ByteString``.
2831
 *
2832
 * The example files ``examples/json_config/server_json_config.json5`` and
2833
 * ``examples/server_json_config.c`` document the intended workflow and the
2834
 * currently supported keys. They cover the common runtime limits as well as
2835
 * optional blocks for discovery, subscriptions, historizing, PubSub and
2836
 * security policy configuration.
2837
 *
2838
 * The following functions require JSON encoding support
2839
 * (``UA_ENABLE_JSON_ENCODING``). */
2840
2841
#ifdef UA_ENABLE_JSON_ENCODING
2842
2843
/* Loads the server configuration from a Json5 file into the server.
2844
 *
2845
 * @param jsonConfig The configuration in json5 format.
2846
 */
2847
UA_EXPORT UA_Server *
2848
UA_Server_newFromFile(const UA_ByteString jsonConfig);
2849
2850
/* Loads a server configuration from a file.  The passed server configuration
2851
 * is cleared.  Memory will be allocated for fields in config.
2852
 *
2853
 * @param config The server configuration.
2854
 * @param jsonConfig The configuration in json5 format.
2855
 */
2856
UA_EXPORT UA_StatusCode
2857
UA_ServerConfig_loadFromFile(UA_ServerConfig *config, const UA_ByteString jsonConfig);
2858
2859
#endif /* UA_ENABLE_JSON_ENCODING */
2860
2861
_UA_END_DECLS
2862
2863
#ifdef UA_ENABLE_PUBSUB
2864
#include <open62541/server_pubsub.h>
2865
#endif
2866
2867
#endif /* UA_SERVER_H_ */