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