2 * Copyright (c) 2012 Damien Miller <djm@mindrot.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 /* $OpenBSD: modpipe.c,v 1.6 2013/11/21 03:16:47 djm Exp $ */
21 #include <sys/types.h>
31 #include "openbsd-compat/getopt_long.c"
36 fprintf(stderr, "Usage: modpipe -w [-m modspec ...] < in > out\n");
37 fprintf(stderr, "modspec is one of:\n");
38 fprintf(stderr, " xor:offset:value - XOR \"value\" at \"offset\"\n");
39 fprintf(stderr, " andor:offset:val1:val2 - AND \"val1\" then OR \"val2\" at \"offset\"\n");
43 #define MAX_MODIFICATIONS 256
45 enum { MOD_XOR, MOD_AND_OR } what;
46 unsigned long long offset;
51 parse_modification(const char *s, struct modification *m)
57 if ((n = sscanf(s, "%16[^:]%*[:]%llu%*[:]%i%*[:]%i",
58 what, &m->offset, &m1, &m2)) < 3)
59 errx(1, "Invalid modification spec \"%s\"", s);
60 if (strcasecmp(what, "xor") == 0) {
62 errx(1, "Invalid modification spec \"%s\"", s);
63 if (m1 < 0 || m1 > 0xff)
64 errx(1, "Invalid XOR modification value");
67 } else if (strcasecmp(what, "andor") == 0) {
69 errx(1, "Invalid modification spec \"%s\"", s);
70 if (m1 < 0 || m1 > 0xff)
71 errx(1, "Invalid AND modification value");
72 if (m2 < 0 || m2 > 0xff)
73 errx(1, "Invalid OR modification value");
78 errx(1, "Invalid modification type \"%s\"", what);
82 main(int argc, char **argv)
88 struct modification mods[MAX_MODIFICATIONS];
89 u_int i, wflag = 0, num_mods = 0;
91 while ((ch = getopt(argc, argv, "wm:")) != -1) {
94 if (num_mods >= MAX_MODIFICATIONS)
95 errx(1, "Too many modifications");
96 parse_modification(optarg, &(mods[num_mods++]));
107 r = s = read(STDIN_FILENO, buf, sizeof(buf));
111 if (errno == EAGAIN || errno == EINTR)
115 for (i = 0; i < num_mods; i++) {
116 if (mods[i].offset < total ||
117 mods[i].offset >= total + s)
119 switch (mods[i].what) {
121 buf[mods[i].offset - total] ^= mods[i].m1;
124 buf[mods[i].offset - total] &= mods[i].m1;
125 buf[mods[i].offset - total] |= mods[i].m2;
129 for (o = 0; o < s; o += r) {
130 r = write(STDOUT_FILENO, buf, s - o);
134 if (errno == EAGAIN || errno == EINTR)
141 /* Warn if modifications not reached in input stream */
143 for (i = 0; wflag && i < num_mods; i++) {
144 if (mods[i].offset < total)
147 fprintf(stderr, "modpipe: warning - mod %u not reached\n", i);