cs-3516-assignment-1/client/http_client.c

71 lines
2.2 KiB
C

#include "http_client.h"
#include "../common/http_types.h"
#include "../common/socket_helper.h"
#include "http_socket.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char* argv[]) {
if (argc == 1) {
printf("%s", USAGE_STRING);
return 1;
}
bool print_rtt = strcmp(argv[1], RTT_FLAG) == 0;
if ((print_rtt && argc != 4) || (!print_rtt && argc != 3)) {
printf("%s", USAGE_STRING);
return 1;
}
char *dest = argv[argc - 2];
char *port = argv[argc - 1];
char *path_buffer = malloc(strlen(dest) + 1);
char *host_buffer = malloc(strlen(dest) + 1);
long port_num = strtol(port, NULL, 10);
if (port_num < MIN_PORT || port_num > MAX_PORT || errno == ERANGE || errno == EINVAL) {
printf("%s", PORT_ERROR);
}
get_parts(dest, path_buffer, host_buffer);
struct http_message req = build_basic_request("GET", host_buffer, path_buffer, port_num);
struct response_info res;
enum socket_read_result read_result = send_request(req, &res);
if (read_result != RESULT_OK) {
printf("An error occured while opening the socket. Please try again.\n");
} else {
if (print_rtt) {
printf("RTT: %lld ms\n\n", res.rtt);
}
printf("%s\n", res.contents);
}
free_basic_request(req);
free(res.contents);
free(host_buffer);
free(path_buffer);
}
/**
* Get the parts of a url
*
* @param dest The destination specified by the user
* @param path_buffer A buffer large enough to hold the path of the dest
* @param host_buffer A buffer large enough to hold the host of the dest
*/
void get_parts(const char *dest, char *path_buffer, char *host_buffer) {
// If the destination starts with PROTO_PREFIX, skip it
if (strstr(dest, PROTO_PREFIX) == dest) {
dest += strlen(PROTO_PREFIX);
}
const char *slash_cursor;
for (slash_cursor = dest; *slash_cursor != '\0' && *slash_cursor != '/'; slash_cursor++);
if (*slash_cursor == '\0') {
strcpy(path_buffer, "/");
strcpy(host_buffer, dest);
return;
}
strcpy(path_buffer, slash_cursor);
strncpy(host_buffer, dest, slash_cursor - dest);
host_buffer[slash_cursor - dest] = '\0';
}