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