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, int *c)
31 struct addrinfo *addresses;
32 struct addrinfo *addr;
37 memset(&hint, 0, sizeof(hint));
38 hint.ai_family = AF_UNSPEC;
39 hint.ai_socktype = SOCK_STREAM;
40 hint.ai_protocol = IPPROTO_TCP;
41 hint.ai_flags = AI_ADDRCONFIG;
42 r = getaddrinfo(address, port, &hint, &addresses);
46 for (addr = addresses; addr != NULL; addr = addr->ai_next) {
47 fd = socket(addr->ai_family, addr->ai_socktype,
54 freeaddrinfo(addresses);
65 struct sockaddr *saddr;
70 struct friend *friends;
73 int create_cache(struct cache **cache)
75 *cache = malloc(sizeof(*cache));
78 (*cache)->nfriends = 0;
79 (*cache)->friends = NULL;
83 int destroy_cache(struct cache *cache)
90 int cache_add_friend(struct cache *cache, char *friend, char *address, char *port)
92 struct friend *tfriend;
93 if (!cache->friends) {
94 cache->friends = malloc(sizeof(struct friend));
97 struct friend *new_friends;
99 new_friends = realloc(cache->friends, cache->nfriends * sizeof(struct friend));
104 cache->friends = new_friends;
106 tfriend = &cache->friends[cache->nfriends - 1];
107 tfriend->name = friend;
108 tfriend->address = address;
109 tfriend->port = port;
110 tfriend->saddr = NULL;
114 int load_cache(struct cache *cache, char *fname)
121 file = fopen(fname, "r");
124 while ((r = getline(&buffer, &len, file)) > 0) {
131 while (*++address != '\t');
134 while (*++port != '\t');
137 while (*++end != '\n');
139 fprintf(file, "%s\t%s\t%s\n", name, address, port);
140 cache_add_friend(cache, strdup(name), strdup(address), strdup(port));
147 int store_cache(struct cache *cache, char *fname)
152 file = fopen(fname, "w");
155 for (i = 0; i < cache->nfriends; i++) {
156 struct friend *friend = &cache->friends[i];
157 fprintf(file, "%s\t%s\t%s\n", friend->name, friend->address, friend->port);