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