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