aboutsummaryrefslogtreecommitdiff
path: root/client/helloworld/main.c
blob: 079b957bf6da1c6380532fd32f25fa4a3aeff3be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
 * Created by yuuta on 7/20/22.
 */

#include <libac.h>
#include "net.h"

#include <stdio.h>

#ifndef WIN32

#include <signal.h>
#include <errno.h>
#include <string.h>

#endif

#ifdef __STDC_NO_THREADS__
# ifdef WIN32
#define THREAD_WIN32
#include <windows.h>
static HANDLE mtx_conn;

int lock(void) { \
DWORD _dwlck = WaitForSingleObject(mtx_conn, 0); \
if (_dwlck == WAIT_FAILED) { _dwlck = GetLastError(); } \
if (_dwlck) { fprintf(stderr, "Cannot lock the mutex: %d.\n", _dwlck); return _dwlck; } \
return 0; \
}

int unlock(void) { \
if (!ReleaseMutex(mtx_conn)) { \
int r = GetLastError();        \
fprintf(stderr, "Cannot release the mutex: %d.\n", r); \
return r;      \
} \
return 0;    \
}

# else
#error "Either C11 threading or Win32 API is required for concurrency."
# endif
#else

#define THREAD_C11

#include <threads.h>

static mtx_t mtx_conn;

int lock(void) {
    \
if (mtx_lock(&mtx_conn) != thrd_success) {
        \
fprintf(stderr, "Cannot lock the mutex.\n"); \
return 1;    \

    }            \
return 0;   \

}

int unlock(void) {
    \
if (mtx_unlock(&mtx_conn) != thrd_success) {
        \
fprintf(stderr, "Cannot release the mutex.\n"); \
return 1;      \

    }              \
return 0; \

}

#endif

static bool ready = false;

static const char *world_name(const enum ac_world world) {
    switch (world) {
        case overworld:
            return "overworld";
        case nether:
            return "nether";
        case end:
            return "end";
        default:
            return "unknown world";
    }
}

static void handle_event(const ac_event_t *event) {
    switch (event->type) {
        case AC_EVENT_LAGGING: {
            ac_event_lagging_t *o = (ac_event_lagging_t *) event;
            printf("Server lagging: running %ld milliseconds (%ld ticks) behind.\n",
                   o->ms,
                   o->ticks);
            break;
        }
        case AC_EVENT_ENTITY_DEATH: {
            ac_event_entity_death_t *o = (ac_event_entity_death_t *) event;
            printf("Entity '%s' (%s) died at %s(%.2f, %.2f, %.2f): %s.\n",
                   o->entity.name,
                   o->entity.type,
                   world_name(o->entity.world),
                   o->entity.pos.x,
                   o->entity.pos.y,
                   o->entity.pos.z,
                   o->message);
            break;
        }
        case AC_EVENT_PLAYER_MESSAGE: {
            ac_event_player_message_t *o = (ac_event_player_message_t *) event;
            printf("Player '%s' said at %s(%.2f, %.2f, %.2f): %s.\n",
                   o->player.name,
                   world_name(o->player.world),
                   o->player.pos.x,
                   o->player.pos.y,
                   o->player.pos.z,
                   o->text);
            break;
        }
        case AC_EVENT_PLAYER_DISCONNECT: {
            ac_event_player_disconnect_t *o = (ac_event_player_disconnect_t *) event;
            if (!o->player) {
                printf("Unknown player disconnected: %s.\n", o->reason);
            } else {
                printf("Player '%s' disconnected at %s(%.2f, %.2f, %.2f): %s.\n",
                       o->player->name,
                       world_name(o->player->world),
                       o->player->pos.x,
                       o->player->pos.y,
                       o->player->pos.z,
                       o->reason);
            }
            break;
        }
        case AC_EVENT_PLAYER_JOIN: {
            ac_event_player_join_t *o = (ac_event_player_join_t *) event;
            printf("Player '%s' joined at %s(%.2f, %.2f, %.2f).\n",
                   o->player.name,
                   world_name(o->player.world),
                   o->player.pos.x,
                   o->player.pos.y,
                   o->player.pos.z);
            break;
        }
        default: {
            printf("Received an unrecognized event of type '%u'.\n",
                   event->type);
        }
    }
}

static void handle_response(const ac_response_t *response) {
    switch (response->type) {
        case AC_RESPONSE_OK: {
            ac_response_ok_t *o = (ac_response_ok_t *) response;
            printf("Request %d OK.\n",
                   o->id);
            break;
        }
        case AC_RESPONSE_ERROR: {
            ac_response_error_t *o = (ac_response_error_t *) response;
            printf("Request %d failed: %s (%d).\n",
                   o->id,
                   o->message,
                   o->code);
            break;
        }
        case AC_RESPONSE_CMD_OUT: {
            ac_response_cmd_out_t *o = (ac_response_cmd_out_t *) response;
            printf("Request %d output by %s: %s.\n",
                   o->id,
                   o->sender,
                   o->out);
            break;
        }
        case AC_RESPONSE_CMD_RESULT: {
            ac_response_cmd_result_t *o = (ac_response_cmd_result_t *) response;
            printf("Request %d is done: %s (%d).\n",
                   o->id,
                   o->success ? "Success" : "Failed",
                   o->result);
            break;
        }
        default: {
            printf("Received an unrecognized response of type '%u'.\n",
                   response->type);
        }
    }
}

#ifndef WIN32

static void intr(int signum) {}

#endif

static int on_send(const void *sock,
                   const void *buffer,
                   const size_t len) {
    int r;
    printf("Writing %lu bytes.\n", len);
    if ((r = net_send(sock, buffer, len))) {
        fprintf(stderr, "Cannot write %lu bytes to server: %s (%d).\n",
                len,
                net_strerror(r),
                r);
    }
    return r;
}

static int say(void *connection) {
    int r;
    ac_config_t conf = {
            .name = "helloworld"
    };
    ac_request_cmd_t req = {
            .type = AC_REQUEST_CMD,
            .id = 100,
            .config = &conf,
            .cmd = "say Hi"
    };
    if ((r = ac_request(connection, (ac_request_t *) &req))) {
        return r;
    }
    return 0;
}

static int process(void *connection, ac_obj_t *obj) {
    int r;
    if (!ready) {
        /* Wait until ready. */
        enum ac_connection_state state;
        if ((r = ac_get_state(connection, &state))) {
            return r;
        }
        switch (state) {
            case AC_STATE_INIT:
                return 0;
            case AC_STATE_READY:
                printf("Connection is established.\n");
                ready = true;
                say(connection);
                return 0;
            default:
                fprintf(stderr, "Unexpected state.\n");
                return 1;
        }
    }
    if (!obj) {
        return 0;
    }
    if (AC_IS_EVENT(obj->type)) {
        handle_event((ac_event_t *) obj);
    } else if (AC_IS_RESPONSE(obj->type)) {
        handle_response((ac_response_t *) obj);
    }
    ac_object_free(obj);
    return 0;
}

int main(int argc, char **argv) {
    int r;
    if ((r = net_init())) {
        return r;
    }
#if defined(THREAD_WIN32)
    if (!(mtx_conn = CreateMutex(NULL, TRUE, NULL))) {
        r = GetLastError();
        fprintf(stderr, "Cannot create mutex: %d.\n", r);
        return r;
    }
#elif defined(THREAD_C11)
    if (mtx_init(&mtx_conn, mtx_plain) != thrd_success) {
        fprintf(stderr, "Cannot create mutex.\n");
        return 1;
    }
#endif

#ifdef WIN32
    fprintf(stderr, "Warning: ^C handler on Windows is not yet available.\n");
#else
    struct sigaction sa;
    sa.sa_handler = intr;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGINT, &sa, NULL) ||
        sigaction(SIGTERM, &sa, NULL)) {
        const int e = errno;
        fprintf(stderr, "Cannot set SIGINT or SIGTERM handlers: %s (%d).\n",
                strerror(e),
                e);
        return e;
    }
#endif
    libac_config_t config = {
#ifdef DEBUG
            .out = stderr,
#else
            .out = NULL,
#endif
            .tok = NULL
    };
    if ((r = ac_init(&config))) return r;
    void *connection;
    SOCKET sock;
    ac_connection_parameters_t parameters = {
            .host = "localhost",
            .port = 25575,
            .id = "1",
            .token = "123",
            .version = 0,
            .sock = NULL,
            .on_send = on_send
    };
    if ((r = net_connect(parameters.host, parameters.port, &sock))) {
        fprintf(stderr, "Cannot connect to server: %s (%d).\n",
                net_strerror(r),
                r);
        ac_free();
        net_free();
        return r;
    }
    parameters.sock = &sock;
    if ((r = ac_connect(parameters, &connection))) {
        net_close(&sock);
        ac_free();
        net_free();
        return r;
    }
    ac_obj_t *obj;
    int nr;
    uint8_t buffer[1000U];
    printf("Waiting until the connection is established.\n");
    bool again = false;
    while (1) {
        size_t read = 0;
        size_t pos = 0;
        size_t bytes;
        if ((nr = net_read(&sock, buffer, sizeof(buffer), &bytes, 10))) {
            if (nr == NET_TIMEOUT) {
                printf("Receive timeout.\n");
                continue;
            } else {
                goto end;
            }
        }
        if ((r = lock())) { goto end; }
        if ((r = ac_receive(connection, buffer, pos, bytes, &obj, &read))) {
            bool again = r == AC_E_AGAIN;
            if (!again) {
                unlock();
                goto end;
            }
        }
        r = process(connection, obj);
        if ((r = unlock())) { goto end; }
        if (r) { goto end; }
        while (!again) {
            if ((r = lock())) { goto end; }
            if ((r = ac_receive(connection, NULL, 0, 0, &obj, NULL))) {
                bool again = r == AC_E_AGAIN;
                if (!again) {
                    unlock();
                    goto end;
                }
            }
            again = false;
            r = process(connection, obj);
            if ((r = unlock())) { goto end; }
            if (r) { goto end; }
        }
    }
    end:
    if (nr) {
        if (nr == NET_CLOSED) {
            fprintf(stderr, "Connection is closed while reading from the server.\n");
        } else {
            fprintf(stderr, "Cannot receive from server: %s (%d).\n",
                    net_strerror(nr),
                    nr);
        }
    }
    if ((r = lock())) { goto end; }
    ac_disconnect(connection, false);
    if ((r = unlock())) { goto end; }
    net_close(&sock);
    ac_free();
    net_free();
#if defined(THREAD_WIN32)
    CloseHandle(mtx_conn);
#elif defined(THREAD_C11)
    mtx_destroy(&mtx_conn);
#endif
    return r;
}