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