summary refs log tree commit diff stats
path: root/normalize.c
blob: 821df35a28c57a4f68d1bdba0777886d89be0437 (plain) (blame)
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
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include "yuri.h"

static int
_eat(struct uri *u, int index)
{
	int i;
	char **path;

	free(u->path[index]);
	for (i = index+1; i < u->npath; i++)
		u->path[i-1] = u->path[i];
	u->npath--;

	if (u->npath == 0) {
		free(u->path);
		u->path = NULL;
	} else {
		path = realloc(u->path, sizeof(*u->path)*u->npath);
		if (path == NULL)
			return -1;
		u->path = path;
	}

	return 0;
}

int
uri_normalize(struct uri *u)
{
	int i;
	int therewaspath;

	if (u->scheme) {
		for (i = 0; i < strlen(u->scheme); i++) {
			if (isalpha(u->scheme[i]))
				u->scheme[i] = tolower(u->scheme[i]);
		}
	}

	if (u->authority.host) {
		for (i = 0; i < strlen(u->authority.host); i++) {
			if (isalpha(u->authority.host[i]))
				u->authority.host[i] = tolower(u->authority.host[i]);
		}
	}

	if (u->npath != 0)
		therewaspath = 1;
	else
		therewaspath = 0;

	for (i = 0; i < u->npath; i++) {
		if (i != u->npath-1 || u->npath == 1) {
			if (strcmp(u->path[i], "") == 0) {
				if (_eat(u, i) == -1)
					return -1;
				i = 0; /* count altered, reset back */
			}
		}
	}

	for (i = 0; i < u->npath; i++) {
		if (strcmp(u->path[i], ".") == 0) {
			if (_eat(u, i) == -1)
				return -1;
			i = 0; /* count altered, reset back */
		}
	}

	for (i = 0; i < u->npath; i++) {
		if (strcmp(u->path[i], "..") == 0) {
			if (_eat(u, i) == -1)
				return -1;
			if (i-1 >= 0) {
				if (_eat(u, i-1) == -1)
					return -1;
			}
			i = 0; /* count altered, reset back */
		}
	}

	/* if there was a path and all redundant segments were remved
	 * we'd be left with no path and path list would be set to NULL
	 * indicating that path has never exists, we don't want that,
	 * so we just add an empty path back */
	if (therewaspath && u->npath == 0) {
		if (uri_append_path(u, "") == -1)
			return -1;
	}

	return 0;
}