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