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