Merge remote-tracking branch 'pc3/master'

This commit is contained in:
lucic71 2020-06-08 14:07:19 +03:00
commit 9f57f2ac99
28 changed files with 6103 additions and 0 deletions

7
Protocoale-Comunicatie-3/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
# gdb stuff
.gdb_history
.gdbinit
# object files and executable
*.o
client

View File

@ -0,0 +1,32 @@
CLIENT=client
SOURCES=$(wildcard *.c)
LIBRARY=none
INCPATHS=include
LIBPATHS=
LDFLAGS=
CCFLAGS=-c -Wall -g3
CC=gcc
# Automatic generation of some important lists
# tell the makefile to generate object files for each source file
OBJECTS=$(SOURCES:.c=.o)
INCFLAGS=$(foreach TMP,$(INCPATHS),-I$(TMP))
LIBFLAGS=$(foreach TMP,$(LIBPATHS),-L$(TMP))
# Set up the output file names for the different output types
all: $(SOURCES) $(CLIENT)
$(CLIENT): $(OBJECTS)
$(CC) $(LIBFLAGS) $(OBJECTS) $(LDFLAGS) -o $@
.c.o:
$(CC) $(INCFLAGS) $(CCFLAGS) -fPIC $< -o $@
distclean: clean
rm -f $(CLIENT)
clean:
rm -f $(OBJECTS)

View File

@ -0,0 +1,110 @@
POPESCU LUCIAN IOAN 321CD
-------------------------
TEMA 3 PROTOCOALE DE COMUNICATIE
--------------------------------
I. File structure
-----------------
include/
authentication.h Contains a auth_info_t object
book.h Contains a book_info_t object and a book_id_t object
buffer.h Functions used in connection.c
cJSON.h JSON parsing library
commands.h Prototypes of the implemented commands
connection.h Functions that deal with connection with the server
dns.h Functions that send DNS requests
error.h Macros used to print and deal with errors
http.h Functions that extract info from HTTP headers, etc
memory.h Macros used for safe memory management(CALLOC, MALLOC, FREE)
prompt.h Extract data from prompts (for example: username, password)
requests.h Functions that build GET, POST and DELETE requests
server.h Information about the server (URLS, NAME, etc)
./
authentication.c Implements specific functionality
book.c Implements specific functionality
buffer.c Implements specific functionality
cJSON.c JSON library implementation
client.c Main driver for client
commands.c Implements specific functionality
connection.c Implements specific functionality
dns.c Implements specific functionality
http.c Implements specific functionality
prompt.c Implements specific functionality
requests.c Implements specific functionality
Makefile Makefile to build the client
README This file
II. Design
----------
A. Client and operations(commands)
----------------------------------
The implementation of the client is pretty straight forward. The client reads
input from stdin and using a huge block of if..else statements, it decides which
operation to make.
Each operation has three return status codes: OPERATION_SUCCESSFUL,
OPERATION_CONNECTION_CLOSED and OPERATION_FAILED. The client checks after each
operation the return code to make sure that the connection with the server is
still ok, if not it retries to re-establish it. It also checks that the
operations were successful in order to manage the correct creation and deletion
of cookies and JWT tokens.
The operations are implemented using the same rules:
- fetch data from user if needed
- build the HTTP request
- send the request and receive the response
- work with the response if needed
Moreover each operation takes care of the errors which may occur during the
above mentioned steps. For this each variable is declared at the beginning
of each opearion and if an error occurs the memory will be free'd for this
variables using a goto statement and a label at the end of the current
operation.
B. JSON
-------
For parsing, converting and working with JSON objects I used the cJSON library.
It is a simple library containing only a header file and a source file, that
can easily be inserted in the project.
I chose this library because it has a basic interface containing functions and
objects that require a small amount of time to understand, as the authors say:
"cJSON aims to be the dumbest possible parser that you can get your job done
with".
More info and tutorials can be found on their github page:
"https://github.com/DaveGamble/cJSON".
C. Reading data from user
-------------------------
prompt.c is the file where this functionality is implemented. It pops up a
prompt for the required data and using a basic read function like fgets it
gets the job done. I also added password safety by turning off the echoing
when the password is inserted.
D. Other objects and functionality
----------------------------------
For keeping all as simple as possible, I encapsulated the information coming
from the user (username, password, book info) in objects that have their own
metods for parsing to JSON or deletion. Their location can be found in
I. File structure.
The functionality for connecting with the server and creating requests is
mainly borrowed from lab10 HTTP with some minor changes.
III. Conclusions
----------------
Overall, the application works very smoothly and does not have problems with
memory leaks or any kind of buffer overflows coming from user. It covers the
basic functionality of working with a REST API and has a clean and readable
codebase.

Binary file not shown.

View File

@ -0,0 +1,63 @@
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include "authentication.h"
#include "cJSON.h"
#include "error.h"
#include "memory.h"
#include "prompt.h"
auth_info_t *get_auth_info() {
char *username = read_item(USERNAME, MAX_USER_SZ, ECHO_ON);
char *password = read_item(PASSWORD, MAX_PASS_SZ, ECHO_OFF);
if (username == NULL || password == NULL) {
FREE(username);
FREE(password);
return NULL;
}
/*
* Declare the return variable.
*
*/
auth_info_t *auth_info;
CALLOC(auth_info, sizeof(auth_info_t));
auth_info->username = username;
auth_info->password = password;
return auth_info;
}
cJSON *auth_to_json(auth_info_t *auth_info) {
cJSON *json_object = cJSON_CreateObject();
cJSON *username_item = cJSON_CreateString(auth_info->username);
cJSON_AddItemToObject(json_object, USERNAME, username_item);
cJSON *password_item = cJSON_CreateString(auth_info->password);
cJSON_AddItemToObject(json_object, PASSWORD, password_item);
return json_object;
}
void delete_auth_info(auth_info_t *auth_info) {
if (auth_info == NULL) {
return;
}
FREE(auth_info->username);
FREE(auth_info->password);
FREE(auth_info);
}

View File

@ -0,0 +1,220 @@
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "book.h"
#include "error.h"
#include "memory.h"
#include "prompt.h"
#include "cJSON.h"
book_info_t *get_book_info() {
/*
* Read the elements from a book.
*
*/
char *title = read_item(TITLE, MAX_BOOK_ELEM_SIZE, ECHO_ON);
char *author = read_item(AUTHOR, MAX_BOOK_ELEM_SIZE, ECHO_ON);
char *genre = read_item(GENRE, MAX_BOOK_ELEM_SIZE, ECHO_ON);
char *page_count = read_item(PAGE_COUNT, MAX_BOOK_ELEM_SIZE, ECHO_ON);
char *publisher = read_item(PUBLISHER, MAX_BOOK_ELEM_SIZE, ECHO_ON);
if (title == NULL || author == NULL || genre == NULL || page_count == NULL
|| publisher == NULL) {
FREE(title);
FREE(author);
FREE(genre);
FREE(page_count);
FREE(publisher);
return NULL;
}
/*
* Convert page_count to int and delete page_count.
*
*/
int *page_count_integer;
CALLOC(page_count_integer, sizeof(int));
sscanf(page_count, "%d", page_count_integer);
FREE(page_count);
/*
* Build the book_info_t data type.
*
*/
book_info_t *book_info;
CALLOC(book_info, sizeof(book_info));
book_info->title = title;
book_info->author = author;
book_info->genre = genre;
book_info->page_count = page_count_integer;
book_info->publisher = publisher;
return book_info;
}
book_id_t *get_book_id() {
char *id = read_item(ID, MAX_BOOK_ID_ELEM_SIZE, ECHO_ON);
if (id == NULL) {
FREE(id);
return NULL;
}
/*
* Build the book_id_t data type.
*
*/
book_id_t *book_id;
CALLOC(book_id, sizeof(book_id));
book_id->id = id;
return book_id;
}
cJSON *book_to_json(book_info_t *book_info) {
cJSON *json_object = cJSON_CreateObject();
cJSON *title_item = cJSON_CreateString(book_info->title);
cJSON_AddItemToObject(json_object, TITLE, title_item);
cJSON *author_item = cJSON_CreateString(book_info->author);
cJSON_AddItemToObject(json_object, AUTHOR, author_item);
cJSON *genre_item = cJSON_CreateString(book_info->genre);
cJSON_AddItemToObject(json_object, GENRE, genre_item);
cJSON *page_count_item = cJSON_CreateNumber(*(book_info->page_count));
cJSON_AddItemToObject(json_object, PAGE_COUNT, page_count_item);
cJSON *publisher_item = cJSON_CreateString(book_info->publisher);
cJSON_AddItemToObject(json_object, PUBLISHER, publisher_item);
return json_object;
}
void delete_book_info(book_info_t *book_info) {
if (book_info == NULL) {
return;
}
FREE(book_info->title);
FREE(book_info->author);
FREE(book_info->genre);
FREE(book_info->page_count);
FREE(book_info->publisher);
FREE(book_info);
}
void delete_book_id(book_id_t *book_id) {
if (book_id == NULL) {
return;
}
FREE(book_id->id);
FREE(book_id);
}
void print_json_book_list(char *book_list_string) {
int books_counter = 0;
cJSON *book_list = cJSON_Parse(book_list_string);
cJSON *book = NULL;
cJSON_ArrayForEach(book, book_list) {
cJSON *title = cJSON_GetObjectItemCaseSensitive(book, TITLE);
cJSON *id = cJSON_GetObjectItemCaseSensitive(book, ID);
char *title_string = cJSON_Print(title);
char *id_string = cJSON_Print(id);
printf("\n%s: %s\n"
"%s: %s\n\n",
TITLE, title_string,
ID, id_string);
FREE(title_string);
FREE(id_string);
books_counter++;
}
cJSON_Delete(book_list);
if (books_counter == 0) {
puts(NO_BOOKS_ERROR);
}
}
void print_json_book(char *book_string) {
int books_counter = 0;
cJSON *books = cJSON_Parse(book_string);
cJSON *book = NULL;
cJSON_ArrayForEach(book, books) {
cJSON *title = cJSON_GetObjectItemCaseSensitive(book, TITLE);
cJSON *author = cJSON_GetObjectItemCaseSensitive(book, AUTHOR);
cJSON *genre = cJSON_GetObjectItemCaseSensitive(book, GENRE);
cJSON *page_count = cJSON_GetObjectItemCaseSensitive(book, PAGE_COUNT);
cJSON *publisher = cJSON_GetObjectItemCaseSensitive(book, PUBLISHER);
char *title_string = cJSON_Print(title);
char *author_string = cJSON_Print(author);
char *genre_string = cJSON_Print(genre);
char *page_count_string = cJSON_Print(page_count);
char *publisher_string = cJSON_Print(publisher);
printf("\n%s: %s\n"
"%s: %s\n"
"%s: %s\n"
"%s: %s\n"
"%s: %s\n",
TITLE, title_string,
AUTHOR, author_string,
GENRE, genre_string,
PAGE_COUNT, page_count_string,
PUBLISHER, publisher_string);
FREE(title_string);
FREE(author_string);
FREE(genre_string);
FREE(page_count_string);
FREE(publisher_string);
books_counter++;
}
cJSON_Delete(books);
if (books_counter == 0) {
puts(NO_BOOKS_ERROR);
}
}

View File

@ -0,0 +1,86 @@
#include "buffer.h"
#include "memory.h"
buffer buffer_init(void)
{
buffer buffer;
buffer.data = NULL;
buffer.size = 0;
return buffer;
}
void buffer_destroy(buffer *buffer)
{
if (buffer->data != NULL) {
FREE(buffer->data);
buffer->data = NULL;
}
buffer->size = 0;
}
int buffer_is_empty(buffer *buffer)
{
return buffer->data == NULL;
}
void buffer_add(buffer *buffer, const char *data, size_t data_size)
{
if (buffer->data != NULL) {
buffer->data = realloc(buffer->data, (buffer->size + data_size) * sizeof(char));
} else {
CALLOC(buffer->data, data_size);
}
memcpy(buffer->data + buffer->size, data, data_size);
buffer->size += data_size;
}
int buffer_find(buffer *buffer, const char *data, size_t data_size)
{
if (data_size > buffer->size)
return -1;
size_t last_pos = buffer->size - data_size + 1;
for (size_t i = 0; i < last_pos; ++i) {
size_t j;
for (j = 0; j < data_size; ++j) {
if (buffer->data[i + j] != data[j]) {
break;
}
}
if (j == data_size)
return i;
}
return -1;
}
int buffer_find_insensitive(buffer *buffer, const char *data, size_t data_size)
{
if (data_size > buffer->size)
return -1;
size_t last_pos = buffer->size - data_size + 1;
for (size_t i = 0; i < last_pos; ++i) {
size_t j;
for (j = 0; j < data_size; ++j) {
if (tolower(buffer->data[i + j]) != tolower(data[j])) {
break;
}
}
if (j == data_size)
return i;
}
return -1;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,185 @@
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "error.h"
#include "connection.h"
#include "server.h"
#include "dns.h"
#include "memory.h"
#include "commands.h"
int main() {
/*
* Get the IP of the server.
*
*/
char *server_ip = get_ip(SERVER);
/*
* If the DNS request did not succeed then there is no internet connection.
*
*/
if (server_ip == NULL) {
ERROR(NO_INTERNET_CONNECTION);
exit(EXIT_FAILURE);
}
/*
* Open a connection with the server.
*
*/
int sockfd = open_connection(server_ip, PORT, AF_INET, SOCK_STREAM, 0);
/*
* Buffer for reading the input from the user.
*
*/
char input_buffer[MAX_COMMAND_SZ] = {0};
/*
* Login @cookie is computed in #login and @jwt_token is computed
* in #enter_libary.
*
*/
char *cookie = NULL;
char *jwt_token = NULL;
while (1) {
/*
* Display promt.
*
*/
printf("$ ");
fflush(stdout);
/*
* Fill the buffer with 0's and read the input.
*
*/
memset(input_buffer, 0x00, MAX_COMMAND_SZ);
fgets(input_buffer, MAX_COMMAND_SZ - 1, stdin);
/*
* Possible values:
*
* OPERATION_SUCCESSFUL
* OPERATION_FAILED
* OPERATION_CONNECTION_CLOSED
*
*/
int operation_status;
if (strncmp(input_buffer, REGISTER, sizeof(REGISTER) - 1) == 0) {
operation_status = op_register(&sockfd);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
} else if (strncmp(input_buffer, LOGIN, sizeof(LOGIN) - 1) == 0) {
operation_status = login(&sockfd, &cookie);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
/*
* If the login was successful then the client must delete the previous
* @jwt_token.
*
*/
if (operation_status == OPERATION_SUCCESSFUL) {
FREE(jwt_token);
}
} else if (strncmp(input_buffer, ENTER_LIBRARY, sizeof(ENTER_LIBRARY) - 1) == 0) {
/*
* If a jwt_token was already stored in the @jwt_token then
* delete it because a new enter_library will generate a new jwt_token.
*
*/
operation_status = enter_library(&sockfd, cookie, &jwt_token);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
} else if (strncmp(input_buffer, GET_BOOKS, sizeof(GET_BOOKS) - 1) == 0) {
operation_status = get_books(&sockfd, jwt_token);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
} else if (strncmp(input_buffer, GET_BOOK, sizeof(GET_BOOK) - 1) == 0) {
operation_status = get_book(&sockfd, jwt_token);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
} else if (strncmp(input_buffer, ADD_BOOK, sizeof(ADD_BOOK) - 1) == 0) {
operation_status = add_book(&sockfd, jwt_token);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
} else if (strncmp(input_buffer, DELETE_BOOK, sizeof(DELETE_BOOK) - 1) == 0) {
operation_status = delete_book(&sockfd, jwt_token);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
} else if (strncmp(input_buffer, LOGOUT, sizeof(LOGOUT) - 1) == 0) {
operation_status = logout(&sockfd, cookie);
if (operation_status == OPERATION_CONNECTION_CLOSED) {
restore_connection(&sockfd, server_ip);
}
/*
* Delete the cookie and the jwt_token if the operation was successful.
*
*/
if (operation_status == OPERATION_SUCCESSFUL) {
FREE(cookie);
FREE(jwt_token);
}
} else if (strncmp(input_buffer, EXIT, sizeof(EXIT) - 1) == 0) {
puts(GOODBYE);
close(sockfd);
FREE(cookie);
FREE(jwt_token);
break;
} else {
/*
* The command does not exist.
*
*/
ERROR(INVALID_COMMAND_ERROR);
}
}
return EXIT_SUCCESS;
}

View File

@ -0,0 +1,663 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "commands.h"
#include "cJSON.h"
#include "requests.h"
#include "error.h"
#include "connection.h"
#include "authentication.h"
#include "book.h"
#include "memory.h"
#include "http.h"
#include "server.h"
int op_register(int *sockfd) {
auth_info_t *auth_info = NULL;
cJSON *register_json = NULL;
char *register_json_string = NULL;
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Get the authentication info.
*
*/
auth_info = get_auth_info();
if (auth_info == NULL) {
ERROR(AUTH_INFO_ERROR);
return_status = OPERATION_FAILED;
goto op_register_end;
}
/*
* Generate the json payload for the POST request. And convert
* the JSON object to a string.
*
*/
register_json = auth_to_json(auth_info);
register_json_string = cJSON_Print(register_json);
/*
* Generate the POST request.
*
*/
request = compute_post_request(SERVER, REGISTER_URL,
JSON_CONTENT_TYPE, &register_json_string, 1, NULL, 0, NULL);
if (request == NULL) {
ERROR(POST_ERROR);
return_status = OPERATION_FAILED;
goto op_register_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto op_register_end;
}
if (!contains_status_code(response, CREATED)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto op_register_end;
}
puts(REGISTER_SUCCESS);
op_register_end:
delete_auth_info(auth_info);
cJSON_Delete(register_json);
FREE(register_json_string);
FREE(request);
FREE(response);
return return_status;
}
int login(int *sockfd, char **cookie) {
auth_info_t *auth_info = NULL;
cJSON *login_json = NULL;
char *login_json_string = NULL;
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (cookie == NULL) {
ERROR(COOKIE_ERROR);
return_status = OPERATION_FAILED;
goto login_end;
}
/*
* If there is already an active session then the user must
* firstly logout before it wants to login.
*
*/
if (*cookie != NULL) {
ERROR(ACTIVE_COOKIE_ERROR);
return_status = OPERATION_FAILED;
goto login_end;
}
/*
* Get auth info.
*
*/
auth_info = get_auth_info();
if (auth_info == NULL) {
ERROR(AUTH_INFO_ERROR);
return_status = OPERATION_FAILED;
goto login_end;
}
/*
* Generate the json payload for the POST request. And convert
* the JSON object to a string.
*
*/
login_json = auth_to_json(auth_info);
login_json_string = cJSON_Print(login_json);
/*
* Generate the POST request.
*
*/
request = compute_post_request(SERVER, LOGIN_URL,
JSON_CONTENT_TYPE, &login_json_string, 1, NULL, 0, NULL);
if (request == NULL) {
ERROR(POST_ERROR);
return_status = OPERATION_FAILED;
goto login_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto login_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto login_end;
}
/*
* Extract the cookie from the response and put its value in the @cookie argument.
*
*/
char *cookie_line = basic_extract_cookie_response(response);
char *cookie_line_end = basic_extract_crlf_response(cookie_line);
cookie_line[cookie_line_end - cookie_line] = 0x00;
CALLOC(*cookie, strlen(cookie_line) + 1);
strcpy(*cookie, cookie_line);
puts(LOGIN_SUCCESS);
login_end:
delete_auth_info(auth_info);
cJSON_Delete(login_json);
FREE(login_json_string);
FREE(request);
FREE(response);
return return_status;
}
int enter_library(int *sockfd, char *cookie, char **jwt_token) {
char *request = NULL;
char *response = NULL;
cJSON *json_received_object = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (cookie == NULL) {
ERROR(COOKIE_ERROR);
return_status = OPERATION_FAILED;
goto enter_library_end;
}
if (jwt_token == NULL) {
ERROR(JWT_TOKEN_ERROR);
return_status = OPERATION_FAILED;
goto enter_library_end;
}
/*
* If the user is already logged in in library then skip this operation.
*
*/
if (*jwt_token != NULL && cookie != NULL) {
puts(ENTER_LIBARY_ERROR);
return_status = OPERATION_FAILED;
goto enter_library_end;
}
/*
* Generate the GET request using the @cookie.
*
*/
request = compute_get_request(SERVER, ENTER_LIBRARY_URL, NULL, &cookie, 1, NULL);
if (request == NULL) {
ERROR(GET_ERROR);
return_status = OPERATION_FAILED;
goto enter_library_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto enter_library_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto enter_library_end;
}
/*
* Parse the JWT token received in the HTTP response.
*
*/
char *json_body = basic_extract_json_response(response);
json_received_object = cJSON_Parse(json_body);
cJSON *cJSON_token = cJSON_GetObjectItemCaseSensitive(json_received_object,
JWT_TOKEN);
/*
* Put the token in @jwt_token.
*
*/
CALLOC(*jwt_token, strlen(cJSON_token->valuestring) + 1);
strcpy(*jwt_token, cJSON_token->valuestring);
puts(ENTER_LIBRARY_SUCCESS);
enter_library_end:
cJSON_Delete(json_received_object);
FREE(request);
FREE(response);
return return_status;
}
int get_books(int *sockfd, char *jwt_token) {
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (jwt_token == NULL) {
ERROR(JWT_TOKEN_ERROR);
return_status = OPERATION_FAILED;
goto get_books_end;
}
/*
* Add the jwt token to the GET request.
*
*/
request = compute_get_request(SERVER, GET_BOOKS_URL, NULL, NULL, 0, jwt_token);
if (request == NULL) {
ERROR(GET_ERROR);
return_status = OPERATION_FAILED;
goto get_books_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto get_books_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto get_books_end;
}
print_json_book_list(basic_extract_json_list_response(response));
get_books_end:
FREE(request);
FREE(response);
return return_status;
}
int get_book(int *sockfd, char *jwt_token) {
book_id_t *book_id = NULL;
char *book_url = NULL;
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (jwt_token == NULL) {
ERROR(JWT_TOKEN_ERROR);
return_status = OPERATION_FAILED;
goto get_book_end;
}
/*
* Get the ID from user.
*
*/
book_id = get_book_id();
/*
* Add the jwt token to the GET request. Add the book id to URL.
*
*/
CALLOC(book_url, sizeof(GET_BOOKS_URL) - 1 + strlen("/") + strlen(book_id->id) + 1);
sprintf(book_url, "%s/%s", GET_BOOKS_URL, book_id->id);
request = compute_get_request(SERVER, book_url, NULL, NULL, 0, jwt_token);
if (request == NULL) {
ERROR(GET_ERROR);
return_status = OPERATION_FAILED;
goto get_book_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto get_book_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto get_book_end;
}
print_json_book(basic_extract_json_list_response(response));
get_book_end:
delete_book_id(book_id);
FREE(book_url);
FREE(request);
FREE(response);
return return_status;
}
int add_book(int *sockfd, char *jwt_token) {
book_info_t *book_info = NULL;
cJSON *book_json = NULL;
char *book_json_string = NULL;
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (jwt_token == NULL) {
ERROR(JWT_TOKEN_ERROR);
return_status = OPERATION_FAILED;
goto add_book_end;
}
/*
* Get book info.
*
*/
book_info = get_book_info();
if (book_info == NULL) {
ERROR("Could not get book info");
return_status = OPERATION_FAILED;
goto add_book_end;
}
/*
* Generate the payload for the POST request.
*
*/
book_json = book_to_json(book_info);
book_json_string = cJSON_Print(book_json);
/*
* Generate the POST request.
*
*/
request = compute_post_request(SERVER, ADD_BOOK_URL,
JSON_CONTENT_TYPE, &book_json_string, 1, NULL, 0, jwt_token);
if (request == NULL) {
ERROR(POST_ERROR);
return_status = OPERATION_FAILED;
goto add_book_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto add_book_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto add_book_end;
}
puts(ADD_BOOK_SUCCESS);
add_book_end:
delete_book_info(book_info);
cJSON_Delete(book_json);
FREE(book_json_string);
FREE(request);
FREE(response);
return return_status;
}
int delete_book(int *sockfd, char *jwt_token) {
book_id_t *book_id = NULL;
char *book_url = NULL;
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (jwt_token == NULL) {
ERROR(JWT_TOKEN_ERROR);
return_status = OPERATION_FAILED;
goto delete_book_end;
}
/*
* Get the ID from user.
*
*/
book_id = get_book_id();
/*
* Add the jwt token to the DELETE request. Add the book id to URL.
*
*/
CALLOC(book_url, sizeof(DELETE_BOOK_URL) - 1 + strlen("/") + strlen(book_id->id) + 1);
sprintf(book_url, "%s/%s", DELETE_BOOK_URL, book_id->id);
request = compute_delete_request(SERVER, book_url, NULL, NULL, 0, jwt_token);
if (request == NULL) {
ERROR(DELETE_ERROR);
return_status = OPERATION_FAILED;
goto delete_book_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto delete_book_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto delete_book_end;
}
puts(DELETE_BOOK_SUCCESS);
delete_book_end:
delete_book_id(book_id);
FREE(book_url);
FREE(request);
FREE(response);
return return_status;
}
int logout(int *sockfd, char *cookie) {
char *request = NULL;
char *response = NULL;
int return_status = OPERATION_SUCCESSFUL;
/*
* Guard for input.
*
*/
if (cookie == NULL) {
ERROR(COOKIE_ERROR);
return_status = OPERATION_FAILED;
goto logout_end;
}
/*
* Generate the GET request using the @cookie.
*
*/
request = compute_get_request(SERVER, LOGOUT_URL, NULL, &cookie, 1, NULL);
if (request == NULL) {
ERROR(GET_ERROR);
return_status = OPERATION_FAILED;
goto logout_end;
}
/*
* Send the request and receive the response.
*
*/
int send_and_receive_ret = send_and_receive(sockfd, request, &response);
if (send_and_receive_ret == SEND_RECV_FAIL) {
return_status = OPERATION_CONNECTION_CLOSED;
goto logout_end;
}
if (!contains_status_code(response, SUCCESS)) {
print_http_error(basic_extract_json_response(response));
return_status = OPERATION_FAILED;
goto logout_end;
}
puts(LOGOUT_SUCCESS);
logout_end:
FREE(response);
FREE(request);
return return_status;
}

View File

@ -0,0 +1,242 @@
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <time.h>
#include "connection.h"
#include "error.h"
#include "buffer.h"
#include "server.h"
#include "dns.h"
void compute_message(char *message, const char *line) {
strcat(message, line);
strcat(message, "\r\n");
}
int open_connection(char *host_ip, int portno, int ip_type, int socket_type, int flag) {
/*
* Open the socket.
*
*/
int sockfd = socket(ip_type, socket_type, flag);
ERROR_HANDLER(sockfd < 0, OPEN_CONNECTION_FAILED);
/*
* Fill the information about the server in a struct sockaddr_in.
*
*/
struct sockaddr_in serv_addr;
memset(&serv_addr, 0x00, sizeof(serv_addr));
serv_addr.sin_family = ip_type;
serv_addr.sin_port = htons(portno);
inet_aton(host_ip, &serv_addr.sin_addr);
/*
* Set timeout.
*
*/
struct timeval tv;
tv.tv_sec = CONNECTION_TIMEOUT;
tv.tv_usec = 0;
setsockopt(sockfd, IPPROTO_TCP, SO_RCVTIMEO, (const char *) &tv, sizeof(tv));
/*
* Connect to server.
*
*/
int connect_ret = connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
ERROR_HANDLER(connect_ret < 0, OPEN_CONNECTION_FAILED);
return sockfd;
}
void close_connection(int sockfd) {
close(sockfd);
}
int send_to_server(int sockfd, char *message) {
int bytes, sent = 0;
int total = strlen(message);
do {
bytes = write(sockfd, message + sent, total - sent);
ERROR_HANDLER(bytes < 0, SEND_TO_SERVER_FAILED);
if (bytes == 0) {
puts("[DEBUG] Message sent successfully!");
break;
}
sent += bytes;
} while (sent < total);
return SEND_TO_SERVER_SUCCESSFUL;
}
char *receive_from_server(int sockfd) {
char response[BUFLEN];
buffer buffer = buffer_init();
int header_end = 0;
int content_length = 0;
/*
* Read the header.
*
*/
do {
int bytes = read(sockfd, response, BUFLEN);
if (bytes < 0){
buffer_destroy(&buffer);
ERROR_HANDLER(true, NULL);
}
if (bytes == 0) {
buffer_destroy(&buffer);
ERROR_HANDLER(true, NULL);
}
buffer_add(&buffer, response, (size_t) bytes);
header_end = buffer_find(&buffer, HEADER_TERMINATOR, HEADER_TERMINATOR_SIZE);
if (header_end >= 0) {
header_end += HEADER_TERMINATOR_SIZE;
int content_length_start = buffer_find_insensitive(&buffer, CONTENT_LENGTH, CONTENT_LENGTH_SIZE);
if (content_length_start < 0) {
continue;
}
content_length_start += CONTENT_LENGTH_SIZE;
content_length = strtol(buffer.data + content_length_start, NULL, 10);
break;
}
} while (1);
/*
* Read the content.
*
*/
size_t total = content_length + (size_t) header_end;
while (buffer.size < total) {
int bytes = read(sockfd, response, BUFLEN);
if (bytes < 0){
buffer_destroy(&buffer);
ERROR_HANDLER(true, NULL);
}
if (bytes == 0) {
buffer_destroy(&buffer);
ERROR_HANDLER(true, NULL);
}
buffer_add(&buffer, response, (size_t) bytes);
}
buffer_add(&buffer, "", 1);
return buffer.data;
}
int send_and_receive(int *sockfd, char *request, char **response) {
char *server_ip = get_ip(SERVER);
/*
* If the internet connection dies while the client runs, get_ip will
* detect this because it makes a DNS request that will use the connection.
*
* So the client will die to.
*
*/
if (server_ip == NULL) {
ERROR(NO_INTERNET_CONNECTION);
exit(EXIT_FAILURE);
}
bool connection_failed = false;
int return_status = SEND_RECV_FAIL;
for (size_t i = 0; i < SEND_RECV_TIMEOUT; i++) {
/*
* Repoen the connection if it closed.
*
*/
if (connection_failed == true) {
*sockfd = open_connection(server_ip, PORT, AF_INET, SOCK_STREAM, 0);
connection_failed = false;
}
/*
* Maybe the connection failed and sockfd is now -1.
*
*/
if (*sockfd == -1) {
continue;
}
/*
* Try to send to server and to receive.
*
*/
int send_to_server_ret = send_to_server(*sockfd, request);
if (send_to_server_ret == SEND_TO_SERVER_FAILED) {
connection_failed = true;
continue;
}
*response = receive_from_server(*sockfd);
if (*response == NULL) {
connection_failed = true;
continue;
}
/*
* If the above operations did not fail then break from loop.
*
*/
return_status = SEND_RECV_SUCC;
break;
}
return return_status;
}
void restore_connection(int *sockfd, char *server_ip) {
for (size_t i = 0; i < SEND_RECV_TIMEOUT; i++) {
*sockfd = open_connection(server_ip, PORT, AF_INET, SOCK_STREAM, 0);
if (*sockfd > 0) {
return;
}
}
ERROR(UNSTABLE_INTERNET_CONNECTION);
exit(EXIT_FAILURE);
}

View File

@ -0,0 +1,46 @@
#include <stdio.h>
#include "dns.h"
#include "error.h"
char *get_ip(char *name) {
/*
* Set the hints for getaddrinfo(3).
*
*/
struct addrinfo hints = {
.ai_flags = 0,
.ai_family = AF_INET,
.ai_socktype = SOCK_DGRAM,
.ai_protocol = 0,
.ai_addrlen = 0,
.ai_addr = NULL,
.ai_canonname = NULL,
.ai_next = NULL,
};
/*
* Call getaddrinfo(3) and store the info in @result.
*
*/
struct addrinfo *result;
int getaddrinfo_ret = getaddrinfo(name, NULL, &hints, &result);
ERROR_HANDLER(getaddrinfo_ret < 0, NULL);
/*
* Get the IPv4 address from @result.
*
*/
struct sockaddr_in *ipv4_addr = (struct sockaddr_in *) result->ai_addr;
uint32_t ip_addr = ipv4_addr->sin_addr.s_addr;
freeaddrinfo(result);
/*
* Return the IPv4 address converted to char array.
*
*/
return inet_ntoa((struct in_addr) { .s_addr = ip_addr});
}

View File

@ -0,0 +1,56 @@
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <http.h>
#include <cJSON.h>
#include "error.h"
#define ERROR_JSON_OBJECT "error"
bool contains_status_code(char *response, char *status_code) {
if (strstr(response, status_code) != NULL) {
return true;
} else {
return false;
}
}
char *basic_extract_json_response(char *response) {
return strstr(response, "{\"");
}
char *basic_extract_json_list_response(char *response) {
return strstr(response, "[");
}
char *basic_extract_cookie_response(char *response) {
return strstr(response, SET_COOKIE) + SET_COOKIE_SIZE;
}
char *basic_extract_crlf_response(char *response) {
return strstr(response, CRLF);
}
void print_http_error(char *json_response) {
if (json_response == NULL) {
return;
}
cJSON *cjson_response = cJSON_Parse(json_response);
if (cjson_response == NULL) {
return;
}
cJSON *cjson_error = cJSON_GetObjectItemCaseSensitive(cjson_response, ERROR_JSON_OBJECT);
ERROR(cjson_error->valuestring);
cJSON_Delete(cjson_response);
}

View File

@ -0,0 +1,48 @@
#ifndef AUTHENTICATION_H_
#define AUTHENTICATION_H_
#include "cJSON.h"
#define MAX_USER_SZ 100
#define MAX_PASS_SZ 100
/*
* Number of components used in a register/login operation:
* username
* psasword
*
*/
#define AUTH_INFO_ELEMS 2
/*
* Names of the fields in auth_info_t.
*
*/
#define USERNAME "username"
#define PASSWORD "password"
typedef struct auth_info {
char *username;
char *password;
} auth_info_t;
/*
* Display a prompt with username and password, let the user enter the
* info and return it in a auth_info_t data type.
*
*/
auth_info_t *get_auth_info();
/*
* Convert a auth_info_t object to JSON format.
*
*/
cJSON *auth_to_json(auth_info_t *auth_info);
/*
* Frees the memory for a auth_info_t object.
*
*/
void delete_auth_info(auth_info_t *auth_info);
#endif

View File

@ -0,0 +1,89 @@
#ifndef BOOK_H_
#define BOOK_H_
#include "cJSON.h"
/*
* Number of elements in a book_info structure.
*
*/
#define BOOK_INFO_ELEMS 5
/*
* Max number of characters in the strings defined in book_info_t.
*
*/
#define MAX_BOOK_ELEM_SIZE 100
#define MAX_BOOK_ID_ELEM_SIZE 100
/*
* Names of prompts in ADD_BOOK operation.
*
*/
#define ID "id"
#define TITLE "title"
#define AUTHOR "author"
#define GENRE "genre"
#define PUBLISHER "publisher"
#define PAGE_COUNT "page_count"
typedef struct book_id {
char *id;
} book_id_t;
typedef struct book_info {
char *title;
char *author;
char *genre;
int *page_count;
char *publisher;
} book_info_t;
/*
* Display a prompt for each element in book_info_t, let the user enter the
* info and return it in a book_info_t data type.
*
*/
book_info_t *get_book_info();
/*
* Display a prompt for each element in book_id_t, let the user enter the
* info and return it in a book_id_t data type.
*
*/
book_id_t *get_book_id();
/*
* Convert the book_info_t object to JSON format.
*
*/
cJSON *book_to_json(book_info_t *book_info);
/*
* Frees the memory for a book_info_t object.
*
*/
void delete_book_info(book_info_t *book_info);
/*
* Frees the memory for a book_id_t object.
*
*/
void delete_book_id(book_id_t *book_id);
/*
* Print the ID and the TITLE of each book received in @book_list_string
*
*/
void print_json_book_list(char *book_list_string);
/*
* Print a JSON book accordingly to book_info_t and book_id_t format.
*
*/
void print_json_book(char *book_string);
#endif

View File

@ -0,0 +1,28 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct {
char *data;
size_t size;
} buffer;
// initializes a buffer
buffer buffer_init(void);
// destroys a buffer
void buffer_destroy(buffer *buffer);
// adds data of size data_size to a buffer
void buffer_add(buffer *buffer, const char *data, size_t data_size);
// checks if a buffer is empty
int buffer_is_empty(buffer *buffer);
// finds data of size data_size in a buffer and returns its position
int buffer_find(buffer *buffer, const char *data, size_t data_size);
// finds data of size data_size in a buffer in a
// case-insensitive fashion and returns its position
int buffer_find_insensitive(buffer *buffer, const char *data, size_t data_size);

View File

@ -0,0 +1,293 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
#define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
#endif
#else /* !__WINDOWS__ */
#define CJSON_CDECL
#define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 13
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(cJSON *item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
* The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
* The input pointer json cannot point to a read-only address area, such as a string constant,
* but should point to a readable and writable adress area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,107 @@
#ifndef COMMANDS_H_
#define COMMANDS_H_
/*
* Maximum sizes of different inputs.
*
*/
#define MAX_COMMAND_SZ 20
/*
* Format of commands given by the user.
*
*/
#define REGISTER "register"
#define LOGIN "login"
#define ENTER_LIBRARY "enter_library"
#define GET_BOOKS "get_books"
#define GET_BOOK "get_book"
#define ADD_BOOK "add_book"
#define DELETE_BOOK "delete_book"
#define LOGOUT "logout"
#define EXIT "exit"
/*
* Status codes for all commands listed below.
*
*/
#define OPERATION_SUCCESSFUL 0
#define OPERATION_FAILED 1
#define OPERATION_CONNECTION_CLOSED 2
/*
* Registers an account to the server. The connection
* with the server must be established on @*sockfd.
*
* If the server closed the connection with the client then
* OPERATION_CONNECTION_CLOSED error code will be returned. If any other
* error occured then OPERATION_FAILED will be returned.
*
* On success, OPERATION_SUCCESSFUL is returned.
*
* The function is called 'op_register', not 'register' because the
* latter one is a keyword in C and cannot be used as a function
* name.
*/
int op_register(int *sockfd);
/*
* Logins to the server and returns a session cookie.
*
* If this function fails then it will return NULL.
*
*/
int login(int *sockfd, char **cookie);
/*
* Using a @cookie, send a GET request to the library access URL and return
* a JWT Token in @jwt_token.
*
*/
int enter_library(int *sockfd, char *cookie, char **jwt_token);
/*
* Using a @jwt_token, send a GET request to the library URL and print the
* received list of JSON object.
*
*/
int get_books(int *sockfd, char *jwt_token);
/*
* Using a @jwt_token, send a GET request to the library URL and print the
* info about the book.
*
*/
int get_book(int *sockfd, char *jwt_token);
/*
* Using a @jwt_token, send a POST request to the add book URL. The info
* about the book will be fed from a prompt.
*
*/
int add_book(int *sockfd, char *jwt_token);
/*
* Using a @jwt_token, send a DELETE request to the add book URL. The info
* about the book will be fed from a prompt.
*
*/
int delete_book(int *sockfd, char *jwt_token);
/*
* Logs out using the @cookie.
*
*/
int logout(int *sockfd, char *cookie);
#endif

View File

@ -0,0 +1,80 @@
#ifndef CONNECTION_H_
#define CONNECTION_H_
#define BUFLEN 4096
#define LINELEN 1000
#define HEADER_TERMINATOR "\r\n\r\n"
#define HEADER_TERMINATOR_SIZE (sizeof(HEADER_TERMINATOR) - 1)
#define CONTENT_LENGTH "Content-Length: "
#define CONTENT_LENGTH_SIZE (sizeof(CONTENT_LENGTH) - 1)
/*
* Waits 5 second to connect to server.
*
*/
#define CONNECTION_TIMEOUT 5
/*
* Adds a line to a string message.
*
*/
void compute_message(char *message, const char *line);
/*
* Opens a connection with the server at @host_ip on port @portno.
*
* If the connection is successful then it returns a new socket file descriptor,
* else it returns OPEN_CONNECTION_FAILED.
*
*/
#define OPEN_CONNECTION_FAILED -1
int open_connection(char *host_ip, int portno, int ip_type, int socket_type, int flag);
/*
* Closes the connection with the server on socket sockfd.
*
*/
void close_connection(int sockfd);
/*
* Sends a message to a server on socket sockfd.
*
* Returns SEND_TO_SERVER_SUCCESSFUL on success and
* SEND_TO_SERVER_FAILED on failure.
*
*/
#define SEND_TO_SERVER_SUCCESSFUL 0
#define SEND_TO_SERVER_FAILED 1
int send_to_server(int sockfd, char *message);
/*
* Receives and returns a message from server.
*
*/
char *receive_from_server(int sockfd);
/*
* Sends request and tries SEND_RECV_TIMEOUT times to receive a response.
*
* Returns SEND_RECV_FAIL on failure and SEND_RECV_SUCC on success.
*
*/
#define SEND_RECV_FAIL -1
#define SEND_RECV_SUCC 0
#define SEND_RECV_TIMEOUT 10
int send_and_receive(int *sockfd, char *request, char **response);
/*
* Make a stabile connection with the server.
*
*/
void restore_connection(int *sockfd, char *server_ip);
#endif

View File

@ -0,0 +1,18 @@
#ifndef DNS_H_
#define DNS_H_
#include <stdint.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
/*
* Get the IPv4 address in integer format.
* Returns NULL on error.
*
*/
char *get_ip(char *name);
#endif

View File

@ -0,0 +1,97 @@
#ifndef ERROR_H_
#define ERROR_H_
/*
* Success messages for the operations defined in commands.h
*
*/
#define REGISTER_SUCCESS "User registered successfully!"
#define LOGIN_SUCCESS "User logged in successfully!"
#define ENTER_LIBRARY_SUCCESS "Entered library successfully!"
#define ADD_BOOK_SUCCESS "Book added successfully!"
#define DELETE_BOOK_SUCCESS "Book deleted successfully!"
#define LOGOUT_SUCCESS "User logged out successfully!"
/*
* Error messages for the operations defined in commands.h
*
*/
#define REGISTER_FAIL "Username already exists!"
#define LOGIN_FAIL "User does not exist!"
#define ENTER_LIBRARY_FAIL "Entered library failed!"
#define ADD_BOOK_FAIL "Book cannot be added at the moment!"
#define GET_BOOKS_FAIL "Books cannot be received at the moment!"
#define GET_BOOK_FAIL "Book cannot be received at the moment!"
#define DELETE_BOOK_FAIL "Book cannot be deleted at the moment!"
#define LOGOUT_FAIL "User cannot be logged out at the moment"
/*
* Error message for inexistent operations.
*
*/
#define INVALID_COMMAND_ERROR "This command is not supported!"
/*
* Error messages for sending and receiving a packet.
*
*/
#define SEND_ERROR "Could not send request to server"
#define RECV_ERROR "Could not receive a response from server"
/*
* Error messages for generating requests.
*
*/
#define POST_ERROR "Could not generate POST request"
#define GET_ERROR "Could not generate GET request"
#define DELETE_ERROR "Could not generate DELETE request"
/*
* Error messages for prompters.
*
*/
#define AUTH_INFO_ERROR "Could not get authentication info"
#define BOOK_INFO_ERROR "Could not get book info"
/*
* Error messages for the books received as JSON objects.
*
*/
#define NO_BOOKS_ERROR "There are no books in the library!"
/*
* Error messages for connection with the server.
*
*/
#define SERVER_CONNECTION_CLOSED "Server closed the connection. Please retry the operation!"
#define NO_INTERNET_CONNECTION "There is no internet connection!"
#define UNSTABLE_INTERNET_CONNECTION "Unstable internet connection! Please retry."
/*
* Error messages for invalid cookies or tokens.
*
*/
#define ACTIVE_COOKIE_ERROR "You must logout before making this operation!"
#define COOKIE_ERROR "You must login before making this operation!"
#define JWT_TOKEN_ERROR "You must enter library before making this operation!"
#define ENTER_LIBARY_ERROR "You are already in library!"
/*
* Status message for closing the client.
*
*/
#define GOODBYE "Closing the connection with the server, goodbye."
#define ERROR_HANDLER(assertion, return_value) \
do { \
if (assertion) { \
return return_value; \
} \
} while(0)
#define ERROR(error) \
do { \
fprintf(stderr, "[ERROR] %s\n", error); \
} while (0)
#endif

View File

@ -0,0 +1,47 @@
#ifndef HTTP_H_
#define HTTP_H_
#include <stdbool.h>
/*
* Name of a JWT Token in then JSON object received in #enter_library.
*
*/
#define JWT_TOKEN "token"
/*
* Status codes received in HTTP responses.
*
*/
#define SUCCESS "200 OK"
#define CREATED "201 Created"
/*
* Function that checks if HTTP @response contains @status_code.
*
*/
bool contains_status_code(char *response, char *status_code);
/*
* Functions that extract data from a HTTP response.
*
*/
#define CRLF "\r\n"
#define CRLF_SIZE (sizeof(CRLF) - 1)
#define SET_COOKIE "Set-Cookie: "
#define SET_COOKIE_SIZE (sizeof(SET_COOKIE) - 1)
char *basic_extract_json_response(char *response);
char *basic_extract_json_list_response(char *response);
char *basic_extract_cookie_response(char *respose);
char *basic_extract_crlf_response(char *response);
void print_http_error(char *json_response);
#endif

View File

@ -0,0 +1,50 @@
#include <stdlib.h>
#include <stdio.h>
/*
* This header file deals with memory allocation.
*
*/
#define ERROR_ALLOC_MESSAGE "Insufficient memory"
#define MALLOC(p, n) \
do \
{ \
if ( !( (p) = malloc(sizeof(*(p)) * (n)) ) ) \
{ \
fprintf(stderr, ERROR_ALLOC_MESSAGE); \
exit(EXIT_FAILURE); \
} \
} \
while(0)
#define CALLOC(p, n) \
do \
{ \
if ( !( (p) = calloc((n), sizeof(*(p))) ) ) \
{ \
fprintf(stderr, ERROR_ALLOC_MESSAGE); \
exit(EXIT_FAILURE); \
} \
} \
while(0)
#define REALLOC(p, n) \
do \
{ \
if ( !( (p) = realloc((p), sizeof(*(p)) * (n)) ) ) \
{ \
fprintf(stderr, ERROR_ALLOC_MESSAGE); \
exit(EXIT_FAILURE); \
} \
} \
while(0)
#define FREE(p) \
do \
{ \
free(p); \
p = NULL; \
} \
while(0)

View File

@ -0,0 +1,16 @@
#ifndef PROMPT_H_
#define PROMPT_H_
/*
* Prompts the user the message @item_name and waits for an input
* of at most @item_max_len bytes.
*
* Returns a heap memory array that will contain the user data.
*
*/
#define ECHO_ON 1
#define ECHO_OFF 0
char *read_item(char *item_name, int item_max_len, int echo);
#endif

View File

@ -0,0 +1,46 @@
#ifndef REQUESTS_H_
#define REQUESTS_H_
/*
* Computes a GET request addressed to the @url hosted by @host.
*
* @query_params and @cookies can be set to NULL if not needed.
*
* @return: a char array containing the GET request.
* NULL if the operation faield (input was invalid)
*
*/
char *compute_get_request(char *host, char *url, char *query_params,
char **cookies, int cookies_count, char *auth_token);
/*
* Computes a DELETE request addressed to the @url hosted by @host.
*
* @query_params and @cookies can be set to NULL if not needed.
*
* @return: a char array containing the DELETE request.
* NULL if the operation faield (input was invalid)
*
*/
char *compute_delete_request(char *host, char *url, char *query_params,
char **cookies, int cookies_count, char *auth_token);
/*
* Computes a POST request addressed to the @url hosted by @host.
*
* @cookies can be set to NULL if not needed.
* @body_data is the data contained in the POST request.
*
* @return: a char array containing the POST request.
*
*/
char *compute_post_request(char *host, char *url, char* content_type, char **body_data,
int body_data_fields_count, char** cookies, int cookies_count, char *auth_token);
/*
* Adds a x-access-token field in the header of the GET request.
*
*/
char *add_access_token(char *request, char *jwt_token);
#endif

View File

@ -0,0 +1,29 @@
#ifndef SERVER_H_
#define SERVER_H_
/*
* Info about the server.
*
*/
#define SERVER "ec2-3-8-116-10.eu-west-2.compute.amazonaws.com"
#define PORT 8080
/*
* Content types.
*
*/
#define JSON_CONTENT_TYPE "application/json"
/*
* URLs.
*
*/
#define REGISTER_URL "/api/v1/tema/auth/register"
#define LOGIN_URL "/api/v1/tema/auth/login"
#define ENTER_LIBRARY_URL "/api/v1/tema/library/access"
#define GET_BOOKS_URL "/api/v1/tema/library/books"
#define ADD_BOOK_URL "/api/v1/tema/library/books"
#define DELETE_BOOK_URL "/api/v1/tema/library/books"
#define LOGOUT_URL "/api/v1/tema/auth/logout"
#endif

View File

@ -0,0 +1,79 @@
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include "prompt.h"
#include "memory.h"
#include "error.h"
char *read_item(char *item_name, int item_max_len, int echo) {
/*
* Print the prompt.
*
*/
printf("%s: ", item_name);
fflush(stdout);
struct termios current, modified;
if (echo == ECHO_OFF) {
/*
* If echoing is off then disable it usint tcgetattr, tcsetattr.
*
*/
// get current attributes
int tcgetattr_ret = tcgetattr(STDIN_FILENO, &current);
ERROR_HANDLER(tcgetattr_ret == -1, NULL);
modified = current;
modified.c_lflag &= ~ECHO;
int tcsetattr_ret = tcsetattr(STDIN_FILENO, TCSAFLUSH, &modified);
ERROR_HANDLER(tcsetattr_ret == -1, NULL);
}
/*
* Read at most @item_max_len chars in a buffer allocated
* on stack.
*
*/
char stack_item[item_max_len];
memset(stack_item, 0x00, item_max_len);
fgets(stack_item, item_max_len - 1, stdin);
stack_item[strlen(stack_item) - 1] = 0x00;
if (echo == ECHO_OFF) {
/*
* Restore original settings for echoing.
*
*/
int tcsetattr_ret = tcsetattr(STDIN_FILENO, TCSANOW, &current);
ERROR_HANDLER(tcsetattr_ret == -1, NULL);
}
/*
* If echoing is off then put a newline after the read is done. It makes it look
* prettier.
*
*/
if (echo == ECHO_OFF) {
puts("");
}
/*
* Return a pointer on heap that will contain excactly
* strlen + 1 bytes from @stack_item.
*
*/
char *heap_item;
CALLOC(heap_item, strlen(stack_item) + 1);
strcpy(heap_item, stack_item);
return heap_item;
}

View File

@ -0,0 +1,292 @@
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "connection.h"
#include "requests.h"
#include "error.h"
#include "memory.h"
char *compute_get_request(char *host, char *url, char *query_params,
char **cookies, int cookies_count, char *auth_token) {
char *message;
CALLOC(message, BUFLEN);
char *line;
CALLOC(line, LINELEN);
/*
* Append queries to the first line of the request.
*
*/
if (query_params != NULL) {
sprintf(line, "GET %s?%s HTTP/1.1", url, query_params);
} else {
sprintf(line, "GET %s HTTP/1.1", url);
}
compute_message(message, line);
if (host == NULL) {
FREE(message);
FREE(line);
ERROR_HANDLER(true, NULL);
}
memset(line, 0x00, LINELEN);
sprintf(line, "Host: %s", host);
compute_message(message, line);
/*
* Add headers and/or cookies, according to the protocol format
*
*/
if (cookies != NULL) {
memset(line, 0x00, LINELEN);
sprintf(line, "Cookie: %s", cookies[0]);
for (size_t i = 1; i < cookies_count; i++) {
sprintf(line, "%s; %s", line, cookies[i]);
}
compute_message(message, line);
}
/*
* Add the authorization token.
*
*/
if (auth_token != NULL) {
memset(line, 0x00, LINELEN);
sprintf(line, "Authorization: Bearer %s", auth_token);
compute_message(message, line);
}
/*
* Add a final newline.
*
*/
compute_message(message, "");
/*
* FREE the memory and return.
*
*/
FREE(line);
return message;
}
char *compute_delete_request(char *host, char *url, char *query_params,
char **cookies, int cookies_count, char *auth_token) {
char *message;
CALLOC(message, BUFLEN);
char *line;
CALLOC(line, LINELEN);
/*
* Append queries to the first line of the request.
*
*/
if (query_params != NULL) {
sprintf(line, "DELETE %s?%s HTTP/1.1", url, query_params);
} else {
sprintf(line, "DELETE %s HTTP/1.1", url);
}
compute_message(message, line);
if (host == NULL) {
FREE(message);
FREE(line);
ERROR_HANDLER(true, NULL);
}
memset(line, 0x00, LINELEN);
sprintf(line, "Host: %s", host);
compute_message(message, line);
/*
* Add headers and/or cookies, according to the protocol format
*
*/
if (cookies != NULL) {
memset(line, 0x00, LINELEN);
sprintf(line, "Cookie: %s", cookies[0]);
for (size_t i = 1; i < cookies_count; i++) {
sprintf(line, "%s; %s", line, cookies[i]);
}
compute_message(message, line);
}
/*
* Add the authorization token.
*
*/
if (auth_token != NULL) {
memset(line, 0x00, LINELEN);
sprintf(line, "Authorization: Bearer %s", auth_token);
compute_message(message, line);
}
/*
* Add a final newline.
*
*/
compute_message(message, "");
/*
* FREE the memory and return.
*
*/
FREE(line);
return message;
}
char *compute_post_request(char *host, char *url, char* content_type, char **body_data,
int body_data_fields_count, char **cookies, int cookies_count, char *auth_token) {
char *message;
CALLOC(message, BUFLEN);
char *line;
CALLOC(line, LINELEN);
char *body_data_buffer;
CALLOC(body_data_buffer, LINELEN);
/*
* Write the method name, URL and protocol type.
*
*/
sprintf(line, "POST %s HTTP/1.1", url);
compute_message(message, line);
/*
* Add the host.
*
*/
if (host == NULL) {
FREE(message);
FREE(line);
FREE(body_data_buffer);
ERROR_HANDLER(true, NULL);
}
memset(line, 0x00, LINELEN);
sprintf(line, "Host: %s", host);
compute_message(message, line);
/*
* Add Content-Type to the request.
*
*/
memset(line, 0x00, LINELEN);
sprintf(line, "Content-Type: %s", content_type);
compute_message(message, line);
if (body_data_fields_count == 0) {
FREE(message);
FREE(line);
FREE(body_data_buffer);
ERROR_HANDLER(true, NULL);
}
/*
* Compute Content-Length.
*
*/
size_t content_length = 0;
for (size_t i = 0; i < body_data_fields_count; i++) {
content_length += strlen(body_data[i]);
}
// add the number of &'s from body_Data to length
content_length += (body_data_fields_count - 1);
memset(line, 0x00, LINELEN);
sprintf(line, "Content-Length: %ld", content_length);
compute_message(message, line);
/*
* Add the cookies.
*
*/
if (cookies != NULL) {
memset(line, 0x00, LINELEN);
sprintf(line, "Cookie: %s", cookies[0]);
for (size_t i = 1; i < cookies_count; i++) {
sprintf(line, "%s; %s", line, cookies[i]);
}
compute_message(message, line);
}
/*
* Add the authorization token.
*
*/
if (auth_token != NULL) {
memset(line, 0x00, LINELEN);
sprintf(line, "Authorization: Bearer %s", auth_token);
compute_message(message, line);
}
/*
* Add a newline at the final of the header.
*/
compute_message(message, "");
/*
* Add the payload of the POST request.
*
*/
memset(body_data_buffer, 0x00, LINELEN);
sprintf(body_data_buffer, "%s", body_data[0]);
for (size_t i = 1; i < body_data_fields_count; i++) {
sprintf(body_data_buffer, "%s&%s", body_data_buffer, body_data[i]);
}
compute_message(message, body_data_buffer);
/*
* FREE the memory and return.
*
*/
FREE(line);
FREE(body_data_buffer);
return message;
}