09fbc6ad144fb6c86eed833a3be9e14f62886585
[oweals/busybox.git] / printutils / lpr.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * bare bones version of lpr & lpq: BSD printing utilities
4  *
5  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6  *
7  * Original idea and code:
8  *      Walter Harms <WHarms@bfs.de>
9  *
10  * Licensed under GPLv2, see file LICENSE in this tarball for details.
11  *
12  * See RFC 1179 for protocol description.
13  */
14 #include "libbb.h"
15
16 /*
17  * LPD returns binary 0 on success.
18  * Otherwise it returns error message.
19  */
20 static void get_response_or_say_and_die(const char *errmsg)
21 {
22         ssize_t sz;
23         char buf[128];
24
25         fflush(stdout);
26
27         buf[0] = ' ';
28         sz = safe_read(STDOUT_FILENO, buf, 1);
29         if ('\0' != buf[0]) {
30                 // request has failed
31                 // try to make sure last char is '\n', but do not add
32                 // superfluous one
33                 sz = full_read(STDOUT_FILENO, buf + 1, 126);
34                 bb_error_msg("error while %s%s", errmsg,
35                                 (sz > 0 ? ". Server said:" : ""));
36                 if (sz > 0) {
37                         // sz = (bytes in buf) - 1
38                         if (buf[sz] != '\n')
39                                 buf[++sz] = '\n';
40                         safe_write(STDERR_FILENO, buf, sz + 1);
41                 }
42                 xfunc_die();
43         }
44 }
45
46 int lpqr_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
47 int lpqr_main(int argc, char *argv[])
48 {
49         enum {
50                 OPT_P           = 1 << 0, // -P queue[@host[:port]]. If no -P is given use $PRINTER, then "lp@localhost:515"
51                 OPT_U           = 1 << 1, // -U username
52
53                 LPR_V           = 1 << 2, // -V: be verbose
54                 LPR_h           = 1 << 3, // -h: want banner printed    
55                 LPR_C           = 1 << 4, // -C class: job "class" (? supposedly printed on banner)
56                 LPR_J           = 1 << 5, // -J title: the job title for the banner page
57                 LPR_m           = 1 << 6, // -m: send mail back to user
58
59                 LPQ_SHORT_FMT   = 1 << 2, // -s: short listing format
60                 LPQ_DELETE      = 1 << 3, // -d: delete job(s)
61                 LPQ_FORCE       = 1 << 4, // -f: force waiting job(s) to be printed
62         };
63         char tempfile[sizeof("/tmp/lprXXXXXX")];
64         const char *job_title;
65         const char *printer_class = "";   // printer class, max 32 char
66         const char *queue;                // name of printer queue
67         const char *server = "localhost"; // server[:port] of printer queue
68         char *hostname;
69         // N.B. IMHO getenv("USER") can be way easily spoofed!
70         const char *user = bb_getpwuid(NULL, -1, getuid());
71         unsigned job;
72         unsigned opts;
73         int old_stdout, fd;
74
75         // parse options
76         // TODO: set opt_complementary: s,d,f are mutually exclusive
77         opts = getopt32(argv,
78                 (/*lp*/'r' == applet_name[2]) ? "P:U:VhC:J:m" : "P:U:sdf"
79                 , &queue, &user
80                 , &printer_class, &job_title
81         );
82         argv += optind;
83
84         // if queue is not specified -> use $PRINTER
85         if (!(opts & OPT_P))
86                 queue = getenv("PRINTER");
87         // if queue is still not specified ->
88         if (!queue) {
89                 // ... queue defaults to "lp"
90                 // server defaults to "localhost"
91                 queue = "lp";
92         // if queue is specified ->
93         } else {
94                 // queue name is to the left of '@'
95                 char *s = strchr(queue, '@');
96                 if (s) {
97                         // server name is to the right of '@'
98                         *s = '\0';
99                         server = s + 1;
100                 }
101         }
102
103         // do connect
104         fd = create_and_connect_stream_or_die(server, 515);
105         // play with descriptors to save space: fdprintf > printf
106         old_stdout = dup(STDOUT_FILENO);
107         xmove_fd(fd, STDOUT_FILENO);
108
109         //
110         // LPQ ------------------------
111         //
112         if (/*lp*/'q' == applet_name[2]) {
113                 char cmd;
114                 // force printing of every job still in queue
115                 if (opts & LPQ_FORCE) {
116                         cmd = 1;
117                         goto command;
118                 // delete job(s)
119                 } else if (opts & LPQ_DELETE) {
120                         printf("\x5" "%s %s", queue, user);
121                         while (*argv) {
122                                 printf(" %s", *argv++);
123                         }
124                         bb_putchar('\n');
125                 // dump current jobs status
126                 // N.B. periodical polling should be achieved
127                 // via "watch -n delay lpq"
128                 // They say it's the UNIX-way :)
129                 } else {
130                         cmd = (opts & LPQ_SHORT_FMT) ? 3 : 4;
131  command:
132                         printf("%c" "%s\n", cmd, queue);
133                         bb_copyfd_eof(STDOUT_FILENO, old_stdout);
134                 }
135
136                 return EXIT_SUCCESS;
137         }
138
139         //
140         // LPR ------------------------
141         //
142         if (opts & LPR_V)
143                 bb_error_msg("connected to server");
144
145         job = getpid() % 1000;
146         // TODO: when do finally we invent char *xgethostname()?!!
147         hostname = xzalloc(MAXHOSTNAMELEN+1);
148         gethostname(hostname, MAXHOSTNAMELEN);
149
150         // no files given on command line? -> use stdin
151         if (!*argv)
152                 *--argv = (char *)"-";
153
154         printf("\x2" "%s\n", queue);
155         get_response_or_say_and_die("setting queue");
156
157         // process files
158         do {
159                 struct stat st;
160                 char *c;
161                 char *remote_filename;
162                 char *controlfile;
163
164                 // if data file is stdin, we need to dump it first
165                 if (LONE_DASH(*argv)) {
166                         strcpy(tempfile, "/tmp/lprXXXXXX");
167                         fd = mkstemp(tempfile);
168                         if (fd < 0)
169                                 bb_perror_msg_and_die("mkstemp");
170                         bb_copyfd_eof(STDIN_FILENO, fd);
171                         xlseek(fd, 0, SEEK_SET);
172                         *argv = (char*)bb_msg_standard_input;
173                 } else {
174                         fd = xopen(*argv, O_RDONLY);
175                 }
176
177                 /* "The name ... should start with ASCII "cfA",
178                  * followed by a three digit job number, followed
179                  * by the host name which has constructed the file."
180                  * We supply 'c' or 'd' as needed for control/data file. */
181                 remote_filename = xasprintf("fA%03u%s", job, hostname);
182
183                 // create control file
184                 // TODO: all lines but 2 last are constants! How we can use this fact?
185                 controlfile = xasprintf(
186                         "H" "%.32s\n" "P" "%.32s\n" /* H HOST, P USER */
187                         "C" "%.32s\n" /* C CLASS - printed on banner page (if L cmd is also given) */
188                         "J" "%.99s\n" /* J JOBNAME */
189                         /* "class name for banner page and job name
190                          * for banner page commands must precede L command" */
191                         "L" "%.32s\n" /* L USER - print banner page, with given user's name */
192                         "M" "%.32s\n" /* M WHOM_TO_MAIL */
193                         "l" "d%.31s\n" /* l DATA_FILE_NAME ("dfAxxx") */
194                         , hostname, user
195                         , printer_class /* can be "" */
196                         , ((opts & LPR_J) ? job_title : *argv)
197                         , (opts & LPR_h) ? user : ""
198                         , (opts & LPR_m) ? user : ""
199                         , remote_filename
200                 );
201                 // delete possible "\nX\n" patterns
202                 c = controlfile;
203                 while ((c = strchr(c, '\n')) != NULL) {
204                         c++;
205                         while (c[0] && c[1] == '\n')
206                                 memmove(c, c+2, strlen(c+1)); /* strlen(c+1) == strlen(c+2) + 1 */
207                 }
208
209                 // send control file
210                 if (opts & LPR_V)
211                         bb_error_msg("sending control file");
212                 /* "Once all of the contents have
213                  * been delivered, an octet of zero bits is sent as
214                  * an indication that the file being sent is complete.
215                  * A second level of acknowledgement processing
216                  * must occur at this point." */
217                 printf("\x2" "%u c%s\n" "%s" "%c",
218                                 (unsigned)strlen(controlfile),
219                                 remote_filename, controlfile, '\0');
220                 get_response_or_say_and_die("sending control file");
221
222                 // send data file, with name "dfaXXX"
223                 if (opts & LPR_V)
224                         bb_error_msg("sending data file");
225                 st.st_size = 0; /* paranoia: fstat may theoretically fail */
226                 fstat(fd, &st);
227                 printf("\x3" "%"OFF_FMT"u d%s\n", st.st_size, remote_filename);
228                 if (bb_copyfd_size(fd, STDOUT_FILENO, st.st_size) != st.st_size) {
229                         // We're screwed. We sent less bytes than we advertised.
230                         bb_error_msg_and_die("local file changed size?!");
231                 }
232                 bb_putchar('\0');
233                 get_response_or_say_and_die("sending data file");
234
235                 // delete temporary file if we dumped stdin
236                 if (*argv == (char*)bb_msg_standard_input)
237                         unlink(tempfile);
238
239                 // cleanup
240                 close(fd);
241                 free(remote_filename);
242                 free(controlfile);
243
244                 // next, please!
245                 job = (job + 1) % 1000;
246         } while (*++argv);
247
248         return EXIT_SUCCESS;
249 }