]> git.ipfire.org Git - thirdparty/cups.git/blob - backend/socket.c
66bc529216fe751929ed80e9ac4f119d77022427
[thirdparty/cups.git] / backend / socket.c
1 /*
2 * "$Id: socket.c 6910 2007-09-04 20:34:29Z mike $"
3 *
4 * AppSocket backend for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 2007-2008 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, /* Name of option */
72 *value, /* Value of option */
73 sep; /* Option separator */
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 _cupsLangPrintf(stderr,
126 _("Usage: %s job-id user title copies options [file]\n"),
127 argv[0]);
128 return (CUPS_BACKEND_FAILED);
129 }
130
131 /*
132 * If we have 7 arguments, print the file named on the command-line.
133 * Otherwise, send stdin instead...
134 */
135
136 if (argc == 6)
137 {
138 print_fd = 0;
139 copies = 1;
140 }
141 else
142 {
143 /*
144 * Try to open the print file...
145 */
146
147 if ((print_fd = open(argv[6], O_RDONLY)) < 0)
148 {
149 _cupsLangPrintf(stderr,
150 _("ERROR: Unable to open print file \"%s\": %s\n"),
151 argv[6], strerror(errno));
152 return (CUPS_BACKEND_FAILED);
153 }
154
155 copies = atoi(argv[4]);
156 }
157
158 /*
159 * Extract the hostname and port number from the URI...
160 */
161
162 httpSeparateURI(HTTP_URI_CODING_ALL, cupsBackendDeviceURI(argv),
163 method, sizeof(method), username, sizeof(username),
164 hostname, sizeof(hostname), &port,
165 resource, sizeof(resource));
166
167 if (port == 0)
168 port = 9100; /* Default to HP JetDirect/Tektronix PhaserShare */
169
170 /*
171 * Get options, if any...
172 */
173
174 waiteof = 1;
175 contimeout = 7 * 24 * 60 * 60;
176
177 if ((options = strchr(resource, '?')) != NULL)
178 {
179 /*
180 * Yup, terminate the device name string and move to the first
181 * character of the options...
182 */
183
184 *options++ = '\0';
185
186 /*
187 * Parse options...
188 */
189
190 while (*options)
191 {
192 /*
193 * Get the name...
194 */
195
196 name = options;
197
198 while (*options && *options != '=' && *options != '+' && *options != '&')
199 options ++;
200
201 if ((sep = *options) != '\0')
202 *options++ = '\0';
203
204 if (sep == '=')
205 {
206 /*
207 * Get the value...
208 */
209
210 value = options;
211
212 while (*options && *options != '+' && *options != '&')
213 options ++;
214
215 if (*options)
216 *options++ = '\0';
217 }
218 else
219 value = (char *)"";
220
221 /*
222 * Process the option...
223 */
224
225 if (!strcasecmp(name, "waiteof"))
226 {
227 /*
228 * Set the wait-for-eof value...
229 */
230
231 waiteof = !value[0] || !strcasecmp(value, "on") ||
232 !strcasecmp(value, "yes") || !strcasecmp(value, "true");
233 }
234 else if (!strcasecmp(name, "contimeout"))
235 {
236 /*
237 * Set the connection timeout...
238 */
239
240 if (atoi(value) > 0)
241 contimeout = atoi(value);
242 }
243 }
244 }
245
246 /*
247 * Then try to connect to the remote host...
248 */
249
250 recoverable = 0;
251 start_time = time(NULL);
252
253 sprintf(portname, "%d", port);
254
255 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
256 {
257 _cupsLangPrintf(stderr, _("ERROR: Unable to locate printer \'%s\'!\n"),
258 hostname);
259 return (CUPS_BACKEND_STOP);
260 }
261
262 _cupsLangPrintf(stderr,
263 _("INFO: Attempting to connect to host %s on port %d\n"),
264 hostname, port);
265
266 fputs("STATE: +connecting-to-device\n", stderr);
267
268 for (delay = 5;;)
269 {
270 if ((addr = httpAddrConnect(addrlist, &device_fd)) == NULL)
271 {
272 error = errno;
273 device_fd = -1;
274
275 if (getenv("CLASS") != NULL)
276 {
277 /*
278 * If the CLASS environment variable is set, the job was submitted
279 * to a class and not to a specific queue. In this case, we want
280 * to abort immediately so that the job can be requeued on the next
281 * available printer in the class.
282 */
283
284 _cupsLangPuts(stderr,
285 _("INFO: Unable to contact printer, queuing on next "
286 "printer in class...\n"));
287
288 /*
289 * Sleep 5 seconds to keep the job from requeuing too rapidly...
290 */
291
292 sleep(5);
293
294 return (CUPS_BACKEND_FAILED);
295 }
296
297 if (error == ECONNREFUSED || error == EHOSTDOWN ||
298 error == EHOSTUNREACH)
299 {
300 if (contimeout && (time(NULL) - start_time) > contimeout)
301 {
302 _cupsLangPuts(stderr, _("ERROR: Printer not responding!\n"));
303 return (CUPS_BACKEND_FAILED);
304 }
305
306 recoverable = 1;
307
308 _cupsLangPrintf(stderr,
309 _("WARNING: recoverable: Network host \'%s\' is busy; "
310 "will retry in %d seconds...\n"),
311 hostname, delay);
312
313 sleep(delay);
314
315 if (delay < 30)
316 delay += 5;
317 }
318 else
319 {
320 recoverable = 1;
321
322 _cupsLangPrintf(stderr, "DEBUG: Connection error: %s\n",
323 strerror(errno));
324 _cupsLangPuts(stderr,
325 _("ERROR: recoverable: Unable to connect to printer; "
326 "will retry in 30 seconds...\n"));
327 sleep(30);
328 }
329 }
330 else
331 break;
332 }
333
334 if (recoverable)
335 {
336 /*
337 * If we've shown a recoverable error make sure the printer proxies
338 * have a chance to see the recovered message. Not pretty but
339 * necessary for now...
340 */
341
342 fputs("INFO: recovered: \n", stderr);
343 sleep(5);
344 }
345
346 fputs("STATE: -connecting-to-device\n", stderr);
347 _cupsLangPrintf(stderr, _("INFO: Connected to %s...\n"), hostname);
348
349 #ifdef AF_INET6
350 if (addr->addr.addr.sa_family == AF_INET6)
351 fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6)...\n",
352 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
353 ntohs(addr->addr.ipv6.sin6_port));
354 else
355 #endif /* AF_INET6 */
356 if (addr->addr.addr.sa_family == AF_INET)
357 fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4)...\n",
358 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
359 ntohs(addr->addr.ipv4.sin_port));
360
361 /*
362 * Print everything...
363 */
364
365 tbytes = 0;
366
367 while (copies > 0 && tbytes >= 0)
368 {
369 copies --;
370
371 if (print_fd != 0)
372 {
373 fputs("PAGE: 1 1\n", stderr);
374 lseek(print_fd, 0, SEEK_SET);
375 }
376
377 tbytes = backendRunLoop(print_fd, device_fd, 1, side_cb);
378
379 if (print_fd != 0 && tbytes >= 0)
380 _cupsLangPrintf(stderr,
381 #ifdef HAVE_LONG_LONG
382 _("INFO: Sent print file, %lld bytes...\n"),
383 #else
384 _("INFO: Sent print file, %ld bytes...\n"),
385 #endif /* HAVE_LONG_LONG */
386 CUPS_LLCAST tbytes);
387 }
388
389 /*
390 * Get any pending back-channel data...
391 */
392
393 while (wait_bc(device_fd, 5) > 0);
394
395 if (waiteof)
396 {
397 /*
398 * Shutdown the socket and wait for the other end to finish...
399 */
400
401 _cupsLangPuts(stderr,
402 _("INFO: Print file sent, waiting for printer to finish...\n"));
403
404 shutdown(device_fd, 1);
405
406 while (wait_bc(device_fd, 90) > 0);
407 }
408
409 /*
410 * Close the socket connection...
411 */
412
413 close(device_fd);
414
415 httpAddrFreeList(addrlist);
416
417 /*
418 * Close the input file and return...
419 */
420
421 if (print_fd != 0)
422 close(print_fd);
423
424 if (tbytes >= 0)
425 _cupsLangPuts(stderr, _("INFO: Ready to print.\n"));
426
427 return (tbytes < 0 ? CUPS_BACKEND_FAILED : CUPS_BACKEND_OK);
428 }
429
430
431 /*
432 * 'side_cb()' - Handle side-channel requests...
433 */
434
435 static void
436 side_cb(int print_fd, /* I - Print file */
437 int device_fd, /* I - Device file */
438 int use_bc) /* I - Using back-channel? */
439 {
440 cups_sc_command_t command; /* Request command */
441 cups_sc_status_t status; /* Request/response status */
442 char data[2048]; /* Request/response data */
443 int datalen; /* Request/response data size */
444 const char *device_id; /* 1284DEVICEID env var */
445
446
447 datalen = sizeof(data);
448
449 if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
450 {
451 _cupsLangPuts(stderr, _("WARNING: Failed to read side-channel request!\n"));
452 return;
453 }
454
455 switch (command)
456 {
457 case CUPS_SC_CMD_DRAIN_OUTPUT :
458 /*
459 * Our sockets disable the Nagle algorithm and data is sent immediately.
460 */
461
462 if (backendDrainOutput(print_fd, device_fd))
463 status = CUPS_SC_STATUS_IO_ERROR;
464 else
465 status = CUPS_SC_STATUS_OK;
466
467 datalen = 0;
468 break;
469
470 case CUPS_SC_CMD_GET_BIDI :
471 data[0] = use_bc;
472 datalen = 1;
473 break;
474
475 case CUPS_SC_CMD_GET_DEVICE_ID :
476 if ((device_id = getenv("1284DEVICEID")) != NULL)
477 {
478 strlcpy(data, device_id, sizeof(data));
479 datalen = (int)strlen(data);
480 break;
481 }
482
483 default :
484 status = CUPS_SC_STATUS_NOT_IMPLEMENTED;
485 datalen = 0;
486 break;
487 }
488
489 cupsSideChannelWrite(command, status, data, datalen, 1.0);
490 }
491
492
493 /*
494 * 'wait_bc()' - Wait for back-channel data...
495 */
496
497 static int /* O - # bytes read or -1 on error */
498 wait_bc(int device_fd, /* I - Socket */
499 int secs) /* I - Seconds to wait */
500 {
501 struct timeval timeout; /* Timeout for select() */
502 fd_set input; /* Input set for select() */
503 ssize_t bytes; /* Number of back-channel bytes read */
504 char buffer[1024]; /* Back-channel buffer */
505
506
507 /*
508 * Wait up to "secs" seconds for backchannel data...
509 */
510
511 timeout.tv_sec = secs;
512 timeout.tv_usec = 0;
513
514 FD_ZERO(&input);
515 FD_SET(device_fd, &input);
516
517 if (select(device_fd + 1, &input, NULL, NULL, &timeout) > 0)
518 {
519 /*
520 * Grab the data coming back and spit it out to stderr...
521 */
522
523 if ((bytes = read(device_fd, buffer, sizeof(buffer))) > 0)
524 {
525 fprintf(stderr, "DEBUG: Received %d bytes of back-channel data!\n",
526 (int)bytes);
527 cupsBackChannelWrite(buffer, bytes, 1.0);
528 }
529
530 return (bytes);
531 }
532 else
533 return (-1);
534 }
535
536
537 /*
538 * End of "$Id: socket.c 6910 2007-09-04 20:34:29Z mike $".
539 */