lpd.c 8.1 KB

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