f4c902c79719648c46fe9395f91a3181cedc66de
[oweals/busybox.git] / printutils / lpd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * micro lpd
4  *
5  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6  *
7  * Licensed under GPLv2, see file LICENSE in this tarball for details.
8  */
9
10 /*
11  * A typical usage of BB lpd looks as follows:
12  * # tcpsvd -E 0 515 lpd [SPOOLDIR] [HELPER-PROG [ARGS...]]
13  *
14  * This starts TCP listener on port 515 (default for LP protocol).
15  * When a client connection is made (via lpr) lpd first changes its
16  * working directory to SPOOLDIR (current dir is the default).
17  *
18  * SPOOLDIR is the spool directory which contains printing queues
19  * and should have the following structure:
20  *
21  * SPOOLDIR/
22  *      <queue1>
23  *      ...
24  *      <queueN>
25  *
26  * <queueX> can be of two types:
27  *      A. a printer character device, an ordinary file or a link to such;
28  *      B. a directory.
29  *
30  * In case A lpd just dumps the data it receives from client (lpr) to the
31  * end of queue file/device. This is non-spooling mode.
32  *
33  * In case B lpd enters spooling mode. It reliably saves client data along
34  * with control info in two unique files under the queue directory. These
35  * files are named dfAXXXHHHH and cfAXXXHHHH, where XXX is the job number
36  * and HHHH is the client hostname. Unless a printing helper application
37  * is specified lpd is done at this point.
38  *
39  * NB: file names are produced by peer! They actually may be anything at all.
40  * lpd only sanitizes them (by removing most non-alphanumerics).
41  *
42  * If HELPER-PROG (with optional arguments) is specified then lpd continues
43  * to process client data:
44  *      1. it reads and parses control file (cfA...). The parse process
45  *      results in setting environment variables whose values were passed
46  *      in control file; when parsing is complete, lpd deletes control file.
47  *      2. it spawns specified helper application. It is then
48  *      the helper application who is responsible for both actual printing
49  *      and deleting of processed data file.
50  *
51  * A good lpr passes control files which when parsed provides the following
52  * variables:
53  * $H = host which issues the job
54  * $P = user who prints
55  * $C = class of printing (what is printed on banner page)
56  * $J = the name of the job
57  * $L = print banner page
58  * $M = the user to whom a mail should be sent if a problem occurs
59  *
60  * We specifically filter out and NOT provide:
61  * $l = name of datafile ("dfAxxx") - file whose content are to be printed
62  *
63  * lpd provides $DATAFILE instead - the ACTUAL name
64  * of the datafile under which it was saved.
65  * $l would be not reliable (you would be at mercy of remote peer).
66  *
67  * Thus, a typical helper can be something like this:
68  * #!/bin/sh
69  * cat ./"$DATAFILE" >/dev/lp0
70  * mv -f ./"$DATAFILE" save/
71  */
72
73 #include "libbb.h"
74
75 // strip argument of bad chars
76 static char *sane(char *str)
77 {
78         char *s = str;
79         char *p = s;
80         while (*s) {
81                 if (isalnum(*s) || '-' == *s || '_' == *s) {
82                         *p++ = *s;
83                 }
84                 s++;
85         }
86         *p = '\0';
87         return str;
88 }
89
90 // we can use leaky setenv since we are about to exec or exit
91 static void exec_helper(char **filenames, char **argv) ATTRIBUTE_NORETURN;
92 static void exec_helper(char **filenames, char **argv)
93 {
94         char *p, *q;
95         char var[2];
96
97         var[1] = '\0';
98
99         // read and delete ctrlfile
100         q = xmalloc_open_read_close(filenames[0], NULL);
101         unlink(filenames[0]);
102         // provide datafile name
103         xsetenv("DATAFILE", filenames[1]);
104         // parse control file by "\n"
105         while ((p = strchr(q, '\n')) != NULL
106          && isalpha(*q)
107         ) {
108                 *p++ = '\0';
109                 // q is a line of <SYM><VALUE>,
110                 // we are setting environment string <SYM>=<VALUE>.
111                 // Ignoring "l<datafile>", exporting others:
112                 if (*q != 'l') {
113                         var[0] = *q++;
114                         xsetenv(var, q);
115                 }
116                 // next line, plz!
117                 q = p;
118         }
119         // we are the helper, we wanna be silent.
120         // this call reopens stdio fds to "/dev/null"
121         // (no daemonization is done)
122         bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO | DAEMON_ONLY_SANITIZE, NULL);
123         BB_EXECVP(*argv, argv);
124         exit(127); // it IS error if helper cannot be executed!
125 }
126
127 static char *xmalloc_read_stdin(void)
128 {
129         // SECURITY:
130         size_t max = 4 * 1024; // more than enough for commands!
131         return xmalloc_reads(STDIN_FILENO, NULL, &max);
132 }
133
134 int lpd_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
135 int lpd_main(int argc ATTRIBUTE_UNUSED, char *argv[])
136 {
137         int spooling = spooling; // for compiler
138         char *s, *queue;
139         char *filenames[2];
140
141         // goto spool directory
142         if (*++argv)
143                 xchdir(*argv++);
144
145         // error messages of xfuncs will be sent over network
146         xdup2(STDOUT_FILENO, STDERR_FILENO);
147
148         // nullify ctrl/data filenames
149         memset(filenames, 0, sizeof(filenames));
150
151         // read command
152         s = queue = xmalloc_read_stdin();
153         // we understand only "receive job" command
154         if (2 != *queue) {
155  unsupported_cmd:
156                 printf("Command %02x %s\n",
157                         (unsigned char)s[0], "is not supported");
158                 goto err_exit;
159         }
160
161         // parse command: "2 | QUEUE_NAME | '\n'"
162         queue++;
163         // protect against "/../" attacks
164         // *strchrnul(queue, '\n') = '\0'; - redundant, sane() will do
165         if (!*sane(queue))
166                 return EXIT_FAILURE;
167
168         // queue is a directory -> chdir to it and enter spooling mode
169         spooling = chdir(queue) + 1; // 0: cannot chdir, 1: done
170         // we don't free(s), we might need "queue" var later
171
172         while (1) {
173                 char *fname;
174                 int fd;
175                 // int is easier than ssize_t: can use xatoi_u,
176                 // and can correctly display error returns (-1)
177                 int expected_len, real_len;
178
179                 // signal OK
180                 safe_write(STDOUT_FILENO, "", 1);
181
182                 // get subcommand
183                 // valid s must be of form: "SUBCMD | LEN | space | FNAME"
184                 // N.B. we bail out on any error
185                 s = xmalloc_read_stdin();
186                 if (!s) { // (probably) EOF
187                         if (spooling /* && 7 != spooling - always true */) {
188                                 // we didn't see both ctrlfile & datafile!
189                                 goto err_exit;
190                         }
191                         // one of only two non-error exits
192                         return EXIT_SUCCESS;
193                 }
194
195                 // validate input.
196                 // we understand only "control file" or "data file" cmds
197                 if (2 != s[0] && 3 != s[0])
198                         goto unsupported_cmd;
199                 if (spooling & (1 << (s[0]-1))) {
200                         printf("Duplicated subcommand\n");
201                         goto err_exit;
202                 }
203                 // get filename
204                 *strchrnul(s, '\n') = '\0';
205                 fname = strchr(s, ' ');
206                 if (!fname) {
207 // bad_fname:
208                         printf("No or bad filename\n");
209                         goto err_exit;
210                 }
211                 *fname++ = '\0';
212 //              // s[0]==2: ctrlfile, must start with 'c'
213 //              // s[0]==3: datafile, must start with 'd'
214 //              if (fname[0] != s[0] + ('c'-2))
215 //                      goto bad_fname;
216                 // get length
217                 expected_len = bb_strtou(s + 1, NULL, 10);
218                 if (errno || expected_len < 0) {
219                         printf("Bad length\n");
220                         goto err_exit;
221                 }
222                 if (2 == s[0] && expected_len > 16 * 1024) {
223                         // SECURITY:
224                         // ctrlfile can't be big (we want to read it back later!)
225                         printf("File is too big\n");
226                         goto err_exit;
227                 }
228
229                 // open the file
230                 if (spooling) {
231                         // spooling mode: dump both files
232                         // job in flight has mode 0200 "only writable"
233                         sane(fname);
234                         fd = open3_or_warn(fname, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0200);
235                         if (fd < 0)
236                                 goto err_exit;
237                         filenames[s[0] - 2] = xstrdup(fname);
238                 } else {
239                         // non-spooling mode:
240                         // 2: control file (ignoring), 3: data file
241                         fd = -1;
242                         if (3 == s[0])
243                                 fd = xopen(queue, O_RDWR | O_APPEND);
244                 }
245
246                 // copy the file
247                 real_len = bb_copyfd_size(STDIN_FILENO, fd, expected_len);
248                 if (real_len != expected_len) {
249                         printf("Expected %d but got %d bytes\n",
250                                 expected_len, real_len);
251                         goto err_exit;
252                 }
253                 // get ACK and see whether it is NUL (ok)
254                 // (and don't trash s[0]!)
255                 if (safe_read(STDIN_FILENO, &s[1], 1) != 1 || s[1] != 0) {
256                         // don't send error msg to peer - it obviously
257                         // doesn't follow the protocol, so probably
258                         // it can't understand us either
259                         goto err_exit;
260                 }
261
262                 if (spooling) {
263                         // chmod completely downloaded file as "readable+writable"
264                         fchmod(fd, 0600);
265                         // accumulate dump state
266                         // N.B. after all files are dumped spooling should be 1+2+4==7
267                         spooling |= (1 << (s[0]-1)); // bit 1: ctrlfile; bit 2: datafile
268                 }
269
270                 free(s);
271                 close(fd); // NB: can do close(-1). Who cares?
272
273                 // spawn spool helper and exit if all files are dumped
274                 if (7 == spooling && *argv) {
275                         // signal OK
276                         safe_write(STDOUT_FILENO, "", 1);
277                         // does not return (exits 0)
278                         exec_helper(filenames, argv);
279                 }
280         } // while (1)
281
282  err_exit:
283         // don't keep corrupted files
284         if (spooling) {
285 #define i spooling
286                 for (i = 2; --i >= 0; )
287                         if (filenames[i])
288                                 unlink(filenames[i]);
289         }
290         return EXIT_FAILURE;
291 }