added IOHandler
[TransparentIRC.git] / src / UserClient.c
1 /* UserClient.c - TransparentIRC 0.1
2  * Copyright (C) 2011-2012  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17 #include "UserClient.c"
18 #include "IOHandler.h"
19
20 static void userclient_callback(struct IOEvent *event);
21
22 static struct UserClient *userclients = NULL;
23
24 void userclient_accepted(struct ServerSocket *server, int sockfd) {
25     struct UserClient *client;
26     struct IODescriptor *iofd = iohandler_add(sockfd, IOTYPE_CLIENT, userclient_callback);
27     if(!iofd) return;
28     iofd->state = IO_CONNECTED;
29     iofd->read_lines = 1;
30     iohandler_update(iofd);
31     client = malloc(sizeof(*client));
32     client->iofd = iofd;
33     client->server = server;
34     server->clientcount++;
35     
36     //add UserClient to the list
37     sock->prev = NULL;
38     sock->next = serversockets;
39     serversockets->prev = sock;
40     serversockets = sock;
41     
42     //let's say hello to the client
43     iohandler_printf(iofd, "NOTICE AUTH :*** TransparentIRC " TRANSIRC_VERSION " (use /quote transirc for more information)");
44 }
45
46 void userclient_close(struct UserClient *client) {
47     iohandler_close(client->iofd);
48     client->server->clientcount--;
49     if(client->prev)
50         client->prev->next = client->next;
51     else
52         userclients = client->next;
53     if(client->next)
54         client->next->prev = client->prev;
55     free(client);
56 }
57
58 void userclient_close_server(struct ServerSocket *server, int keep_clients) {
59     struct UserClient *client, *next_client;
60     for(client = userclients; client; client = next_client) {
61         if(client->server == server) {
62             if(keep_clients)
63                 client->server = NULL;
64             else
65                 userclient_close(client);
66         }
67     }
68 }
69
70 static void userclient_callback(struct IOEvent *event) {
71     switch(event->type) {
72         case IOEVENT_RECV:
73             char *line = event->data.recv_str;
74             iohandler_printf(event->iofd, "reply: %s", line);
75             break;
76         case IOEVENT_CLOSED:
77             userclient_close(event->iofd);
78             break;
79     }
80 }