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