2 * Copyright (C) 2013 Thadeu Lima de Souza Cascardo <cascardo@cascardo.info>
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.
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.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
29 static int connect_friend(struct sockaddr **saddr, char *address, char *port)
31 struct addrinfo *addresses;
32 struct addrinfo *addr;
35 memset(&hint, 0, sizeof(hint));
36 hint.ai_family = AF_UNSPEC;
37 hint.ai_socktype = SOCK_STREAM;
38 hint.ai_protocol = IPPROTO_TCP;
39 hint.ai_flags = AI_ADDRCONFIG;
40 r = getaddrinfo(address, port, &hint, &addresses);
44 if (addresses != NULL) {
45 *saddr = malloc(addresses->ai_addrlen);
49 memcpy(*saddr, addresses->ai_addr, addresses->ai_addrlen);
52 freeaddrinfo(addresses);
62 struct sockaddr *saddr;
67 struct friend *friends;
70 int create_cache(struct cache **cache)
72 *cache = malloc(sizeof(*cache));
75 (*cache)->nfriends = 0;
76 (*cache)->friends = NULL;
80 int destroy_cache(struct cache *cache)
87 int cache_add_friend(struct cache *cache, char *friend, char *address, char *port)
89 struct friend *tfriend;
90 if (!cache->friends) {
91 cache->friends = malloc(sizeof(struct friend));
94 struct friend *new_friends;
96 new_friends = realloc(cache->friends, cache->nfriends * sizeof(struct friend));
101 cache->friends = new_friends;
103 tfriend = &cache->friends[cache->nfriends - 1];
104 tfriend->name = friend;
105 tfriend->address = address;
106 tfriend->port = port;
107 connect_friend(&tfriend->saddr, tfriend->address, tfriend->port);
111 int load_cache(struct cache *cache, char *fname)
118 file = fopen(fname, "r");
121 while ((r = getline(&buffer, &len, file)) > 0) {
128 while (*++address != '\t');
131 while (*++port != '\t');
134 while (*++end != '\n');
136 fprintf(file, "%s\t%s\t%s\n", name, address, port);
137 cache_add_friend(cache, strdup(name), strdup(address), strdup(port));
144 int store_cache(struct cache *cache, char *fname)
149 file = fopen(fname, "w");
152 for (i = 0; i < cache->nfriends; i++) {
153 struct friend *friend = &cache->friends[i];
154 fprintf(file, "%s\t%s\t%s\n", friend->name, friend->address, friend->port);