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