summaryrefslogtreecommitdiff
path: root/src/assuan-domain-connect.c
blob: 63947f9739827e6ff4eb024ac7954af2729289e7 (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
524
525
526
527
528
/* assuan-domain-connect.c - Assuan unix domain socket based client
 *	Copyright (C) 2002, 2003, 2005 Free Software Foundation, Inc.
 *
 * This file is part of Assuan.
 *
 * Assuan is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * Assuan 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
 * USA. 
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#ifndef HAVE_W32_SYSTEM
#include <sys/socket.h>
#include <sys/un.h>
#else
#include <windows.h>
#endif
#if HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>

#include "assuan-defs.h"

#ifndef PF_LOCAL
# ifdef PF_UNIX
#  define PF_LOCAL PF_UNIX
# else
#  define PF_LOCAL AF_UNIX
# endif
# ifndef AF_LOCAL
#  define AF_LOCAL AF_UNIX
# endif
#endif



/* Read an integer from byte address ADDR.  Works even if ADDR is
   misaligned.  */
static int
read_int (const char *addr)
{
  int val;

  memcpy (&val, addr, sizeof (int));

  return val;
}


/* Write the integer VAL to byte address ADDR.  Works even if ADDR is
   misaligned.  */
static void
write_int (char *addr, int val)
{
  memcpy (addr, &val, sizeof (int));
}
 

static void
do_deinit (assuan_context_t ctx)
{
  if (ctx->inbound.fd != -1)
    _assuan_close (ctx->inbound.fd);
  ctx->inbound.fd = -1;
  ctx->outbound.fd = -1;

  if (ctx->domainbuffer)
    {
      assert (ctx->domainbufferallocated);
      free (ctx->domainbuffer);
    }

  if (ctx->pendingfds)
    {
      int i;

      assert (ctx->pendingfdscount > 0);
      for (i = 0; i < ctx->pendingfdscount; i ++)
	_assuan_close (ctx->pendingfds[i]);

      free (ctx->pendingfds);
    }

  unlink (ctx->myaddr.sun_path);
}


/* Read from the socket server.  */
static ssize_t
domain_reader (assuan_context_t ctx, void *buf, size_t buflen)
{
  int len = ctx->domainbuffersize;

#ifndef HAVE_W32_SYSTEM
 start:
  if (len == 0)
    /* No data is buffered.  */
    {
      struct msghdr msg;
      struct iovec iovec;
      struct sockaddr_un sender;
      struct
      {
	struct cmsghdr hdr;
	int fd;
      }
      cmsg;

      memset (&msg, 0, sizeof (msg));

      for (;;)
	{
	  msg.msg_name = &sender;
	  msg.msg_namelen = sizeof (struct sockaddr_un);
	  msg.msg_iov = &iovec;
	  msg.msg_iovlen = 1;
	  iovec.iov_base = ctx->domainbuffer;
	  iovec.iov_len = ctx->domainbufferallocated;
	  msg.msg_control = &cmsg;
	  msg.msg_controllen = sizeof cmsg;

	  /* Peek first: if the buffer we have is too small then it
	     will be truncated.  */
	  len = recvmsg (ctx->inbound.fd, &msg, MSG_PEEK);
	  if (len < 0)
	    {
	      printf ("domain_reader: %m\n");
	      return -1;
	    }

	  if (strcmp (ctx->serveraddr.sun_path,
		      ((struct sockaddr_un *) msg.msg_name)->sun_path) != 0)
	    {
	      /* XXX: Arg.  Not from whom we expected!  What do we
		 want to do?  Should we just ignore it?  Either way,
		 we still need to consume the message.  */
	      break;
	    }

	  if (msg.msg_flags & MSG_TRUNC)
	    /* Enlarge the buffer and try again.  */
	    {
	      int size = ctx->domainbufferallocated;
	      void *tmp;

	      if (size == 0)
		size = 4 * 1024;
	      else
		size *= 2;

	      tmp = malloc (size);
	      if (! tmp)
		return -1;

	      free (ctx->domainbuffer);
	      ctx->domainbuffer = tmp;
	      ctx->domainbufferallocated = size;
	    }
	  else
	    /* We have enough space!  */
	    break;
	}

      /* Now we have to actually consume it (remember, we only
	 peeked).  */
      msg.msg_name = &sender;
      msg.msg_namelen = sizeof (struct sockaddr_un);
      msg.msg_iov = &iovec;
      msg.msg_iovlen = 1;
      iovec.iov_base = ctx->domainbuffer;
      iovec.iov_len = ctx->domainbufferallocated;
      msg.msg_control = &cmsg;
      msg.msg_controllen = sizeof cmsg;

      if (strcmp (ctx->serveraddr.sun_path,
		  ((struct sockaddr_un *) msg.msg_name)->sun_path) != 0)
	{
	  /* XXX: Arg.  Not from whom we expected!  What do we want to
	     do?  Should we just ignore it?  We shall do the latter
	     for the moment.  */
	  _assuan_log_printf ("not setup to receive messages from `%s'\n",
                              ((struct sockaddr_un *) msg.msg_name)->sun_path);
	  goto start;
	}

      len = recvmsg (ctx->inbound.fd, &msg, 0);
      if (len < 0)
	{
	  _assuan_log_printf ("domain_reader: %s\n", strerror (errno));
	  return -1;
	}

      ctx->domainbuffersize = len;
      ctx->domainbufferoffset = 0;

      if (sizeof (cmsg) == msg.msg_controllen)
	/* We received a file descriptor.  */
	{
	  void *tmp;

	  tmp = realloc (ctx->pendingfds,
			 sizeof (int) * (ctx->pendingfdscount + 1));
	  if (! tmp)
	    {
	      _assuan_log_printf ("domain_reader: %s\n", strerror (errno));
	      return -1;
	    }

	  ctx->pendingfds = tmp;
	  ctx->pendingfds[ctx->pendingfdscount++]
	    = read_int (CMSG_DATA (&cmsg.hdr));

	  _assuan_log_printf ("received file descriptor %d from peer\n",
	       ctx->pendingfds[ctx->pendingfdscount - 1]);
	}

      if (len == 0)
	goto start;
    }
#else
  len = recvfrom (ctx->inbound.fd, buf, buflen, 0, NULL, NULL);
#endif

  /* Return some data to the user.  */

  if (len > buflen)
    /* We have more than the user requested.  */
    len = buflen;

  memcpy (buf, ctx->domainbuffer + ctx->domainbufferoffset, len);
  ctx->domainbuffersize -= len;
  assert (ctx->domainbuffersize >= 0);
  ctx->domainbufferoffset += len;
  assert (ctx->domainbufferoffset <= ctx->domainbufferallocated);

  return len;
}

/* Write to the domain server.  */
static ssize_t
domain_writer (assuan_context_t ctx, const void *buf, size_t buflen)
{
#ifndef HAVE_W32_SYSTEM
  struct msghdr msg;
  struct iovec iovec;
  ssize_t len;

  memset (&msg, 0, sizeof (msg));

  msg.msg_name = &ctx->serveraddr;
  msg.msg_namelen = offsetof (struct sockaddr_un, sun_path)
    + strlen (ctx->serveraddr.sun_path) + 1;

  msg.msg_iovlen = 1;
  msg.msg_iov = &iovec;
  iovec.iov_base = (void *) buf;
  iovec.iov_len = buflen;
  msg.msg_control = 0;
  msg.msg_controllen = 0;

  len = sendmsg (ctx->outbound.fd, &msg, 0);
  if (len < 0)
    _assuan_log_printf ("domain_writer: %s\n", strerror (errno));
#else
  int len;
  
  len = sendto (ctx->outbound.fd, buf, buflen, 0,
                (struct sockaddr *)&ctx->serveraddr,
                sizeof (struct sockaddr_in));
#endif  
  return len;
}

static assuan_error_t
domain_sendfd (assuan_context_t ctx, int fd)
{
#ifndef HAVE_W32_SYSTEM
  struct msghdr msg;
  struct
  {
    struct cmsghdr hdr;
    int fd;
  }
  cmsg;
  int len;

  memset (&msg, 0, sizeof (msg));

  msg.msg_name = &ctx->serveraddr;
  msg.msg_namelen = offsetof (struct sockaddr_un, sun_path)
    + strlen (ctx->serveraddr.sun_path) + 1;

  msg.msg_iovlen = 0;
  msg.msg_iov = 0;

  cmsg.hdr.cmsg_level = SOL_SOCKET;
  cmsg.hdr.cmsg_type = SCM_RIGHTS;
  cmsg.hdr.cmsg_len = sizeof (cmsg);

  msg.msg_control = &cmsg;
  msg.msg_controllen = sizeof (cmsg);

  write_int (CMSG_DATA (&cmsg.hdr), fd);

  len = sendmsg (ctx->outbound.fd, &msg, 0);
  if (len < 0)
    {
      _assuan_log_printf ("domain_sendfd: %s\n", strerror (errno));
      return ASSUAN_General_Error;
    }
  else
    return 0;
#else
  return 0;
#endif
}

static assuan_error_t
domain_receivefd (assuan_context_t ctx, int *fd)
{
#ifndef HAVE_W32_SYSTEM
  if (ctx->pendingfds == 0)
    {
      _assuan_log_printf ("no pending file descriptors!\n");
      return ASSUAN_General_Error;
    }

  *fd = ctx->pendingfds[0];
  if (-- ctx->pendingfdscount == 0)
    {
      free (ctx->pendingfds);
      ctx->pendingfds = 0;
    }
  else
    /* Fix the array.  */
    {
      memmove (ctx->pendingfds, ctx->pendingfds + 1,
	       ctx->pendingfdscount * sizeof (int));
      ctx->pendingfds = realloc (ctx->pendingfds,
				 ctx->pendingfdscount * sizeof (int));
    }
#endif
  return 0;
}



/* Make a connection to the Unix domain socket NAME and return a new
   Assuan context in CTX.  SERVER_PID is currently not used but may
   become handy in the future.  */
assuan_error_t
_assuan_domain_init (assuan_context_t *r_ctx, int rendezvousfd, pid_t peer)
{
  static struct assuan_io io = { domain_reader, domain_writer,
				 domain_sendfd, domain_receivefd };

  assuan_error_t err;
  assuan_context_t ctx;
  int fd;
  size_t len;
  int tries;

  if (!r_ctx)
    return ASSUAN_Invalid_Value;
  *r_ctx = NULL;

  err = _assuan_new_context (&ctx); 
  if (err)
    return err;

  /* Save it in case we need it later.  */
  ctx->pid = peer;

  /* Override the default (NOP) handlers.  */
  ctx->deinit_handler = do_deinit;

  /* Setup the socket.  */

  fd = _assuan_sock_new (PF_LOCAL, SOCK_DGRAM, 0);
  if (fd == -1)
    {
      _assuan_log_printf ("can't create socket: %s\n", strerror (errno));
      _assuan_release_context (ctx);
      return ASSUAN_General_Error;
    }
  
  ctx->inbound.fd = fd;
  ctx->outbound.fd = fd;
  
  /* And the io buffers.  */

  ctx->io = &io;
  ctx->domainbuffer = 0;
  ctx->domainbufferoffset = 0;
  ctx->domainbuffersize = 0;
  ctx->domainbufferallocated = 0;
  ctx->pendingfds = 0;
  ctx->pendingfdscount = 0;

  /* Get usable name and bind to it.  */

  for (tries = 0; tries < TMP_MAX; tries ++)
    {
      char *p;
      char buf[L_tmpnam];

      /* XXX: L_tmpnam must be shorter than sizeof (sun_path)!  */
      assert (L_tmpnam < sizeof (ctx->myaddr.sun_path));

      /* XXX: W32 tmpnam is broken */
      p = tmpnam (buf);
      if (! p)
	{
	  _assuan_log_printf ("cannot determine an appropriate temporary file "
            "name.  DoS in progress?\n");
	  _assuan_release_context (ctx);
	  _assuan_close (fd);
	  return ASSUAN_General_Error;
	}

      memset (&ctx->myaddr, 0, sizeof ctx->myaddr);
      ctx->myaddr.sun_family = AF_LOCAL;
      len = strlen (buf) + 1;
      memcpy (ctx->myaddr.sun_path, buf, len);
      len += offsetof (struct sockaddr_un, sun_path);

      err = _assuan_sock_bind (fd, (struct sockaddr *) &ctx->myaddr, len);
      if (! err)
	break;
    }

  if (err)
    {
      _assuan_log_printf ("can't bind to `%s': %s\n", ctx->myaddr.sun_path,
           strerror (errno));
      _assuan_release_context (ctx);
      _assuan_close (fd);
      return ASSUAN_Connect_Failed;
    }

  /* Rendezvous with our peer.  */
  {
    FILE *fp;
    char *p;

    fp = fdopen (rendezvousfd, "w+");
    if (! fp)
      {
	_assuan_log_printf ("can't open rendezvous port: %s\n", strerror (errno));
	return ASSUAN_Connect_Failed;
      }

    /* Send our address.  */
    fprintf (fp, "%s\n", ctx->myaddr.sun_path);
    fflush (fp);

    /* And receive our peer's.  */
    memset (&ctx->serveraddr, 0, sizeof ctx->serveraddr);
    for (p = ctx->serveraddr.sun_path;
	 p < (ctx->serveraddr.sun_path
	      + sizeof ctx->serveraddr.sun_path - 1);
	 p ++)
      {
	*p = fgetc (fp);
	if (*p == '\n')
	  break;
      }
    *p = '\0';
    fclose (fp);

    ctx->serveraddr.sun_family = AF_LOCAL;
  }

  *r_ctx = ctx;
  return 0;
}

assuan_error_t
assuan_domain_connect (assuan_context_t * r_ctx, int rendezvousfd, pid_t peer)
{
  assuan_error_t aerr;
  int okay, off;

  aerr = _assuan_domain_init (r_ctx, rendezvousfd, peer);
  if (aerr)
    return aerr;

  /* Initial handshake.  */
  aerr = _assuan_read_from_server (*r_ctx, &okay, &off);
  if (aerr)
    _assuan_log_printf ("can't connect to server: %s\n",
                        assuan_strerror (aerr));
  else if (okay != 1)
    {
      _assuan_log_printf ("can't connect to server: `");
      _assuan_log_sanitized_string ((*r_ctx)->inbound.line);
      fprintf (assuan_get_assuan_log_stream (), "'\n");
      aerr = ASSUAN_Connect_Failed;
    }

  if (aerr)
    assuan_disconnect (*r_ctx);

  return aerr;
}