File extrace-0.9.obscpio of Package extrace

07070100000000000081A400000000000000000000000161E8527500000BA1000000000000000000000000000000000000001400000000extrace-0.9/LICENSE/* pwait - wait for processes to terminate
 * extrace - trace exec() calls system-wide
 *
 * Copyright (C) 2014-2019 Leah Neukirchen <leah@vuxu.org>
 *
 * hacked from sources of:
 */
/* FreeBSD: head/bin/pwait/pwait.c 245506 2013-01-16 18:15:25Z delphij */
/*-
 * Copyright (c) 2004-2009, Jilles Tjoelker
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that the
 * following conditions are met:
 *
 * 1. Redistributions of source code must retain the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer.
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and
 *    the following disclaimer in the documentation and/or
 *    other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */
/* exec-notify, so you can watch your acrobat reader or vim executing "bash -c"
 * commands ;-)
 * Requires some 2.6.x Linux kernel with proc connector enabled.
 *
 * $  cc -Wall -ansi -pedantic -std=c99 exec-notify.c
 *
 * (C) 2007-2010 Sebastian Krahmer <krahmer@suse.de> original netlink handling
 * stolen from an proc-connector example, copyright folows:
 */
/* Copyright (C) Matt Helsley, IBM Corp. 2005
 * Derived from fcctl.c by Guillaume Thouvenin
 * Original copyright notice follows:
 *
 * Copyright (C) 2005 BULL SA.
 * Written by Guillaume Thouvenin <guillaume.thouvenin@bull.net>
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

07070100000001000081A400000000000000000000000161E8527500000203000000000000000000000000000000000000001500000000extrace-0.9/MakefileALL=extrace pwait

CFLAGS?=-g -O2 -Wall -Wno-switch -Wextra -Wwrite-strings -pedantic -ansi

DESTDIR=
PREFIX?=/usr/local
BINDIR=$(PREFIX)/bin
MANDIR=$(PREFIX)/share/man

all: $(ALL)

README: extrace.1 pwait.1
	mandoc -Tutf8 $^ | col -bx >$@

cap: $(ALL)
	sudo setcap cap_net_admin+ep extrace cap_net_admin+ep pwait

clean: FRC
	rm -f $(ALL)

install: FRC all
	mkdir -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(MANDIR)/man1
	install -m0755 $(ALL) $(DESTDIR)$(BINDIR)
	install -m0644 $(ALL:=.1) $(DESTDIR)$(MANDIR)/man1

FRC:
07070100000002000081A400000000000000000000000161E852750000035F000000000000000000000000000000000000001400000000extrace-0.9/NEWS.md## 0.9 (2022-01-19)

* With `-t`, print time when process execed.
* Fix `-p` flag, which was a regression in 0.8.
* Quit when parent specified in `-p` exits.
* Fix likely root cause for pid_db overflow.

## 0.8 (2021-08-05)

* extrace: add option -Q to suppress runtime errors.
* Small fixes.

## 0.7 (2019-02-08)

* pwait: detect and warn for non-existing PID.
* extract: detect and error for non-existing PID in `-p`.
* Bug fixes.

## 0.6 (2018-06-19)

* Add `-u` to print owner of process.
* Improved /proc/$PID/stat parser.

## 0.5 (2018-03-23)

* Detect and report out of order and lost messages.
* Ensure cmdline is read first.
* Use openat() for speedup.
* Remove custom SIGINT handler.

## 0.4 (2017-08-21)

* Add `-t` for tracing process exit and duration.

## 0.3.1 (2017-04-25)

* Bug fix release

## 0.3 (2016-06-14)

* Add `-e` to output environment
07070100000003000081A400000000000000000000000161E8527500000D55000000000000000000000000000000000000001300000000extrace-0.9/READMEEXTRACE(1)                  General Commands Manual                 EXTRACE(1)

NAME
     extrace – trace exec() calls system-wide

SYNOPSIS
     extrace [-deflqtu] [-o file] [-p pid | cmd ...]

DESCRIPTION
     extrace traces all program executions occurring on a system.

     The options are as follows:

     -d      Print the current working directory of the new process.

     -e      Print environment of process, or ‘-’ if unreadable.

     -f      Generate flat output without indentation.  By default, the line
             indentation reflects the process hierarchy.

     -l      Resolve full path of the executable.  By default, argv[0] is
             shown.

     -q      Suppress printing of exec(3) arguments.

     -t      Also display process exit status and duration.

     -u      Also display the user running the process.

     -o file
             Redirect trace output to file.

     -p pid  Only trace exec(3) calls descendant of pid.

     cmd ...
             Run cmd ... and only trace descendants of this command.

             By default, all exec(3) calls are traced globally.

EXIT STATUS
     The extrace utility exits 0 on success, and >0 if an error occurs.

ERRORS
     Check these prerequisites if you see this error:

           binding sk_nl error: Operation not permitted

     extrace requires special permissions to run, either root or the Linux
     CAP_NET_ADMIN capability.

     extrace only works on Linux kernels with the kernel options

           CONFIG_CONNECTOR=y
           CONFIG_PROC_EVENTS=y

SEE ALSO
     fatrace(1), ps(1), pwait(1), strace(1)

AUTHORS
     Leah Neukirchen <leah@vuxu.org>

     May contain traces of code from Guillaume Thouvenin, Matt Helsley, and
     Sebastian Krahmer.

BUGS
     While process tracing is exact, looking up all information is inherently
     sensitive to race conditions.  In doubt, you can only trust the PID was
     written correctly.

LICENSE
     extrace is licensed under the terms of the GPLv2.

Void Linux                       June 19, 2018                      Void Linux

------------------------------------------------------------------------------

PWAIT(1)                    General Commands Manual                   PWAIT(1)

NAME
     pwait – wait for processes to terminate

SYNOPSIS
     pwait [-v] [-c] pid ...

DESCRIPTION
     pwait waits until each of the given processes has terminated.

     The options are as follows:

     -v      Print the exit status when each process terminates.

     -c      Return 111 if any process exited non-successfully.

EXIT STATUS
     The pwait utility exits 0 on success, and >0 if an error occurs.

     Invalid pids elicit a warning message but are otherwise ignored.

ERRORS
     Check these prerequisites if you see this error:

           binding sk_nl error: Operation not permitted

     pwait requires special permissions to run, either root or the Linux
     CAP_NET_ADMIN capability.

     pwait only works on Linux kernels with the kernel options

           CONFIG_CONNECTOR=y
           CONFIG_PROC_EVENTS=y

SEE ALSO
     extrace(1), kill(1), pkill(1), ps(1), wait(1)

AUTHORS
     Leah Neukirchen <leah@vuxu.org>

     Built upon code from FreeBSD pwait written by Jilles Tjoelker.

LICENSE
     pwait is licensed under the terms of the GPLv2.

Void Linux                    September 17, 2018                    Void Linux
07070100000004000081ED00000000000000000000000161E8527500000BD9000000000000000000000000000000000000001800000000extrace-0.9/extrace-bpf#!/usr/bin/env ruby

require 'optparse'
require 'etc'

# TODO: -p / cmd... (how?)

BPF = <<'EOF'
BEGIN {
  printf("SEP2\n");
}
tracepoint:syscalls:sys_enter_execve {
  printf("%ld +%d %d", elapsed, pid, uid);
  join(args->argv, "SEP1");
  printf("SEP2\n");
}
tracepoint:syscalls:sys_enter_exit_group {
  printf("%ld -%d %d\nSEP2\n", elapsed, pid, args->error_code);
}
EOF

SEP1 = "\xff\xff\xff".b
SEP2 = "\xff\xfe\xff".b

Procc = Struct.new(:pid, :uid, :name, :args, :start_time, :ppid, :depth)

PIDS = {}

def pid_depth(pid)
  procc = PIDS[pid]
  if procc && procc.depth
    procc.depth
  else
    procc = (PIDS[pid] ||= Procc.new(pid))
    stat = File.read("/proc/#{pid}/stat").b
    if stat =~ /.*\) . (\d+)/
      ppid = $1.to_i
      if ppid == 0
        return 0
      else
        procc.ppid = ppid
        procc.depth = pid_depth(ppid) + 1
      end
    end
  end
rescue Errno::ENOENT, Errno::ESRCH => e
  puts "failed to get pid #{pid} info: #{e}"
  0
end

def fmtcmd(c)
  if c.empty? || c =~ /[\001-\040`^#*\[\]|\\?${}()'\"<>&;\177]/
    "'" + c.gsub("'", "'\\''").gsub("\n", "'$'\\n''") + "'"
  else
    c
  end
end

def fmtcmds(cmds)
  cmds.map { |cmd| fmtcmd(cmd) }.join(' ')
end

params = ARGV.getopts("deflqtu")
dflag = params['d']
eflag = params['e']
fflag = params['f']
lflag = params['l']
qflag = params['q']
tflag = params['t']
uflag = params['u']

IO.popen(["bpftrace", "-e", BPF.gsub("SEP1", SEP1).gsub("SEP2", SEP2)],
         "r:BINARY") { |output|
  while line = output.gets("\n#{SEP2}\n")
    line.chomp!("\n#{SEP2}\n")
    case line
    when /\A(\d+) \+(\d+) (\d+)/
      elapsed = $1.to_i
      pid = $2.to_i
      uid = $3.to_i
      comm = $'.split(SEP1)
      
      next  unless comm.first

      PIDS[pid] = Procc.new(pid, uid, comm.first, comm[1..-1], elapsed)

      print "  " * pid_depth(pid)  unless fflag
      print pid
      print "+"  if tflag
      print " "
      print "<#{Etc.getpwuid(uid).name}> "  if uflag
      if dflag
        print (File.readlink("/proc/#{pid}/cwd") rescue "-")
        print " % "
      end
      comm[0] = (File.readlink("/proc/#{pid}/exe") rescue comm[0])  if lflag
      if qflag
        print fmtcmd(comm[0])
      else
        print fmtcmds(comm)
      end
      if eflag
        print "   "
        print (File.read("/proc/#{pid}/environ") rescue "-").
                b.split("\x00").map { |e|
          if e =~ /\A[a-zA-Z0-9_]+=/
            $& + fmtcmd($')
          else
            fmtcmd(e)
          end
        }.join(" ")
      end
      puts
    when /\A(\d+) -(\d+) (\d+)/
      elapsed = $1.to_i
      pid = $2.to_i
      status = $3.to_i

      if procc = PIDS[pid]
        PIDS.delete(pid)
        next  unless procc.name
        if tflag
          dur = (elapsed - procc.start_time) / 1e9
          print "  " * pid_depth(pid)  unless fflag
          puts "#{pid}- #{procc.name} exited status=#{status} time=#{"%.3f" % dur}s"
        end
      end
    when /^Attaching/
      # ignore
    else
      warn "can't parse #{line}"
    end
  end
}
07070100000005000081A400000000000000000000000161E852750000077F000000000000000000000000000000000000001600000000extrace-0.9/extrace.1.Dd June 19, 2018
.Dt EXTRACE 1
.Os
.Sh NAME
.Nm extrace
.Nd trace exec() calls system-wide
.Sh SYNOPSIS
.Nm
.Op Fl deflqQtu
.Op Fl o Ar file
.Op Fl p Ar pid | cmd\ ...
.Sh DESCRIPTION
.Nm
traces all program executions occurring on a system.
.Pp
The options are as follows:
.Bl -tag -width Ds
.It Fl d
Print the current working directory of the new process.
.It Fl e
Print environment of process, or
.Sq Li -
if unreadable.
.It Fl f
Generate flat output without indentation.
By default, the line indentation reflects the process hierarchy.
.It Fl l
Resolve full path of the executable.
By default,
.Li "argv[0]"
is shown.
.It Fl q
Suppress printing of
.Xr exec 3
arguments.
.It Fl Q
Suppress printing of runtime errors.
.It Fl t
Also display process exit status and duration.
.It Fl u
Also display the user running the process.
.It Fl o Ar file
Redirect trace output to
.Ar file .
.It Fl p Ar pid
Only trace
.Xr exec 3
calls descendant of
.Ar pid .
.It Ar cmd\ ...
Run
.Ar cmd\ ...
and only trace descendants of this command.
.Pp
By default, all
.Xr exec 3
calls are traced globally.
.El
.Sh EXIT STATUS
.Ex -std
.Sh ERRORS
Check these prerequisites if you see this error:
.Bd -literal -offset Ds
binding sk_nl error: Operation not permitted
.Ed
.Pp
.Nm
requires special permissions to run, either root or the Linux
.Li "CAP_NET_ADMIN"
capability.
.Pp
.Nm
only works on Linux kernels with the kernel options
.Bd -literal -offset Ds
CONFIG_CONNECTOR=y
CONFIG_PROC_EVENTS=y
.Ed
.Sh SEE ALSO
.Xr fatrace 1 ,
.Xr ps 1 ,
.Xr pwait 1 ,
.Xr strace 1
.Sh AUTHORS
.An Leah Neukirchen Aq Mt leah@vuxu.org
.Pp
May contain traces of code from
Guillaume Thouvenin,
Matt Helsley,
and
Sebastian Krahmer.
.Sh BUGS
While process tracing is exact, looking up all information is
inherently sensitive to race conditions.
In doubt, you can only trust the PID was written correctly.
.Sh LICENSE
.Nm
is licensed under the terms of the GPLv2.
07070100000006000081A400000000000000000000000161E8527500003902000000000000000000000000000000000000001600000000extrace-0.9/extrace.c/* extrace - trace exec() calls system-wide
 *
 * Requires CONFIG_CONNECTOR=y and CONFIG_PROC_EVENTS=y.
 * Requires root or "setcap cap_net_admin+ep extrace".
 *
 * Usage: extrace [-deflqQtu] [-o FILE] [-p PID|CMD...]
 * default: show all exec(), globally
 * -p PID   only show exec() descendant of PID
 * CMD...   run CMD... and only show exec() descendant of it
 * -o FILE  log to FILE instead of standard output
 * -d       print cwd of process
 * -e       print environment of process
 * -f       flat output: no indentation
 * -l       print full path of argv[0]
 * -q       don't print exec() arguments
 * -Q       don't print error messages
 * -u       print user of process
 *
 * Copyright (C) 2014-2019 Leah Neukirchen <leah@vuxu.org>
 *
 * hacked from sources of:
 */
/* exec-notify, so you can watch your acrobat reader or vim executing "bash -c"
 * commands ;-)
 * Requires some 2.6.x Linux kernel with proc connector enabled.
 *
 * $  cc -Wall -ansi -pedantic -std=c99 exec-notify.c
 *
 * (C) 2007-2010 Sebastian Krahmer <krahmer@suse.de> original netlink handling
 * stolen from an proc-connector example, copyright folows:
 */
/* Copyright (C) Matt Helsley, IBM Corp. 2005
 * Derived from fcctl.c by Guillaume Thouvenin
 * Original copyright notice follows:
 *
 * Copyright (C) 2005 BULL SA.
 * Written by Guillaume Thouvenin <guillaume.thouvenin@bull.net>
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#define _XOPEN_SOURCE 700

#include <linux/cn_proc.h>
#include <linux/connector.h>
#include <linux/netlink.h>

#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define max(x, y) ((y) < (x) ? (x) : (y))
#define min(x, y) ((y) > (x) ? (x) : (y))

#define SEND_MESSAGE_LEN (NLMSG_LENGTH(sizeof (struct cn_msg) + \
                                       sizeof (enum proc_cn_mcast_op)))
#define RECV_MESSAGE_LEN (NLMSG_LENGTH(sizeof (struct cn_msg) + \
                                       sizeof (struct proc_event)))

#define SEND_MESSAGE_SIZE (NLMSG_SPACE(SEND_MESSAGE_LEN))
#define RECV_MESSAGE_SIZE (NLMSG_SPACE(RECV_MESSAGE_LEN))

#define BUFF_SIZE (max(max(SEND_MESSAGE_SIZE, RECV_MESSAGE_SIZE), 1024))
#define MIN_RECV_SIZE (min(SEND_MESSAGE_SIZE, RECV_MESSAGE_SIZE))

#define CMDLINE_MAX 32768
#define CMDLINE_DB_MAX 32
pid_t parent = 1;
int flat = 0;
int run = 0;
int full_path = 0;
int show_args = 1;
int show_errors = 1;
int show_cwd = 0;
int show_env = 0;
int show_exit = 0;
int show_user = 0;
FILE *output;
sig_atomic_t quit = 0;
#define CPU_MAX 4096
uint32_t last_seq[CPU_MAX];

#define PID_DB_SIZE 1024
struct {
	pid_t pid;
	int depth;
	uint64_t start;
	char cmdline[CMDLINE_DB_MAX];
} pid_db[PID_DB_SIZE];

static void
print_runtime_error(const char* fmt, ...) {
	va_list ap;
	if (show_errors) {
		va_start(ap, fmt);
		vfprintf(stderr, fmt, ap);
		va_end(ap);
	}
}

static int
open_proc_dir(pid_t pid) {
	char name[48];
	snprintf(name, sizeof name, "/proc/%d", pid);
	return open(name, O_DIRECTORY);
}

static int
pid_depth(pid_t pid)
{
	pid_t ppid = 0;
	char name[PATH_MAX];
	char buf[2048];
	char *s;
	int fd, d, i;

	if (pid == 1 && parent == 1)
		return 0;

	snprintf(name, sizeof name, "/proc/%d/stat", pid);

	if ((fd = open(name, O_RDONLY)) < 0)
		return 0;
	if (read(fd, buf, sizeof buf) <= 0)
		return 0;
	close(fd);

	s = strrchr(buf, ')');  /* find end of COMM (recommended way) */
	if (!s)
		return 0;
	while (*++s == ' ')
		;
	/* skip over STATE */
	while (*++s == ' ')
		;
	errno = 0;
	ppid = strtol(s, 0, 10);  /* parse PPID */
	if (errno != 0)
		return 0;

	if (ppid == parent)
		return 0;

	if (ppid == 0)
		return -1;  /* a parent we are not interested in */

	for (i = 0; i < PID_DB_SIZE - 1; i++)
		if (pid_db[i].pid == ppid)
			d = pid_db[i].depth;
	if (i == PID_DB_SIZE - 1)
		d = pid_depth(ppid);  /* we need to recurse */

	if (d == -1)
		return -1;

	return d + 1;
}

static const char *
sig2name(int sig)
{
	switch (sig) {
#define X(s) case s: return #s;
		/* signals defined in POSIX.1-1990 */
		X(SIGHUP)
		X(SIGINT)
		X(SIGQUIT)
		X(SIGILL)
		X(SIGABRT)
		X(SIGFPE)
		X(SIGKILL)
		X(SIGSEGV)
		X(SIGUSR1)
		X(SIGUSR2)
		X(SIGPIPE)
		X(SIGALRM)
		X(SIGTERM)
		X(SIGCHLD)
		X(SIGCONT)
		X(SIGSTOP)
		X(SIGTSTP)
		X(SIGTTIN)
		X(SIGTTOU)

		/* signals defined in POSIX.1-2001 */
		X(SIGBUS)
		X(SIGPOLL)
		X(SIGPROF)
		X(SIGSYS)
		X(SIGTRAP)
		X(SIGURG)
		X(SIGVTALRM)
		X(SIGXCPU)
		X(SIGXFSZ)

		/* other signals */
#ifdef SIGSTKFLT
		X(SIGSTKFLT)  /* Stack fault on coprocessor (unused) */
#endif
#ifdef SIGWINCH
		X(SIGWINCH)   /* Window resize signal (4.3BSD) */
#endif
#ifdef SIGPWR
		X(SIGPWR)     /* Power failure (System V) */
#endif

#undef X
	default: {
		static char buf[8];
		snprintf(buf, sizeof buf, "SIG%d", sig);
		return buf;
	}
	}
}

static void
sigchld(int sig)
{
	(void)sig;
	while (waitpid(-1, NULL, WNOHANG) > 0)
		;
	quit = 1;
}

static void
print_shquoted(const char *s)
{
	if (*s && !strpbrk(s,
	    "\001\002\003\004\005\006\007\010"
	    "\011\012\013\014\015\016\017\020"
	    "\021\022\023\024\025\026\027\030"
	    "\031\032\033\034\035\036\037\040"
	    "`^#*[]=|\\?${}()'\"<>&;\177")) {
		fprintf(output, "%s", s);
		return;
	}

	putc('\'', output);
	for (; *s; s++)
		if (*s == '\'')
			fprintf(output, "'\\''");
		else if (*s == '\n')
			fprintf(output, "'$'\\n''");
		else
			putc(*s, output);
	putc('\'', output);
}

static void
print_env(int proc_dir_fd)
{
	int fd;
	FILE *env;

	fprintf(output, "  ");
	fd = openat(proc_dir_fd, "environ", O_RDONLY);
	if (fd >= 0 && (env = fdopen(fd, "r"))) {
		char *line = 0, *eq = 0;
		size_t linelen = 0;
		while (getdelim(&line, &linelen, '\0', env) >= 0) {
			putc(' ', output);
			if ((eq = strchr(line, '='))) {
				/* print split so = doesn't trigger escaping.  */
				*eq = 0;
				print_shquoted(line);
				putc('=', output);
				print_shquoted(eq+1);
			} else {
				/* weird env entry without equal sign.  */
				print_shquoted(line);
			}
		}
		free(line);
		fclose(env);
	} else {
		fprintf(output, " -");
	}
}

static void
handle_msg(struct cn_msg *cn_hdr)
{
	char cmdline[CMDLINE_MAX];
	char exe[PATH_MAX];
	char cwd[PATH_MAX];
	char *argvrest;

	int r = 0, r2 = 0, r3 = 0, fd, d;
	struct proc_event *ev = (struct proc_event *)cn_hdr->data;

	if (ev->what == PROC_EVENT_EXEC) {
		pid_t pid = ev->event_data.exec.process_pid;
		int i = 0;
		int proc_dir_fd = open_proc_dir(pid);
		if (proc_dir_fd < 0) {
			print_runtime_error(
			    "extrace: process vanished before notification: pid %d\n",
			    pid);
			return;
		}

		memset(&cmdline, 0, sizeof cmdline);
		fd = openat(proc_dir_fd, "cmdline", O_RDONLY);
		if (fd >= 0) {
			r = read(fd, cmdline, sizeof cmdline);
			close(fd);

			if (r > 0)
				cmdline[r] = 0;

			if (full_path) {
				r2 = readlinkat(proc_dir_fd, "exe", exe, sizeof exe);
				if (r2 > 0)
					exe[r2] = 0;
			}

			argvrest = strchr(cmdline, 0) + 1;
		}

		d = pid_depth(pid);
		if (d < 0) {
			if (parent == 1) {
				if (*cmdline) {
					print_runtime_error(
					    "extrace: process vanished before we found its parent: pid %d: %s\n",
					    pid, cmdline);
				} else {
					print_runtime_error(
					    "extrace: process vanished without a name: pid %d\n",
					    pid);
				}
			}
			close(proc_dir_fd);
			return;
		}

		if (show_exit || !flat) {
			for (i = 0; i < PID_DB_SIZE - 1; i++)
				if (pid_db[i].pid == 0 || pid_db[i].pid == pid)
					break;
			if (i == PID_DB_SIZE - 1)
				print_runtime_error("extrace: warning: pid_db of "
				    "size %d overflowed\n", PID_DB_SIZE);

			if (show_exit && pid_db[i].pid == pid) {
				if (!flat)
					fprintf(output, "%*s", 2*d, "");
				fprintf(output, "%d- %s execed time=%.3fs\n",
				    pid,
				    pid_db[i].cmdline,
				    (ev->timestamp_ns - pid_db[i].start) / 1e9);
			}

			pid_db[i].pid = pid;
			pid_db[i].depth = d;
			pid_db[i].start = ev->timestamp_ns;
		}

		if (show_cwd) {
			r3 = readlinkat(proc_dir_fd, "cwd", cwd, sizeof cwd);
			if (r3 > 0)
				cwd[r3] = 0;
		}

		if (!flat)
			fprintf(output, "%*s", 2*d, "");
		fprintf(output, "%d", pid);
		if (show_exit) {
			putc('+', output);
			snprintf(pid_db[i].cmdline, CMDLINE_DB_MAX,
			    "%s", cmdline);
		}
		if (show_user) {
			struct stat st;
			struct passwd *p;

			if (fstat(proc_dir_fd, &st) < 0)
				st.st_uid = -1;
			if ((p = getpwuid(st.st_uid)))
				fprintf(output," <%s>", p->pw_name);
			else
				fprintf(output," <%d>", st.st_uid);
		}
		putc(' ', output);
		if (show_cwd) {
			print_shquoted(cwd);
			fprintf(output, " %% ");
		}

		if (full_path)
			print_shquoted(exe);
		else
			print_shquoted(cmdline);

		if (show_args && r > 0) {
			while (argvrest - cmdline < r) {
				putc(' ', output);
				print_shquoted(argvrest);
				argvrest = strchr(argvrest, 0)+1;
			}
		}

		if (r == sizeof cmdline)
			fprintf(output, "... <truncated>");

		if (show_env)
			print_env(proc_dir_fd);

		close(proc_dir_fd);

		fprintf(output, "\n");
		fflush(output);
	} else if ((show_exit || !flat) && ev->what == PROC_EVENT_EXIT) {
		pid_t pid = ev->event_data.exit.process_pid;
		int i;

		if (pid == parent)
			quit = 1;

		for (i = 0; i < PID_DB_SIZE; i++)
			if (pid_db[i].pid == pid)
				break;
		if (i == PID_DB_SIZE)
			return;

		pid_db[i].pid = 0;

		if (!show_exit)
			return;

		if (!flat)
			fprintf(output, "%*s",
			    2*pid_db[i].depth, "");

		fprintf(output, "%d- ", pid);
		print_shquoted(pid_db[i].cmdline);

		if (!WIFEXITED(ev->event_data.exit.exit_code))
			fprintf(output, " exited signal=%s",
			    sig2name(WTERMSIG(ev->event_data.exit.exit_code)));
		else
			fprintf(output, " exited status=%d",
			    WEXITSTATUS(ev->event_data.exit.exit_code));
		fprintf(output, " time=%.3fs\n",
		    (ev->timestamp_ns - pid_db[i].start) / 1e9);
		fflush(output);
	}
}

static pid_t
parse_pid(char *s)
{
	pid_t pid;
	char *end;

	errno = 0;
	pid = strtol(s, &end, 10);
	if (pid <= 0 || *end || errno != 0) {
		fprintf(stderr, "extrace: %s: invalid process id\n", s);
		exit(1);
	}

	errno = 0;
	kill(pid, 0);
	if (errno == ESRCH) {
		fprintf(stderr, "extrace: %s: no such process\n", s);
		exit(1);
	}

	return pid;
}

int
main(int argc, char *argv[])
{
	int sk_nl;
	struct sockaddr_nl my_nla, kern_nla, from_nla;
	socklen_t from_nla_len;
	char buff[BUFF_SIZE];
	struct nlmsghdr *nl_hdr, *nlh;
	struct cn_msg *cn_hdr, *cmsg;
	struct proc_event *cproc;
	enum proc_cn_mcast_op *mcop_msg;
	size_t recv_len = 0;
	int rc = -1, opt;

	output = stdout;

	while ((opt = getopt(argc, argv, "+deflo:p:qQtwu")) != -1)
		switch (opt) {
		case 'd': show_cwd = 1; break;
		case 'e': show_env = 1; break;
		case 'f': flat = 1; break;
		case 'l': full_path = 1; break;
		case 'p': parent = parse_pid(optarg); break;
		case 'q': show_args = 0; break;
		case 'Q': show_errors = 0; break;
		case 't': show_exit = 1; break;
		case 'o':
			output = fopen(optarg, "w");
			if (!output) {
				perror("fopen");
				exit(1);
			}
			break;
		case 'w': /* obsoleted, ignore */; break;
		case 'u': show_user = 1; break;
		default: goto usage;
		}

	if (parent != 1 && optind != argc) {
usage:
		fprintf(stderr, "Usage: extrace [-deflqQtu] [-o FILE] [-p PID|CMD...]\n");
		exit(1);
	}

	sk_nl = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
	if (sk_nl == -1) {
		perror("socket sk_nl error");
		exit(1);
	}

	my_nla.nl_family = AF_NETLINK;
	my_nla.nl_groups = CN_IDX_PROC;
	my_nla.nl_pid = getpid();

	kern_nla.nl_family = AF_NETLINK;
	kern_nla.nl_groups = CN_IDX_PROC;
	kern_nla.nl_pid = 1;

	if (bind(sk_nl, (struct sockaddr *)&my_nla, sizeof my_nla) == -1) {
		perror("binding sk_nl error");
		goto close_and_exit;
	}
	nl_hdr = (struct nlmsghdr *)buff;
	cn_hdr = (struct cn_msg *)NLMSG_DATA(nl_hdr);
	mcop_msg = (enum proc_cn_mcast_op *)&cn_hdr->data[0];

	memset(buff, 0, sizeof buff);
	*mcop_msg = PROC_CN_MCAST_LISTEN;

	nl_hdr->nlmsg_len = SEND_MESSAGE_LEN;
	nl_hdr->nlmsg_type = NLMSG_DONE;
	nl_hdr->nlmsg_flags = 0;
	nl_hdr->nlmsg_seq = 0;
	nl_hdr->nlmsg_pid = getpid();

	cn_hdr->id.idx = CN_IDX_PROC;
	cn_hdr->id.val = CN_VAL_PROC;
	cn_hdr->seq = 0;
	cn_hdr->ack = 0;
	cn_hdr->len = sizeof (enum proc_cn_mcast_op);

	if (send(sk_nl, nl_hdr, nl_hdr->nlmsg_len, 0) != nl_hdr->nlmsg_len) {
		printf("failed to send proc connector mcast ctl op!\n");
		goto close_and_exit;
	}

	if (*mcop_msg == PROC_CN_MCAST_IGNORE) {
		rc = 0;
		goto close_and_exit;
	}

	if (optind != argc) {
		pid_t child;

		parent = getpid();
		signal(SIGCHLD, sigchld);

		child = fork();
		if (child == -1) {
			perror("fork");
			goto close_and_exit;
		}
		if (child == 0) {
			execvp(argv[optind], argv+optind);
			perror("execvp");
			goto close_and_exit;
		}
	}

	rc = 0;
	while (!quit) {
		cmsg = (struct cn_msg *)(buff + sizeof (struct nlmsghdr));
		cproc = (struct proc_event *)(buff + sizeof (struct nlmsghdr) + sizeof (struct cn_msg));

		memset(buff, 0, sizeof buff);
		from_nla_len = sizeof from_nla;
		nlh = (struct nlmsghdr *)buff;
		memcpy(&from_nla, &kern_nla, sizeof from_nla);
		recv_len = recvfrom(sk_nl, buff, BUFF_SIZE, 0,
		    (struct sockaddr *)&from_nla, &from_nla_len);
		if (from_nla.nl_pid != 0 || recv_len < 1)
			continue;

		if (cproc->what == PROC_EVENT_NONE)
			continue;
	
		if (last_seq[cproc->cpu] &&
		    cmsg->seq != last_seq[cproc->cpu] + 1)
			print_runtime_error(
			    "extrace: out of order message on cpu %d\n",
			    cproc->cpu);
		last_seq[cproc->cpu] = cmsg->seq;

		while (NLMSG_OK(nlh, recv_len)) {
			if (nlh->nlmsg_type == NLMSG_NOOP)
				continue;
			if (nlh->nlmsg_type == NLMSG_ERROR ||
			    nlh->nlmsg_type == NLMSG_OVERRUN)
				break;

			handle_msg(NLMSG_DATA(nlh));

			if (nlh->nlmsg_type == NLMSG_DONE)
				break;
			nlh = NLMSG_NEXT(nlh, recv_len);
		}
	}

close_and_exit:
	close(sk_nl);
	return rc;
}
07070100000007000081A400000000000000000000000161E8527500000452000000000000000000000000000000000000001400000000extrace-0.9/pwait.1.Dd September 17, 2018
.Dt PWAIT 1
.Os
.Sh NAME
.Nm pwait
.Nd wait for processes to terminate
.Sh SYNOPSIS
.Nm
.Op Fl v
.Op Fl c
.Ar pid\ ...
.Sh DESCRIPTION
.Nm pwait
waits until each of the given processes has terminated.
.Pp
The options are as follows:
.Bl -tag -width Ds
.It Fl v
Print the exit status when each process terminates.
.It Fl c
Return 111 if any process exited non-successfully.
.El
.Sh EXIT STATUS
.Ex -std
.Pp
Invalid pids elicit a warning message but are otherwise ignored.
.Sh ERRORS
Check these prerequisites if you see this error:
.Bd -literal -offset Ds
binding sk_nl error: Operation not permitted
.Ed
.Pp
.Nm
requires special permissions to run, either root or the Linux
.Li "CAP_NET_ADMIN"
capability.
.Pp
.Nm
only works on Linux kernels with the kernel options
.Bd -literal -offset Ds
CONFIG_CONNECTOR=y
CONFIG_PROC_EVENTS=y
.Ed
.Sh SEE ALSO
.Xr extrace 1 ,
.Xr kill 1 ,
.Xr pkill 1 ,
.Xr ps 1 ,
.Xr wait 1
.Sh AUTHORS
.An Leah Neukirchen Aq Mt leah@vuxu.org
.Pp
Built upon code from
.Fx
.Nm
written by Jilles Tjoelker.
.Sh LICENSE
.Nm
is licensed under the terms of the GPLv2.
07070100000008000081A400000000000000000000000161E8527500002047000000000000000000000000000000000000001400000000extrace-0.9/pwait.c/* pwait - wait for processes to terminate
 *
 * Requires CONFIG_CONNECTOR=y and CONFIG_PROC_EVENTS=y.
 * Requires root or "setcap cap_net_admin+ep pwait".
 *
 * Usage: pwait [-v] [-c] PID...
 * -v  Print the exit status when each process terminates.
 * -c  Check for PIDs to exit successfully, else return 111.
 *
 * Copyright (C) 2014-2019 Leah Neukirchen <leah@vuxu.org>
 *
 * hacked from sources of:
 */
/* FreeBSD: head/bin/pwait/pwait.c 245506 2013-01-16 18:15:25Z delphij */
/*-
 * Copyright (c) 2004-2009, Jilles Tjoelker
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that the
 * following conditions are met:
 *
 * 1. Redistributions of source code must retain the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer.
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and
 *    the following disclaimer in the documentation and/or
 *    other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */
/* exec-notify, so you can watch your acrobat reader or vim executing "bash -c"
 * commands ;-)
 * Requires some 2.6.x Linux kernel with proc connector enabled.
 *
 * $  cc -Wall -ansi -pedantic -std=c99 exec-notify.c
 *
 * (C) 2007-2010 Sebastian Krahmer <krahmer@suse.de> original netlink handling
 * stolen from an proc-connector example, copyright folows:
 */
/* Copyright (C) Matt Helsley, IBM Corp. 2005
 * Derived from fcctl.c by Guillaume Thouvenin
 * Original copyright notice follows:
 *
 * Copyright (C) 2005 BULL SA.
 * Written by Guillaume Thouvenin <guillaume.thouvenin@bull.net>
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#define _XOPEN_SOURCE 700

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <linux/cn_proc.h>
#include <linux/connector.h>
#include <linux/netlink.h>

#define max(x, y) ((y) < (x) ? (x) : (y))
#define min(x, y) ((y) > (x) ? (x) : (y))

#define SEND_MESSAGE_LEN (NLMSG_LENGTH(sizeof (struct cn_msg) + \
				       sizeof (enum proc_cn_mcast_op)))
#define RECV_MESSAGE_LEN (NLMSG_LENGTH(sizeof (struct cn_msg) + \
				       sizeof (struct proc_event)))

#define SEND_MESSAGE_SIZE    (NLMSG_SPACE(SEND_MESSAGE_LEN))
#define RECV_MESSAGE_SIZE    (NLMSG_SPACE(RECV_MESSAGE_LEN))

#define BUFF_SIZE (max(max(SEND_MESSAGE_SIZE, RECV_MESSAGE_SIZE), 1024))
#define MIN_RECV_SIZE (min(SEND_MESSAGE_SIZE, RECV_MESSAGE_SIZE))

sig_atomic_t quit = 0;

static void
sigint(int sig)
{
	(void)sig;
	quit = 1;
}

static void
display(pid_t pid, int status)
{
	if (WIFEXITED(status))
		printf("%ld: exited with status %d.\n",
		    (long)pid,
		    WEXITSTATUS(status));
	else if (WIFSIGNALED(status))
		printf("%ld: killed by signal %d.\n",
		    (long)pid,
		    WTERMSIG(status));
	else
		printf("%ld: terminated.\n",
		    (long)pid);
}

int
main(int argc, char *argv[])
{
	int sk_nl;
	struct sockaddr_nl my_nla, kern_nla, from_nla;
	socklen_t from_nla_len;
	char buff[BUFF_SIZE];
	struct nlmsghdr *nl_hdr, *nlh;
	struct cn_msg *cn_hdr;
	struct proc_event *ev;
	enum proc_cn_mcast_op *mcop_msg;
	size_t recv_len = 0;
	int opt;
	int n, m;
	pid_t *pids;
	pid_t pid;
	char *end;
	int verbose = 0;
	int check = 0;
	int seen = 0;
	int rc = -1;

	while ((opt = getopt(argc, argv, "+cv")) != -1)
		switch (opt) {
		case 'c': check = 1; break;
		case 'v': verbose = 1; break;
		default: goto usage;
		}

	argc -= optind;
	argv += optind;

	if (argc == 0) {
usage:
		fprintf(stderr, "Usage: pwait [-v] [-c] PID...\n");
		exit(1);
	}

	pids = calloc(argc, sizeof (pid_t));
	if (!pids) {
		perror("pwait: calloc");
		exit(1);
	}

	for (n = m = 0; n < argc; n++) {
		errno = 0;
		pid = strtol(argv[n], &end, 10);
		if (pid <= 0 || *end || errno != 0) {
			fprintf(stderr, "pwait: %s: invalid process id\n",
			    argv[n]);
			continue;
		}
		pids[m++] = pid;
	}

	if (m == 0)
		exit(1);

	sk_nl = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
	if (sk_nl == -1) {
		perror("pwait: socket sk_nl error");
		exit(1);
	}

	my_nla.nl_family = AF_NETLINK;
	my_nla.nl_groups = CN_IDX_PROC;
	my_nla.nl_pid = getpid();

	kern_nla.nl_family = AF_NETLINK;
	kern_nla.nl_groups = CN_IDX_PROC;
	kern_nla.nl_pid = 1;

	if (bind(sk_nl, (struct sockaddr *)&my_nla, sizeof my_nla) == -1) {
		perror("pwait: binding sk_nl error");
		goto close_and_exit;
	}
	nl_hdr = (struct nlmsghdr *)buff;
	cn_hdr = (struct cn_msg *)NLMSG_DATA(nl_hdr);
	mcop_msg = (enum proc_cn_mcast_op *)&cn_hdr->data[0];

	memset(buff, 0, sizeof buff);
	*mcop_msg = PROC_CN_MCAST_LISTEN;

	nl_hdr->nlmsg_len = SEND_MESSAGE_LEN;
	nl_hdr->nlmsg_type = NLMSG_DONE;
	nl_hdr->nlmsg_flags = 0;
	nl_hdr->nlmsg_seq = 0;
	nl_hdr->nlmsg_pid = getpid();

	cn_hdr->id.idx = CN_IDX_PROC;
	cn_hdr->id.val = CN_VAL_PROC;
	cn_hdr->seq = 0;
	cn_hdr->ack = 0;
	cn_hdr->len = sizeof (enum proc_cn_mcast_op);

	if (send(sk_nl, nl_hdr, nl_hdr->nlmsg_len, 0) != nl_hdr->nlmsg_len) {
		fprintf(stderr,
		    "pwait: failed to send proc connector mcast ctl op!\n");
		goto close_and_exit;
	}

	if (*mcop_msg == PROC_CN_MCAST_IGNORE)
		goto close_and_exit;

	quit = 1;
	for (n = 0; n < m; n++) {
		errno = 0;
		kill(pids[n], 0);
		if (errno == ESRCH) {
			fprintf(stderr, "pwait: %d: no such process\n",
			    pids[n]);
			pids[n] = 0;
			continue;
		}
		quit = 0;
	}
	if (quit)
		exit(1);

	signal(SIGINT, sigint);

	rc = 0;
	while (!quit) {
		memset(buff, 0, sizeof buff);

		from_nla_len = sizeof from_nla;
		nlh = (struct nlmsghdr *)buff;
		memcpy(&from_nla, &kern_nla, sizeof from_nla);
		recv_len = recvfrom(sk_nl, buff, BUFF_SIZE, 0,
		    (struct sockaddr *)&from_nla, &from_nla_len);
		if (from_nla.nl_pid != 0 || recv_len < 1)
			continue;

		while (NLMSG_OK(nlh, recv_len)) {
			if (nlh->nlmsg_type == NLMSG_NOOP)
				continue;
			if (nlh->nlmsg_type == NLMSG_ERROR ||
			    nlh->nlmsg_type == NLMSG_OVERRUN)
				break;

			ev = (struct proc_event *)
			    ((struct cn_msg *)NLMSG_DATA(nlh))->data;

			if (ev->what == PROC_EVENT_EXIT) {
				int status = ev->event_data.exit.exit_code;
				pid_t pid = ev->event_data.exit.process_pid;

				seen = 0;
				for (n = 0; n < m; n++)
					if (pids[n] == pid) {
						if (verbose && !seen)
							display(pid, status);
						pids[n] = 0;
						seen = 1;
						if (check && rc == 0 &&
						    (!WIFEXITED(status) ||
						    WEXITSTATUS(status) != 0))
							rc = 111;
					}
			}

			if (nlh->nlmsg_type == NLMSG_DONE)
				break;
			nlh = NLMSG_NEXT(nlh, recv_len);
		}

		quit = 1;
		for (n = 0; n < m; n++)
			if (pids[n] != 0)
				quit = 0;
	}

close_and_exit:
	close(sk_nl);
	free(pids);
	return rc;
}
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!75 blocks
openSUSE Build Service is sponsored by