Coverage Report

Created: 2026-10-05 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541_15/src/server/ua_services_discovery.c
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-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
6
 *    Copyright 2014-2016 (c) Sten GrĂ¼ner
7
 *    Copyright 2014, 2017 (c) Florian Palm
8
 *    Copyright 2016 (c) Oleksiy Vasylyev
9
 *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
10
 *    Copyright 2017 (c) frax2222
11
 *    Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
12
 *    Copyright 2026 (c) o6 Automation GmbH (Author: Andreas Ebner)
13
 */
14
15
#include "ua_server_internal.h"
16
#include "ua_discovery.h"
17
#include "ua_services.h"
18
19
#ifdef UA_ENABLE_DISCOVERY
20
21
#include <open62541/client.h>
22
23
static UA_StatusCode
24
setApplicationDescriptionFromRegisteredServer(const UA_FindServersRequest *request,
25
                                              UA_ApplicationDescription *target,
26
0
                                              const UA_RegisteredServer *rs) {
27
0
    UA_StatusCode retval =  UA_STATUSCODE_GOOD;
28
0
    target->applicationType = rs->serverType;
29
0
    retval |= UA_String_copy(&rs->serverUri, &target->applicationUri);
30
0
    retval |= UA_String_copy(&rs->productUri, &target->productUri);
31
0
    retval |= UA_String_copy(&rs->gatewayServerUri, &target->gatewayServerUri);
32
0
    if(retval != UA_STATUSCODE_GOOD)
33
0
        return retval;
34
35
    /* If the client requests a specific locale, select the corresponding server
36
     * name */
37
0
    if(request->localeIdsSize) {
38
0
        UA_Boolean appNameFound = false;
39
0
        for(size_t i = 0; i < request->localeIdsSize && !appNameFound; i++) {
40
0
            for(size_t j =0; j < rs->serverNamesSize; j++) {
41
0
                if(UA_String_equal(&request->localeIds[i],
42
0
                                   &rs->serverNames[j].locale)) {
43
0
                    retval = UA_LocalizedText_copy(&rs->serverNames[j],
44
0
                                                   &target->applicationName);
45
0
                    if(retval != UA_STATUSCODE_GOOD)
46
0
                        return retval;
47
0
                    appNameFound = true;
48
0
                    break;
49
0
                }
50
0
            }
51
0
        }
52
53
        /* Server does not have the requested local, therefore we can select the
54
         * most suitable one */
55
0
        if(!appNameFound && rs->serverNamesSize) {
56
0
            retval = UA_LocalizedText_copy(&rs->serverNames[0],
57
0
                                           &target->applicationName);
58
0
            if(retval != UA_STATUSCODE_GOOD)
59
0
                return retval;
60
0
        }
61
0
    } else if(rs->serverNamesSize) {
62
        /* Just take the first name */
63
0
        retval = UA_LocalizedText_copy(&rs->serverNames[0],
64
0
                                       &target->applicationName);
65
0
        if(retval != UA_STATUSCODE_GOOD)
66
0
            return retval;
67
0
    }
68
69
    /* TODO: Where do we get the discoveryProfileUri for application data? */
70
71
0
    if(rs->discoveryUrlsSize > 0) {
72
0
        target->discoveryUrls = (UA_String *)
73
0
            UA_calloc(rs->discoveryUrlsSize, sizeof(UA_String));
74
0
        if(!target->discoveryUrls)
75
0
            return UA_STATUSCODE_BADOUTOFMEMORY;
76
0
        target->discoveryUrlsSize = rs->discoveryUrlsSize;
77
0
        for(size_t i = 0; i < rs->discoveryUrlsSize; i++)
78
0
            retval |= UA_String_copy(&rs->discoveryUrls[i],
79
0
                                     &target->discoveryUrls[i]);
80
0
    }
81
82
0
    return retval;
83
0
}
84
#endif
85
86
UA_Boolean
87
Service_FindServers(UA_Server *server, UA_Session *session,
88
                    const UA_FindServersRequest *request,
89
180
                    UA_FindServersResponse *response) {
90
180
    UA_ServerConfig *sc = &server->config;
91
180
    UA_LOG_DEBUG_SESSION(sc->logging, session, "Processing FindServersRequest");
92
180
    UA_LOCK_ASSERT(&server->serviceMutex);
93
94
    /* Return the server itself? */
95
180
    UA_Boolean foundSelf = false;
96
180
    if(request->serverUrisSize) {
97
3.46k
        for(size_t i = 0; i < request->serverUrisSize; i++) {
98
3.31k
            if(UA_String_equal(&request->serverUris[i],
99
3.31k
                               &sc->applicationDescription.applicationUri)) {
100
1
                foundSelf = true;
101
1
                break;
102
1
            }
103
3.31k
        }
104
154
    } else {
105
26
        foundSelf = true;
106
26
    }
107
108
#ifndef UA_ENABLE_DISCOVERY
109
    if(!foundSelf)
110
        return true;
111
112
    response->responseHeader.serviceResult =
113
        UA_Array_copy(&sc->applicationDescription, 1, (void**)&response->servers,
114
                      &UA_TYPES[UA_TYPES_APPLICATIONDESCRIPTION]);
115
    if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
116
        return true;
117
118
    response->serversSize = 1;
119
#else
120
180
    UA_DiscoveryManager *dm = (UA_DiscoveryManager*)
121
180
        getServerComponentByName(server, UA_STRING("discovery"));
122
180
    if(!dm) {
123
0
        response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR;
124
0
        return true;
125
0
    }
126
127
    /* Allocate enough memory, including memory for the "self" response */
128
180
    size_t maxResults = dm->registeredServersSize + 1;
129
180
    response->servers = (UA_ApplicationDescription*)
130
180
        UA_Array_new(maxResults, &UA_TYPES[UA_TYPES_APPLICATIONDESCRIPTION]);
131
180
    if(!response->servers) {
132
0
        response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
133
0
        return true;
134
0
    }
135
136
180
    size_t pos = 0;
137
180
    registeredServer *current;
138
139
    /* Copy "self" ApplicationDescriptions into the response */
140
180
    if(foundSelf) {
141
27
        response->responseHeader.serviceResult =
142
27
            UA_ApplicationDescription_copy(&sc->applicationDescription,
143
27
                                           &response->servers[pos]);
144
27
        pos++;
145
27
        if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
146
0
            goto cleanup;
147
27
    }
148
149
    /* Copy registered ApplicationDescriptions into the response */
150
180
    LIST_FOREACH(current, &dm->registeredServers, pointers) {
151
0
        UA_Boolean usable = (request->serverUrisSize == 0);
152
0
        if(!usable) {
153
            /* If client only requested a specific set of servers */
154
0
            for(size_t i = 0; i < request->serverUrisSize; i++) {
155
0
                if(UA_String_equal(&current->registeredServer.serverUri,
156
0
                                   &request->serverUris[i])) {
157
0
                    usable = true;
158
0
                    break;
159
0
                }
160
0
            }
161
0
        }
162
163
0
        if(!usable)
164
0
            continue;
165
166
0
        response->responseHeader.serviceResult |=
167
0
            setApplicationDescriptionFromRegisteredServer(request,
168
0
                                                          &response->servers[pos],
169
0
                                                          &current->registeredServer);
170
0
        pos++;
171
0
    }
172
173
180
 cleanup:
174
175
    /* Set the final size */
176
180
    if(pos == 0) {
177
153
        UA_free(response->servers);
178
153
        response->servers = NULL;
179
153
    }
180
180
    response->serversSize = pos;
181
180
#endif
182
183
    /* Mirror back the expected EndpointUrl */
184
180
    if(request->endpointUrl.length > 0) {
185
19
        for(size_t i = 0; i < response->serversSize; i++) {
186
8
            UA_ApplicationDescription *ad = &response->servers[i];
187
8
            UA_Array_delete(ad->discoveryUrls, ad->discoveryUrlsSize,
188
8
                            &UA_TYPES[UA_TYPES_STRING]);
189
8
            ad->discoveryUrls = NULL;
190
8
            ad->discoveryUrlsSize = 0;
191
8
            response->responseHeader.serviceResult =
192
8
                UA_Array_copy(&request->endpointUrl, 1,
193
8
                              (void**)&ad->discoveryUrls,
194
8
                              &UA_TYPES[UA_TYPES_STRING]);
195
8
            if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
196
0
                break;
197
8
            ad->discoveryUrlsSize = 1;
198
8
        }
199
11
    }
200
201
180
    return true;
202
180
}
203
204
#if defined(UA_ENABLE_DISCOVERY) && defined(UA_ENABLE_DISCOVERY_MULTICAST)
205
/* All filter criteria must be fulfilled in the list entry. The comparison is
206
 * case insensitive. Returns true if the entry matches the filter. */
207
static UA_Boolean
208
entryMatchesCapabilityFilter(size_t serverCapabilityFilterSize,
209
                             UA_String *serverCapabilityFilter,
210
0
                             UA_ServerOnNetwork *current) {
211
    /* If the entry has less capabilities defined than the filter, there's no match */
212
0
    if(serverCapabilityFilterSize > current->serverCapabilitiesSize)
213
0
        return false;
214
0
    for(size_t i = 0; i < serverCapabilityFilterSize; i++) {
215
0
        UA_Boolean capabilityFound = false;
216
0
        for(size_t j = 0; j < current->serverCapabilitiesSize; j++) {
217
0
            if(UA_String_equal_ignorecase(&serverCapabilityFilter[i],
218
0
                               &current->serverCapabilities[j])) {
219
0
                capabilityFound = true;
220
0
                break;
221
0
            }
222
0
        }
223
0
        if(!capabilityFound)
224
0
            return false;
225
0
    }
226
0
    return true;
227
0
}
228
229
UA_Boolean
230
Service_FindServersOnNetwork(UA_Server *server, UA_Session *session,
231
                             const UA_FindServersOnNetworkRequest *request,
232
50
                             UA_FindServersOnNetworkResponse *response) {
233
50
    UA_LOCK_ASSERT(&server->serviceMutex);
234
235
50
    UA_DiscoveryManager *dm = (UA_DiscoveryManager*)
236
50
        getServerComponentByName(server, UA_STRING("discovery"));
237
50
    if(!dm) {
238
0
        response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR;
239
0
        return true;
240
0
    }
241
242
50
    if(!server->config.mdnsEnabled) {
243
50
        response->responseHeader.serviceResult = UA_STATUSCODE_BADNOTIMPLEMENTED;
244
50
        return true;
245
50
    }
246
247
    /* Set LastCounterResetTime */
248
0
    response->lastCounterResetTime =
249
0
        UA_DiscoveryManager_getServerOnNetworkCounterResetTime(dm);
250
251
    /* Compute the max number of records to return */
252
0
    UA_UInt32 recordCount = 0;
253
0
    UA_UInt32 serverOnNetworkRecordIdCounter =
254
0
        UA_DiscoveryManager_getServerOnNetworkRecordIdCounter(dm);
255
0
    if(request->startingRecordId < serverOnNetworkRecordIdCounter)
256
0
        recordCount = serverOnNetworkRecordIdCounter - request->startingRecordId;
257
0
    if(request->maxRecordsToReturn && recordCount > request->maxRecordsToReturn)
258
0
        recordCount = UA_MIN(recordCount, request->maxRecordsToReturn);
259
0
    if(recordCount == 0) {
260
0
        response->serversSize = 0;
261
0
        return true;
262
0
    }
263
264
    /* Count the matching records without placing a cache-sized temporary
265
     * array on the stack. The service mutex keeps the list stable between
266
     * this pass and the copy pass below. */
267
0
    UA_UInt32 filteredCount = 0;
268
0
    UA_ServerOnNetwork *current = UA_DiscoveryManager_getServerOnNetworkList(dm);
269
0
    for(; current && filteredCount < recordCount;
270
0
        current = UA_DiscoveryManager_getNextServerOnNetworkRecord(dm, current)) {
271
0
        if(current->recordId < request->startingRecordId)
272
0
            continue;
273
0
        if(!entryMatchesCapabilityFilter(request->serverCapabilityFilterSize,
274
0
                                         request->serverCapabilityFilter, current))
275
0
            continue;
276
0
        filteredCount++;
277
0
    }
278
279
0
    if(filteredCount == 0)
280
0
        return true;
281
282
    /* Allocate the array for the response */
283
0
    response->servers = (UA_ServerOnNetwork*)
284
0
        UA_Array_new(filteredCount, &UA_TYPES[UA_TYPES_SERVERONNETWORK]);
285
0
    if(!response->servers) {
286
0
        response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
287
0
        return true;
288
0
    }
289
0
    response->serversSize = filteredCount;
290
291
    /* Copy the server names in the same oldest-to-newest order as before */
292
0
    size_t pos = filteredCount;
293
0
    current = UA_DiscoveryManager_getServerOnNetworkList(dm);
294
0
    for(; current && pos > 0;
295
0
        current = UA_DiscoveryManager_getNextServerOnNetworkRecord(dm, current)) {
296
0
        if(current->recordId < request->startingRecordId)
297
0
            continue;
298
0
        if(!entryMatchesCapabilityFilter(request->serverCapabilityFilterSize,
299
0
                                         request->serverCapabilityFilter, current))
300
0
            continue;
301
0
        UA_StatusCode retval =
302
0
            UA_ServerOnNetwork_copy(current, &response->servers[--pos]);
303
0
        if(retval != UA_STATUSCODE_GOOD) {
304
0
            UA_Array_delete(response->servers, response->serversSize,
305
0
                            &UA_TYPES[UA_TYPES_SERVERONNETWORK]);
306
0
            response->servers = NULL;
307
0
            response->serversSize = 0;
308
0
            response->responseHeader.serviceResult = retval;
309
0
            return true;
310
0
        }
311
0
    }
312
0
    if(pos != 0) {
313
0
        UA_Array_delete(response->servers, response->serversSize,
314
0
                        &UA_TYPES[UA_TYPES_SERVERONNETWORK]);
315
0
        response->servers = NULL;
316
0
        response->serversSize = 0;
317
0
        response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR;
318
0
    }
319
0
    return true;
320
0
}
321
#endif
322
323
static UA_String basic256Sha256Uri = UA_STRING_STATIC("http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
324
325
/* Get an encrypted policy or NULL if no encrypted policy is defined */
326
UA_SecurityPolicy *
327
getDefaultEncryptedSecurityPolicy(UA_Server *server,
328
2.06k
                                  UA_SecurityPolicyType type) {
329
2.06k
    UA_SecurityPolicy *best = NULL;
330
2.06k
    UA_Byte securityLevel = 0;
331
332
2.06k
    (void)type;
333
4.12k
    for(size_t i = 0; i < server->config.securityPoliciesSize; i++) {
334
2.06k
        UA_SecurityPolicy *sp = &server->config.securityPolicies[i];
335
2.06k
        if(sp->policyType == UA_SECURITYPOLICYTYPE_NONE)
336
2.06k
            continue;
337
        /* This SecurityPolicy is used to secure a UserIdentityToken on top of a
338
         * #None SecureChannel (the only situation this function is called for).
339
         * ECC and RSA-DH policies use ephemeral key agreement that must be
340
         * bound to a secured SecureChannel - they must never be used to secure
341
         * an auth token over #None. Only the static-RSA encryption policies
342
         * (e.g. Basic256Sha256, Aes*_RsaOaep/RsaPss) qualify. */
343
0
        if(UA_SecurityPolicy_isEcc(sp) || UA_SecurityPolicy_isEnhancedSecurity(sp))
344
0
            continue;
345
        /* Return early with Basic256Sha256 when available. "Secure enough" and
346
         * most clients support it.*/
347
0
        if(UA_String_equal(&basic256Sha256Uri, &sp->policyUri))
348
0
            return sp;
349
0
        if(sp->securityLevel >= securityLevel) {
350
0
            best = sp;
351
0
            securityLevel = sp->securityLevel;
352
0
        }
353
0
    }
354
2.06k
    return best;
355
2.06k
}
356
357
static const char *securityModeStrs[4] = {"-invalid", "-none", "-sign", "-sign+encrypt"};
358
359
UA_String
360
2.33k
securityPolicyUriPostfix(const UA_String uri) {
361
2.33k
    if(uri.length == 0) return uri;
362
11.6k
    for(UA_Byte *b = uri.data + uri.length - 1; b >= uri.data; b--) {
363
11.6k
        if(*b != '#')
364
9.34k
            continue;
365
2.33k
        UA_String postfix = {uri.length - (size_t)(b - uri.data), b};
366
2.33k
        return postfix;
367
11.6k
    }
368
0
    return uri;
369
2.33k
}
370
371
static UA_StatusCode
372
updateEndpointUserIdentityToken(UA_Server *server,
373
                                UA_SecurityPolicyType policyType,
374
2.17k
                                UA_EndpointDescription *ed) {
375
    /* Public endpoint configurations must be checked before indexing by mode. */
376
2.17k
    if((UA_UInt32)ed->securityMode < UA_MESSAGESECURITYMODE_NONE ||
377
2.17k
       (UA_UInt32)ed->securityMode > UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
378
0
        return UA_STATUSCODE_BADSECURITYMODEREJECTED;
379
380
    /* Don't modify the UserIdentityTokens if there are manually configured
381
     * entries */
382
2.17k
    if(ed->userIdentityTokensSize > 0)
383
0
        return UA_STATUSCODE_GOOD;
384
385
    /* Copy the UserTokenPolicies from the AccessControl plugin, but only the
386
     * matching ones to the securityPolicyUri.
387
     * TODO: Different instances of the AccessControl plugin per Endpoint */
388
2.17k
    UA_StatusCode res = UA_STATUSCODE_GOOD;
389
2.17k
    UA_ServerConfig *sc = &server->config;
390
6.51k
    for(size_t i = 0; i < sc->accessControl.userTokenPoliciesSize; i++) {
391
4.34k
        UA_UserTokenPolicy *utp = &sc->accessControl.userTokenPolicies[i];
392
393
        /* Append the UserTokenPolicy from the AccesssControl plugin */
394
4.34k
        res = UA_Array_appendCopy((void**)&ed->userIdentityTokens,
395
4.34k
                                  &ed->userIdentityTokensSize, utp,
396
4.34k
                                  &UA_TYPES[UA_TYPES_USERTOKENPOLICY]);
397
4.34k
        if(res != UA_STATUSCODE_GOOD)
398
0
            return res;
399
400
        /* Now we modify the freshly copied last entry and ignore whatever
401
         * SecurityPolicy was set in sc->accessControl.userTokenPolicies and
402
         * choose something appropriate. If empty, the SecurityPolicy of the
403
         * SecureChannel is used. */
404
4.34k
        utp = &ed->userIdentityTokens[ed->userIdentityTokensSize - 1];
405
4.34k
        UA_String_clear(&utp->securityPolicyUri);
406
407
4.34k
#ifdef UA_ENABLE_ENCRYPTION
408
        /* Anonymous tokens don't need encryption. All other tokens require
409
         * encryption with the exception of Username/Password if also the
410
         * allowNonePolicyPassword option has been set. The same logic is used
411
         * in selectEndpointAndTokenPolicy (ua_services_session.c). */
412
4.34k
        if(utp->tokenType != UA_USERTOKENTYPE_ANONYMOUS &&
413
2.17k
           UA_String_equal(&ed->securityPolicyUri, &UA_SECURITY_POLICY_NONE_URI) &&
414
2.17k
           (!sc->allowNonePolicyPassword || utp->tokenType != UA_USERTOKENTYPE_USERNAME)) {
415
            /* Use the SecurityPolicy for the SecureChannel also for the
416
             * username/password. Otherwise pick the "bĂ«st" SecurityPolicĂ¿. */
417
2.17k
            UA_SecurityPolicy *encSP;
418
2.17k
            if(ed->securityMode == UA_MESSAGESECURITYMODE_NONE)
419
2.01k
                encSP = getDefaultEncryptedSecurityPolicy(server, policyType);
420
162
            else
421
162
                encSP = getSecurityPolicyByUri(server, &ed->securityPolicyUri);
422
2.17k
            if(!encSP) {
423
                /* No encrypted SecurityPolicy available */
424
2.01k
                UA_LOG_WARNING(sc->logging, UA_LOGCATEGORY_CLIENT,
425
2.01k
                               "Removing a UserTokenPolicy that would allow the "
426
2.01k
                               "password to be transmitted without encryption "
427
2.01k
                               "(Can be enabled via config->allowNonePolicyPassword)");
428
2.01k
                UA_StatusCode res2 =
429
2.01k
                    UA_Array_resize((void **)&ed->userIdentityTokens,
430
2.01k
                                    &ed->userIdentityTokensSize,
431
2.01k
                                    ed->userIdentityTokensSize - 1,
432
2.01k
                                    &UA_TYPES[UA_TYPES_USERTOKENPOLICY]);
433
2.01k
                (void)res2;
434
2.01k
                continue;
435
2.01k
            }
436
162
            res |= UA_String_copy(&encSP->policyUri, &utp->securityPolicyUri);
437
162
        }
438
2.33k
#endif
439
440
        /* Append the SecurityMode and SecurityPolicy postfix to the PolicyId to
441
         * make it unique */
442
2.33k
        UA_String postfix;
443
2.33k
        if(utp->securityPolicyUri.length > 0)
444
162
            postfix = securityPolicyUriPostfix(utp->securityPolicyUri);
445
2.17k
        else
446
2.17k
            postfix = securityPolicyUriPostfix(ed->securityPolicyUri);
447
2.33k
        size_t newLen = utp->policyId.length + postfix.length +
448
2.33k
            strlen(securityModeStrs[ed->securityMode]);
449
2.33k
        UA_Byte *newString = (UA_Byte*)
450
2.33k
            UA_realloc((void*)((uintptr_t)utp->policyId.data &
451
2.33k
                               ~(uintptr_t)UA_EMPTY_ARRAY_SENTINEL), newLen);
452
2.33k
        if(!newString)
453
0
            continue;
454
2.33k
        size_t pos = utp->policyId.length;
455
2.33k
        memcpy(&newString[pos], securityModeStrs[ed->securityMode],
456
2.33k
               strlen(securityModeStrs[ed->securityMode]));
457
2.33k
        pos += strlen(securityModeStrs[ed->securityMode]);
458
2.33k
        memcpy(&newString[pos], postfix.data, postfix.length);
459
2.33k
        utp->policyId.data = newString;
460
2.33k
        utp->policyId.length = newLen;
461
2.33k
    }
462
463
2.17k
    return res;
464
2.17k
}
465
466
/* Also reused to create the EndpointDescription array in the
467
 * CreateSessionResponse */
468
UA_StatusCode
469
setCurrentEndpointsArray(UA_Server *server, const UA_String endpointUrl,
470
                         UA_String *profileUris, size_t profileUrisSize,
471
4.27k
                         UA_EndpointDescription **arr, size_t *arrSize) {
472
4.27k
    UA_ServerConfig *sc = &server->config;
473
474
    /* Clone the endpoint for each discoveryURL? */
475
4.27k
    size_t clone_times = 1;
476
4.27k
    if(endpointUrl.length == 0)
477
3.76k
        clone_times = sc->applicationDescription.discoveryUrlsSize;
478
479
    /* Allocate the array */
480
4.27k
    *arr = (UA_EndpointDescription*)
481
4.27k
        UA_Array_new(sc->endpointsSize * clone_times,
482
4.27k
                     &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
483
4.27k
    if(!*arr)
484
0
        return UA_STATUSCODE_BADOUTOFMEMORY;
485
486
4.27k
    size_t pos = 0;
487
4.27k
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
488
8.54k
    for(size_t j = 0; j < sc->endpointsSize; ++j) {
489
4.27k
        const UA_EndpointDescription *ep = &sc->endpoints[j];
490
491
        /* Test if the supported binary profile shall be returned */
492
4.27k
        UA_Boolean usable = (profileUrisSize == 0);
493
4.27k
        if(!usable) {
494
1.74k
            for(size_t i = 0; i < profileUrisSize; ++i) {
495
1.70k
                if(!UA_String_equal(&profileUris[i], &ep->transportProfileUri))
496
1.70k
                    continue;
497
0
                usable = true;
498
0
                break;
499
1.70k
            }
500
45
        }
501
4.27k
        if(!usable)
502
45
            continue;
503
504
        /* Get the SecurityPolicy */
505
4.22k
        UA_SecurityPolicy *sp =
506
4.22k
            getSecurityPolicyByUri(server, &ep->securityPolicyUri);
507
4.22k
        if(!sp) {
508
0
            UA_LOG_WARNING(server->config.logging, UA_LOGCATEGORY_SERVER,
509
0
                           "GetEndpoints: Endpoint defines SecurityPolicy "
510
0
                           "%S which is not available", ep->securityPolicyUri);
511
0
            continue;
512
0
        }
513
514
        /* Copy into the results */
515
4.73k
        for(size_t i = 0; i < clone_times; ++i) {
516
            /* Copy the endpoint with a current ApplicationDescription */
517
510
            UA_EndpointDescription *ed = &(*arr)[pos];
518
510
            retval |= UA_EndpointDescription_copy(&sc->endpoints[j], ed);
519
510
            UA_ApplicationDescription_clear(&ed->server);
520
510
            retval |= UA_ApplicationDescription_copy(&sc->applicationDescription,
521
510
                                                     &ed->server);
522
523
            /* Set the local certificate configured for the SecurityPolicy */
524
510
            UA_ByteString_clear(&ed->serverCertificate);
525
510
            retval |= UA_ByteString_copy(&sp->localCertificate,
526
510
                                         &ed->serverCertificate);
527
528
            /* Set the User Identity Token list from the AccessControl plugin.
529
             * This also selects an appropriate SecurityPolicy for the
530
             * AuthenticationToken. */
531
510
            retval |= updateEndpointUserIdentityToken(server, sp->policyType, ed);
532
533
            /* OPC UA Part 4 §5.4.2:
534
             *
535
             * If the endpoint uses None security but a token policy requires
536
             * encryption, the client needs a certificate to encrypt the token.
537
             * Set serverCertificate from the first token policy's encryption
538
             * SecurityPolicy so the client can encrypt the credential. */
539
510
            if(ed->serverCertificate.length == 0) {
540
1.02k
                for(size_t ti = 0; ti < ed->userIdentityTokensSize; ti++) {
541
510
                    UA_UserTokenPolicy *utp = &ed->userIdentityTokens[ti];
542
510
                    if(utp->securityPolicyUri.length == 0)
543
510
                        continue;
544
0
                    UA_SecurityPolicy *encSP =
545
0
                        getSecurityPolicyByUri(server, &utp->securityPolicyUri);
546
0
                    if(!encSP || encSP->localCertificate.length == 0)
547
0
                        continue;
548
0
                    retval |= UA_ByteString_copy(&encSP->localCertificate,
549
0
                                                 &ed->serverCertificate);
550
0
                    break;
551
0
                }
552
510
            }
553
554
            /* Set the EndpointURL */
555
510
            UA_String_clear(&ed->endpointUrl);
556
510
            if(endpointUrl.length == 0) {
557
0
                retval |= UA_String_copy(&sc->applicationDescription.discoveryUrls[i],
558
0
                                         &ed->endpointUrl);
559
510
            } else {
560
                /* Mirror back the requested EndpointUrl and also add it to the
561
                 * array of discovery urls */
562
510
                retval |= UA_String_copy(&endpointUrl, &ed->endpointUrl);
563
564
                /* Check if the ServerUrl is already present in the DiscoveryUrl
565
                 * array */
566
510
                size_t k = 0;
567
510
                for(; k < ed->server.discoveryUrlsSize; k++) {
568
0
                    if(UA_String_equal(&ed->endpointUrl, &ed->server.discoveryUrls[k]))
569
0
                        break;
570
0
                }
571
510
                if(k == ed->server.discoveryUrlsSize) {
572
510
                    retval |= UA_Array_appendCopy((void **)&ed->server.discoveryUrls,
573
510
                                                  &ed->server.discoveryUrlsSize,
574
510
                                                  &endpointUrl,
575
510
                                                  &UA_TYPES[UA_TYPES_STRING]);
576
510
                }
577
510
            }
578
510
            if(retval != UA_STATUSCODE_GOOD)
579
0
                goto error;
580
581
510
            pos++;
582
510
        }
583
4.22k
    }
584
585
4.27k
    *arrSize = pos;
586
4.27k
    return UA_STATUSCODE_GOOD;
587
588
0
 error:
589
0
    UA_Array_delete(*arr, sc->endpointsSize * clone_times,
590
0
                    &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
591
0
    *arr = NULL;
592
0
    return retval;
593
4.27k
}
594
595
UA_Boolean
596
Service_GetEndpoints(UA_Server *server, UA_Session *session,
597
                     const UA_GetEndpointsRequest *request,
598
458
                     UA_GetEndpointsResponse *response) {
599
458
    UA_LOCK_ASSERT(&server->serviceMutex);
600
601
458
    UA_LOG_DEBUG_SESSION(server->config.logging, session,
602
458
                         "Processing GetEndpointsRequest with endpointUrl %S",
603
458
                         request->endpointUrl);
604
605
    /* If the client expects to see a specific endpointurl, mirror it back. If
606
     * not, clone the endpoints with the discovery url of all networklayers. */
607
458
    response->responseHeader.serviceResult =
608
458
        setCurrentEndpointsArray(server, request->endpointUrl,
609
458
                                 request->profileUris, request->profileUrisSize,
610
458
                                 &response->endpoints, &response->endpointsSize);
611
458
    return true;
612
458
}
613
614
#ifdef UA_ENABLE_DISCOVERY
615
616
static void
617
process_RegisterServer(UA_Server *server, UA_Session *session,
618
                       const UA_RequestHeader* requestHeader,
619
                       const UA_RegisteredServer *requestServer,
620
                       const size_t requestDiscoveryConfigurationSize,
621
                       const UA_ExtensionObject *requestDiscoveryConfiguration,
622
                       UA_ResponseHeader* responseHeader,
623
                       size_t *responseConfigurationResultsSize,
624
                       UA_StatusCode **responseConfigurationResults,
625
                       size_t *responseDiagnosticInfosSize,
626
11
                       UA_DiagnosticInfo *responseDiagnosticInfos) {
627
11
    UA_LOCK_ASSERT(&server->serviceMutex);
628
629
11
    UA_DiscoveryManager *dm = (UA_DiscoveryManager*)
630
11
        getServerComponentByName(server, UA_STRING("discovery"));
631
11
    if(!dm)
632
0
        return;
633
634
11
    UA_ServerConfig *sc = &server->config;
635
11
    if(sc->applicationDescription.applicationType != UA_APPLICATIONTYPE_DISCOVERYSERVER) {
636
11
        responseHeader->serviceResult = UA_STATUSCODE_BADSERVICEUNSUPPORTED;
637
11
        return;
638
11
    }
639
640
    /* Find the server from the request in the registered list */
641
0
    registeredServer *rs = NULL;
642
0
    LIST_FOREACH(rs, &dm->registeredServers, pointers) {
643
0
        if(UA_String_equal(&rs->registeredServer.serverUri, &requestServer->serverUri))
644
0
            break;
645
0
    }
646
647
0
    UA_MdnsDiscoveryConfiguration *mdnsConfig = NULL;
648
649
0
    const UA_String* mdnsServerName = NULL;
650
0
    if(requestDiscoveryConfigurationSize) {
651
0
        *responseConfigurationResults =
652
0
            (UA_StatusCode *)UA_Array_new(requestDiscoveryConfigurationSize,
653
0
                                          &UA_TYPES[UA_TYPES_STATUSCODE]);
654
0
        if(!(*responseConfigurationResults)) {
655
0
            responseHeader->serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
656
0
            return;
657
0
        }
658
0
        *responseConfigurationResultsSize = requestDiscoveryConfigurationSize;
659
660
0
        for(size_t i = 0; i < requestDiscoveryConfigurationSize; i++) {
661
0
            const UA_ExtensionObject *object = &requestDiscoveryConfiguration[i];
662
0
            if(!mdnsConfig && (object->encoding == UA_EXTENSIONOBJECT_DECODED ||
663
0
                               object->encoding == UA_EXTENSIONOBJECT_DECODED_NODELETE) &&
664
0
               (object->content.decoded.type == &UA_TYPES[UA_TYPES_MDNSDISCOVERYCONFIGURATION])) {
665
0
                mdnsConfig = (UA_MdnsDiscoveryConfiguration *)object->content.decoded.data;
666
0
                mdnsServerName = &mdnsConfig->mdnsServerName;
667
0
                (*responseConfigurationResults)[i] = UA_STATUSCODE_GOOD;
668
0
            } else {
669
0
                (*responseConfigurationResults)[i] = UA_STATUSCODE_BADNOTSUPPORTED;
670
0
            }
671
0
        }
672
0
    }
673
674
0
    if(!mdnsServerName && requestServer->serverNamesSize)
675
0
        mdnsServerName = &requestServer->serverNames[0].text;
676
677
0
    if(!mdnsServerName) {
678
0
        responseHeader->serviceResult = UA_STATUSCODE_BADSERVERNAMEMISSING;
679
0
        return;
680
0
    }
681
682
0
    if(requestServer->discoveryUrlsSize == 0) {
683
0
        responseHeader->serviceResult = UA_STATUSCODE_BADDISCOVERYURLMISSING;
684
0
        return;
685
0
    }
686
687
    /* Bound the records queued for mDNS probing by one registration. */
688
0
    if(requestServer->discoveryUrlsSize > 16) {
689
0
        responseHeader->serviceResult = UA_STATUSCODE_BADTOOMANYOPERATIONS;
690
0
        return;
691
0
    }
692
693
0
    if(requestServer->semaphoreFilePath.length) {
694
0
#ifdef UA_ENABLE_DISCOVERY_SEMAPHORE
695
0
        char* filePath = (char*)
696
0
            UA_malloc(sizeof(char)*requestServer->semaphoreFilePath.length+1);
697
0
        if(!filePath) {
698
0
            UA_LOG_ERROR_SESSION(sc->logging, session,
699
0
                                 "Cannot allocate memory for semaphore path. "
700
0
                                 "Out of memory.");
701
0
            responseHeader->serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
702
0
            return;
703
0
        }
704
0
        memcpy(filePath, requestServer->semaphoreFilePath.data,
705
0
               requestServer->semaphoreFilePath.length );
706
0
        filePath[requestServer->semaphoreFilePath.length] = '\0';
707
0
        if(!UA_fileExists( filePath )) {
708
0
            responseHeader->serviceResult = UA_STATUSCODE_BADSEMAPHOREFILEMISSING;
709
0
            UA_free(filePath);
710
0
            return;
711
0
        }
712
0
        UA_free(filePath);
713
#else
714
        UA_LOG_WARNING(sc->logging, UA_LOGCATEGORY_CLIENT,
715
                       "Ignoring semaphore file path. open62541 not compiled "
716
                       "with UA_ENABLE_DISCOVERY_SEMAPHORE=ON");
717
#endif
718
0
    }
719
720
0
#ifdef UA_ENABLE_DISCOVERY_MULTICAST
721
0
    if(sc->mdnsEnabled) {
722
0
        for(size_t i = 0; i < requestServer->discoveryUrlsSize; i++) {
723
            /* create TXT if is online and first index, delete TXT if is offline
724
             * and last index */
725
0
            UA_Boolean updateTxt = (requestServer->isOnline && i==0) ||
726
0
                (!requestServer->isOnline && i==requestServer->discoveryUrlsSize);
727
0
            UA_Discovery_updateMdnsForDiscoveryUrl(dm, *mdnsServerName, mdnsConfig,
728
0
                                                   requestServer->discoveryUrls[i],
729
0
                                                   requestServer->isOnline, updateTxt);
730
0
        }
731
0
    }
732
0
#endif
733
734
0
    if(!requestServer->isOnline) {
735
        /* Server is shutting down. Remove it from the registered servers list */
736
0
        if(!rs) {
737
            /* Server not found, show warning */
738
0
            UA_LOG_WARNING_SESSION(sc->logging, session,
739
0
                                   "Could not unregister server %S. Not registered.",
740
0
                                   requestServer->serverUri);
741
0
            responseHeader->serviceResult = UA_STATUSCODE_BADNOTHINGTODO;
742
0
            return;
743
0
        }
744
745
0
        if(dm->registerServerCallback)
746
0
            dm->registerServerCallback(requestServer, dm->registerServerCallbackData);
747
748
        /* Server found, remove from list */
749
0
        LIST_REMOVE(rs, pointers);
750
0
        UA_RegisteredServer_clear(&rs->registeredServer);
751
0
        UA_free(rs);
752
0
        dm->registeredServersSize--;
753
0
        responseHeader->serviceResult = UA_STATUSCODE_GOOD;
754
0
        return;
755
0
    }
756
757
0
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
758
0
    if(!rs) {
759
        /* Server not yet registered, register it by adding it to the list */
760
0
        UA_LOG_DEBUG_SESSION(sc->logging, session,
761
0
                             "Registering new server: %S",
762
0
                             requestServer->serverUri);
763
764
0
        rs = (registeredServer*)UA_malloc(sizeof(registeredServer));
765
0
        if(!rs) {
766
0
            responseHeader->serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
767
0
            return;
768
0
        }
769
770
0
        LIST_INSERT_HEAD(&dm->registeredServers, rs, pointers);
771
0
        dm->registeredServersSize++;
772
0
    } else {
773
0
        UA_RegisteredServer_clear(&rs->registeredServer);
774
0
    }
775
776
    /* Always call the callback, if it is set. Previously we only called it if
777
     * it was a new register call. It may be the case that this endpoint
778
     * registered before, then crashed, restarts and registeres again. In that
779
     * case the entry is not deleted and the callback would not be called. */
780
0
    if(dm->registerServerCallback)
781
0
        dm->registerServerCallback(requestServer,
782
0
                                   dm->registerServerCallbackData);
783
784
    /* Ccopy the data from the request into the list */
785
0
    UA_EventLoop *el = sc->eventLoop;
786
0
    UA_DateTime nowMonotonic = el->dateTime_nowMonotonic(el);
787
0
    UA_RegisteredServer_copy(requestServer, &rs->registeredServer);
788
0
    rs->lastSeen = nowMonotonic;
789
0
    responseHeader->serviceResult = retval;
790
0
}
791
792
UA_Boolean
793
Service_RegisterServer(UA_Server *server, UA_Session *session,
794
                       const UA_RegisterServerRequest *request,
795
5
                       UA_RegisterServerResponse *response) {
796
5
    UA_LOG_DEBUG_SESSION(server->config.logging, session,
797
5
                         "Processing RegisterServerRequest");
798
5
    UA_LOCK_ASSERT(&server->serviceMutex);
799
5
    process_RegisterServer(server, session, &request->requestHeader,
800
5
                           &request->server, 0, NULL, &response->responseHeader,
801
5
                           0, NULL, 0, NULL);
802
5
    return true;
803
5
}
804
805
UA_Boolean
806
Service_RegisterServer2(UA_Server *server, UA_Session *session,
807
                        const UA_RegisterServer2Request *request,
808
12
                        UA_RegisterServer2Response *response) {
809
12
    UA_LOG_DEBUG_SESSION(server->config.logging, session,
810
12
                         "Processing RegisterServer2Request");
811
12
    UA_LOCK_ASSERT(&server->serviceMutex);
812
12
    process_RegisterServer(server, session, &request->requestHeader,
813
12
                           &request->server,
814
12
                           request->discoveryConfigurationSize,
815
12
                           request->discoveryConfiguration,
816
12
                           &response->responseHeader,
817
12
                           &response->configurationResultsSize,
818
12
                           &response->configurationResults,
819
12
                           &response->diagnosticInfosSize,
820
12
                           response->diagnosticInfos);
821
    return true;
822
12
}
823
824
#endif /* UA_ENABLE_DISCOVERY */