]> git.ipfire.org Git - thirdparty/cups.git/blob - backend/socket.c
Load cups into easysw/current.
[thirdparty/cups.git] / backend / socket.c
1 /*
2 * "$Id: socket.c 6649 2007-07-11 21:46:42Z mike $"
3 *
4 * AppSocket backend for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 2007 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * "LICENSE" which should have been included with this file. If this
13 * file is missing or damaged, see the license at "http://www.cups.org/".
14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 *
17 * Contents:
18 *
19 * main() - Send a file to the printer or server.
20 * side_cb() - Handle side-channel requests...
21 * wait_bc() - Wait for back-channel data...
22 */
23
24 /*
25 * Include necessary headers.
26 */
27
28 #include <cups/http-private.h>
29 #include "backend-private.h"
30 #include <stdarg.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33
34 #ifdef WIN32
35 # include <winsock.h>
36 #else
37 # include <unistd.h>
38 # include <fcntl.h>
39 # include <sys/socket.h>
40 # include <netinet/in.h>
41 # include <arpa/inet.h>
42 # include <netdb.h>
43 #endif /* WIN32 */
44
45
46 /*
47 * Local functions...
48 */
49
50 static void side_cb(int print_fd, int device_fd, int use_bc);
51 static int wait_bc(int device_fd, int secs);
52
53
54 /*
55 * 'main()' - Send a file to the printer or server.
56 *
57 * Usage:
58 *
59 * printer-uri job-id user title copies options [file]
60 */
61
62 int /* O - Exit status */
63 main(int argc, /* I - Number of command-line arguments (6 or 7) */
64 char *argv[]) /* I - Command-line arguments */
65 {
66 char method[255], /* Method in URI */
67 hostname[1024], /* Hostname */
68 username[255], /* Username info (not used) */
69 resource[1024], /* Resource info (not used) */
70 *options, /* Pointer to options */
71 name[255], /* Name of option */
72 value[255], /* Value of option */
73 *ptr; /* Pointer into name or value */
74 int print_fd; /* Print file */
75 int copies; /* Number of copies to print */
76 time_t start_time; /* Time of first connect */
77 int recoverable; /* Recoverable error shown? */
78 int contimeout; /* Connection timeout */
79 int waiteof; /* Wait for end-of-file? */
80 int port; /* Port number */
81 char portname[255]; /* Port name */
82 int delay; /* Delay for retries... */
83 int device_fd; /* AppSocket */
84 int error; /* Error code (if any) */
85 http_addrlist_t *addrlist, /* Address list */
86 *addr; /* Connected address */
87 char addrname[256]; /* Address name */
88 ssize_t tbytes; /* Total number of bytes written */
89 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
90 struct sigaction action; /* Actions for POSIX signals */
91 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
92
93
94 /*
95 * Make sure status messages are not buffered...
96 */
97
98 setbuf(stderr, NULL);
99
100 /*
101 * Ignore SIGPIPE signals...
102 */
103
104 #ifdef HAVE_SIGSET
105 sigset(SIGPIPE, SIG_IGN);
106 #elif defined(HAVE_SIGACTION)
107 memset(&action, 0, sizeof(action));
108 action.sa_handler = SIG_IGN;
109 sigaction(SIGPIPE, &action, NULL);
110 #else
111 signal(SIGPIPE, SIG_IGN);
112 #endif /* HAVE_SIGSET */
113
114 /*
115 * Check command-line...
116 */
117
118 if (argc == 1)
119 {
120 puts("network socket \"Unknown\" \"AppSocket/HP JetDirect\"");
121 return (CUPS_BACKEND_OK);
122 }
123 else if (argc < 6 || argc > 7)
124 {
125 fprintf(stderr, _("Usage: %s job-id user title copies options [file]\n"),
126 argv[0]);
127 return (CUPS_BACKEND_FAILED);
128 }
129
130 /*
131 * If we have 7 arguments, print the file named on the command-line.
132 * Otherwise, send stdin instead...
133 */
134
135 if (argc == 6)
136 {
137 print_fd = 0;
138 copies = 1;
139 }
140 else
141 {
142 /*
143 * Try to open the print file...
144 */
145
146 if ((print_fd = open(argv[6], O_RDONLY)) < 0)
147 {
148 perror("ERROR: unable to open print file");
149 return (CUPS_BACKEND_FAILED);
150 }
151
152 copies = atoi(argv[4]);
153 }
154
155 /*
156 * Extract the hostname and port number from the URI...
157 */
158
159 httpSeparateURI(HTTP_URI_CODING_ALL, cupsBackendDeviceURI(argv),
160 method, sizeof(method), username, sizeof(username),
161 hostname, sizeof(hostname), &port,
162 resource, sizeof(resource));
163
164 if (port == 0)
165 port = 9100; /* Default to HP JetDirect/Tektronix PhaserShare */
166
167 /*
168 * Get options, if any...
169 */
170
171 waiteof = 1;
172 contimeout = 7 * 24 * 60 * 60;
173
174 if ((options = strchr(resource, '?')) != NULL)
175 {
176 /*
177 * Yup, terminate the device name string and move to the first
178 * character of the options...
179 */
180
181 *options++ = '\0';
182
183 /*
184 * Parse options...
185 */
186
187 while (*options)
188 {
189 /*
190 * Get the name...
191 */
192
193 for (ptr = name; *options && *options != '=';)
194 if (ptr < (name + sizeof(name) - 1))
195 *ptr++ = *options++;
196 *ptr = '\0';
197
198 if (*options == '=')
199 {
200 /*
201 * Get the value...
202 */
203
204 options ++;
205
206 for (ptr = value; *options && *options != '+' && *options != '&';)
207 if (ptr < (value + sizeof(value) - 1))
208 *ptr++ = *options++;
209 *ptr = '\0';
210
211 if (*options == '+' || *options == '&')
212 options ++;
213 }
214 else
215 value[0] = '\0';
216
217 /*
218 * Process the option...
219 */
220
221 if (!strcasecmp(name, "waiteof"))
222 {
223 /*
224 * Set the wait-for-eof value...
225 */
226
227 waiteof = !value[0] || !strcasecmp(value, "on") ||
228 !strcasecmp(value, "yes") || !strcasecmp(value, "true");
229 }
230 else if (!strcasecmp(name, "contimeout"))
231 {
232 /*
233 * Set the connection timeout...
234 */
235
236 if (atoi(value) > 0)
237 contimeout = atoi(value);
238 }
239 }
240 }
241
242 /*
243 * Then try to connect to the remote host...
244 */
245
246 recoverable = 0;
247 start_time = time(NULL);
248
249 sprintf(portname, "%d", port);
250
251 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
252 {
253 fprintf(stderr, _("ERROR: Unable to locate printer \'%s\'!\n"), hostname);
254 return (CUPS_BACKEND_STOP);
255 }
256
257 fprintf(stderr, _("INFO: Attempting to connect to host %s on port %d\n"),
258 hostname, port);
259
260 fputs("STATE: +connecting-to-device\n", stderr);
261
262 for (delay = 5;;)
263 {
264 if ((addr = httpAddrConnect(addrlist, &device_fd)) == NULL)
265 {
266 error = errno;
267 device_fd = -1;
268
269 if (getenv("CLASS") != NULL)
270 {
271 /*
272 * If the CLASS environment variable is set, the job was submitted
273 * to a class and not to a specific queue. In this case, we want
274 * to abort immediately so that the job can be requeued on the next
275 * available printer in the class.
276 */
277
278 fputs(_("INFO: Unable to contact printer, queuing on next "
279 "printer in class...\n"), stderr);
280
281 /*
282 * Sleep 5 seconds to keep the job from requeuing too rapidly...
283 */
284
285 sleep(5);
286
287 return (CUPS_BACKEND_FAILED);
288 }
289
290 if (error == ECONNREFUSED || error == EHOSTDOWN ||
291 error == EHOSTUNREACH)
292 {
293 if (contimeout && (time(NULL) - start_time) > contimeout)
294 {
295 fputs(_("ERROR: Printer not responding!\n"), stderr);
296 return (CUPS_BACKEND_FAILED);
297 }
298
299 recoverable = 1;
300
301 fprintf(stderr,
302 _("WARNING: recoverable: Network host \'%s\' is busy; will "
303 "retry in %d seconds...\n"),
304 hostname, delay);
305
306 sleep(delay);
307
308 if (delay < 30)
309 delay += 5;
310 }
311 else
312 {
313 recoverable = 1;
314
315 fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(errno));
316 fputs(_("ERROR: recoverable: Unable to connect to printer; will "
317 "retry in 30 seconds...\n"), stderr);
318 sleep(30);
319 }
320 }
321 else
322 break;
323 }
324
325 if (recoverable)
326 {
327 /*
328 * If we've shown a recoverable error make sure the printer proxies
329 * have a chance to see the recovered message. Not pretty but
330 * necessary for now...
331 */
332
333 fputs("INFO: recovered: \n", stderr);
334 sleep(5);
335 }
336
337 fputs("STATE: -connecting-to-device\n", stderr);
338 fprintf(stderr, _("INFO: Connected to %s...\n"), hostname);
339
340 #ifdef AF_INET6
341 if (addr->addr.addr.sa_family == AF_INET6)
342 fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6)...\n",
343 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
344 ntohs(addr->addr.ipv6.sin6_port));
345 else
346 #endif /* AF_INET6 */
347 if (addr->addr.addr.sa_family == AF_INET)
348 fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4)...\n",
349 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
350 ntohs(addr->addr.ipv4.sin_port));
351
352 /*
353 * Print everything...
354 */
355
356 tbytes = 0;
357
358 while (copies > 0 && tbytes >= 0)
359 {
360 copies --;
361
362 if (print_fd != 0)
363 {
364 fputs("PAGE: 1 1\n", stderr);
365 lseek(print_fd, 0, SEEK_SET);
366 }
367
368 tbytes = backendRunLoop(print_fd, device_fd, 1, side_cb);
369
370 if (print_fd != 0 && tbytes >= 0)
371 fprintf(stderr,
372 #ifdef HAVE_LONG_LONG
373 _("INFO: Sent print file, %lld bytes...\n"),
374 #else
375 _("INFO: Sent print file, %ld bytes...\n"),
376 #endif /* HAVE_LONG_LONG */
377 CUPS_LLCAST tbytes);
378 }
379
380 /*
381 * Get any pending back-channel data...
382 */
383
384 while (wait_bc(device_fd, 5) > 0);
385
386 if (waiteof)
387 {
388 /*
389 * Shutdown the socket and wait for the other end to finish...
390 */
391
392 fputs(_("INFO: Print file sent, waiting for printer to finish...\n"),
393 stderr);
394
395 shutdown(device_fd, 1);
396
397 while (wait_bc(device_fd, 90) > 0);
398 }
399
400 /*
401 * Close the socket connection...
402 */
403
404 close(device_fd);
405
406 httpAddrFreeList(addrlist);
407
408 /*
409 * Close the input file and return...
410 */
411
412 if (print_fd != 0)
413 close(print_fd);
414
415 if (tbytes >= 0)
416 fputs(_("INFO: Ready to print.\n"), stderr);
417
418 return (tbytes < 0 ? CUPS_BACKEND_FAILED : CUPS_BACKEND_OK);
419 }
420
421
422 /*
423 * 'side_cb()' - Handle side-channel requests...
424 */
425
426 static void
427 side_cb(int print_fd, /* I - Print file */
428 int device_fd, /* I - Device file */
429 int use_bc) /* I - Using back-channel? */
430 {
431 cups_sc_command_t command; /* Request command */
432 cups_sc_status_t status; /* Request/response status */
433 char data[2048]; /* Request/response data */
434 int datalen; /* Request/response data size */
435
436
437 datalen = sizeof(data);
438
439 if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
440 {
441 fputs(_("WARNING: Failed to read side-channel request!\n"), stderr);
442 return;
443 }
444
445 switch (command)
446 {
447 case CUPS_SC_CMD_DRAIN_OUTPUT :
448 /*
449 * Our sockets disable the Nagle algorithm and data is sent immediately.
450 */
451
452 if (backendDrainOutput(print_fd, device_fd))
453 status = CUPS_SC_STATUS_IO_ERROR;
454 else
455 status = CUPS_SC_STATUS_OK;
456
457 datalen = 0;
458 break;
459
460 case CUPS_SC_CMD_GET_BIDI :
461 data[0] = use_bc;
462 datalen = 1;
463 break;
464
465 default :
466 status = CUPS_SC_STATUS_NOT_IMPLEMENTED;
467 datalen = 0;
468 break;
469 }
470
471 cupsSideChannelWrite(command, status, data, datalen, 1.0);
472 }
473
474
475 /*
476 * 'wait_bc()' - Wait for back-channel data...
477 */
478
479 static int /* O - # bytes read or -1 on error */
480 wait_bc(int device_fd, /* I - Socket */
481 int secs) /* I - Seconds to wait */
482 {
483 struct timeval timeout; /* Timeout for select() */
484 fd_set input; /* Input set for select() */
485 ssize_t bytes; /* Number of back-channel bytes read */
486 char buffer[1024]; /* Back-channel buffer */
487
488
489 /*
490 * Wait up to "secs" seconds for backchannel data...
491 */
492
493 timeout.tv_sec = secs;
494 timeout.tv_usec = 0;
495
496 FD_ZERO(&input);
497 FD_SET(device_fd, &input);
498
499 if (select(device_fd + 1, &input, NULL, NULL, &timeout) > 0)
500 {
501 /*
502 * Grab the data coming back and spit it out to stderr...
503 */
504
505 if ((bytes = read(device_fd, buffer, sizeof(buffer))) > 0)
506 {
507 fprintf(stderr, "DEBUG: Received %d bytes of back-channel data!\n",
508 (int)bytes);
509 cupsBackChannelWrite(buffer, bytes, 1.0);
510 }
511
512 return (bytes);
513 }
514 else
515 return (-1);
516 }
517
518
519 /*
520 * End of "$Id: socket.c 6649 2007-07-11 21:46:42Z mike $".
521 */