]> git.ipfire.org Git - thirdparty/cups.git/blob - backend/socket.c
Merge changes from CUPS 1.5svn-r8849.
[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-2009 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 scheme[255], /* Scheme 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 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 int snmp_fd, /* SNMP socket */
89 start_count, /* Page count via SNMP at start */
90 page_count, /* Page count via SNMP */
91 have_supplies; /* Printer supports supply levels? */
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 printf("network socket \"Unknown\" \"%s\"\n",
125 _cupsLangString(cupsLangDefault(), _("AppSocket/HP JetDirect")));
126 return (CUPS_BACKEND_OK);
127 }
128 else if (argc < 6 || argc > 7)
129 {
130 _cupsLangPrintf(stderr,
131 _("Usage: %s job-id user title copies options [file]\n"),
132 argv[0]);
133 return (CUPS_BACKEND_FAILED);
134 }
135
136 /*
137 * If we have 7 arguments, print the file named on the command-line.
138 * Otherwise, send stdin instead...
139 */
140
141 if (argc == 6)
142 {
143 print_fd = 0;
144 copies = 1;
145 }
146 else
147 {
148 /*
149 * Try to open the print file...
150 */
151
152 if ((print_fd = open(argv[6], O_RDONLY)) < 0)
153 {
154 _cupsLangPrintf(stderr,
155 _("ERROR: Unable to open print file \"%s\": %s\n"),
156 argv[6], strerror(errno));
157 return (CUPS_BACKEND_FAILED);
158 }
159
160 copies = atoi(argv[4]);
161 }
162
163 /*
164 * Extract the hostname and port number from the URI...
165 */
166
167 if ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
168 return (CUPS_BACKEND_FAILED);
169
170 httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme),
171 username, sizeof(username), 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 start_time = time(NULL);
258
259 sprintf(portname, "%d", port);
260
261 fputs("STATE: +connecting-to-device\n", stderr);
262 fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname);
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", hostname, port);
272 _cupsLangPuts(stderr, _("INFO: Connecting to printer...\n"));
273
274 for (delay = 5;;)
275 {
276 if ((addr = httpAddrConnect(addrlist, &device_fd)) == NULL)
277 {
278 error = errno;
279 device_fd = -1;
280
281 if (getenv("CLASS") != NULL)
282 {
283 /*
284 * If the CLASS environment variable is set, the job was submitted
285 * to a class and not to a specific queue. In this case, we want
286 * to abort immediately so that the job can be requeued on the next
287 * available printer in the class.
288 */
289
290 _cupsLangPuts(stderr,
291 _("INFO: Unable to contact printer, queuing on next "
292 "printer in class...\n"));
293
294 /*
295 * Sleep 5 seconds to keep the job from requeuing too rapidly...
296 */
297
298 sleep(5);
299
300 return (CUPS_BACKEND_FAILED);
301 }
302
303 if (error == ECONNREFUSED || error == EHOSTDOWN ||
304 error == EHOSTUNREACH)
305 {
306 if (contimeout && (time(NULL) - start_time) > contimeout)
307 {
308 _cupsLangPuts(stderr, _("ERROR: Printer not responding\n"));
309 return (CUPS_BACKEND_FAILED);
310 }
311
312 _cupsLangPrintf(stderr,
313 _("WARNING: Network host \'%s\' is busy; will retry in "
314 "%d seconds...\n"), hostname, delay);
315
316 sleep(delay);
317
318 if (delay < 30)
319 delay += 5;
320 }
321 else
322 {
323 _cupsLangPrintf(stderr, "DEBUG: Connection error: %s\n",
324 strerror(errno));
325 _cupsLangPuts(stderr,
326 _("ERROR: Unable to connect to printer; will retry in 30 "
327 "seconds...\n"));
328 sleep(30);
329 }
330 }
331 else
332 break;
333 }
334
335 fputs("STATE: -connecting-to-device\n", stderr);
336 _cupsLangPuts(stderr, _("INFO: Connected to printer...\n"));
337
338 #ifdef AF_INET6
339 if (addr->addr.addr.sa_family == AF_INET6)
340 fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6)...\n",
341 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
342 ntohs(addr->addr.ipv6.sin6_port));
343 else
344 #endif /* AF_INET6 */
345 if (addr->addr.addr.sa_family == AF_INET)
346 fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4)...\n",
347 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
348 ntohs(addr->addr.ipv4.sin_port));
349
350 /*
351 * See if the printer supports SNMP...
352 */
353
354 if ((snmp_fd = _cupsSNMPOpen(addr->addr.addr.sa_family)) >= 0)
355 {
356 have_supplies = !backendSNMPSupplies(snmp_fd, &(addr->addr), &start_count,
357 NULL);
358 }
359 else
360 have_supplies = start_count = 0;
361
362 /*
363 * Print everything...
364 */
365
366 tbytes = 0;
367
368 while (copies > 0 && tbytes >= 0)
369 {
370 copies --;
371
372 if (print_fd != 0)
373 {
374 fputs("PAGE: 1 1\n", stderr);
375 lseek(print_fd, 0, SEEK_SET);
376 }
377
378 tbytes = backendRunLoop(print_fd, device_fd, snmp_fd, &(addr->addr), 1,
379 backendNetworkSideCB);
380
381 if (print_fd != 0 && tbytes >= 0)
382 _cupsLangPrintf(stderr,
383 #ifdef HAVE_LONG_LONG
384 _("INFO: Sent print file, %lld bytes...\n"),
385 #else
386 _("INFO: Sent print file, %ld bytes...\n"),
387 #endif /* HAVE_LONG_LONG */
388 CUPS_LLCAST tbytes);
389 }
390
391 /*
392 * Wait up to 5 seconds to get any pending back-channel data...
393 */
394
395 wait_time = time(NULL) + 5;
396 while (wait_time >= time(&current_time))
397 if (wait_bc(device_fd, wait_time - current_time) <= 0)
398 break;
399
400 if (waiteof)
401 {
402 /*
403 * Shutdown the socket and wait for the other end to finish...
404 */
405
406 _cupsLangPuts(stderr,
407 _("INFO: Print file sent, waiting for printer to finish...\n"));
408
409 shutdown(device_fd, 1);
410
411 while (wait_bc(device_fd, 90) > 0);
412 }
413
414 /*
415 * Collect the final page count as needed...
416 */
417
418 if (have_supplies &&
419 !backendSNMPSupplies(snmp_fd, &(addr->addr), &page_count, NULL) &&
420 page_count > start_count)
421 fprintf(stderr, "PAGE: total %d\n", page_count - start_count);
422
423 /*
424 * Close the socket connection...
425 */
426
427 close(device_fd);
428
429 httpAddrFreeList(addrlist);
430
431 /*
432 * Close the input file and return...
433 */
434
435 if (print_fd != 0)
436 close(print_fd);
437
438 if (tbytes >= 0)
439 _cupsLangPuts(stderr, _("INFO: Ready to print.\n"));
440
441 return (tbytes < 0 ? CUPS_BACKEND_FAILED : CUPS_BACKEND_OK);
442 }
443
444
445 /*
446 * 'wait_bc()' - Wait for back-channel data...
447 */
448
449 static int /* O - # bytes read or -1 on error */
450 wait_bc(int device_fd, /* I - Socket */
451 int secs) /* I - Seconds to wait */
452 {
453 struct timeval timeout; /* Timeout for select() */
454 fd_set input; /* Input set for select() */
455 ssize_t bytes; /* Number of back-channel bytes read */
456 char buffer[1024]; /* Back-channel buffer */
457
458
459 /*
460 * Wait up to "secs" seconds for backchannel data...
461 */
462
463 timeout.tv_sec = secs;
464 timeout.tv_usec = 0;
465
466 FD_ZERO(&input);
467 FD_SET(device_fd, &input);
468
469 if (select(device_fd + 1, &input, NULL, NULL, &timeout) > 0)
470 {
471 /*
472 * Grab the data coming back and spit it out to stderr...
473 */
474
475 if ((bytes = read(device_fd, buffer, sizeof(buffer))) > 0)
476 {
477 fprintf(stderr, "DEBUG: Received %d bytes of back-channel data\n",
478 (int)bytes);
479 cupsBackChannelWrite(buffer, bytes, 1.0);
480 }
481
482 return (bytes);
483 }
484 else
485 return (-1);
486 }
487
488
489 /*
490 * End of "$Id: socket.c 7881 2008-08-28 20:21:56Z mike $".
491 */