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