f284ba0f8f7da246f48b2d493494ce75bb0d5a74
[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       cr = lc->cr_head;
296       while (cr != NULL) 
297         {
298           prd = GSF_pending_request_get_data_ (cr->pr);
299           if ( (0 != memcmp (&prd->query,
300                              &sm->query,
301                              sizeof (GNUNET_HashCode))) &&
302                (prd->type == type) )
303             break;
304           cr = cr->next;
305         }
306       if (cr != NULL)   
307         { 
308 #if DEBUG_FS
309           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
310                       "Have existing request, merging content-seen lists.\n");
311 #endif
312           GSF_pending_request_update_ (cr->pr,
313                                        (const GNUNET_HashCode*) &sm[1],
314                                        sc);
315           GNUNET_STATISTICS_update (GSF_stats,
316                                     gettext_noop ("# client searches updated (merged content seen list)"),
317                                     1,
318                                     GNUNET_NO);
319           GNUNET_SERVER_receive_done (client,
320                                       GNUNET_OK);
321           return NULL;
322         }
323     }
324
325   GNUNET_STATISTICS_update (GSF_stats,
326                             gettext_noop ("# client searches active"),
327                             1,
328                             GNUNET_NO);
329   cr = GNUNET_malloc (sizeof (struct ClientRequest));
330   cr->lc = lc;
331   GNUNET_CONTAINER_DLL_insert (lc->cr_head,
332                                lc->cr_tail,
333                                cr);
334   options = GSF_PRO_LOCAL_REQUEST;  
335   if (0 != (1 & ntohl (sm->options)))
336     options |= GSF_PRO_LOCAL_ONLY;
337   cr->pr = GSF_pending_request_create_ (options,
338                                         type,
339                                         &sm->query,
340                                         (type == GNUNET_BLOCK_TYPE_FS_SBLOCK)
341                                         ? &sm->target /* namespace */
342                                         : NULL,
343                                         (0 != memcmp (&sm->target,
344                                                       &all_zeros,
345                                                       sizeof (GNUNET_HashCode)))
346                                         ? (const struct GNUNET_PeerIdentity*) &sm->target
347                                         : NULL,
348                                         NULL, 0, 0 /* bf */, 
349                                         ntohl (sm->anonymity_level),
350                                         0 /* priority */,
351                                         0 /* ttl */,
352                                         0 /* sender PID */,
353                                         (const GNUNET_HashCode*) &sm[1], sc,
354                                         &client_response_handler,
355                                         cr);
356   return cr->pr;
357 }
358
359
360 /**
361  * Transmit the given message by copying it to the target buffer
362  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
363  * for writing in the meantime.  In that case, do nothing
364  * (the disconnect or shutdown handler will take care of the rest).
365  * If we were able to transmit messages and there are still more
366  * pending, ask core again for further calls to this function.
367  *
368  * @param cls closure, pointer to the 'struct GSF_LocalClient'
369  * @param size number of bytes available in buf
370  * @param buf where the callee should write the message
371  * @return number of bytes written to buf
372  */
373 static size_t
374 transmit_to_client (void *cls,
375                     size_t size,
376                     void *buf)
377 {
378   struct GSF_LocalClient *lc = cls;
379   char *cbuf = buf;
380   struct ClientResponse *res;
381   size_t msize;
382   
383   lc->th = NULL;
384   if (NULL == buf)
385     return 0;
386   msize = 0;
387   while ( (NULL != (res = lc->res_head) ) &&
388           (res->msize <= size) )
389     {
390       memcpy (&cbuf[msize], &res[1], res->msize);
391       msize += res->msize;
392       size -= res->msize;
393       GNUNET_CONTAINER_DLL_remove (lc->res_head,
394                                    lc->res_tail,
395                                    res);
396       GNUNET_free (res);
397     }
398   if (NULL != res)
399     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
400                                                   res->msize,
401                                                   GNUNET_TIME_UNIT_FOREVER_REL,
402                                                   &transmit_to_client,
403                                                   lc);
404   return msize;
405 }
406
407
408 /**
409  * Transmit a message to the given local client as soon as possible.
410  * If the client disconnects before transmission, the message is
411  * simply discarded.
412  *
413  * @param lc recipient
414  * @param msg message to transmit to client
415  */
416 void
417 GSF_local_client_transmit_ (struct GSF_LocalClient *lc,
418                             const struct GNUNET_MessageHeader *msg)
419 {
420   struct ClientResponse *res;
421   size_t msize;
422
423   msize = ntohs (msg->size);
424   res = GNUNET_malloc (sizeof (struct ClientResponse) + msize);
425   res->lc = lc;
426   res->msize = msize;
427   memcpy (&res[1], msg, msize);
428   GNUNET_CONTAINER_DLL_insert_tail (lc->res_head,
429                                     lc->res_tail,
430                                     res);
431   if (NULL == lc->th)
432     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
433                                                   msize,
434                                                   GNUNET_TIME_UNIT_FOREVER_REL,
435                                                   &transmit_to_client,
436                                                   lc);
437 }
438
439
440 /**
441  * A client disconnected from us.  Tear down the local client
442  * record.
443  *
444  * @param cls unused
445  * @param client handle of the client
446  */
447 void
448 GSF_client_disconnect_handler_ (void *cls,
449                                 struct GNUNET_SERVER_Client *client)
450 {
451   struct GSF_LocalClient *pos;
452   struct ClientRequest *cr;
453   struct ClientResponse *res;
454
455   pos = client_head;
456   while ( (pos != NULL) &&
457           (pos->client != client) )
458     pos = pos->next;
459   if (pos == NULL)
460     return;
461   while (NULL != (cr = pos->cr_head))
462     {      
463       GNUNET_CONTAINER_DLL_remove (pos->cr_head,
464                                    pos->cr_tail,
465                                    cr);
466       GSF_pending_request_cancel_ (cr->pr);
467       GNUNET_free (cr);
468     }
469   while (NULL != (res = pos->res_head))
470     {
471       GNUNET_CONTAINER_DLL_remove (pos->res_head,
472                                    pos->res_tail,
473                                    res);
474       GNUNET_free (res);
475     }
476   if (pos->th != NULL)
477     {
478       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
479       pos->th = NULL;
480     }
481   GSF_handle_local_client_disconnect_ (pos);
482   GNUNET_free (pos);
483 }
484
485
486 /* end of gnunet-service-fs_lc.c */