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