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