3908b8a558b4ec6218f0969e298863988cf1849a
[oweals/gnunet.git] / src / fs / gnunet-service-fs_lc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs_lc.c
23  * @brief API to handle 'connected peers'
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet-service-fs.h"
29 #include "gnunet-service-fs_lc.h"
30 #include "gnunet-service-fs_cp.h"
31 #include "gnunet-service-fs_pr.h"
32
33
34 /**
35  * Doubly-linked list of requests we are performing
36  * on behalf of the same client.
37  */
38 struct ClientRequest
39 {
40
41   /**
42    * This is a doubly-linked list.
43    */
44   struct ClientRequest *next;
45
46   /**
47    * This is a doubly-linked list.
48    */
49   struct ClientRequest *prev;
50
51   /**
52    * Request this entry represents.
53    */
54   struct GSF_PendingRequest *pr;
55
56   /**
57    * Client list this request belongs to.
58    */
59   struct GSF_LocalClient *lc;
60
61 };
62
63
64 /**
65  * Replies to be transmitted to the client.  The actual
66  * response message is allocated after this struct.
67  */
68 struct ClientResponse
69 {
70   /**
71    * This is a doubly-linked list.
72    */
73   struct ClientResponse *next;
74
75   /**
76    * This is a doubly-linked list.
77    */
78   struct ClientResponse *prev;
79
80   /**
81    * Client list entry this response belongs to.
82    */
83   struct GSF_LocalClient *lc;
84
85   /**
86    * Number of bytes in the response.
87    */
88   size_t msize;
89 };
90
91
92 /**
93  * A local client.
94  */
95 struct GSF_LocalClient
96 {
97
98   /**
99    * We keep clients in a DLL.
100    */
101   struct GSF_LocalClient *next;
102
103   /**
104    * We keep clients in a DLL.
105    */
106   struct GSF_LocalClient *prev;
107
108   /**
109    * ID of the client.
110    */
111   struct GNUNET_SERVER_Client *client;
112
113   /**
114    * Head of list of requests performed on behalf
115    * of this client right now.
116    */
117   struct ClientRequest *cr_head;
118
119   /**
120    * Tail of list of requests performed on behalf
121    * of this client right now.
122    */
123   struct ClientRequest *cr_tail;
124
125   /**
126    * Head of linked list of responses.
127    */
128   struct ClientResponse *res_head;
129
130   /**
131    * Tail of linked list of responses.
132    */
133   struct ClientResponse *res_tail;
134
135   /**
136    * Context for sending replies.
137    */
138   struct GNUNET_CONNECTION_TransmitHandle *th;
139
140 };
141
142
143 /**
144  * Head of linked list of our local clients.
145  */
146 static struct GSF_LocalClient *client_head;
147
148
149 /**
150  * Head of linked list of our local clients.
151  */
152 static struct GSF_LocalClient *client_tail;
153
154
155 /**
156  * Look up a local client record or create one if it
157  * doesn't exist yet.
158  *
159  * @param client handle of the client
160  * @return handle to local client entry
161  */
162 struct GSF_LocalClient *
163 GSF_local_client_lookup_ (struct GNUNET_SERVER_Client *client)
164 {
165   struct GSF_LocalClient *pos;
166
167   pos = client_head;
168   while ( (pos != NULL) &&
169           (pos->client != client) )
170     pos = pos->next;
171   if (pos != NULL)
172     return pos;
173   pos = GNUNET_malloc (sizeof (struct GSF_LocalClient));
174   pos->client = client;
175   GNUNET_CONTAINER_DLL_insert (client_head,
176                                client_tail,
177                                pos);
178   return pos;
179 }
180
181
182 /**
183  * Handle a reply to a pending request.  Also called if a request
184  * expires (then with data == NULL).  The handler may be called
185  * many times (depending on the request type), but will not be
186  * called during or after a call to GSF_pending_request_cancel 
187  * and will also not be called anymore after a call signalling
188  * expiration.
189  *
190  * @param cls user-specified closure
191  * @param pr handle to the original pending request
192  * @param expiration when does 'data' expire? 
193  * @param type type of the block
194  * @param data response data, NULL on request expiration
195  * @param data_len number of bytes in data
196  */
197 static void
198 client_response_handler (void *cls,
199                          struct GSF_PendingRequest *pr,
200                          struct GNUNET_TIME_Absolute expiration,
201                          enum GNUNET_BLOCK_Type type,
202                          const void *data,
203                          size_t data_len)
204 {
205   struct ClientRequest *cr = cls;
206   struct GSF_LocalClient *lc;
207   struct PutMessage *pm;
208   const struct GSF_PendingRequestData *prd;
209   size_t msize;
210
211   if (NULL == data)
212     {
213       /* ugh, request 'timed out' -- how can this be? */
214       GNUNET_break (0);
215       return;
216     }
217   prd = GSF_pending_request_get_data_ (pr);
218   GNUNET_break (type != GNUNET_BLOCK_TYPE_ANY);
219   if ( (prd->type != type) &&
220        (prd->type != GNUNET_BLOCK_TYPE_ANY) )
221     {
222       GNUNET_break (0);
223       return;
224     }
225   GNUNET_STATISTICS_update (GSF_stats,
226                             gettext_noop ("# replies received for local clients"),
227                             1,
228                             GNUNET_NO);
229   GNUNET_assert (pr == cr->pr);
230   lc = cr->lc;
231   msize = sizeof (struct PutMessage) + data_len;
232   pm = GNUNET_malloc (msize);
233   pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
234   pm->header.size = htons (msize);
235   pm->type = htonl (type);
236   pm->expiration = GNUNET_TIME_absolute_hton (expiration);
237   memcpy (&pm[1], data, data_len);      
238   GSF_local_client_transmit_ (lc, &pm->header);
239 #if DEBUG_FS
240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
241               "Queued reply to query `%s' for local client\n",
242               GNUNET_h2s (&prd->query),
243               (unsigned int) prd->type);
244 #endif
245 }
246
247
248 /**
249  * Handle START_SEARCH-message (search request from local client).
250  *
251  * @param client identification of the client
252  * @param message the actual message
253  * @return pending request handle for the request, NULL on error
254  */
255 struct GSF_PendingRequest *
256 GSF_local_client_start_search_handler_ (struct GNUNET_SERVER_Client *client,
257                                         const struct GNUNET_MessageHeader *message)
258 {
259   static GNUNET_HashCode all_zeros;
260   const struct SearchMessage *sm;
261   struct GSF_LocalClient *lc;
262   struct ClientRequest *cr;
263   struct GSF_PendingRequestData *prd;
264   uint16_t msize;
265   unsigned int sc;
266   enum GNUNET_BLOCK_Type type;
267   enum GSF_PendingRequestOptions options;
268
269   msize = ntohs (message->size);
270   if ( (msize < sizeof (struct SearchMessage)) ||
271        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
272     {
273       GNUNET_break (0);
274       GNUNET_SERVER_receive_done (client,
275                                   GNUNET_SYSERR);
276       return NULL;
277     }
278   GNUNET_STATISTICS_update (GSF_stats,
279                             gettext_noop ("# client searches received"),
280                             1,
281                             GNUNET_NO);
282   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
283   sm = (const struct SearchMessage*) message;
284   type = ntohl (sm->type);
285 #if DEBUG_FS
286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
287               "Received request for `%s' of type %u from local client\n",
288               GNUNET_h2s (&sm->query),
289               (unsigned int) type);
290 #endif
291   lc = GSF_local_client_lookup_ (client);
292
293   /* detect duplicate KBLOCK requests */
294   if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
295        (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
296        (type == GNUNET_BLOCK_TYPE_ANY) )
297     {
298       /* FIXME: this does currently not work to filter duplicate
299          results from *local* datastore since the local store is
300          queried before we continue to process additional
301          messages from the client! -- fix protocol? */
302       cr = lc->cr_head;
303       while (cr != NULL) 
304         {
305           prd = GSF_pending_request_get_data_ (cr->pr);
306           if ( (0 != memcmp (&prd->query,
307                              &sm->query,
308                              sizeof (GNUNET_HashCode))) &&
309                (prd->type == type) )
310             break;
311           cr = cr->next;
312         }
313       if (cr != NULL)   
314         { 
315 #if DEBUG_FS
316           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
317                       "Have existing request, merging content-seen lists.\n");
318 #endif
319           GSF_pending_request_update_ (cr->pr,
320                                        (const GNUNET_HashCode*) &sm[1],
321                                        sc);
322           GNUNET_STATISTICS_update (GSF_stats,
323                                     gettext_noop ("# client searches updated (merged content seen list)"),
324                                     1,
325                                     GNUNET_NO);
326           GNUNET_SERVER_receive_done (client,
327                                       GNUNET_OK);
328           return NULL;
329         }
330     }
331
332   GNUNET_STATISTICS_update (GSF_stats,
333                             gettext_noop ("# client searches active"),
334                             1,
335                             GNUNET_NO);
336   cr = GNUNET_malloc (sizeof (struct ClientRequest));
337   cr->lc = lc;
338   GNUNET_CONTAINER_DLL_insert (lc->cr_head,
339                                lc->cr_tail,
340                                cr);
341   options = GSF_PRO_LOCAL_REQUEST;  
342   if (0 != (1 & ntohl (sm->options)))
343     options |= GSF_PRO_LOCAL_ONLY;
344   cr->pr = GSF_pending_request_create_ (options,
345                                         type,
346                                         &sm->query,
347                                         (type == GNUNET_BLOCK_TYPE_FS_SBLOCK)
348                                         ? &sm->target /* namespace */
349                                         : NULL,
350                                         (0 != memcmp (&sm->target,
351                                                       &all_zeros,
352                                                       sizeof (GNUNET_HashCode)))
353                                         ? (const struct GNUNET_PeerIdentity*) &sm->target
354                                         : NULL,
355                                         NULL, 0, 0 /* bf */, 
356                                         ntohl (sm->anonymity_level),
357                                         0 /* priority */,
358                                         0 /* ttl */,
359                                         0 /* sender PID */,
360                                         (const GNUNET_HashCode*) &sm[1], sc,
361                                         &client_response_handler,
362                                         cr);
363   return cr->pr;
364 }
365
366
367 /**
368  * Transmit the given message by copying it to the target buffer
369  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
370  * for writing in the meantime.  In that case, do nothing
371  * (the disconnect or shutdown handler will take care of the rest).
372  * If we were able to transmit messages and there are still more
373  * pending, ask core again for further calls to this function.
374  *
375  * @param cls closure, pointer to the 'struct GSF_LocalClient'
376  * @param size number of bytes available in buf
377  * @param buf where the callee should write the message
378  * @return number of bytes written to buf
379  */
380 static size_t
381 transmit_to_client (void *cls,
382                     size_t size,
383                     void *buf)
384 {
385   struct GSF_LocalClient *lc = cls;
386   char *cbuf = buf;
387   struct ClientResponse *res;
388   size_t msize;
389   
390   lc->th = NULL;
391   if (NULL == buf)
392     return 0;
393   msize = 0;
394   while ( (NULL != (res = lc->res_head) ) &&
395           (res->msize <= size) )
396     {
397       memcpy (&cbuf[msize], &res[1], res->msize);
398       msize += res->msize;
399       size -= res->msize;
400       GNUNET_CONTAINER_DLL_remove (lc->res_head,
401                                    lc->res_tail,
402                                    res);
403       GNUNET_free (res);
404     }
405   if (NULL != res)
406     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
407                                                   res->msize,
408                                                   GNUNET_TIME_UNIT_FOREVER_REL,
409                                                   &transmit_to_client,
410                                                   lc);
411   return msize;
412 }
413
414
415 /**
416  * Transmit a message to the given local client as soon as possible.
417  * If the client disconnects before transmission, the message is
418  * simply discarded.
419  *
420  * @param lc recipient
421  * @param msg message to transmit to client
422  */
423 void
424 GSF_local_client_transmit_ (struct GSF_LocalClient *lc,
425                             const struct GNUNET_MessageHeader *msg)
426 {
427   struct ClientResponse *res;
428   size_t msize;
429
430   msize = ntohs (msg->size);
431   res = GNUNET_malloc (sizeof (struct ClientResponse) + msize);
432   res->lc = lc;
433   res->msize = msize;
434   memcpy (&res[1], msg, msize);
435   GNUNET_CONTAINER_DLL_insert_tail (lc->res_head,
436                                     lc->res_tail,
437                                     res);
438   if (NULL == lc->th)
439     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
440                                                   msize,
441                                                   GNUNET_TIME_UNIT_FOREVER_REL,
442                                                   &transmit_to_client,
443                                                   lc);
444 }
445
446
447 /**
448  * A client disconnected from us.  Tear down the local client
449  * record.
450  *
451  * @param cls unused
452  * @param client handle of the client
453  */
454 void
455 GSF_client_disconnect_handler_ (void *cls,
456                                 struct GNUNET_SERVER_Client *client)
457 {
458   struct GSF_LocalClient *pos;
459   struct ClientRequest *cr;
460   struct ClientResponse *res;
461
462   pos = client_head;
463   while ( (pos != NULL) &&
464           (pos->client != client) )
465     pos = pos->next;
466   if (pos == NULL)
467     return;
468   while (NULL != (cr = pos->cr_head))
469     {      
470       GNUNET_CONTAINER_DLL_remove (pos->cr_head,
471                                    pos->cr_tail,
472                                    cr);
473       GSF_pending_request_cancel_ (cr->pr);
474       GNUNET_STATISTICS_update (GSF_stats,
475                                 gettext_noop ("# client searches active"),
476                                 - 1,
477                                 GNUNET_NO);
478       GNUNET_free (cr);
479     }
480   while (NULL != (res = pos->res_head))
481     {
482       GNUNET_CONTAINER_DLL_remove (pos->res_head,
483                                    pos->res_tail,
484                                    res);
485       GNUNET_free (res);
486     }
487   if (pos->th != NULL)
488     {
489       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
490       pos->th = NULL;
491     }
492   GSF_handle_local_client_disconnect_ (pos);
493   GNUNET_CONTAINER_DLL_remove (client_head,
494                                client_tail,
495                                pos);
496   GNUNET_free (pos);
497 }
498
499
500 /* end of gnunet-service-fs_lc.c */