aboutsummaryrefslogtreecommitdiff
path: root/backend/ipc.c
blob: e1d64377538ab0f40f07371dcfe8406f2419cdf2 (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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/*  ipc.c -- inter-process communication (IPC) support
 *  Copyright (C) 2019 SEIKO EPSON Corporation
 *
 *  License: EPSON END USER SOFTWARE LICENSE
 *  Author : SEIKO EPSON Corporation
 *
 *  This file is part of Image Scan! for Linux.
 *  It is distributed under the terms of the EPSON END USER SOFTWARE LICENSE.
 *
 *  You should have received a verbatim copy of the EPSON END USER SOFTWARE
 *  LICENSE along with the software.
 */


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

#include "ipc.h"

#include <errno.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

#include "defines.h"
#include "message.h"


/*! Attempts to read all the data up to \a size bytes.
 *  MERR is returned if an error, such as a timeout, occurs.
 *  MEOF is returned if EOF is reached.
 *  Otherwise, returns the number of bytes read, which must be greater than 0.
 */
static ssize_t
recv_all (int fd, void *buf, size_t size)
{
  ssize_t n = 0;
  ssize_t t = 1;

  if (0 == size) return MERR;

  while (n < size && t > 0)
    {
      errno = 0;
      t = read (fd, buf + n, size - n);
      if (0 > t)
        {
          err_major ("read failed: %s", strerror (errno));
          return MERR;
        }
      else
        {
          n += t;
          log_call ("transferred %zd bytes, total %zd/%zd", t, n, size);
        }
      if (0 == t) return MEOF;
    }

  return n;
}

/*! Attempts to write all the data up to \a size bytes.
 *  MERR is returned if an error, such as a timeout, occurs.
 *  Otherwise, returns the number of bytes written.
 *  A return value of zero indicates that nothing was written.
 */
static ssize_t
send_all (int fd, const void *buf, size_t size)
{
  ssize_t n = 0;
  ssize_t t = 1;

  if (0 == size) return MERR;

  while (n < size && t > 0)
    {
      errno = 0;
      t = write (fd, buf + n, size - n);
      if (0 > t)
        {
          err_major ("write failed: %s", strerror (errno));
          return MERR;
        }
      else
        {
          n += t;
          log_call ("transferred %zd bytes, total %zd/%zd", t, n, size);
        }
    }

  return n;
}

/*! MERR is returned if an error, such as a timeout, occurs.
 *  MERR is also returned if writing the ipc header failed.
 *  Otherwise, the number of bytes of the payload that were successfully
 *  written is returned.
 *  A return value of zero indicates that nothing was written, this should
 *  only occur when the payload is of zero size.
 */
ssize_t
ipc_send (int sock, uint16_t id, uint8_t type_status,
          size_t size, const void* payload)
{
  ssize_t n = 0;

  n = send_all (sock, &id, sizeof (id));
  if (0 >= n) return MERR;

  n = send_all (sock, &type_status, sizeof (type_status));
  if (0 >= n) return MERR;

  n = send_all (sock, &size, sizeof (size));
  if (0 >= n) return MERR;

  if (0 == size) return 0;
  if (!payload) return MERR;

  n = send_all (sock, payload, size);

  log_info ("send packet {key: %d, msg: 0x%02x, size: %zd}",
            id, type_status, size);

  if (ENABLE_DEBUG && 0 < n)
    {
      if (MSG_DBG_IMG_THRESHOLD < n)
        dbg_img (payload, n);
      else
        dbg_hex (payload, n);
    }

  return n;
}

/*! Caller must have allocated space for \a id, and \a type_status.
 *  \a payload is automatically allocated based on the size field of the
 *  ipcling header, and it is the responsibility of the caller to
 *  deallocate it.
 *
 *  MERR is returned if an error, such as a timeout, occurs.
 *  MEOF is returned if EOF is reached.
 *  Otherwise, returns the number of bytes read.
 *  A return value of zero is valid, as ipc packets do not necessarily
 *  have to contain a payload.
 */
ssize_t
ipc_recv (int sock, uint16_t *id, uint8_t *type_status,
          void** payload)
{
  size_t size = 0;
  char* buf = NULL;
  ssize_t n = 0;

  n = recv_all (sock, id, sizeof (*id));
  if (0 > n) return n;

  n = recv_all (sock, type_status, sizeof (*type_status));
  if (0 > n) return n;

  n = recv_all (sock, &size, sizeof (size));
  if (0 > n) return n;

  if (0 == size) return 0;
  if (!payload) return MERR;

  buf = t_malloc (size, char);
  if (!buf) return MERR;

  n = recv_all (sock, buf, size);

  *payload = buf;

  log_info ("recv packet {key: %d, msg: 0x%02x, size: %zd}",
            *id, *type_status, size);

  if (ENABLE_DEBUG && 0 < n)
    {
      if (MSG_DBG_IMG_THRESHOLD < n)
        dbg_img (*payload, n);
      else
        dbg_hex (*payload, n);
    }

  return n;
}

/*! \brief  Does the real work of starting the \a child process
 */
static
SANE_Status
ipc_fork (process *child)
{
  SANE_Status s = SANE_STATUS_GOOD;

  int pipe_fd[2];

  require (child);

  if (-1 == pipe (pipe_fd))
    {
      err_fatal ("pipe: %s", strerror (errno));
      return SANE_STATUS_ACCESS_DENIED;
    }

  child->pid = fork ();
  if (0 == child->pid)
    {
      /*  replace child process with a plugin program
       */
      close (pipe_fd[0]);           /* unused read end */
      if (0 <= dup2 (pipe_fd[1], STDOUT_FILENO))
        {
          log_info ("%s[%d]: starting", child->name, getpid ());
          if (-1 == execl (child->name, child->name, NULL))
            {
              err_fatal ("%s[%d]: %s", child->name, getpid (),
                         strerror (errno));
            }
        }
      else
        {
          err_major ("%s[%d]: %s", child->name, getpid (),
                     strerror (errno));
        }

      /* notify the parent process that we're done here */
      write (pipe_fd[1], "-1\n", strlen ("-1\n"));
      fsync (pipe_fd[1]);

      close (pipe_fd[1]);
      exit (EXIT_FAILURE);
    }

  if (0 > child->pid)
    {
      err_fatal ("fork: %s", strerror (errno));
      s = SANE_STATUS_CANCELLED;
    }
  else
    {
      /*  Check whether child process has (unexpectedly) exited.  We
          don't want to have zombies in our closet ;-)
       */
      pid_t w = waitpid (child->pid, NULL, WNOHANG);
      if (-1 == w)
        {
          err_minor ("waitpid: %s", strerror (errno));
        }
      if (0 != w)
        {
          log_info ("%s[%d]: exited prematurely", child->name, child->pid);
          s = SANE_STATUS_CANCELLED;
        }
      else
        {
          FILE *fp = fdopen (pipe_fd[0], "rb");
          if (fp)
            {
              if (1 != fscanf (fp, "%d", &(child->port)))
                {
                  err_major ("fscanf: %s", strerror (errno));
                }
              fclose (fp);
            }
          else
            {
              err_fatal ("%s", strerror (errno));
            }
        }
    }
  close (pipe_fd[0]);
  close (pipe_fd[1]);

  if (0 > child->port)
    s = SANE_STATUS_CANCELLED;

  return s;
}

/*! \brief  Requests a connection to a \a child
 */
static
SANE_Status
ipc_connect (process *child)
{
  struct sockaddr_in addr;
  struct timeval t;
  int rv;

  require (child);

  log_call ("(%s, %d)", child->name, child->port);

  errno = 0;
  child->socket = socket (AF_INET, SOCK_STREAM, 0);
  if (0 > child->socket)
    {
      err_major ("socket: %s", strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }

  t.tv_sec = 30;
  t.tv_usec = 0;
  errno = 0;
  rv = setsockopt (child->socket, SOL_SOCKET, SO_RCVTIMEO, &t, sizeof (t));
  if (0 > rv)
    {
      err_minor ("socket option: %s", strerror (errno));
    }

  errno = 0;
  rv = setsockopt (child->socket, SOL_SOCKET, SO_SNDTIMEO, &t, sizeof (t));
  if (0 > rv)
    {
      err_minor ("socket option: %s", strerror (errno));
    }

  memset (&addr, 0, sizeof (addr));
  addr.sin_family      = AF_INET;
  addr.sin_port        = htons (child->port);
  addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);

  if (0 != connect (child->socket, (struct sockaddr *) &addr, sizeof (addr)))
    {
      err_major ("connect: %s", strerror (errno));
      return SANE_STATUS_IO_ERROR;
    }

  return SANE_STATUS_GOOD;
}

process *
ipc_exec (const char *program, const char *pkglibdir, SANE_Status *status)
{
  SANE_Status s  = SANE_STATUS_GOOD;
  process *child = NULL;

  log_call ("(%s, %s, %p)", program, pkglibdir, status);

  child = t_malloc (1, process);
  if (!child)
    {
      if (status) *status = SANE_STATUS_NO_MEM;
      return NULL;
    }

  child->pid    = -1;
  child->port   = -1;
  child->socket = -1;
  child->name   = NULL;

  if (!pkglibdir)
    {
      child->name = strdup (program);
    }
  else
    {
      int n = (strlen (pkglibdir) + strlen (FILE_SEP_STR)
               + strlen (program) + 1);
      char *name = t_malloc (n, char);

      if (name)
        {
          sprintf (name, "%s%s%s", pkglibdir, FILE_SEP_STR, program);
          child->name = name;
        }
    }

  if (!child->name)
    {
      s = SANE_STATUS_NO_MEM;
    }
  else if (access (child->name, X_OK))
    {
      s = SANE_STATUS_ACCESS_DENIED;
    }

  if (SANE_STATUS_GOOD != s)
    {
      if (status) *status = s;
      delete (child);
      return NULL;
    }

  s = ipc_fork (child);
  if (SANE_STATUS_GOOD == s)
    {
      int tries = 5;

      do
        {
          if (SANE_STATUS_GOOD != s)
            sleep (1);
          s = ipc_connect (child);
        }
      while (0 < --tries && SANE_STATUS_GOOD != s);
    }

  if (SANE_STATUS_GOOD != s)
    {
      child = ipc_kill (child);
      promise (!child);
    }
  else
    {
      promise (child);
      promise (0 < child->pid);
      promise (0 < child->port);
      promise (0 < child->socket);
      promise (child->name);
    }

  if (status) *status = s;

  return child;
}

process *
ipc_kill (process *child)
{
  log_call ("(%p)", child);

  if (child)
    {
      int status = 0;

      log_info ("terminating %s (port %d)", child->name, child->port);

      if (0 <= child->socket)
        {
          if (0 != close (child->socket))
            {
              err_minor ("%s", strerror (errno));
            }
        }
      if (1 < child->pid)
        {
          if (0 != kill (child->pid, SIGHUP))
            {
              err_minor ("%s", strerror (errno));
            }
          if (child->pid != waitpid (child->pid, &status, 0))
            {
              err_major ("%s", strerror (errno));
            }

          if (!WIFSIGNALED (status))
            {
              err_major ("%s[%d]: went off the deep end!",
                         child->name, child->pid);
            }
          else
            {
              if (SIGHUP != WTERMSIG (status))
                {
                  err_major ("%s[%d]: %s", child->name, child->pid,
                             strsignal (WTERMSIG (status)));
                }
            }
        }

      const_delete (child->name, char *);
      delete (child);
    }

  return child;
}

void
ipc_dip_proc (process *child, int flag, const ipc_dip_parms *p,
              SANE_Parameters *ctx, void **buffer)
{
  int socket;
  uint8_t  status = STATUS_NG;
  uint16_t id     = 0;
  ssize_t  n;

  require (child);
  socket = child->socket;

  require (TYPE_DIP_SKEW_FLAG == flag || TYPE_DIP_CROP_FLAG == flag);
  require (0 < socket && p && ctx && buffer && *buffer);

  /* inter-process procedure call, status will be STATUS_NG in case
   * anything goes wrong during IPC call sequence
   */
  {
    n = ipc_send (socket, id, flag | TYPE_DIP_CTOR,
                  strlen (p->fw_name), p->fw_name);
    if (strlen (p->fw_name) == n)
      {
        n = ipc_recv (socket, &id, &status, NULL);
        if (STATUS_OK == status)
          {
            if (sizeof (*p) != ipc_send (socket, id, flag | TYPE_DIP_PARM,
                                         sizeof (*p), p))
              {
                status = STATUS_NG;
              }
            else
              {
                ipc_recv (socket, &id, &status, NULL);
                if (STATUS_OK == status)
                  {
                    ssize_t size = ctx->bytes_per_line * ctx->lines;

                    if (size != ipc_send (socket, id, flag | TYPE_DIP_DATA,
                                          size, *buffer))
                      {
                        err_minor ("image truncated");
                        status = STATUS_NG;
                      }
                  }
              }
          }
      }
  }

  if (STATUS_NG == status)      /* abort further processing */
    {
      ipc_send (socket, id, flag | TYPE_DIP_DTOR, 0, NULL);
      ipc_recv (socket, &id, &status, NULL);
      return;
    }

  /* acquire DIP results */
  {
    uint8_t req = flag | TYPE_DIP_PARM;
    void   *buf = NULL;
    ipc_dip_parms par;

    if (sizeof (par) == ipc_recv (socket, &id, &req, &buf))
      {
        ssize_t size;

        memcpy (&par, buf, sizeof (par));
        size = par.parms.bytes_per_line * par.parms.lines;

        req = flag | TYPE_DIP_DATA;
        delete (buf);

        if (size == ipc_recv (socket, &id, &req, &buf))
          {
            memcpy (ctx, &par.parms, sizeof (*ctx));
            delete (*buffer);
            *buffer = buf;
          }
        else
          {
            err_minor ("image truncated");
            delete (buf);
          }
      }
  }
  ipc_send (socket, id, flag | TYPE_DIP_DTOR, 0, NULL);
  ipc_recv (socket, &id, &status, NULL);
}