3
0

lpd.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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.3 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. // we understand only "receive job" command
  125. if (2 != *queue) {
  126. unsupported_cmd:
  127. printf("Command %02x %s\n",
  128. (unsigned char)s[0], "is not supported");
  129. goto err_exit;
  130. }
  131. // parse command: "2 | QUEUE_NAME | '\n'"
  132. queue++;
  133. // protect against "/../" attacks
  134. // *strchrnul(queue, '\n') = '\0'; - redundant, sane() will do
  135. if (!*sane(queue))
  136. return EXIT_FAILURE;
  137. // queue is a directory -> chdir to it and enter spooling mode
  138. spooling = chdir(queue) + 1; // 0: cannot chdir, 1: done
  139. // we don't free(s), we might need "queue" var later
  140. while (1) {
  141. char *fname;
  142. int fd;
  143. // int is easier than ssize_t: can use xatoi_positive,
  144. // and can correctly display error returns (-1)
  145. int expected_len, real_len;
  146. // signal OK
  147. safe_write(STDOUT_FILENO, "", 1);
  148. // get subcommand
  149. // valid s must be of form: "SUBCMD | LEN | space | FNAME"
  150. // N.B. we bail out on any error
  151. s = xmalloc_read_stdin();
  152. if (!s) { // (probably) EOF
  153. char *p, *q, var[2];
  154. // non-spooling mode or no spool helper specified
  155. if (!spooling || !*argv)
  156. return EXIT_SUCCESS; // the only non-error exit
  157. // spooling mode but we didn't see both ctrlfile & datafile
  158. if (spooling != 7)
  159. goto err_exit; // reject job
  160. // spooling mode and spool helper specified -> exec spool helper
  161. // (we exit 127 if helper cannot be executed)
  162. var[1] = '\0';
  163. // read and delete ctrlfile
  164. q = xmalloc_xopen_read_close(filenames[0], NULL);
  165. unlink(filenames[0]);
  166. // provide datafile name
  167. // we can use leaky setenv since we are about to exec or exit
  168. xsetenv("DATAFILE", filenames[1]);
  169. // parse control file by "\n"
  170. while ((p = strchr(q, '\n')) != NULL && isalpha(*q)) {
  171. *p++ = '\0';
  172. // q is a line of <SYM><VALUE>,
  173. // we are setting environment string <SYM>=<VALUE>.
  174. // Ignoring "l<datafile>", exporting others:
  175. if (*q != 'l') {
  176. var[0] = *q++;
  177. xsetenv(var, q);
  178. }
  179. q = p; // next line
  180. }
  181. // helper should not talk over network.
  182. // this call reopens stdio fds to "/dev/null".
  183. bb_daemon_helper(DAEMON_DEVNULL_STDIO);
  184. BB_EXECVP_or_die(argv);
  185. }
  186. // validate input.
  187. // we understand only "control file" or "data file" cmds
  188. if (2 != s[0] && 3 != s[0])
  189. goto unsupported_cmd;
  190. if (spooling & (1 << (s[0]-1))) {
  191. puts("Duplicated subcommand");
  192. goto err_exit;
  193. }
  194. // get filename
  195. chomp(s);
  196. fname = strchr(s, ' ');
  197. if (!fname) {
  198. // bad_fname:
  199. puts("No or bad filename");
  200. goto err_exit;
  201. }
  202. *fname++ = '\0';
  203. // // s[0]==2: ctrlfile, must start with 'c'
  204. // // s[0]==3: datafile, must start with 'd'
  205. // if (fname[0] != s[0] + ('c'-2))
  206. // goto bad_fname;
  207. // get length
  208. expected_len = bb_strtou(s + 1, NULL, 10);
  209. if (errno || expected_len < 0) {
  210. puts("Bad length");
  211. goto err_exit;
  212. }
  213. if (2 == s[0] && expected_len > 16 * 1024) {
  214. // SECURITY:
  215. // ctrlfile can't be big (we want to read it back later!)
  216. puts("File is too big");
  217. goto err_exit;
  218. }
  219. // open the file
  220. if (spooling) {
  221. // spooling mode: dump both files
  222. // job in flight has mode 0200 "only writable"
  223. sane(fname);
  224. fd = open3_or_warn(fname, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0200);
  225. if (fd < 0)
  226. goto err_exit;
  227. filenames[s[0] - 2] = xstrdup(fname);
  228. } else {
  229. // non-spooling mode:
  230. // 2: control file (ignoring), 3: data file
  231. fd = -1;
  232. if (3 == s[0])
  233. fd = xopen(queue, O_RDWR | O_APPEND);
  234. }
  235. // signal OK
  236. safe_write(STDOUT_FILENO, "", 1);
  237. // copy the file
  238. real_len = bb_copyfd_size(STDIN_FILENO, fd, expected_len);
  239. if (real_len != expected_len) {
  240. printf("Expected %d but got %d bytes\n",
  241. expected_len, real_len);
  242. goto err_exit;
  243. }
  244. // get EOF indicator, see whether it is NUL (ok)
  245. // (and don't trash s[0]!)
  246. if (safe_read(STDIN_FILENO, &s[1], 1) != 1 || s[1] != 0) {
  247. // don't send error msg to peer - it obviously
  248. // doesn't follow the protocol, so probably
  249. // it can't understand us either
  250. goto err_exit;
  251. }
  252. if (spooling) {
  253. // chmod completely downloaded file as "readable+writable"
  254. fchmod(fd, 0600);
  255. // accumulate dump state
  256. // N.B. after all files are dumped spooling should be 1+2+4==7
  257. spooling |= (1 << (s[0]-1)); // bit 1: ctrlfile; bit 2: datafile
  258. }
  259. free(s);
  260. close(fd); // NB: can do close(-1). Who cares?
  261. // NB: don't do "signal OK" write here, it will be done
  262. // at the top of the loop
  263. } // while (1)
  264. err_exit:
  265. // don't keep corrupted files
  266. if (spooling) {
  267. #define i spooling
  268. for (i = 2; --i >= 0; )
  269. if (filenames[i])
  270. unlink(filenames[i]);
  271. }
  272. return EXIT_FAILURE;
  273. }