15dd4897ac36aa4130b865f672b6d31481d51088
[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    * Task scheduled to destroy the request.
63    */
64   GNUNET_SCHEDULER_TaskIdentifier kill_task;
65
66 };
67
68
69 /**
70  * Replies to be transmitted to the client.  The actual
71  * response message is allocated after this struct.
72  */
73 struct ClientResponse
74 {
75   /**
76    * This is a doubly-linked list.
77    */
78   struct ClientResponse *next;
79
80   /**
81    * This is a doubly-linked list.
82    */
83   struct ClientResponse *prev;
84
85   /**
86    * Client list entry this response belongs to.
87    */
88   struct GSF_LocalClient *lc;
89
90   /**
91    * Number of bytes in the response.
92    */
93   size_t msize;
94 };
95
96
97 /**
98  * A local client.
99  */
100 struct GSF_LocalClient
101 {
102
103   /**
104    * We keep clients in a DLL.
105    */
106   struct GSF_LocalClient *next;
107
108   /**
109    * We keep clients in a DLL.
110    */
111   struct GSF_LocalClient *prev;
112
113   /**
114    * ID of the client.
115    */
116   struct GNUNET_SERVER_Client *client;
117
118   /**
119    * Head of list of requests performed on behalf
120    * of this client right now.
121    */
122   struct ClientRequest *cr_head;
123
124   /**
125    * Tail of list of requests performed on behalf
126    * of this client right now.
127    */
128   struct ClientRequest *cr_tail;
129
130   /**
131    * Head of linked list of responses.
132    */
133   struct ClientResponse *res_head;
134
135   /**
136    * Tail of linked list of responses.
137    */
138   struct ClientResponse *res_tail;
139
140   /**
141    * Context for sending replies.
142    */
143   struct GNUNET_CONNECTION_TransmitHandle *th;
144
145 };
146
147
148 /**
149  * Head of linked list of our local clients.
150  */
151 static struct GSF_LocalClient *client_head;
152
153
154 /**
155  * Head of linked list of our local clients.
156  */
157 static struct GSF_LocalClient *client_tail;
158
159
160 /**
161  * Look up a local client record or create one if it
162  * doesn't exist yet.
163  *
164  * @param client handle of the client
165  * @return handle to local client entry
166  */
167 struct GSF_LocalClient *
168 GSF_local_client_lookup_ (struct GNUNET_SERVER_Client *client)
169 {
170   struct GSF_LocalClient *pos;
171
172   pos = client_head;
173   while ( (pos != NULL) &&
174           (pos->client != client) )
175     pos = pos->next;
176   if (pos != NULL)
177     return pos;
178   pos = GNUNET_malloc (sizeof (struct GSF_LocalClient));
179   pos->client = client;
180   GNUNET_CONTAINER_DLL_insert (client_head,
181                                client_tail,
182                                pos);
183   return pos;
184 }
185
186
187 /**
188  * Free the given client request.
189  *
190  * @param cls the client request to free
191  * @param tc task context
192  */ 
193 static void
194 client_request_destroy (void *cls,
195                         const struct GNUNET_SCHEDULER_TaskContext *tc)
196 {
197   struct ClientRequest *cr = cls;
198   struct GSF_LocalClient *lc;
199
200   cr->kill_task = GNUNET_SCHEDULER_NO_TASK;
201   lc = cr->lc;
202   GNUNET_CONTAINER_DLL_remove (lc->cr_head,
203                                lc->cr_tail,
204                                cr);
205   GSF_pending_request_cancel_ (cr->pr);
206   GNUNET_STATISTICS_update (GSF_stats,
207                             gettext_noop ("# client searches active"),
208                             - 1,
209                             GNUNET_NO);
210   GNUNET_free (cr);
211 }
212
213
214 /**
215  * Handle a reply to a pending request.  Also called if a request
216  * expires (then with data == NULL).  The handler may be called
217  * many times (depending on the request type), but will not be
218  * called during or after a call to GSF_pending_request_cancel 
219  * and will also not be called anymore after a call signalling
220  * expiration.
221  *
222  * @param cls user-specified closure
223  * @param eval evaluation of the result
224  * @param pr handle to the original pending request
225  * @param expiration when does 'data' expire? 
226  * @param type type of the block
227  * @param data response data, NULL on request expiration
228  * @param data_len number of bytes in data
229  */
230 static void
231 client_response_handler (void *cls,
232                          enum GNUNET_BLOCK_EvaluationResult eval,
233                          struct GSF_PendingRequest *pr,
234                          struct GNUNET_TIME_Absolute expiration,
235                          enum GNUNET_BLOCK_Type type,
236                          const void *data,
237                          size_t data_len)
238 {
239   struct ClientRequest *cr = cls;
240   struct GSF_LocalClient *lc;
241   struct PutMessage *pm;
242   const struct GSF_PendingRequestData *prd;
243   size_t msize;
244
245   if (NULL == data)
246     {
247       /* ugh, request 'timed out' -- how can this be? */
248       GNUNET_break (0);
249       return;
250     }
251   prd = GSF_pending_request_get_data_ (pr);
252   GNUNET_break (type != GNUNET_BLOCK_TYPE_ANY);
253   if ( (prd->type != type) &&
254        (prd->type != GNUNET_BLOCK_TYPE_ANY) )
255     {
256       GNUNET_break (0);
257       return;
258     }
259   GNUNET_STATISTICS_update (GSF_stats,
260                             gettext_noop ("# replies received for local clients"),
261                             1,
262                             GNUNET_NO);
263   GNUNET_assert (pr == cr->pr);
264   lc = cr->lc;
265   msize = sizeof (struct PutMessage) + data_len;
266   pm = GNUNET_malloc (msize);
267   pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
268   pm->header.size = htons (msize);
269   pm->type = htonl (type);
270   pm->expiration = GNUNET_TIME_absolute_hton (expiration);
271   memcpy (&pm[1], data, data_len);      
272   GSF_local_client_transmit_ (lc, &pm->header);
273 #if DEBUG_FS
274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
275               "Queued reply to query `%s' for local client\n",
276               GNUNET_h2s (&prd->query),
277               (unsigned int) prd->type);
278 #endif
279   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
280     return;
281   cr->kill_task = GNUNET_SCHEDULER_add_now (&client_request_destroy,
282                                             cr);
283 }
284
285
286 /**
287  * Handle START_SEARCH-message (search request from local client).
288  *
289  * @param client identification of the client
290  * @param message the actual message
291  * @return pending request handle for the request, NULL on error
292  */
293 struct GSF_PendingRequest *
294 GSF_local_client_start_search_handler_ (struct GNUNET_SERVER_Client *client,
295                                         const struct GNUNET_MessageHeader *message)
296 {
297   static GNUNET_HashCode all_zeros;
298   const struct SearchMessage *sm;
299   struct GSF_LocalClient *lc;
300   struct ClientRequest *cr;
301   struct GSF_PendingRequestData *prd;
302   uint16_t msize;
303   unsigned int sc;
304   enum GNUNET_BLOCK_Type type;
305   enum GSF_PendingRequestOptions options;
306
307   msize = ntohs (message->size);
308   if ( (msize < sizeof (struct SearchMessage)) ||
309        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
310     {
311       GNUNET_break (0);
312       GNUNET_SERVER_receive_done (client,
313                                   GNUNET_SYSERR);
314       return NULL;
315     }
316   GNUNET_STATISTICS_update (GSF_stats,
317                             gettext_noop ("# client searches received"),
318                             1,
319                             GNUNET_NO);
320   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
321   sm = (const struct SearchMessage*) message;
322   type = ntohl (sm->type);
323 #if DEBUG_FS
324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
325               "Received request for `%s' of type %u from local client\n",
326               GNUNET_h2s (&sm->query),
327               (unsigned int) type);
328 #endif
329   lc = GSF_local_client_lookup_ (client);
330
331   /* detect duplicate KBLOCK requests */
332   if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
333        (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
334        (type == GNUNET_BLOCK_TYPE_ANY) )
335     {
336       /* FIXME: this does currently not work to filter duplicate
337          results from *local* datastore since the local store is
338          queried before we continue to process additional
339          messages from the client! -- fix protocol? */
340       cr = lc->cr_head;
341       while (cr != NULL) 
342         {
343           prd = GSF_pending_request_get_data_ (cr->pr);
344           if ( (0 != memcmp (&prd->query,
345                              &sm->query,
346                              sizeof (GNUNET_HashCode))) &&
347                (prd->type == type) )
348             break;
349           cr = cr->next;
350         }
351       if (cr != NULL)   
352         { 
353 #if DEBUG_FS
354           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
355                       "Have existing request, merging content-seen lists.\n");
356 #endif
357           GSF_pending_request_update_ (cr->pr,
358                                        (const GNUNET_HashCode*) &sm[1],
359                                        sc);
360           GNUNET_STATISTICS_update (GSF_stats,
361                                     gettext_noop ("# client searches updated (merged content seen list)"),
362                                     1,
363                                     GNUNET_NO);
364           GNUNET_SERVER_receive_done (client,
365                                       GNUNET_OK);
366           return NULL;
367         }
368     }
369
370   GNUNET_STATISTICS_update (GSF_stats,
371                             gettext_noop ("# client searches active"),
372                             1,
373                             GNUNET_NO);
374   cr = GNUNET_malloc (sizeof (struct ClientRequest));
375   cr->lc = lc;
376   GNUNET_CONTAINER_DLL_insert (lc->cr_head,
377                                lc->cr_tail,
378                                cr);
379   options = GSF_PRO_LOCAL_REQUEST;  
380   if (0 != (1 & ntohl (sm->options)))
381     options |= GSF_PRO_LOCAL_ONLY;
382   cr->pr = GSF_pending_request_create_ (options,
383                                         type,
384                                         &sm->query,
385                                         (type == GNUNET_BLOCK_TYPE_FS_SBLOCK)
386                                         ? &sm->target /* namespace */
387                                         : NULL,
388                                         (0 != memcmp (&sm->target,
389                                                       &all_zeros,
390                                                       sizeof (GNUNET_HashCode)))
391                                         ? (const struct GNUNET_PeerIdentity*) &sm->target
392                                         : NULL,
393                                         NULL, 0, 0 /* bf */, 
394                                         ntohl (sm->anonymity_level),
395                                         0 /* priority */,
396                                         0 /* ttl */,
397                                         0 /* sender PID */,
398                                         (const GNUNET_HashCode*) &sm[1], sc,
399                                         &client_response_handler,
400                                         cr);
401   return cr->pr;
402 }
403
404
405 /**
406  * Transmit the given message by copying it to the target buffer
407  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
408  * for writing in the meantime.  In that case, do nothing
409  * (the disconnect or shutdown handler will take care of the rest).
410  * If we were able to transmit messages and there are still more
411  * pending, ask core again for further calls to this function.
412  *
413  * @param cls closure, pointer to the 'struct GSF_LocalClient'
414  * @param size number of bytes available in buf
415  * @param buf where the callee should write the message
416  * @return number of bytes written to buf
417  */
418 static size_t
419 transmit_to_client (void *cls,
420                     size_t size,
421                     void *buf)
422 {
423   struct GSF_LocalClient *lc = cls;
424   char *cbuf = buf;
425   struct ClientResponse *res;
426   size_t msize;
427   
428   lc->th = NULL;
429   if (NULL == buf)
430     return 0;
431   msize = 0;
432   while ( (NULL != (res = lc->res_head) ) &&
433           (res->msize <= size) )
434     {
435       memcpy (&cbuf[msize], &res[1], res->msize);
436       msize += res->msize;
437       size -= res->msize;
438       GNUNET_CONTAINER_DLL_remove (lc->res_head,
439                                    lc->res_tail,
440                                    res);
441       GNUNET_free (res);
442     }
443   if (NULL != res)
444     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
445                                                   res->msize,
446                                                   GNUNET_TIME_UNIT_FOREVER_REL,
447                                                   &transmit_to_client,
448                                                   lc);
449   return msize;
450 }
451
452
453 /**
454  * Transmit a message to the given local client as soon as possible.
455  * If the client disconnects before transmission, the message is
456  * simply discarded.
457  *
458  * @param lc recipient
459  * @param msg message to transmit to client
460  */
461 void
462 GSF_local_client_transmit_ (struct GSF_LocalClient *lc,
463                             const struct GNUNET_MessageHeader *msg)
464 {
465   struct ClientResponse *res;
466   size_t msize;
467
468   msize = ntohs (msg->size);
469   res = GNUNET_malloc (sizeof (struct ClientResponse) + msize);
470   res->lc = lc;
471   res->msize = msize;
472   memcpy (&res[1], msg, msize);
473   GNUNET_CONTAINER_DLL_insert_tail (lc->res_head,
474                                     lc->res_tail,
475                                     res);
476   if (NULL == lc->th)
477     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
478                                                   msize,
479                                                   GNUNET_TIME_UNIT_FOREVER_REL,
480                                                   &transmit_to_client,
481                                                   lc);
482 }
483
484
485 /**
486  * A client disconnected from us.  Tear down the local client
487  * record.
488  *
489  * @param cls unused
490  * @param client handle of the client
491  */
492 void
493 GSF_client_disconnect_handler_ (void *cls,
494                                 struct GNUNET_SERVER_Client *client)
495 {
496   struct GSF_LocalClient *pos;
497   struct ClientRequest *cr;
498   struct ClientResponse *res;
499
500   pos = client_head;
501   while ( (pos != NULL) &&
502           (pos->client != client) )
503     pos = pos->next;
504   if (pos == NULL)
505     return;
506   while (NULL != (cr = pos->cr_head))
507     {      
508       GNUNET_CONTAINER_DLL_remove (pos->cr_head,
509                                    pos->cr_tail,
510                                    cr);
511       GSF_pending_request_cancel_ (cr->pr);
512       GNUNET_STATISTICS_update (GSF_stats,
513                                 gettext_noop ("# client searches active"),
514                                 - 1,
515                                 GNUNET_NO);
516       if (GNUNET_SCHEDULER_NO_TASK != cr->kill_task)
517         GNUNET_SCHEDULER_cancel (cr->kill_task);
518       GNUNET_free (cr);
519     }
520   while (NULL != (res = pos->res_head))
521     {
522       GNUNET_CONTAINER_DLL_remove (pos->res_head,
523                                    pos->res_tail,
524                                    res);
525       GNUNET_free (res);
526     }
527   if (pos->th != NULL)
528     {
529       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
530       pos->th = NULL;
531     }
532   GSF_handle_local_client_disconnect_ (pos);
533   GNUNET_CONTAINER_DLL_remove (client_head,
534                                client_tail,
535                                pos);
536   GNUNET_free (pos);
537 }
538
539
540 /* end of gnunet-service-fs_lc.c */