Make rpmsqAction compatible to sa_sigaction
[platform/upstream/rpm.git] / rpmio / rpmsq.c
1 /** \ingroup rpmio
2  * \file rpmio/rpmsq.c
3  */
4
5 #include "system.h"
6
7 #include <signal.h>
8 #include <sys/signal.h>
9 #include <sys/wait.h>
10 #include <search.h>
11 #include <errno.h>
12 #include <stdio.h>
13
14 #if defined(HAVE_PTHREAD_H)
15
16 #include <pthread.h>
17
18 /* XXX suggested in bugzilla #159024 */
19 #if PTHREAD_MUTEX_DEFAULT != PTHREAD_MUTEX_NORMAL
20   #error RPM expects PTHREAD_MUTEX_DEFAULT == PTHREAD_MUTEX_NORMAL
21 #endif
22
23 #ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
24 static pthread_mutex_t rpmsigTbl_lock = PTHREAD_MUTEX_INITIALIZER;
25 #else
26 static pthread_mutex_t rpmsigTbl_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
27 #endif
28
29 #define DO_LOCK()       pthread_mutex_lock(&rpmsigTbl_lock);
30 #define DO_UNLOCK()     pthread_mutex_unlock(&rpmsigTbl_lock);
31 #define INIT_LOCK()     \
32     {   pthread_mutexattr_t attr; \
33         (void) pthread_mutexattr_init(&attr); \
34         (void) pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); \
35         (void) pthread_mutex_init (&rpmsigTbl_lock, &attr); \
36         (void) pthread_mutexattr_destroy(&attr); \
37         rpmsigTbl_sigchld->active = 0; \
38     }
39 #define ADD_REF(__tbl)  (__tbl)->active++
40 #define SUB_REF(__tbl)  --(__tbl)->active
41 #define CLEANUP_HANDLER(__handler, __arg, __oldtypeptr) \
42     (void) pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, (__oldtypeptr));\
43         pthread_cleanup_push((__handler), (__arg));
44 #define CLEANUP_RESET(__execute, __oldtype) \
45     pthread_cleanup_pop(__execute); \
46     (void) pthread_setcanceltype ((__oldtype), &(__oldtype));
47
48 #define SAME_THREAD(_a, _b)     pthread_equal(((pthread_t)_a), ((pthread_t)_b))
49
50 #define ME()    ((void *)pthread_self())
51
52 #else
53
54 #define DO_LOCK()
55 #define DO_UNLOCK()
56 #define INIT_LOCK()
57 #define ADD_REF(__tbl)  (0)
58 #define SUB_REF(__tbl)  (0)
59 #define CLEANUP_HANDLER(__handler, __arg, __oldtypeptr)
60 #define CLEANUP_RESET(__execute, __oldtype)
61
62 #define SAME_THREAD(_a, _b)     (42)
63
64 #define ME()    (((void *)getpid()))
65
66 #endif  /* HAVE_PTHREAD_H */
67
68 #define _RPMSQ_INTERNAL
69 #include <rpm/rpmsq.h>
70
71 #include "debug.h"
72
73 #define _RPMSQ_DEBUG    0
74 int _rpmsq_debug = _RPMSQ_DEBUG;
75
76 static struct rpmsqElem rpmsqRock;
77
78 static rpmsq rpmsqQueue = &rpmsqRock;
79
80 /** \ingroup rpmsq
81  * Insert node into from queue.
82  * @param elem          node to link
83  * @param prev          previous node from queue
84  * @return              0 on success
85  */
86 static int rpmsqInsert(void * elem, void * prev)
87 {
88     rpmsq sq = (rpmsq) elem;
89     int ret = -1;
90
91     if (sq != NULL) {
92 #ifdef _RPMSQ_DEBUG
93 if (_rpmsq_debug)
94 fprintf(stderr, "    Insert(%p): %p\n", ME(), sq);
95 #endif
96         ret = sighold(SIGCHLD);
97         if (ret == 0) {
98             sq->child = 0;
99             sq->reaped = 0;
100             sq->status = 0;
101             sq->reaper = 1;
102             sq->pipes[0] = sq->pipes[1] = -1;
103
104             sq->id = ME();
105             ret = pthread_mutex_init(&sq->mutex, NULL);
106             insque(elem, (prev != NULL ? prev : rpmsqQueue));
107             ret = sigrelse(SIGCHLD);
108         }
109     }
110     return ret;
111 }
112
113 /** \ingroup rpmsq
114  * Remove node from queue.
115  * @param elem          node to link
116  * @return              0 on success
117  */
118 static int rpmsqRemove(void * elem)
119 {
120     rpmsq sq = (rpmsq) elem;
121     int ret = -1;
122
123     if (elem != NULL) {
124
125 #ifdef _RPMSQ_DEBUG
126 if (_rpmsq_debug)
127 fprintf(stderr, "    Remove(%p): %p\n", ME(), sq);
128 #endif
129         ret = sighold (SIGCHLD);
130         if (ret == 0) {
131             remque(elem);
132            
133             /* Unlock the mutex and then destroy it */ 
134             if((ret = pthread_mutex_unlock(&sq->mutex)) == 0)
135                 ret = pthread_mutex_destroy(&sq->mutex);
136
137             sq->id = NULL;
138             if (sq->pipes[1])   ret = close(sq->pipes[1]);
139             if (sq->pipes[0])   ret = close(sq->pipes[0]);
140             sq->pipes[0] = sq->pipes[1] = -1;
141 #ifdef  NOTYET  /* rpmpsmWait debugging message needs */
142             sq->reaper = 1;
143             sq->status = 0;
144             sq->reaped = 0;
145             sq->child = 0;
146 #endif
147             ret = sigrelse(SIGCHLD);
148         }
149     }
150     return ret;
151 }
152
153 static sigset_t rpmsqCaught;
154
155 static struct rpmsig_s {
156     int signum;
157     rpmsqAction_t handler;
158     int active;
159     struct sigaction oact;
160 } rpmsigTbl[] = {
161     { SIGINT,   rpmsqAction },
162 #define rpmsigTbl_sigint        (&rpmsigTbl[0])
163     { SIGQUIT,  rpmsqAction },
164 #define rpmsigTbl_sigquit       (&rpmsigTbl[1])
165     { SIGCHLD,  rpmsqAction },
166 #define rpmsigTbl_sigchld       (&rpmsigTbl[2])
167     { SIGHUP,   rpmsqAction },
168 #define rpmsigTbl_sighup        (&rpmsigTbl[3])
169     { SIGTERM,  rpmsqAction },
170 #define rpmsigTbl_sigterm       (&rpmsigTbl[4])
171     { SIGPIPE,  rpmsqAction },
172 #define rpmsigTbl_sigpipe       (&rpmsigTbl[5])
173     { -1,       NULL },
174 };
175
176 int rpmsqIsCaught(int signum)
177 {
178     return sigismember(&rpmsqCaught, signum);
179 }
180
181 #ifdef SA_SIGINFO
182 void rpmsqAction(int signum, siginfo_t * info, void * context)
183 #else
184 void rpmsqAction(int signum)
185 #endif
186 {
187     int save = errno;
188     rpmsig tbl;
189
190     for (tbl = rpmsigTbl; tbl->signum >= 0; tbl++) {
191         if (tbl->signum != signum)
192             continue;
193
194         (void) sigaddset(&rpmsqCaught, signum);
195
196         switch (signum) {
197         case SIGCHLD:
198             while (1) {
199                 rpmsq sq;
200                 int status = 0;
201                 pid_t reaped = waitpid(0, &status, WNOHANG);
202
203                 /* XXX errno set to ECHILD/EINVAL/EINTR. */
204                 if (reaped <= 0)
205                     break;
206
207                 /* XXX insque(3)/remque(3) are dequeue, not ring. */
208                 for (sq = rpmsqQueue->q_forw;
209                      sq != NULL && sq != rpmsqQueue;
210                      sq = sq->q_forw)
211                 {
212                     int ret;
213
214                     if (sq->child != reaped)
215                         continue;
216                     sq->reaped = reaped;
217                     sq->status = status;
218
219                     /* Unlock the mutex.  The waiter will then be able to 
220                      * aquire the lock.  
221                      *
222                      * XXX: jbj, wtd, if this fails? 
223                      */
224                     ret = pthread_mutex_unlock(&sq->mutex); 
225
226                     break;
227                 }
228             }
229             break;
230         default:
231             break;
232         }
233         break;
234     }
235     errno = save;
236 }
237
238 int rpmsqEnable(int signum, rpmsqAction_t handler)
239 {
240     int tblsignum = (signum >= 0 ? signum : -signum);
241     struct sigaction sa;
242     rpmsig tbl;
243     int ret = -1;
244
245     (void) DO_LOCK ();
246     if (rpmsqQueue->id == NULL)
247         rpmsqQueue->id = ME();
248     for (tbl = rpmsigTbl; tbl->signum >= 0; tbl++) {
249         if (tblsignum != tbl->signum)
250             continue;
251
252         if (signum >= 0) {                      /* Enable. */
253             if (ADD_REF(tbl) <= 0) {
254                 (void) sigdelset(&rpmsqCaught, tbl->signum);
255
256                 /* XXX Don't set a signal handler if already SIG_IGN */
257                 (void) sigaction(tbl->signum, NULL, &tbl->oact);
258                 if (tbl->oact.sa_handler == SIG_IGN)
259                     continue;
260
261                 (void) sigemptyset (&sa.sa_mask);
262 #ifdef SA_SIGINFO
263                 sa.sa_flags = SA_SIGINFO;
264 #else
265                 sa.sa_flags = 0;
266 #endif
267                 sa.sa_sigaction = (handler != NULL ? handler : tbl->handler);
268                 if (sigaction(tbl->signum, &sa, &tbl->oact) < 0) {
269                     SUB_REF(tbl);
270                     break;
271                 }
272                 tbl->active = 1;                /* XXX just in case */
273                 if (handler != NULL)
274                     tbl->handler = handler;
275             }
276         } else {                                /* Disable. */
277             if (SUB_REF(tbl) <= 0) {
278                 if (sigaction(tbl->signum, &tbl->oact, NULL) < 0)
279                     break;
280                 tbl->active = 0;                /* XXX just in case */
281                 tbl->handler = (handler != NULL ? handler : rpmsqAction);
282             }
283         }
284         ret = tbl->active;
285         break;
286     }
287     (void) DO_UNLOCK ();
288     return ret;
289 }
290
291 pid_t rpmsqFork(rpmsq sq)
292 {
293     pid_t pid;
294     int xx;
295     int nothreads = 0;   /* XXX: Shouldn't this be a global? */
296
297     if (sq->reaper) {
298         xx = rpmsqInsert(sq, NULL);
299 #ifdef _RPMSQ_DEBUG
300 if (_rpmsq_debug)
301 fprintf(stderr, "    Enable(%p): %p\n", ME(), sq);
302 #endif
303         xx = rpmsqEnable(SIGCHLD, NULL);
304     }
305
306     xx = pipe(sq->pipes);
307
308     xx = sighold(SIGCHLD);
309
310     /* 
311      * Initialize the cond var mutex.   We have to aquire the lock we 
312      * use for the condition before we fork.  Otherwise it is possible for
313      * the child to exit, we get sigchild and the sig handler to send 
314      * the condition signal before we are waiting on the condition.
315      */
316     if (!nothreads) {
317         if(pthread_mutex_lock(&sq->mutex)) {
318             /* Yack we did not get the lock, lets just give up */
319             xx = close(sq->pipes[0]);
320             xx = close(sq->pipes[1]);
321             sq->pipes[0] = sq->pipes[1] = -1;
322             goto out;
323         }
324     }
325
326     pid = fork();
327     if (pid < (pid_t) 0) {              /* fork failed.  */
328         sq->child = (pid_t)-1;
329         xx = close(sq->pipes[0]);
330         xx = close(sq->pipes[1]);
331         sq->pipes[0] = sq->pipes[1] = -1;
332         goto out;
333     } else if (pid == (pid_t) 0) {      /* Child. */
334         int yy;
335
336         /* Block to permit parent time to wait. */
337         xx = close(sq->pipes[1]);
338         xx = read(sq->pipes[0], &yy, sizeof(yy));
339         xx = close(sq->pipes[0]);
340         sq->pipes[0] = sq->pipes[1] = -1;
341
342 #ifdef _RPMSQ_DEBUG
343 if (_rpmsq_debug)
344 fprintf(stderr, "     Child(%p): %p child %d\n", ME(), sq, getpid());
345 #endif
346
347     } else {                            /* Parent. */
348
349         sq->child = pid;
350
351 #ifdef _RPMSQ_DEBUG
352 if (_rpmsq_debug)
353 fprintf(stderr, "    Parent(%p): %p child %d\n", ME(), sq, sq->child);
354 #endif
355
356     }
357
358 out:
359     xx = sigrelse(SIGCHLD);
360     return sq->child;
361 }
362
363 /**
364  * Wait for child process to be reaped, and unregister SIGCHLD handler.
365  * @todo Rewrite to use waitpid on helper thread.
366  * @param sq            scriptlet queue element
367  * @return              0 on success
368  */
369 static int rpmsqWaitUnregister(rpmsq sq)
370 {
371     int nothreads = 0;
372     int ret = 0;
373     int xx;
374
375     /* Protect sq->reaped from handler changes. */
376     ret = sighold(SIGCHLD);
377
378     /* Start the child, linux often runs child before parent. */
379     if (sq->pipes[0] >= 0)
380         xx = close(sq->pipes[0]);
381     if (sq->pipes[1] >= 0)
382         xx = close(sq->pipes[1]);
383     sq->pipes[0] = sq->pipes[1] = -1;
384
385     /* Put a stopwatch on the time spent waiting to measure performance gain. */
386     (void) rpmswEnter(&sq->op, -1);
387
388     /* Wait for handler to receive SIGCHLD. */
389     while (ret == 0 && sq->reaped != sq->child) {
390         if (nothreads)
391             /* Note that sigpause re-enables SIGCHLD. */
392             ret = sigpause(SIGCHLD);
393         else {
394             xx = sigrelse(SIGCHLD);
395             
396             /* 
397              * We start before the fork with this mutex locked;
398              * The only one that unlocks this the signal handler.
399              * So if we get the lock the child has been reaped.
400              */
401             ret = pthread_mutex_lock(&sq->mutex);
402             xx = sighold(SIGCHLD);
403         }
404     }
405
406     /* Accumulate stopwatch time spent waiting, potential performance gain. */
407     sq->ms_scriptlets += rpmswExit(&sq->op, -1)/1000;
408
409     xx = sigrelse(SIGCHLD);
410
411 #ifdef _RPMSQ_DEBUG
412 if (_rpmsq_debug)
413 fprintf(stderr, "      Wake(%p): %p child %d reaper %d ret %d\n", ME(), sq, sq->child, sq->reaper, ret);
414 #endif
415
416     /* Remove processed SIGCHLD item from queue. */
417     xx = rpmsqRemove(sq);
418
419     /* Disable SIGCHLD handler on refcount == 0. */
420     xx = rpmsqEnable(-SIGCHLD, NULL);
421 #ifdef _RPMSQ_DEBUG
422 if (_rpmsq_debug)
423 fprintf(stderr, "   Disable(%p): %p\n", ME(), sq);
424 #endif
425
426     return ret;
427 }
428
429 pid_t rpmsqWait(rpmsq sq)
430 {
431
432 #ifdef _RPMSQ_DEBUG
433 if (_rpmsq_debug)
434 fprintf(stderr, "      Wait(%p): %p child %d reaper %d\n", ME(), sq, sq->child, sq->reaper);
435 #endif
436
437     if (sq->reaper) {
438         (void) rpmsqWaitUnregister(sq);
439     } else {
440         pid_t reaped;
441         int status;
442         do {
443             reaped = waitpid(sq->child, &status, 0);
444         } while (reaped >= 0 && reaped != sq->child);
445         sq->reaped = reaped;
446         sq->status = status;
447 #ifdef _RPMSQ_DEBUG
448 if (_rpmsq_debug)
449 fprintf(stderr, "   Waitpid(%p): %p child %d reaped %d\n", ME(), sq, sq->child, sq->reaped);
450 #endif
451     }
452
453 #ifdef _RPMSQ_DEBUG
454 if (_rpmsq_debug)
455 fprintf(stderr, "      Fini(%p): %p child %d status 0x%x\n", ME(), sq, sq->child, sq->status);
456 #endif
457
458     return sq->reaped;
459 }
460
461 void * rpmsqThread(void * (*start) (void * arg), void * arg)
462 {
463     pthread_t pth;
464     int ret;
465
466     ret = pthread_create(&pth, NULL, start, arg);
467     return (ret == 0 ? (void *)pth : NULL);
468 }
469
470 int rpmsqJoin(void * thread)
471 {
472     pthread_t pth = (pthread_t) thread;
473     if (thread == NULL)
474         return EINVAL;
475     return pthread_join(pth, NULL);
476 }
477
478 int rpmsqThreadEqual(void * thread)
479 {
480     pthread_t t1 = (pthread_t) thread;
481     pthread_t t2 = pthread_self();
482     return pthread_equal(t1, t2);
483 }
484
485 /**
486  * SIGCHLD cancellation handler.
487  */
488 static void
489 sigchld_cancel (void *arg)
490 {
491     pid_t child = *(pid_t *) arg;
492     pid_t result;
493
494     (void) kill(child, SIGKILL);
495
496     do {
497         result = waitpid(child, NULL, 0);
498     } while (result == (pid_t)-1 && errno == EINTR);
499
500     (void) DO_LOCK ();
501     if (SUB_REF (rpmsigTbl_sigchld) == 0) {
502         (void) rpmsqEnable(-SIGQUIT, NULL);
503         (void) rpmsqEnable(-SIGINT, NULL);
504     }
505     (void) DO_UNLOCK ();
506 }
507
508 /**
509  * Execute a command, returning its status.
510  */
511 int
512 rpmsqExecve (const char ** argv)
513 {
514     int oldtype;
515     int status = -1;
516     pid_t pid = 0;
517     pid_t result;
518     sigset_t newMask, oldMask;
519
520 #ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
521         INIT_LOCK ();
522 #endif
523
524     (void) DO_LOCK ();
525     if (ADD_REF (rpmsigTbl_sigchld) == 0) {
526         if (rpmsqEnable(SIGINT, NULL) < 0) {
527             SUB_REF (rpmsigTbl_sigchld);
528             goto out;
529         }
530         if (rpmsqEnable(SIGQUIT, NULL) < 0) {
531             SUB_REF (rpmsigTbl_sigchld);
532             goto out_restore_sigint;
533         }
534     }
535     (void) DO_UNLOCK ();
536
537     (void) sigemptyset (&newMask);
538     (void) sigaddset (&newMask, SIGCHLD);
539     if (sigprocmask (SIG_BLOCK, &newMask, &oldMask) < 0) {
540         (void) DO_LOCK ();
541         if (SUB_REF (rpmsigTbl_sigchld) == 0)
542             goto out_restore_sigquit_and_sigint;
543         goto out;
544     }
545
546     CLEANUP_HANDLER(sigchld_cancel, &pid, &oldtype);
547
548     pid = fork ();
549     if (pid < (pid_t) 0) {              /* fork failed.  */
550         goto out;
551     } else if (pid == (pid_t) 0) {      /* Child. */
552
553         /* Restore the signals.  */
554         (void) sigaction (SIGINT, &rpmsigTbl_sigint->oact, NULL);
555         (void) sigaction (SIGQUIT, &rpmsigTbl_sigquit->oact, NULL);
556         (void) sigprocmask (SIG_SETMASK, &oldMask, NULL);
557
558         /* Reset rpmsigTbl lock and refcnt. */
559         INIT_LOCK ();
560
561         (void) execve (argv[0], (char *const *) argv, environ);
562         _exit (127);
563     } else {                            /* Parent. */
564         do {
565             result = waitpid(pid, &status, 0);
566         } while (result == (pid_t)-1 && errno == EINTR);
567         if (result != pid)
568             status = -1;
569     }
570
571     CLEANUP_RESET(0, oldtype);
572
573     (void) DO_LOCK ();
574     if ((SUB_REF (rpmsigTbl_sigchld) == 0 &&
575         (rpmsqEnable(-SIGINT, NULL) < 0 || rpmsqEnable (-SIGQUIT, NULL) < 0))
576       || sigprocmask (SIG_SETMASK, &oldMask, NULL) != 0)
577     {
578         status = -1;
579     }
580     goto out;
581
582 out_restore_sigquit_and_sigint:
583     (void) rpmsqEnable(-SIGQUIT, NULL);
584 out_restore_sigint:
585     (void) rpmsqEnable(-SIGINT, NULL);
586 out:
587     (void) DO_UNLOCK ();
588     return status;
589 }