Bump to version 1.22.1
[platform/upstream/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 source tree.
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 //usage:#define lpd_trivial_usage
74 //usage:       "SPOOLDIR [HELPER [ARGS]]"
75 //usage:#define lpd_full_usage "\n\n"
76 //usage:       "SPOOLDIR must contain (symlinks to) device nodes or directories"
77 //usage:     "\nwith names matching print queue names. In the first case, jobs are"
78 //usage:     "\nsent directly to the device. Otherwise each job is stored in queue"
79 //usage:     "\ndirectory and HELPER program is called. Name of file to print"
80 //usage:     "\nis passed in $DATAFILE variable."
81 //usage:     "\nExample:"
82 //usage:     "\n        tcpsvd -E 0 515 softlimit -m 999999 lpd /var/spool ./print"
83
84 #include "libbb.h"
85
86 // strip argument of bad chars
87 static char *sane(char *str)
88 {
89         char *s = str;
90         char *p = s;
91         while (*s) {
92                 if (isalnum(*s) || '-' == *s || '_' == *s) {
93                         *p++ = *s;
94                 }
95                 s++;
96         }
97         *p = '\0';
98         return str;
99 }
100
101 static char *xmalloc_read_stdin(void)
102 {
103         // SECURITY:
104         size_t max = 4 * 1024; // more than enough for commands!
105         return xmalloc_reads(STDIN_FILENO, &max);
106 }
107
108 int lpd_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
109 int lpd_main(int argc UNUSED_PARAM, char *argv[])
110 {
111         int spooling = spooling; // for compiler
112         char *s, *queue;
113         char *filenames[2];
114
115         // goto spool directory
116         if (*++argv)
117                 xchdir(*argv++);
118
119         // error messages of xfuncs will be sent over network
120         xdup2(STDOUT_FILENO, STDERR_FILENO);
121
122         // nullify ctrl/data filenames
123         memset(filenames, 0, sizeof(filenames));
124
125         // read command
126         s = queue = xmalloc_read_stdin();
127         // we understand only "receive job" command
128         if (2 != *queue) {
129  unsupported_cmd:
130                 printf("Command %02x %s\n",
131                         (unsigned char)s[0], "is not supported");
132                 goto err_exit;
133         }
134
135         // parse command: "2 | QUEUE_NAME | '\n'"
136         queue++;
137         // protect against "/../" attacks
138         // *strchrnul(queue, '\n') = '\0'; - redundant, sane() will do
139         if (!*sane(queue))
140                 return EXIT_FAILURE;
141
142         // queue is a directory -> chdir to it and enter spooling mode
143         spooling = chdir(queue) + 1; // 0: cannot chdir, 1: done
144         // we don't free(s), we might need "queue" var later
145
146         while (1) {
147                 char *fname;
148                 int fd;
149                 // int is easier than ssize_t: can use xatoi_positive,
150                 // and can correctly display error returns (-1)
151                 int expected_len, real_len;
152
153                 // signal OK
154                 safe_write(STDOUT_FILENO, "", 1);
155
156                 // get subcommand
157                 // valid s must be of form: "SUBCMD | LEN | space | FNAME"
158                 // N.B. we bail out on any error
159                 s = xmalloc_read_stdin();
160                 if (!s) { // (probably) EOF
161                         char *p, *q, var[2];
162
163                         // non-spooling mode or no spool helper specified
164                         if (!spooling || !*argv)
165                                 return EXIT_SUCCESS; // the only non-error exit
166                         // spooling mode but we didn't see both ctrlfile & datafile
167                         if (spooling != 7)
168                                 goto err_exit; // reject job
169
170                         // spooling mode and spool helper specified -> exec spool helper
171                         // (we exit 127 if helper cannot be executed)
172                         var[1] = '\0';
173                         // read and delete ctrlfile
174                         q = xmalloc_xopen_read_close(filenames[0], NULL);
175                         unlink(filenames[0]);
176                         // provide datafile name
177                         // we can use leaky setenv since we are about to exec or exit
178                         xsetenv("DATAFILE", filenames[1]);
179                         // parse control file by "\n"
180                         while ((p = strchr(q, '\n')) != NULL && isalpha(*q)) {
181                                 *p++ = '\0';
182                                 // q is a line of <SYM><VALUE>,
183                                 // we are setting environment string <SYM>=<VALUE>.
184                                 // Ignoring "l<datafile>", exporting others:
185                                 if (*q != 'l') {
186                                         var[0] = *q++;
187                                         xsetenv(var, q);
188                                 }
189                                 q = p; // next line
190                         }
191                         // helper should not talk over network.
192                         // this call reopens stdio fds to "/dev/null"
193                         // (no daemonization is done)
194                         bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO | DAEMON_ONLY_SANITIZE, NULL);
195                         BB_EXECVP_or_die(argv);
196                 }
197
198                 // validate input.
199                 // we understand only "control file" or "data file" cmds
200                 if (2 != s[0] && 3 != s[0])
201                         goto unsupported_cmd;
202                 if (spooling & (1 << (s[0]-1))) {
203                         printf("Duplicated subcommand\n");
204                         goto err_exit;
205                 }
206                 // get filename
207                 *strchrnul(s, '\n') = '\0';
208                 fname = strchr(s, ' ');
209                 if (!fname) {
210 // bad_fname:
211                         printf("No or bad filename\n");
212                         goto err_exit;
213                 }
214                 *fname++ = '\0';
215 //              // s[0]==2: ctrlfile, must start with 'c'
216 //              // s[0]==3: datafile, must start with 'd'
217 //              if (fname[0] != s[0] + ('c'-2))
218 //                      goto bad_fname;
219                 // get length
220                 expected_len = bb_strtou(s + 1, NULL, 10);
221                 if (errno || expected_len < 0) {
222                         printf("Bad length\n");
223                         goto err_exit;
224                 }
225                 if (2 == s[0] && expected_len > 16 * 1024) {
226                         // SECURITY:
227                         // ctrlfile can't be big (we want to read it back later!)
228                         printf("File is too big\n");
229                         goto err_exit;
230                 }
231
232                 // open the file
233                 if (spooling) {
234                         // spooling mode: dump both files
235                         // job in flight has mode 0200 "only writable"
236                         sane(fname);
237                         fd = open3_or_warn(fname, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0200);
238                         if (fd < 0)
239                                 goto err_exit;
240                         filenames[s[0] - 2] = xstrdup(fname);
241                 } else {
242                         // non-spooling mode:
243                         // 2: control file (ignoring), 3: data file
244                         fd = -1;
245                         if (3 == s[0])
246                                 fd = xopen(queue, O_RDWR | O_APPEND);
247                 }
248
249                 // signal OK
250                 safe_write(STDOUT_FILENO, "", 1);
251
252                 // copy the file
253                 real_len = bb_copyfd_size(STDIN_FILENO, fd, expected_len);
254                 if (real_len != expected_len) {
255                         printf("Expected %d but got %d bytes\n",
256                                 expected_len, real_len);
257                         goto err_exit;
258                 }
259                 // get EOF indicator, see whether it is NUL (ok)
260                 // (and don't trash s[0]!)
261                 if (safe_read(STDIN_FILENO, &s[1], 1) != 1 || s[1] != 0) {
262                         // don't send error msg to peer - it obviously
263                         // doesn't follow the protocol, so probably
264                         // it can't understand us either
265                         goto err_exit;
266                 }
267
268                 if (spooling) {
269                         // chmod completely downloaded file as "readable+writable"
270                         fchmod(fd, 0600);
271                         // accumulate dump state
272                         // N.B. after all files are dumped spooling should be 1+2+4==7
273                         spooling |= (1 << (s[0]-1)); // bit 1: ctrlfile; bit 2: datafile
274                 }
275
276                 free(s);
277                 close(fd); // NB: can do close(-1). Who cares?
278
279                 // NB: don't do "signal OK" write here, it will be done
280                 // at the top of the loop
281         } // while (1)
282
283  err_exit:
284         // don't keep corrupted files
285         if (spooling) {
286 #define i spooling
287                 for (i = 2; --i >= 0; )
288                         if (filenames[i])
289                                 unlink(filenames[i]);
290         }
291         return EXIT_FAILURE;
292 }