]> git.cworth.org Git - ttt/blob - src/ttt-client.c
2005-12-10 Richard D. Worth <richard@theworths.org>
[ttt] / src / ttt-client.c
1 /* ttt-client.c - client handling code for tic-tac-toe game server
2  *
3  * Copyright © 2005 Carl Worth
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * Author: Carl Worth <cworth@cworth.org>
20  */
21
22 #include "ttt-client.h"
23 #include "ttt-error.h"
24 #include "ttt-server.h"
25 #include "ttt-socket.h"
26 #include "ttt-token.h"
27
28 #define YY_DECL int yylex (yyscan_t yyscanner, ttt_token_t *token)
29 #include "ttt-lex.h"
30 YY_DECL;
31
32 struct _ttt_client {
33     pthread_mutex_t mutex;
34     pthread_t       thread;
35     
36     ttt_server_t    *server;
37     int             socket;
38     yyscan_t        scanner;
39     
40     char            **request_strings;
41     int             num_request_strings;
42     
43     char            *username;
44     ttt_bool_t      registered;
45     int             num_wins;
46 };
47
48 typedef ttt_error_t (*ttt_command_func_t) (ttt_client_t *client,
49                                            char         **args,
50                                            int          num_args);
51
52 static ttt_error_t
53 _ttt_client_execute_helo (ttt_client_t *client,
54                           char         **args,
55                           int          num_args);
56
57 static ttt_error_t
58 _ttt_client_execute_who (ttt_client_t *client,
59                          char         **args,
60                          int          num_args);
61
62 static ttt_error_t
63 _ttt_client_execute_statistics (ttt_client_t *client,
64                                 char         **args,
65                                 int          num_args);
66
67 static ttt_error_t
68 _ttt_client_execute_message (ttt_client_t *client,
69                              char         **args,
70                              int          num_args);
71
72 static ttt_error_t
73 _ttt_client_execute_help (ttt_client_t  *client,
74                           char          **args,
75                           int           num_args);
76
77 static ttt_error_t
78 _ttt_client_execute_version (ttt_client_t  *client,
79                              char          **args,
80                              int           num_args);
81
82 static ttt_error_t
83 _ttt_client_execute_quit (ttt_client_t *client,
84                           char         **args,
85                           int          num_args);
86
87 static ttt_error_t
88 _ttt_client_execute_invite (ttt_client_t *client,
89                             char         **args,
90                             int          num_args);
91
92 static ttt_error_t
93 _ttt_client_execute_accept (ttt_client_t *client,
94                             char         **args,
95                             int          num_args);
96
97 static ttt_error_t
98 _ttt_client_execute_retract (ttt_client_t *client,
99                              char         **args,
100                              int          num_args);
101
102 static ttt_error_t
103 _ttt_client_execute_decline (ttt_client_t *client,
104                              char         **args,
105                              int          num_args);
106
107 typedef struct _ttt_command_description {
108     const char         *command;
109     int                args_min;
110     int                args_max;
111     ttt_command_func_t execute;
112     const char         *usage;
113     const char         *description;
114 } ttt_command_description_t;
115
116 ttt_command_description_t command_descriptions[] = {
117     {"HELO",    1, 1, _ttt_client_execute_helo,
118      "HELO <username>         ", "Register."},
119
120     {"HELP",    0, 1, _ttt_client_execute_help,
121      "HELP <command>          ", "Display help for a command."},
122
123     {"INVITE",  1, 1, _ttt_client_execute_invite,
124      "INVITE <username>       ", "Invite a player to play a game."},
125
126     {"ACCEPT",  1, 1, _ttt_client_execute_accept,
127      "ACCEPT <username>       ", "Accept a game invitation."},
128
129     {"RETRACT", 1, 1, _ttt_client_execute_retract,
130      "RETRACT <username>      ", "Retract a game invitation."},
131
132     {"DECLINE", 1, 1, _ttt_client_execute_decline,
133      "DECLINE <username>      ", "Decline a game invitation."},
134
135     {"MESSAGE", 1, 1, _ttt_client_execute_message,
136      "MESSAGE <message>       ", "Send a message to everyone."},
137
138     {"STATISTICS", 1, 1, _ttt_client_execute_statistics,
139      "STATISTICS <username>   ", "Lists the statistics for the specified user."},
140
141     {"QUIT",    0, 0, _ttt_client_execute_quit,
142      "QUIT                    ", "Quit session."},
143
144     {"VERSION", 1, 1, _ttt_client_execute_version,
145      "VERSION <client-version>", "Negotiate protocol version."},
146
147     {"WHO",     0, 0, _ttt_client_execute_who,
148      "WHO                     ", "List registered users."}
149 };
150
151 #define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
152
153 static ttt_error_t
154 _ttt_client_execute_helo (ttt_client_t *client,
155                           char         **args,
156                           int          num_args)
157 {
158     char        *response;
159     char        *notice;
160     ttt_error_t error;
161
162     assert (num_args == 1);
163
164     if (!(client->registered))
165     {
166         ttt_client_set_username (client, args[0]);
167
168         error = ttt_server_register_client (client->server, client);
169         if (error)
170             return error;
171         client->registered = TRUE;
172
173         xasprintf (&notice, "NOTICE USER %s\r\n",
174                    ttt_client_get_username (client));
175         ttt_server_broadcast (client->server, notice);
176
177         free (notice);
178     }
179
180     xasprintf (&response, "HELO %s %s %s\r\n",
181                ttt_client_get_username (client),
182                ttt_server_get_host (client->server),
183                ttt_server_get_port (client->server));
184     ttt_client_send (client, response);
185
186     free (response);
187
188     return TTT_ERROR_NONE;
189 }
190
191 static ttt_error_t
192 _ttt_client_execute_who (ttt_client_t *client,
193                          char         **args,
194                          int          num_args)
195 {
196     char *response;
197
198     assert (num_args == 0);
199
200     if (!client->registered)
201         return TTT_ERROR_NO_NAME_SET;
202
203     response = xstrdup (ttt_server_who (client->server));
204     ttt_client_send (client, response);
205
206     free (response);
207
208     return TTT_ERROR_NONE;
209 }
210
211 static ttt_error_t
212 _ttt_client_execute_statistics (ttt_client_t *client,
213                                 char         **args,
214                                 int          num_args)
215 {
216     const char   *argusername;
217     ttt_client_t *argclient;
218     char         *response;
219     ttt_error_t  error;
220
221     assert (num_args == 1);
222
223     argusername = args[0];
224
225     if (!client->registered)
226         return TTT_ERROR_NO_NAME_SET;
227
228     error = ttt_server_get_client_from_username (client->server,
229                                                  argusername,
230                                                  &argclient);
231     if (error)
232         return error;
233
234     xasprintf (&response, "STATISTICS %s \"\r\n"
235                "TICTACTOE WINS %d\r\n"
236                "\"\r\n",
237                ttt_client_get_username(argclient),
238                ttt_client_get_num_wins(argclient));
239
240     ttt_client_send (client, response);
241
242     free (response);
243
244     return TTT_ERROR_NONE;
245 }
246
247 static ttt_error_t
248 _ttt_client_execute_message (ttt_client_t  *client,
249                              char          **args,
250                              int           num_args)
251 {
252     const char *argmessage;
253     char       *response;
254     char       *notice;
255
256     assert (num_args == 1);
257
258     argmessage = args[0];
259
260     if (!client->registered)
261         return TTT_ERROR_NO_NAME_SET;
262
263     xasprintf (&response, "MESSAGE\r\n");
264     ttt_client_send (client, response);
265
266     xasprintf (&notice, "NOTICE MESSAGE %s \"%s\"\r\n",
267                ttt_client_get_username(client),
268                argmessage);
269     ttt_server_broadcast (client->server, notice);
270
271     free (notice);
272     free (response);
273
274     return TTT_ERROR_NONE;
275 }
276
277 static ttt_error_t
278 _ttt_client_execute_help (ttt_client_t  *client,
279                           char          **args,
280                           int           num_args)
281 {
282     char                      *response;
283     char                      *argcommand;
284     ttt_command_description_t *desc;
285     ttt_bool_t                is_command = FALSE;
286     int i;
287     
288     if (num_args == 0) {
289         xasprintf (&response, "HELP \"\r\n"
290                    "Available Commands:\r\n");
291         for (i = 0; i < ARRAY_SIZE(command_descriptions); i++) {
292             desc = &command_descriptions[i];
293             xasprintf (&response, "%s\r\n  %s - %s\r\n",
294                        response,
295                        desc->usage,
296                        desc->description);
297         }
298         xasprintf (&response, "%s\"\r\n", response);
299     } else {
300         argcommand = args[0];
301         for (i = 0; i < ARRAY_SIZE(command_descriptions); i++) {
302             desc = &command_descriptions[i];
303             if (strcasecmp (desc->command, argcommand) == 0) {
304                 is_command = TRUE;
305                 xasprintf (&response, "HELP %s \"\r\n"
306                            "%s\r\n"
307                            "\r\n"
308                            "Usage:\r\n"
309                            "  %s\r\n"
310                            "\"\r\n",
311                            desc->command,
312                            desc->description,
313                            desc->usage);
314                 /* XXX: Add detailed help. */
315             }
316         }
317     }
318     
319     if ((num_args == 1) && (!is_command))
320         return TTT_ERROR_SYNTAX;
321
322     ttt_client_send (client, response);
323
324     free (response);
325     return TTT_ERROR_NONE;
326 }
327
328 static ttt_error_t
329 _ttt_client_execute_version (ttt_client_t  *client,
330                              char          **args,
331                              int           num_args)
332 {
333     char *response;
334     char *argversion;
335     int  version;
336     int i;
337
338     assert (num_args == 1);
339
340     argversion = args[0];
341
342     /* Verify that provided version arg is a positive integer */
343     for (i = 0; i < strlen(argversion); i++)
344         if (!isdigit (argversion[i]))
345             return TTT_ERROR_SYNTAX;
346
347     version = atoi (argversion);
348
349     if (version < 1)
350         return TTT_ERROR_SYNTAX;
351
352     if (version > TTT_SERVER_PROTOCOL_VERSION)
353         version = TTT_SERVER_PROTOCOL_VERSION;
354
355     xasprintf (&response, "VERSION %d\r\n",
356                version);
357     ttt_client_send (client, response);
358
359     free (response);
360     return TTT_ERROR_NONE;
361 }
362
363 static ttt_error_t
364 _ttt_client_execute_quit (ttt_client_t *client,
365                           char         **args,
366                           int          num_args)
367 {
368     char *notice;
369
370     assert (num_args == 0);
371
372     if (!client->registered)
373         return TTT_ERROR_QUIT_REQUESTED;
374     
375     xasprintf (&notice, "NOTICE QUIT %s\r\n",
376                ttt_client_get_username(client));
377     ttt_server_broadcast (client->server, notice);
378     
379     free (notice);
380
381     return TTT_ERROR_QUIT_REQUESTED;
382 }
383
384 static ttt_error_t
385 _ttt_client_execute_invite (ttt_client_t *client,
386                             char         **args,
387                             int          num_args)
388 {
389     const char   *invitee_username;
390     ttt_client_t *invitee;
391     char         *response;
392     char         *notice;
393     ttt_error_t  error;
394
395     assert (num_args == 1);
396
397     invitee_username = args[0];
398
399     if (!client->registered)
400         return TTT_ERROR_NO_NAME_SET;
401
402     error = ttt_server_get_client_from_username (client->server,
403                                                  invitee_username,
404                                                  &invitee);
405     if (error)
406         return error;
407
408     ttt_server_add_invite (client->server,
409                            client,
410                            invitee);
411
412     xasprintf (&response, "INVITE\r\n");
413     ttt_client_send (client, response);
414
415     xasprintf (&notice, "NOTICE INVITE %s %s\r\n",
416                ttt_client_get_username(client),
417                ttt_client_get_username(invitee));
418     ttt_server_broadcast (client->server, notice);
419
420     free (notice);
421     free (response);
422
423     return TTT_ERROR_NONE;
424 }
425
426 static ttt_error_t
427 _ttt_client_execute_accept (ttt_client_t *client,
428                             char         **args,
429                             int          num_args)
430 {
431     const char   *actor_username;
432     ttt_client_t *actor;
433     char         *response;
434     char         *notice;
435     ttt_error_t  error;
436
437     assert (num_args == 1);
438
439     actor_username = args[0];
440
441     if (!client->registered)
442         return TTT_ERROR_NO_NAME_SET;
443
444     error = ttt_server_get_client_from_username (client->server,
445                                                  actor_username,
446                                                  &actor);
447     if (error)
448         return error;
449
450     error = ttt_server_remove_invite (client->server,
451                                       actor,
452                                       client);
453     if (error)
454         return error;
455
456     xasprintf (&response, "ACCEPT\r\n");
457     ttt_client_send (client, response);
458
459     xasprintf (&notice, "NOTICE ACCEPT %s %s\r\n",
460                ttt_client_get_username(client),
461                ttt_client_get_username(actor));
462     ttt_server_broadcast (client->server, notice);
463
464     /* XXX: Start a new game */
465
466     free (notice);
467     free (response);
468
469     return TTT_ERROR_NONE;
470 }
471
472 static ttt_error_t
473 _ttt_client_execute_retract (ttt_client_t *client,
474                              char         **args,
475                              int          num_args)
476 {
477     const char   *invitee_username;
478     ttt_client_t *invitee;
479     char         *response;
480     char         *notice;
481     ttt_error_t  error;
482
483     assert (num_args == 1);
484
485     invitee_username = args[0];
486
487     if (!client->registered)
488         return TTT_ERROR_NO_NAME_SET;
489
490     error = ttt_server_get_client_from_username (client->server,
491                                                  invitee_username,
492                                                  &invitee);
493     if (error)
494         return error;
495
496     error = ttt_server_remove_invite (client->server,
497                                       client,
498                                       invitee);
499     if (error)
500         return error;
501     
502     xasprintf (&response, "RETRACT\r\n");
503     ttt_client_send (client, response);
504
505     xasprintf (&notice, "NOTICE RETRACT %s %s\r\n",
506                ttt_client_get_username(client),
507                ttt_client_get_username(invitee));
508     ttt_server_broadcast (client->server, notice);
509
510     free (notice);
511     free (response);
512
513     return TTT_ERROR_NONE;
514 }
515
516 static ttt_error_t
517 _ttt_client_execute_decline (ttt_client_t *client,
518                              char         **args,
519                              int          num_args)
520 {
521     const char   *actor_username;
522     ttt_client_t *actor;
523     char         *response;
524     char         *notice;
525     ttt_error_t  error;
526
527     assert (num_args == 1);
528
529     actor_username = args[0];
530
531     if (!client->registered)
532         return TTT_ERROR_NO_NAME_SET;
533
534     error = ttt_server_get_client_from_username (client->server,
535                                                  actor_username,
536                                                  &actor);
537     if (error)
538         return error;
539
540     error = ttt_server_remove_invite (client->server,
541                                       actor,
542                                       client);
543     if (error)
544         return error;
545
546     xasprintf (&response, "DECLINE\r\n");
547     ttt_client_send (client, response);
548
549     xasprintf (&notice, "NOTICE DECLINE %s %s\r\n",
550                ttt_client_get_username(client),
551                ttt_client_get_username(actor));
552     ttt_server_broadcast (client->server, notice);
553
554     free (notice);
555     free (response);
556
557     return TTT_ERROR_NONE;
558 }
559
560 static void
561 _free_request (ttt_client_t *client);
562
563 static void
564 _ttt_client_init (ttt_client_t  *client,
565                   ttt_server_t  *server,
566                   int            socket)
567 {
568     FILE *file;
569
570     pthread_mutex_init (&client->mutex, NULL);
571
572     client->server = server;
573     client->socket = socket;
574
575     file = xfdopen (socket, "r");
576     yylex_init (&client->scanner);
577     yyset_in (file, client->scanner);
578
579     client->request_strings = NULL;
580     client->num_request_strings = 0;
581
582     client->username = NULL;
583     client->registered = FALSE;
584     client->num_wins = 0;
585 }
586
587 static void
588 _ttt_client_fini (ttt_client_t *client)
589 {
590     pthread_mutex_lock (&client->mutex);
591
592     if (client->registered)
593         ttt_server_unregister_client (client->server, client);
594
595     free (client->username);
596     client->username = NULL;
597
598     yylex_destroy (client->scanner);
599     shutdown (client->socket, SHUT_RDWR);
600
601     _free_request (client);
602
603     pthread_mutex_unlock (&client->mutex);
604
605     pthread_mutex_destroy (&client->mutex);
606 }
607
608 /* XXX: The memory management for the request strings is pretty cheesy. */
609 static void
610 _append_to_request (ttt_client_t        *client,
611                     const char          *string)
612 {
613     client->num_request_strings++;
614     client->request_strings =
615         xrealloc (client->request_strings,
616                   client->num_request_strings * sizeof (char *));
617
618     client->request_strings[client->num_request_strings - 1] = xstrdup (string);
619 }
620
621 static void
622 _free_request (ttt_client_t *client)
623 {
624     int i;
625
626     for (i = 0; i < client->num_request_strings; i++)
627         free (client->request_strings[i]);
628
629     free (client->request_strings);
630
631     client->request_strings = NULL;
632     client->num_request_strings = 0;
633 }
634
635 static ttt_status_t
636 _read_request (ttt_client_t *client)
637 {
638     ttt_token_t      token;
639     ttt_token_type_t token_type;
640
641     _free_request (client);
642
643     while (1) {
644         token_type = yylex (client->scanner, &token);
645         /* Yes, EOF in two different enums is pretty ugly. */
646         if (token_type == TTT_TOKEN_TYPE_EOF)
647             return TTT_STATUS_EOF;
648
649         if (token_type == TTT_TOKEN_TYPE_NEWLINE) {
650             if (client->num_request_strings)
651                 return TTT_STATUS_SUCCESS;
652             else
653                 continue;
654         }
655
656         assert (token_type == TTT_TOKEN_TYPE_STRING);
657          
658         _append_to_request (client, token.u.string);
659         
660         free (token.u.string);
661     }
662 }
663
664 static ttt_error_t
665 _execute_request (ttt_client_t *client)
666 {
667     char                      *command = client->request_strings[0];
668     int                       num_args = client->num_request_strings - 1;
669     ttt_command_description_t *desc;
670     int i;
671
672     for (i = 0; i < strlen (command); i++)
673         command[i] = toupper (command[i]);
674
675     for (i = 0; i < ARRAY_SIZE(command_descriptions); i++) {
676         desc = &command_descriptions[i];
677         if (strcmp (command, desc->command) == 0) {
678             if ((num_args < desc->args_min) || (num_args > desc->args_max))
679                 return TTT_ERROR_SYNTAX;
680             return (desc->execute) (client,
681                                     &client->request_strings[1],
682                                     num_args);
683         }
684     }
685
686     return TTT_ERROR_COMMAND;
687 }
688
689 static void *
690 _handle_requests_thread (void *closure)
691 {
692     ttt_status_t status;
693     ttt_client_t *client = closure;
694     ttt_error_t  error;
695
696     while (1) {
697         status = _read_request (client);
698         if (status == TTT_STATUS_EOF)
699             break;
700         if (status)
701             ASSERT_NOT_REACHED;
702
703         error = _execute_request (client);
704         if (error == TTT_ERROR_QUIT_REQUESTED)
705             break;
706         if (error)
707             ttt_client_send (client, ttt_error_string (error));
708     }
709
710     _ttt_client_fini (client);
711     free (client);
712
713     return (void *) 0;
714 }
715
716 /* Exported: See ttt-client.h for documentation. */
717 void
718 ttt_client_new (void *closure, int client_socket)
719 {
720     ttt_server_t *server = closure;
721     ttt_client_t *client;
722     int err;
723
724     client = xmalloc (sizeof (ttt_client_t));
725     
726     _ttt_client_init (client, server, client_socket);
727
728     err = pthread_create (&client->thread, NULL,
729                           _handle_requests_thread, client);
730     if (err != 0) {
731         fprintf (stderr, "Error: pthread_create failed: %s. Aborting.\r\n",
732                  strerror (err));
733         exit (1);
734     }
735 }
736
737 /* Exported: See ttt-client.h for documentation. */
738 void
739 ttt_client_send (ttt_client_t *client, const char *message)
740 {
741     pthread_mutex_lock (&client->mutex);
742
743     ttt_socket_write (client->socket, message, strlen (message));
744
745     pthread_mutex_unlock (&client->mutex);
746 }
747
748 /* Exported: See ttt-client.h for documentation. */
749 const char*
750 ttt_client_get_username (ttt_client_t *client)
751 {
752     return client->username;
753 }
754
755 /* Exported: See ttt-client.h for documentation. */
756 void
757 ttt_client_set_username (ttt_client_t *client, const char *username)
758 {
759     free (client->username);
760     client->username = xstrdup (username);
761 }
762
763 /* Exported: See ttt-client.h for documentation. */
764 int
765 ttt_client_get_num_wins (ttt_client_t *client)
766 {
767     return client->num_wins;
768 }
769
770 /* This is just to keep the compiler quiet about a function declared
771  * static but never defined. Just an annoying bug in flex's output. */
772 static int yy_init_globals (yyscan_t yyscanner) {return 0;}
773 void use_yy_init_globals (void);
774 void use_yy_init_globals (void) {yyscan_t scan; yy_init_globals(scan);}