oops
[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
30
31 /**
32  * Doubly-linked list of requests we are performing
33  * on behalf of the same client.
34  */
35 struct ClientRequest
36 {
37
38   /**
39    * This is a doubly-linked list.
40    */
41   struct ClientRequest *next;
42
43   /**
44    * This is a doubly-linked list.
45    */
46   struct ClientRequest *prev;
47
48   /**
49    * Request this entry represents.
50    */
51   struct GSF_PendingRequest *pr;
52
53   /**
54    * Client list this request belongs to.
55    */
56   struct GSF_LocalClient *lc;
57
58 };
59
60
61
62 /**
63  * Replies to be transmitted to the client.  The actual
64  * response message is allocated after this struct.
65  */
66 struct ClientResponse
67 {
68   /**
69    * This is a doubly-linked list.
70    */
71   struct ClientResponse *next;
72
73   /**
74    * This is a doubly-linked list.
75    */
76   struct ClientResponse *prev;
77
78   /**
79    * Client list entry this response belongs to.
80    */
81   struct GSF_LocalClient *lc;
82
83   /**
84    * Number of bytes in the response.
85    */
86   size_t msize;
87 };
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 data response data, NULL on request expiration
192  * @param data_len number of bytes in data
193  * @param more GNUNET_YES if the request remains active (may call
194  *             this function again), GNUNET_NO if the request is
195  *             finished (client must not call GSF_pending_request_cancel_)
196  */
197 static void
198 client_response_handler (void *cls,
199                          struct GSF_PendingRequest *pr,
200                          const void *data,
201                          size_t data_len,
202                          int more)
203 {
204   struct ClientRequest *cr = cls;
205
206   if (NULL == data)
207     {
208       /* ugh, request 'timed out' -- how can this be? */
209       GNUNET_break (0);
210       GNUNET_assert (GNUNET_NO == more);
211       return;
212     }
213   /* FIXME: adapt old code below to new API! */
214
215       GNUNET_STATISTICS_update (stats,
216                                 gettext_noop ("# replies received for local clients"),
217                                 1,
218                                 GNUNET_NO);
219       cl = pr->client_request_list->client_list;
220       msize = sizeof (struct PutMessage) + prq->size;
221       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
222       creply->msize = msize;
223       creply->client_list = cl;
224       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
225                                          cl->res_tail,
226                                          cl->res_tail,
227                                          creply);      
228       pm = (struct PutMessage*) &creply[1];
229       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
230       pm->header.size = htons (msize);
231       pm->type = htonl (prq->type);
232       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
233       memcpy (&pm[1], prq->data, prq->size);      
234       if (NULL == cl->th)
235         {
236 #if DEBUG_FS
237           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
238                       "Transmitting result for query `%s' to client\n",
239                       GNUNET_h2s (key));
240 #endif  
241           cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
242                                                         msize,
243                                                         GNUNET_TIME_UNIT_FOREVER_REL,
244                                                         &transmit_to_client,
245                                                         cl);
246         }
247       GNUNET_break (cl->th != NULL);
248       if (pr->do_remove)                
249         {
250           prq->finished = GNUNET_YES;
251           destroy_pending_request (pr);         
252         }
253
254 }
255
256
257
258 /**
259  * Handle START_SEARCH-message (search request from local client).
260  *
261  * @param client identification of the client
262  * @param message the actual message
263  * @return pending request handle for the request, NULL on error
264  */
265 struct GSF_PendingRequest *
266 GSF_local_client_start_search_handler_ (struct GNUNET_SERVER_Client *client,
267                                         const struct GNUNET_MessageHeader *message)
268 {
269   static GNUNET_HashCode all_zeros;
270   const struct SearchMessage *sm;
271   struct GSF_LocalClient *lc;
272   struct ClientRequest *cr;
273   struct GSF_PendingRequest *pr;
274   uint16_t msize;
275   unsigned int sc;
276   enum GNUNET_BLOCK_Type type;
277   enum GSF_PendingRequestOptions options;
278
279   msize = ntohs (message->size);
280   if ( (msize < sizeof (struct SearchMessage)) ||
281        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
282     {
283       GNUNET_break (0);
284       GNUNET_SERVER_receive_done (client,
285                                   GNUNET_SYSERR);
286       return NULL;
287     }
288   GNUNET_STATISTICS_update (stats,
289                             gettext_noop ("# client searches received"),
290                             1,
291                             GNUNET_NO);
292   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
293   sm = (const struct SearchMessage*) message;
294   type = ntohl (sm->type);
295 #if DEBUG_FS
296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
297               "Received request for `%s' of type %u from local client\n",
298               GNUNET_h2s (&sm->query),
299               (unsigned int) type);
300 #endif
301   lc = GSF_local_client_lookup_ (client);
302
303   /* detect duplicate KBLOCK requests */
304   if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
305        (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
306        (type == GNUNET_BLOCK_TYPE_ANY) )
307     {
308       cr = lc->cr_head;
309       while ( (cl != NULL) &&
310               ( (0 != memcmp (GSF_pending_request_get_query_ (cr->pr),
311                               &sm->query,
312                               sizeof (GNUNET_HashCode))) ||
313                 (GSF_pending_request_get_type_ (cr->pr) != type) ) )
314         cr = cr->next;
315       if (crl != NULL)  
316         { 
317 #if DEBUG_FS
318           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
319                       "Have existing request, merging content-seen lists.\n");
320 #endif
321           GSF_pending_request_update_ (cr->pr,
322                                        &sm[1],
323                                        sc);
324           GNUNET_STATISTICS_update (stats,
325                                     gettext_noop ("# client searches updated (merged content seen list)"),
326                                     1,
327                                     GNUNET_NO);
328           GNUNET_SERVER_receive_done (client,
329                                       GNUNET_OK);
330           return NULL;
331         }
332     }
333
334   GNUNET_STATISTICS_update (stats,
335                             gettext_noop ("# client searches active"),
336                             1,
337                             GNUNET_NO);
338   cr = GNUNET_malloc (sizeof (struct ClientRequest));
339   cr->lc = lc;
340   GNUNET_CONTAINER_DLL_insert (lc->cr_head,
341                                lc->cr_tail,
342                                cr);
343   options = GSF_PRO_LOCAL_REQUEST;  
344   if (0 != (1 & ntohl (sm->options)))
345     options |= GSF_PRO_LOCAL_ONLY;
346   cr->pr = GSF_pending_request_create_ (options,
347                                         type,
348                                         &sm->query,
349                                         (type == GNUNET_BLOCK_TYPE_SBLOCK)
350                                         ? &sm->target /* namespace */
351                                         : NULL,
352                                         (0 != memcmp (&sm->target,
353                                                       &all_zeros,
354                                                       sizeof (GNUNET_HashCode)))
355                                         ? &sm->target,
356                                         : NULL,
357                                         NULL, 0, 0 /* bf */, 
358                                         ntohl (sm->anonymity_level),
359                                         0 /* priority */,
360                                         &sm[1], sc,
361                                         &client_response_handler,
362                                         cr);
363   return cr->pr;
364 }
365
366
367 /**
368  * Transmit the given message by copying it to the target buffer
369  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
370  * for writing in the meantime.  In that case, do nothing
371  * (the disconnect or shutdown handler will take care of the rest).
372  * If we were able to transmit messages and there are still more
373  * pending, ask core again for further calls to this function.
374  *
375  * @param cls closure, pointer to the 'struct GSF_LocalClient'
376  * @param size number of bytes available in buf
377  * @param buf where the callee should write the message
378  * @return number of bytes written to buf
379  */
380 static size_t
381 transmit_to_client (void *cls,
382                     size_t size,
383                     void *buf)
384 {
385   struct GSF_LocalClient *lc = cls;
386   char *cbuf = buf;
387   struct ClientResponse *res;
388   size_t msize;
389   
390   cl->th = NULL;
391   if (NULL == buf)
392     return 0;
393   msize = 0;
394   while ( (NULL != (res = lc->res_head) ) &&
395           (res->msize <= size) )
396     {
397       memcpy (&cbuf[msize], &res[1], res->msize);
398       msize += res->msize;
399       size -= res->msize;
400       GNUNET_CONTAINER_DLL_remove (cl->res_head,
401                                    cl->res_tail,
402                                    res);
403       GNUNET_free (res);
404     }
405   if (NULL != res)
406     lc->th = GNUNET_SERVER_notify_transmit_ready (lc->client,
407                                                   res->msize,
408                                                   GNUNET_TIME_UNIT_FOREVER_REL,
409                                                   &transmit_to_client,
410                                                   lc);
411   return msize;
412 }
413
414
415 /**
416  * Transmit a message to the given local client as soon as possible.
417  * If the client disconnects before transmission, the message is
418  * simply discarded.
419  *
420  * @param lc recipient
421  * @param msg message to transmit to client
422  */
423 void
424 GSF_local_client_transmit_ (struct GSF_LocalClient *lc,
425                             const struct GNUNET_MessageHeader *msg)
426 {
427   struct ClientResponse *res;
428   size_t msize;
429
430   msize = ntohs (msg->size);
431   res = GNUNET_malloc (sizeof (struct ClientResponse) + msize);
432   res->lc = lc;
433   res->msize = msize;
434   GNUNET_CONTAINER_DLL_insert_tail (lc->res_head,
435                                     lc->res_tail,
436                                     res);
437   if (NULL == lc->tc)
438     lc->tc = GNUNET_CLIENT_notify_transmit_ready (lc->client,
439                                                   msize,
440                                                   GNUNET_TIME_UNIT_FOREVER_REL,
441                                                   GNUNET_NO,
442                                                   &transmit_to_client,
443                                                   lc);
444 }
445
446
447 /**
448  * A client disconnected from us.  Tear down the local client
449  * record.
450  *
451  * @param cls unused
452  * @param client handle of the client
453  */
454 void
455 GSF_client_disconnect_handler_ (void *cls,
456                                 const struct GNUNET_SERVER_Client *client)
457 {
458   struct GSF_LocalClient *pos;
459   struct DisconnectCallback *dc;
460   struct ClientRequest *cr;
461   struct ClientResponse *res;
462
463   pos = client_head;
464   while ( (pos != NULL) &&
465           (pos->client != client) )
466     pos = pos->next;
467   if (pos == NULL)
468     return pos;
469   while (NULL != (cr = pos->cr_head))
470     {      
471       GNUNET_CONTAINER_DLL_remove (pos->cr_head,
472                                    pos->cr_tail,
473                                    cr);
474       GSF_pending_request_cancel_ (cr->pr);
475       GNUNET_free (cr);
476     }
477   while (NULL != (res = pos->res_head))
478     {
479       GNUNET_CONTAINER_DLL_remove (pos->res_head,
480                                    pos->res_tail,
481                                    res);
482       GNUNET_free (res);
483     }
484   if (pos->th != NULL)
485     {
486       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
487       pos->th = NULL;
488     }
489   GSF_handle_local_client_disconnect_ (pos);
490   GNUNET_free (pos);
491 }
492
493
494 /* end of gnunet-service-fs_lc.c */