lpd.c 8.8 KB

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