You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB
C

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define DEFAULT_PATH "/"
char* url_to_proto(char* url) {
size_t length = strlen(url);
int sentinel = 0;
char* to_return = malloc(sizeof(char) * 10);
for (int i=0;i<length;i++) {
if (*(url + (sizeof(char) * i)) == ':') { /* If the character is ':' ...*/
sentinel = i; /* ...Then we stop scanning the string */
}
}
strncpy(to_return,url,sentinel);
return to_return;
}
char* url_to_hostname(char* url) {
/* This function relies on a hack-y assumption: that, given a string
that represents a URL (e.g. https://www.example.com/index.html), the length of the host portion
of the address is the distance between the second slash (:/'/') and the third ('/'index.html),
or the second slash and the end of the string, if the path isn't present. */
size_t length = strlen(url);
char* protocol = url_to_proto(url);
char* temp_substring = malloc(sizeof(char) * 256);
char* to_return = malloc(sizeof(char) * 256);
/* This is a very roundabout way of saying that, starting from a certain point in the
URL (length of protocol string + 3 (':','/','/'), we are copying the rest of the string into another
substring. */
strncpy(temp_substring,url+(strlen(protocol) + 3),(length - (strlen(protocol) + 3)));
/* Now we need to substring _this_ substring, by returning only the part before the next slash. */
int sentinel = 0;
for (int i=0;i<strlen(temp_substring);i++) {
if (*(temp_substring+(sizeof(char) * i)) == '/') {
sentinel = i;
}
}
if (sentinel == 0) { /* If there are no more slashes */
return temp_substring;
}
strncpy(to_return,temp_substring,sentinel);
free(temp_substring);
return to_return;
}
char* url_to_path(char* url) {
/* Assumption: The path starts from the third slash to the end of the string. */
int str_len = strlen(url);
int sentinel = 0;
int num_slashes = 0;
char* to_return = malloc(sizeof(char) * 512);
for (int i=0;i<strlen(url);i++) {
if (*(url + (sizeof(char) * i)) == '/') {
num_slashes++;
sentinel = i;
}
if (num_slashes == 3) {
break;
}
}
if (num_slashes < 3 || sentinel == str_len) { /* If we don't find the requisite number of slashes after
parsing the string OR the third slash is at the end of the string
("e.g. www.example.com/")... */
strcpy(to_return,DEFAULT_PATH); /* ...Then return the default path - "/" */
return to_return;
}
/* Copy all bytes of the string, starting from the third slash */
strncpy(to_return, url+(sizeof(char) * sentinel), strlen(url)-(sizeof(char) * sentinel));
return to_return;
}