8727670e8d9fb4e66824323f8453199406cfc8d1
[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 data response data, NULL on request expiration
194  * @param data_len number of bytes in data
195  * @param more GNUNET_YES if the request remains active (may call
196  *             this function again), GNUNET_NO if the request is
197  *             finished (client must not call GSF_pending_request_cancel_)
198  */
199 static void
200 client_response_handler (void *cls,
201                          struct GSF_PendingRequest *pr,
202                          struct GNUNET_TIME_Absolute expiration,
203                          const void *data,
204                          size_t data_len,
205                          int more)
206 {
207   struct ClientRequest *cr = cls;
208   struct GSF_LocalClient *lc;
209   struct PutMessage *pm;
210   const struct GSF_PendingRequestData *prd;
211   size_t msize;
212
213   if (NULL == data)
214     {
215       /* ugh, request 'timed out' -- how can this be? */
216       GNUNET_break (0);
217       GNUNET_assert (GNUNET_NO == more);
218       return;
219     }
220   GNUNET_STATISTICS_update (GSF_stats,
221                             gettext_noop ("# replies received for local clients"),
222                             1,
223                             GNUNET_NO);
224   prd = GSF_pending_request_get_data_ (pr);
225   GNUNET_assert (pr == cr->pr);
226   lc = cr->lc;
227   msize = sizeof (struct PutMessage) + data_len;
228   pm = GNUNET_malloc (msize);
229   pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
230   pm->header.size = htons (msize);
231   pm->type = htonl (prd->type);
232   pm->expiration = GNUNET_TIME_absolute_hton (expiration);
233   memcpy (&pm[1], data, data_len);      
234   GSF_local_client_transmit_ (lc, &pm->header);
235 #if DEBUG_FS
236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
237               "Queued reply to query `%s' for local client\n",
238               GNUNET_h2s (&prd->query),
239               (unsigned int) prd->type);
240 #endif
241   if (GNUNET_NO == more)                
242     {
243       GNUNET_CONTAINER_DLL_remove (lc->cr_head,
244                                    lc->cr_tail,
245                                    cr);
246       GNUNET_SERVER_receive_done (lc->client,
247                                   GNUNET_OK);
248       GNUNET_STATISTICS_update (GSF_stats,
249                                 gettext_noop ("# client searches active"),
250                                 - 1,
251                                 GNUNET_NO);
252       GNUNET_free (cr);
253     }
254 }
255
256
257 /**
258  * Handle START_SEARCH-message (search request from local client).
259  *
260  * @param client identification of the client
261  * @param message the actual message
262  * @return pending request handle for the request, NULL on error
263  */
264 struct GSF_PendingRequest *
265 GSF_local_client_start_search_handler_ (struct GNUNET_SERVER_Client *client,
266                                         const struct GNUNET_MessageHeader *message)
267 {
268   static GNUNET_HashCode all_zeros;
269   const struct SearchMessage *sm;
270   struct GSF_LocalClient *lc;
271   struct ClientRequest *cr;
272   struct GSF_PendingRequestData *prd;
273   uint16_t msize;
274   unsigned int sc;
275   enum GNUNET_BLOCK_Type type;
276   enum GSF_PendingRequestOptions options;
277
278   msize = ntohs (message->size);
279   if ( (msize < sizeof (struct SearchMessage)) ||
280        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
281     {
282       GNUNET_break (0);
283       GNUNET_SERVER_receive_done (client,
284                                   GNUNET_SYSERR);
285       return NULL;
286     }
287   GNUNET_STATISTICS_update (GSF_stats,
288                             gettext_noop ("# client searches received"),
289                             1,
290                             GNUNET_NO);
291   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
292   sm = (const struct SearchMessage*) message;
293   type = ntohl (sm->type);
294 #if DEBUG_FS
295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
296               "Received request for `%s' of type %u from local client\n",
297               GNUNET_h2s (&sm->query),
298               (unsigned int) type);
299 #endif
300   lc = GSF_local_client_lookup_ (client);
301
302   /* detect duplicate KBLOCK requests */
303   if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
304        (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
305        (type == GNUNET_BLOCK_TYPE_ANY) )
306     {
307       /* FIXME: this does currently not work to filter duplicate
308          results from *local* datastore since the local store is
309          queried before we continue to process additional
310          messages from the client! -- fix protocol? */
311       cr = lc->cr_head;
312       while (cr != NULL) 
313         {
314           prd = GSF_pending_request_get_data_ (cr->pr);
315           if ( (0 != memcmp (&prd->query,
316                              &sm->query,
317                              sizeof (GNUNET_HashCode))) &&
318                (prd->type == type) )
319             break;
320           cr = cr->next;
321         }
322       if (cr != NULL)   
323         { 
324 #if DEBUG_FS
325           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
326                       "Have existing request, merging content-seen lists.\n");
327 #endif
328           GSF_pending_request_update_ (cr->pr,
329                                        (const GNUNET_HashCode*) &sm[1],
330                                        sc);
331           GNUNET_STATISTICS_update (GSF_stats,
332                                     gettext_noop ("# client searches updated (merged content seen list)"),
333                                     1,
334                                     GNUNET_NO);
335           GNUNET_SERVER_receive_done (client,
336                                       GNUNET_OK);
337           return NULL;
338         }
339     }
340
341   GNUNET_STATISTICS_update (GSF_stats,
342                             gettext_noop ("# client searches active"),
343                             1,
344                             GNUNET_NO);
345   cr = GNUNET_malloc (sizeof (struct ClientRequest));
346   cr->lc = lc;
347   GNUNET_CONTAINER_DLL_insert (lc->cr_head,
348                                lc->cr_tail,
349                                cr);
350   options = GSF_PRO_LOCAL_REQUEST;  
351   if (0 != (1 & ntohl (sm->options)))
352     options |= GSF_PRO_LOCAL_ONLY;
353   cr->pr = GSF_pending_request_create_ (options,
354                                         type,
355                                         &sm->query,
356                                         (type == GNUNET_BLOCK_TYPE_FS_SBLOCK)
357                                         ? &sm->target /* namespace */
358                                         : NULL,
359                                         (0 != memcmp (&sm->target,
360                                                       &all_zeros,
361                                                       sizeof (GNUNET_HashCode)))
362                                         ? (const struct GNUNET_PeerIdentity*) &sm->target
363                                         : NULL,
364                                         NULL, 0, 0 /* bf */, 
365                                         ntohl (sm->anonymity_level),
366                                         0 /* priority */,
367                                         0 /* ttl */,
368                                         0 /* sender PID */,
369                                         (const GNUNET_HashCode*) &sm[1], sc,
370                                         &client_response_handler,
371                                         cr);
372   return cr->pr;
373 }
374
375
376 /**
377  * Transmit the given message by copying it to the target buffer
378  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
379  * for writing in the meantime.  In that case, do nothing
380  * (the disconnect or shutdown handler will take care of the rest).
381  * If we were able to transmit messages and there are still more
382  * pending, ask core again for further calls to this function.
383  *
384  * @param cls closure, pointer to the 'struct GSF_LocalClient'
385  * @param size number of bytes available in buf
386  * @param buf where the callee should write the message
387  * @return number of bytes written to buf
388  */
389 static size_t
390 transmit_to_client (void *cls,
391                     size_t size,
392                     void *buf)
393 {
394   struct GSF_LocalClient *lc = cls;
395   char *cbuf = buf;
396   struct ClientResponse *res;
397   size_t msize;
398   
399   lc->th = NULL;
400   if (NULL == buf)
401     return 0;
402   msize = 0;
403   while ( (NULL != (res = lc->res_head) ) &&
404           (res->msize <= size) )
405     {
406       memcpy (&cbuf[msize], &res[1], res->msize);
407       msize += res->msize;
408       size -= res->msize;
409       GNUNET_CONTAINER_DLL_remove (lc->res_head,
410                                    lc->res_tail,
411                                    res);
412       GNUNET_free (res);
413     }
414   if (NULL != res)
415     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
416                                                   res->msize,
417                                                   GNUNET_TIME_UNIT_FOREVER_REL,
418                                                   &transmit_to_client,
419                                                   lc);
420   return msize;
421 }
422
423
424 /**
425  * Transmit a message to the given local client as soon as possible.
426  * If the client disconnects before transmission, the message is
427  * simply discarded.
428  *
429  * @param lc recipient
430  * @param msg message to transmit to client
431  */
432 void
433 GSF_local_client_transmit_ (struct GSF_LocalClient *lc,
434                             const struct GNUNET_MessageHeader *msg)
435 {
436   struct ClientResponse *res;
437   size_t msize;
438
439   msize = ntohs (msg->size);
440   res = GNUNET_malloc (sizeof (struct ClientResponse) + msize);
441   res->lc = lc;
442   res->msize = msize;
443   memcpy (&res[1], msg, msize);
444   GNUNET_CONTAINER_DLL_insert_tail (lc->res_head,
445                                     lc->res_tail,
446                                     res);
447   if (NULL == lc->th)
448     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
449                                                   msize,
450                                                   GNUNET_TIME_UNIT_FOREVER_REL,
451                                                   &transmit_to_client,
452                                                   lc);
453 }
454
455
456 /**
457  * A client disconnected from us.  Tear down the local client
458  * record.
459  *
460  * @param cls unused
461  * @param client handle of the client
462  */
463 void
464 GSF_client_disconnect_handler_ (void *cls,
465                                 struct GNUNET_SERVER_Client *client)
466 {
467   struct GSF_LocalClient *pos;
468   struct ClientRequest *cr;
469   struct ClientResponse *res;
470
471   pos = client_head;
472   while ( (pos != NULL) &&
473           (pos->client != client) )
474     pos = pos->next;
475   if (pos == NULL)
476     return;
477   while (NULL != (cr = pos->cr_head))
478     {      
479       GNUNET_CONTAINER_DLL_remove (pos->cr_head,
480                                    pos->cr_tail,
481                                    cr);
482       GSF_pending_request_cancel_ (cr->pr);
483       GNUNET_STATISTICS_update (GSF_stats,
484                                 gettext_noop ("# client searches active"),
485                                 - 1,
486                                 GNUNET_NO);
487       GNUNET_free (cr);
488     }
489   while (NULL != (res = pos->res_head))
490     {
491       GNUNET_CONTAINER_DLL_remove (pos->res_head,
492                                    pos->res_tail,
493                                    res);
494       GNUNET_free (res);
495     }
496   if (pos->th != NULL)
497     {
498       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
499       pos->th = NULL;
500     }
501   GSF_handle_local_client_disconnect_ (pos);
502   GNUNET_CONTAINER_DLL_remove (client_head,
503                                client_tail,
504                                pos);
505   GNUNET_free (pos);
506 }
507
508
509 /* end of gnunet-service-fs_lc.c */