+static
+void destroy_ctx_type(struct ctx_type *type)
+{
+ if (!type) {
+ return;
+ }
+ free(type->opt->symbol);
+ free(type->opt);
+ free(type);
+}
+
+static
+struct ctx_type *create_ctx_type(void)
+{
+ struct ctx_type *type = zmalloc(sizeof(*type));
+
+ if (!type) {
+ PERROR("malloc ctx_type");
+ goto end;
+ }
+
+ type->opt = zmalloc(sizeof(*type->opt));
+ if (!type->opt) {
+ PERROR("malloc ctx_type options");
+ destroy_ctx_type(type);
+ type = NULL;
+ goto end;
+ }
+end:
+ return type;
+}
+
+static
+struct ctx_type *get_context_type(const char *ctx)
+{
+ int opt_index;
+ struct ctx_type *type = NULL;
+ const char app_ctx_prefix[] = "$app.";
+ char *provider_name = NULL, *ctx_name = NULL;
+ size_t i, len, colon_pos = 0, provider_name_len, ctx_name_len;
+
+ if (!ctx) {
+ goto not_found;
+ }
+
+ type = create_ctx_type();
+ if (!type) {
+ goto not_found;
+ }
+
+ /* Check if ctx matches a known static context. */
+ opt_index = find_ctx_type_idx(ctx);
+ if (opt_index >= 0) {
+ *type->opt = ctx_opts[opt_index];
+ type->opt->symbol = strdup(ctx_opts[opt_index].symbol);
+ goto found;
+ }
+
+ /*
+ * No match found against static contexts; check if it is an app
+ * context.
+ */
+ len = strlen(ctx);
+ if (len <= sizeof(app_ctx_prefix) - 1) {
+ goto not_found;
+ }
+
+ /* String starts with $app. */
+ if (strncmp(ctx, app_ctx_prefix, sizeof(app_ctx_prefix) - 1)) {
+ goto not_found;
+ }
+
+ /* Validate that the ':' separator is present. */
+ for (i = sizeof(app_ctx_prefix); i < len; i++) {
+ const char c = ctx[i];
+
+ if (c == ':') {
+ colon_pos = i;
+ break;
+ }
+ }
+
+ /*
+ * No colon found or no ctx name ("$app.provider:") or no provider name
+ * given ("$app.:..."), which is invalid.
+ */
+ if (!colon_pos || colon_pos == len ||
+ colon_pos == sizeof(app_ctx_prefix)) {
+ ERR("Invalid application context provided: no provider or context name provided.");
+ goto not_found;
+ }
+
+ provider_name_len = colon_pos - sizeof(app_ctx_prefix) + 2;
+ provider_name = zmalloc(provider_name_len);
+ if (!provider_name) {
+ PERROR("malloc provider_name");
+ goto not_found;
+ }
+ strncpy(provider_name, ctx + sizeof(app_ctx_prefix) - 1,
+ provider_name_len - 1);
+ type->opt->u.app_ctx.provider_name = provider_name;
+
+ ctx_name_len = len - colon_pos;
+ ctx_name = zmalloc(ctx_name_len);
+ if (!ctx_name) {
+ PERROR("malloc ctx_name");
+ goto not_found;
+ }
+ strncpy(ctx_name, ctx + colon_pos + 1, ctx_name_len - 1);
+ type->opt->u.app_ctx.ctx_name = ctx_name;
+ type->opt->ctx_type = CONTEXT_APP_CONTEXT;
+ type->opt->symbol = strdup(ctx);
+found:
+ return type;
+not_found:
+ free(provider_name);
+ free(ctx_name);
+ destroy_ctx_type(type);
+ return NULL;
+}
+