Coverage Report

Created: 2026-10-15 06:43

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