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