summaryrefslogtreecommitdiff
path: root/src/util/secmod_common.c
blob: 4a45dd58dd0cdbffc99b6a03390ff20c6e65f027 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
  This file is part of TALER
  Copyright (C) 2020 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file util/secmod_common.c
 * @brief Common functions for the exchange security modules
 * @author Florian Dold <dold@taler.net>
 */
#include "platform.h"
#include "taler_util.h"
#include "taler_signatures.h"
#include "secmod_common.h"
#include <poll.h>
#include <sys/eventfd.h>


/**
 * Head of DLL of clients connected to us.
 */
struct TES_Client *TES_clients_head;

/**
 * Tail of DLL of clients connected to us.
 */
struct TES_Client *TES_clients_tail;

/**
 * Lock for the client queue.
 */
pthread_mutex_t TES_clients_lock;

/**
 * Private key of this security module. Used to sign denomination key
 * announcements.
 */
struct TALER_SecurityModulePrivateKeyP TES_smpriv;

/**
 * Public key of this security module.
 */
struct TALER_SecurityModulePublicKeyP TES_smpub;

/**
 * Our listen socket.
 */
static struct GNUNET_NETWORK_Handle *unix_sock;

/**
 * Path where we are listening.
 */
static char *unixpath;

/**
 * Task run to accept new inbound connections.
 */
static struct GNUNET_SCHEDULER_Task *listen_task;

/**
 * Set once we are in shutdown and workers should terminate.
 */
static volatile bool in_shutdown;


enum GNUNET_GenericReturnValue
TES_transmit (int sock,
              const struct GNUNET_MessageHeader *hdr)
{
  ssize_t off = 0;
  const void *pos = hdr;
  uint16_t end = ntohs (hdr->size);

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Sending message of type %u and length %u\n",
              (unsigned int) ntohs (hdr->type),
              (unsigned int) ntohs (hdr->size));
  while (off < end)
  {
    ssize_t ret = send (sock,
                        pos,
                        end - off,
                        0 /* no flags => blocking! */);
    if ( (-1 == ret) &&
         ( (EAGAIN == errno) ||
           (EINTR == errno) ) )
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
                           "send");
      continue;
    }
    if (-1 == ret)
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                           "send");
      return GNUNET_SYSERR;
    }
    if (0 == ret)
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
    off += ret;
    pos += ret;
  }
  return GNUNET_OK;
}


struct GNUNET_NETWORK_Handle *
TES_open_socket (const char *unixpath)
{
  int sock;
  mode_t old_umask;
  struct GNUNET_NETWORK_Handle *ret = NULL;

  /* Change permissions so that group read/writes are allowed.
   * We need this for multi-user exchange deployment with privilege
   * separation, where taler-exchange-httpd is part of a group
   * that allows it to talk to secmod.
   */
  old_umask = umask (S_IROTH | S_IWOTH | S_IXOTH);

  sock = socket (PF_UNIX,
                 SOCK_STREAM,
                 0);
  if (-1 == sock)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "socket");
    goto cleanup;
  }
  {
    struct sockaddr_un un;

    if (GNUNET_OK !=
        GNUNET_DISK_directory_create_for_file (unixpath))
    {
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                "mkdir(dirname)",
                                unixpath);
    }
    if (0 != unlink (unixpath))
    {
      if (ENOENT != errno)
        GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                  "unlink",
                                  unixpath);
    }
    memset (&un,
            0,
            sizeof (un));
    un.sun_family = AF_UNIX;
    strncpy (un.sun_path,
             unixpath,
             sizeof (un.sun_path) - 1);
    if (0 != bind (sock,
                   (const struct sockaddr *) &un,
                   sizeof (un)))
    {
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                                "bind",
                                unixpath);
      GNUNET_break (0 == close (sock));
      goto cleanup;
    }
    ret = GNUNET_NETWORK_socket_box_native (sock);
    if (GNUNET_OK !=
        GNUNET_NETWORK_socket_listen (ret,
                                      512))
    {
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                                "listen",
                                unixpath);
      GNUNET_break (GNUNET_OK ==
                    GNUNET_NETWORK_socket_close (ret));
      ret = NULL;
    }
  }
cleanup:
  (void) umask (old_umask);
  return ret;
}


/**
 * Send a signal to all clients to notify them about a key generation change.
 */
void
TES_wake_clients (void)
{
  uint64_t num = 1;

  GNUNET_assert (0 == pthread_mutex_lock (&TES_clients_lock));
  for (struct TES_Client *client = TES_clients_head;
       NULL != client;
       client = client->next)
  {
    GNUNET_assert (sizeof (num) ==
                   write (client->esock,
                          &num,
                          sizeof (num)));
  }
  GNUNET_assert (0 == pthread_mutex_unlock (&TES_clients_lock));
}


/**
 * Read work request from the client.
 *
 * @param cls a `struct TES_Client *`
 * @param dispatch function to call with work requests received
 * @return #GNUNET_OK on success
 */
enum GNUNET_GenericReturnValue
TES_read_work (void *cls,
               TES_MessageDispatch dispatch)
{
  struct TES_Client *client = cls;
  char *buf = client->iobuf;
  ssize_t buf_size;
  size_t off = 0;
  uint16_t msize;
  const struct GNUNET_MessageHeader *hdr;

  do
  {
    buf_size = recv (client->csock,
                     &buf[off],
                     sizeof (client->iobuf) - off,
                     0);
    if (-1 == buf_size)
    {
      if ( (0 == off) &&
           (EAGAIN == errno) )
        return GNUNET_NO;
      if ( (EINTR == errno) ||
           (EAGAIN == errno) )
      {
        GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
                             "recv");
        continue;
      }
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                           "recv");
      return GNUNET_SYSERR;
    }
    if (0 == buf_size)
    {
      /* regular disconnect? */
      GNUNET_break_op (0 == off);
      return GNUNET_SYSERR;
    }
    off += buf_size;
    if (off < sizeof (struct GNUNET_MessageHeader))
      continue;
    hdr = (const struct GNUNET_MessageHeader *) buf;
    msize = ntohs (hdr->size);
  } while (off < msize);

  if (off > msize)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return dispatch (client,
                   hdr);
}


bool
TES_await_ready (struct TES_Client *client)
{
  /* wait for reply with 1s timeout */
  struct pollfd pfds[] = {
    {
      .fd = client->csock,
      .events = POLLIN
    },
    {
      .fd = client->esock,
      .events = POLLIN
    },
  };
  int ret;

  ret = poll (pfds,
              2,
              -1);
  if ( (-1 == ret) &&
       (EINTR != errno) )
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "poll");
  for (int i = 0; i<2; i++)
  {
    if ( (pfds[i].fd == client->esock) &&
         (POLLIN == pfds[i].revents) )
    {
      uint64_t num;

      GNUNET_assert (sizeof (num) ==
                     read (client->esock,
                           &num,
                           sizeof (num)));
      return true;
    }
  }
  return false;
}


void
TES_free_client (struct TES_Client *client)
{
  GNUNET_assert (0 == pthread_mutex_lock (&TES_clients_lock));
  GNUNET_CONTAINER_DLL_remove (TES_clients_head,
                               TES_clients_tail,
                               client);
  GNUNET_assert (0 == pthread_mutex_unlock (&TES_clients_lock));
  GNUNET_break (0 == close (client->csock));
  GNUNET_break (0 == close (client->esock));
  pthread_detach (client->worker);
  GNUNET_free (client);
}


/**
 * Main function of a worker thread that signs.
 *
 * @param cls the client we are working on
 * @return NULL
 */
static void *
sign_worker (void *cls)
{
  struct TES_Client *client = cls;

  if (GNUNET_OK !=
      client->cb.init (client))
  {
    GNUNET_break (0);
    TES_free_client (client);
    return NULL;
  }
  while (! in_shutdown)
  {
    if (TES_await_ready (client))
    {
      if (GNUNET_OK !=
          client->cb.updater (client))
        break;
    }
    if (GNUNET_SYSERR ==
        TES_read_work (client,
                       client->cb.dispatch))
      break;
  }
  TES_free_client (client);
  return NULL;
}


/**
 * Task that listens for incoming clients.
 *
 * @param cls a `struct TES_Callbacks`
 */
static void
listen_job (void *cls)
{
  const struct TES_Callbacks *cb = cls;
  int s;
  int e;
  struct sockaddr_storage sa;
  socklen_t sa_len = sizeof (sa);

  listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                               unix_sock,
                                               &listen_job,
                                               cls);
  s = accept (GNUNET_NETWORK_get_fd (unix_sock),
              (struct sockaddr *) &sa,
              &sa_len);
  if (-1 == s)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "accept");
    return;
  }
  e = eventfd (0,
               EFD_CLOEXEC);
  if (-1 == e)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "eventfd");
    GNUNET_break (0 == close (s));
    return;
  }
  {
    struct TES_Client *client;

    client = GNUNET_new (struct TES_Client);
    client->cb = *cb;
    client->csock = s;
    client->esock = e;
    GNUNET_assert (0 == pthread_mutex_lock (&TES_clients_lock));
    GNUNET_CONTAINER_DLL_insert (TES_clients_head,
                                 TES_clients_tail,
                                 client);
    GNUNET_assert (0 == pthread_mutex_unlock (&TES_clients_lock));
    if (0 !=
        pthread_create (&client->worker,
                        NULL,
                        &sign_worker,
                        client))
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                           "pthread_create");
      TES_free_client (client);
    }
  }
}


int
TES_listen_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
                  const char *section,
                  const struct TES_Callbacks *cb)
{
  {
    char *pfn;

    if (GNUNET_OK !=
        GNUNET_CONFIGURATION_get_value_filename (cfg,
                                                 section,
                                                 "SM_PRIV_KEY",
                                                 &pfn))
    {
      GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                                 section,
                                 "SM_PRIV_KEY");
      return EXIT_NOTCONFIGURED;
    }
    if (GNUNET_SYSERR ==
        GNUNET_CRYPTO_eddsa_key_from_file (pfn,
                                           GNUNET_YES,
                                           &TES_smpriv.eddsa_priv))
    {
      GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                                 section,
                                 "SM_PRIV_KEY",
                                 "Could not use file to persist private key");
      GNUNET_free (pfn);
      return EXIT_NOPERMISSION;
    }
    GNUNET_free (pfn);
    GNUNET_CRYPTO_eddsa_key_get_public (&TES_smpriv.eddsa_priv,
                                        &TES_smpub.eddsa_pub);
  }


  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_filename (cfg,
                                               section,
                                               "UNIXPATH",
                                               &unixpath))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                               section,
                               "UNIXPATH");
    return EXIT_NOTCONFIGURED;
  }
  GNUNET_assert (NULL != unixpath);
  unix_sock = TES_open_socket (unixpath);
  if (NULL == unix_sock)
  {
    GNUNET_free (unixpath);
    GNUNET_break (0);
    return EXIT_NOPERMISSION;
  }
  /* start job to accept incoming requests on 'sock' */
  listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                               unix_sock,
                                               &listen_job,
                                               (void *) cb);
  return 0;
}


void
TES_listen_stop (void)
{
  if (NULL != listen_task)
  {
    GNUNET_SCHEDULER_cancel (listen_task);
    listen_task = NULL;
  }
  if (NULL != unix_sock)
  {
    GNUNET_break (GNUNET_OK ==
                  GNUNET_NETWORK_socket_close (unix_sock));
    unix_sock = NULL;
  }
  if (0 != unlink (unixpath))
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                              "unlink",
                              unixpath);
  }
  GNUNET_free (unixpath);
  in_shutdown = true;
  TES_wake_clients ();
}