]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/client/client_auth.c
Client: unify error handling
[dragonblocks_alpha.git] / src / client / client_auth.c
1 #include <stddef.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <linenoise/linenoise.h>
5 #include "client.h"
6 #include "client_auth.h"
7 #include "interrupt.h"
8 #include "types.h"
9
10 struct ClientAuth client_auth;
11
12 #include <string.h>
13 static void auth_loop()
14 {
15         while (!interrupt.set) switch (client_auth.state) {
16                 case AUTH_INIT:
17                         if (client_auth.name)
18                                 linenoiseFree(client_auth.name);
19
20                         if (!(client_auth.name = linenoise("Enter name: ")))
21                                 return;
22
23                         printf("[access] authenticating as %s...\n", client_auth.name);
24                         client_auth.state = AUTH_WAIT;
25
26                         dragonnet_peer_send_ToServerAuth(client, &(ToServerAuth) {
27                                 .name = client_auth.name,
28                         });
29
30                         __attribute__((fallthrough));
31
32                 case AUTH_WAIT:
33                         pthread_cond_wait(&client_auth.cv, &client_auth.mtx);
34                         break;
35
36                 case AUTH_SUCCESS:
37                         return;
38         }
39 }
40
41 void client_auth_init()
42 {
43         client_auth.name = NULL;
44         pthread_cond_init(&client_auth.cv, NULL);
45         pthread_mutex_init(&client_auth.mtx, NULL);
46
47         pthread_mutex_lock(&client_auth.mtx);
48         client_auth.state = AUTH_INIT;
49         flag_sub(&interrupt, &client_auth.cv); // make sure Ctrl+C will work during AUTH_WAIT
50
51         auth_loop();
52
53         flag_uns(&interrupt, &client_auth.cv);
54
55         if (client_auth.state != AUTH_SUCCESS) {
56                 fprintf(stderr, "[error] authentication failed due to interruption or read failure\n");
57                 abort();
58         }
59
60         pthread_mutex_unlock(&client_auth.mtx);
61 }
62
63 void client_auth_deinit()
64 {
65         pthread_cond_destroy(&client_auth.cv);
66         pthread_mutex_destroy(&client_auth.mtx);
67         linenoiseFree(client_auth.name);
68 }