3232#define MAX_EVENTS 10
3333#define PORT "18898"
3434
35- void handle_request (int fd , char * raw_req , size_t size )
35+ int handle_request (int fd , char * raw_req , size_t size )
3636{
3737 assert (fd > 0 );
3838 assert (raw_req != NULL );
3939 if (size == 0 ) {
4040 log_error ("handle_request: raw request size is zero" );
41- return ;
41+ return 1 ;
4242 }
4343
4444 // Split and handle requests here
4545 struct is_prime_request * req = NULL , * it = NULL ;
4646 int r = is_prime_request_builder (& req , raw_req , size );
4747 if (r <= 0 ) {
4848 log_warn ("recv_and_handle: is_prime_request_builder returned '%d'" , r );
49- return ;
49+ return -1 ;
5050 }
5151
52- int l = 0 , sl = 0 , res = 0 ;
52+ int l = 0 , sl = 0 , res = 0 , mal = 0 ;
5353 for (it = req ; it != NULL ; it = it -> next ) {
5454 l = (int )strlen (it -> response );
5555 sl = l ;
@@ -58,18 +58,24 @@ void handle_request(int fd, char* raw_req, size_t size)
5858 log_error ("handle_request: failed during sendall function" );
5959 if (req != NULL )
6060 is_prime_free (& req );
61- return ;
61+ return -2 ;
6262 }
6363 if (sl != l ) {
6464 log_error ("handle_request: failed to sendall the data" );
6565 if (req != NULL )
6666 is_prime_free (& req );
67- return ;
67+ return -3 ;
68+ }
69+
70+ if (it -> number < 0 ) {
71+ mal = 1 ;
72+ break ;
6873 }
6974 }
7075
7176 if (req != NULL )
7277 is_prime_free (& req );
78+ return (mal == 1 ? 0 : 1 );
7379}
7480
7581int main ()
@@ -151,11 +157,19 @@ int main()
151157
152158 // Handle there's data to process
153159 if (size > 0 ) {
154- log_trace (
155- "main epoll loop: handling prime request of size '%d' on fd '%d'" ,
156- size ,
157- fd );
158- handle_request (fd , data , (size_t )size );
160+ log_trace ("main epoll loop: raw request(%d): '%s'" , fd , data );
161+ int result = handle_request (fd , data , (size_t )size );
162+ if (result <= 0 ) {
163+ if (result == 0 )
164+ log_info ("main epoll loop: there was a malformed respoonse. need to close socket" );
165+ else
166+ log_info ("main epoll loop: there was an error sending a response. need to close socket" );
167+ if (fd_poll_del_and_close (& epci ) == -1 ) {
168+ perror ("epoll_ctl: recv 0" );
169+ exit (EXIT_FAILURE );
170+ }
171+ continue ;
172+ }
159173 }
160174
161175 // Handle socket still open
0 commit comments