Commit | Line | Data |
---|---|---|
71a559f8 | 1 | /* |
ab5be9fa | 2 | * Copyright (C) 2016 Jérémie Galarneau <jeremie.galarneau@efficios.com> |
71a559f8 | 3 | * |
ab5be9fa | 4 | * SPDX-License-Identifier: LGPL-2.1-only |
71a559f8 | 5 | * |
71a559f8 JG |
6 | */ |
7 | ||
c9e313bc | 8 | #include "context.hpp" |
28ab034a | 9 | |
c9e313bc SM |
10 | #include <common/error.hpp> |
11 | #include <common/macros.hpp> | |
71a559f8 | 12 | |
28ab034a JG |
13 | #include <stddef.h> |
14 | #include <string.h> | |
15 | ||
16 | int parse_application_context(const char *str, char **out_provider_name, char **out_ctx_name) | |
71a559f8 JG |
17 | { |
18 | const char app_ctx_prefix[] = "$app."; | |
cd9adb8b | 19 | char *provider_name = nullptr, *ctx_name = nullptr; |
71a559f8 JG |
20 | size_t i, len, colon_pos = 0, provider_name_len, ctx_name_len; |
21 | ||
22 | if (!str || !out_provider_name || !out_ctx_name) { | |
23 | goto not_found; | |
24 | } | |
25 | ||
26 | len = strlen(str); | |
27 | if (len <= sizeof(app_ctx_prefix) - 1) { | |
28 | goto not_found; | |
29 | } | |
30 | ||
31 | /* String starts with $app. */ | |
5c7248cd | 32 | if (strncmp(str, app_ctx_prefix, sizeof(app_ctx_prefix) - 1) != 0) { |
71a559f8 JG |
33 | goto not_found; |
34 | } | |
35 | ||
36 | /* Validate that the ':' separator is present. */ | |
37 | for (i = sizeof(app_ctx_prefix); i < len; i++) { | |
38 | const char c = str[i]; | |
39 | ||
40 | if (c == ':') { | |
41 | colon_pos = i; | |
42 | break; | |
43 | } | |
44 | } | |
45 | ||
46 | /* | |
47 | * No colon found or no ctx name ("$app.provider:") or no provider name | |
48 | * given ("$app.:..."), which is invalid. | |
49 | */ | |
28ab034a | 50 | if (!colon_pos || colon_pos == len || colon_pos == sizeof(app_ctx_prefix)) { |
71a559f8 JG |
51 | goto not_found; |
52 | } | |
53 | ||
54 | provider_name_len = colon_pos - sizeof(app_ctx_prefix) + 2; | |
64803277 | 55 | provider_name = calloc<char>(provider_name_len); |
71a559f8 JG |
56 | if (!provider_name) { |
57 | PERROR("malloc provider_name"); | |
58 | goto not_found; | |
59 | } | |
28ab034a | 60 | strncpy(provider_name, str + sizeof(app_ctx_prefix) - 1, provider_name_len - 1); |
71a559f8 JG |
61 | |
62 | ctx_name_len = len - colon_pos; | |
64803277 | 63 | ctx_name = calloc<char>(ctx_name_len); |
71a559f8 JG |
64 | if (!ctx_name) { |
65 | PERROR("malloc ctx_name"); | |
66 | goto not_found; | |
67 | } | |
68 | strncpy(ctx_name, str + colon_pos + 1, ctx_name_len - 1); | |
69 | ||
70 | *out_provider_name = provider_name; | |
71 | *out_ctx_name = ctx_name; | |
72 | return 0; | |
73 | not_found: | |
74 | free(provider_name); | |
75 | free(ctx_name); | |
76 | return -1; | |
77 | } |