3
0

lpd.c 8.6 KB

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