aboutsummaryrefslogtreecommitdiffstats
path: root/src/afb-hswitch.c
blob: 9e55f29b6809fd6db49cd9c70a99d0613d5dd3ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
 * Copyright (C) 2015-2020 "IoT.bzh"
 * Author "Fulup Ar Foll"
 * Author José Bollo <jose.bollo@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _GNU_SOURCE

#include <stdlib.h>
#include <string.h>

#include <microhttpd.h>

#include "afb-context.h"
#include "afb-hreq.h"
#include "afb-apiset.h"
#include "afb-session.h"
#include "afb-websock.h"

int afb_hswitch_apis(struct afb_hreq *hreq, void *data)
{
	const char *api, *verb, *i;
	size_t lenapi, lenverb;
	struct afb_apiset *apiset = data;

	/* api is the first hierarchical item */
	i = hreq->tail;
	while (*i == '/')
		i++;
	if (!*i)
		return 0; /* no API */
	api = i;

	/* search end of the api and get its length */
	while (*++i && *i != '/');
	lenapi = (size_t)(i - api);

	/* search the verb */
	while (*i == '/')
		i++;
	if (!*i)
		return 0; /* no verb */
	verb = i;

	/* get the verb length */
	while (*++i);
	lenverb = (size_t)(i - verb);

	/* found api + verb so process the call */
	afb_hreq_call(hreq, apiset, api, lenapi, verb, lenverb);
	return 1;
}

int afb_hswitch_one_page_api_redirect(struct afb_hreq *hreq, void *data)
{
	size_t plen;
	char *url;

	if (hreq->lentail >= 2 && hreq->tail[1] == '#')
		return 0;
	/*
	 * Here we have for example:
	 *    url  = "/pre/dir/page"   lenurl = 13
	 *    tail =     "/dir/page"   lentail = 9
	 *
	 * We will produce "/pre/#!dir/page"
	 *
	 * Let compute plen that include the / at end (for "/pre/")
	 */
	plen = hreq->lenurl - hreq->lentail + 1;
	url = alloca(hreq->lenurl + 3);
	memcpy(url, hreq->url, plen);
	url[plen++] = '#';
	url[plen++] = '!';
	memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
	afb_hreq_redirect_to(hreq, url, 1);
	return 1;
}

int afb_hswitch_websocket_switch(struct afb_hreq *hreq, void *data)
{
	struct afb_apiset *apiset = data;

	if (hreq->lentail != 0)
		return 0;

	if (afb_hreq_init_context(hreq) < 0) {
		afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
		return 1;
	}

	return afb_websock_check_upgrade(hreq, apiset);
}