Coverage Report

Created: 2026-11-05 06:53

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