]> git.ipfire.org Git - thirdparty/cups.git/blob - backend/socket.c
d7f98d9b07872c4cc9d39334e957b5036fb3f9d6
[thirdparty/cups.git] / backend / socket.c
1 /*
2 * "$Id$"
3 *
4 * AppSocket backend for CUPS.
5 *
6 * Copyright 2007-2014 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
18 /*
19 * Include necessary headers.
20 */
21
22 #include <cups/http-private.h>
23 #include "backend-private.h"
24 #include <stdarg.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27
28 #ifdef WIN32
29 # include <winsock.h>
30 #else
31 # include <unistd.h>
32 # include <fcntl.h>
33 # include <sys/socket.h>
34 # include <netinet/in.h>
35 # include <arpa/inet.h>
36 # include <netdb.h>
37 #endif /* WIN32 */
38
39
40 /*
41 * Local functions...
42 */
43
44 static ssize_t wait_bc(int device_fd, int secs);
45
46
47 /*
48 * 'main()' - Send a file to the printer or server.
49 *
50 * Usage:
51 *
52 * printer-uri job-id user title copies options [file]
53 */
54
55 int /* O - Exit status */
56 main(int argc, /* I - Number of command-line arguments (6 or 7) */
57 char *argv[]) /* I - Command-line arguments */
58 {
59 const char *device_uri; /* Device URI */
60 char scheme[255], /* Scheme in URI */
61 hostname[1024], /* Hostname */
62 username[255], /* Username info (not used) */
63 resource[1024], /* Resource info (not used) */
64 *options, /* Pointer to options */
65 *name, /* Name of option */
66 *value, /* Value of option */
67 sep; /* Option separator */
68 int print_fd; /* Print file */
69 int copies; /* Number of copies to print */
70 time_t start_time; /* Time of first connect */
71 int contimeout; /* Connection timeout */
72 int waiteof; /* Wait for end-of-file? */
73 int port; /* Port number */
74 char portname[255]; /* Port name */
75 int delay; /* Delay for retries... */
76 int device_fd; /* AppSocket */
77 int error; /* Error code (if any) */
78 http_addrlist_t *addrlist, /* Address list */
79 *addr; /* Connected address */
80 char addrname[256]; /* Address name */
81 int snmp_enabled = 1; /* Is SNMP enabled? */
82 int snmp_fd, /* SNMP socket */
83 start_count, /* Page count via SNMP at start */
84 page_count, /* Page count via SNMP */
85 have_supplies; /* Printer supports supply levels? */
86 ssize_t bytes = 0, /* Initial bytes read */
87 tbytes; /* Total number of bytes written */
88 char buffer[1024]; /* Initial print buffer */
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 printf("network socket \"Unknown\" \"%s\"\n",
121 _cupsLangString(cupsLangDefault(), _("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]"),
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 _cupsLangPrintError("ERROR", _("Unable to open print file"));
151 return (CUPS_BACKEND_FAILED);
152 }
153
154 copies = atoi(argv[4]);
155 }
156
157 /*
158 * Extract the hostname and port number from the URI...
159 */
160
161 while ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
162 {
163 _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer."));
164 sleep(10);
165
166 if (getenv("CLASS") != NULL)
167 return (CUPS_BACKEND_FAILED);
168 }
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 (!_cups_strcasecmp(name, "waiteof"))
233 {
234 /*
235 * Set the wait-for-eof value...
236 */
237
238 waiteof = !value[0] || !_cups_strcasecmp(value, "on") ||
239 !_cups_strcasecmp(value, "yes") || !_cups_strcasecmp(value, "true");
240 }
241 else if (!_cups_strcasecmp(name, "snmp"))
242 {
243 /*
244 * Enable/disable SNMP stuff...
245 */
246
247 snmp_enabled = !value[0] || !_cups_strcasecmp(value, "on") ||
248 !_cups_strcasecmp(value, "yes") ||
249 !_cups_strcasecmp(value, "true");
250 }
251 else if (!_cups_strcasecmp(name, "contimeout"))
252 {
253 /*
254 * Set the connection timeout...
255 */
256
257 if (atoi(value) > 0)
258 contimeout = atoi(value);
259 }
260 }
261 }
262
263 /*
264 * Then try finding the remote host...
265 */
266
267 start_time = time(NULL);
268
269 sprintf(portname, "%d", port);
270
271 fputs("STATE: +connecting-to-device\n", stderr);
272 fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname);
273
274 while ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
275 {
276 _cupsLangPrintFilter(stderr, "INFO",
277 _("Unable to locate printer \"%s\"."), hostname);
278 sleep(10);
279
280 if (getenv("CLASS") != NULL)
281 {
282 fputs("STATE: -connecting-to-device\n", stderr);
283 return (CUPS_BACKEND_STOP);
284 }
285 }
286
287 /*
288 * See if the printer supports SNMP...
289 */
290
291 if (snmp_enabled)
292 snmp_fd = _cupsSNMPOpen(addrlist->addr.addr.sa_family);
293 else
294 snmp_fd = -1;
295
296 if (snmp_fd >= 0)
297 have_supplies = !backendSNMPSupplies(snmp_fd, &(addrlist->addr),
298 &start_count, NULL);
299 else
300 have_supplies = start_count = 0;
301
302 /*
303 * Wait for data from the filter...
304 */
305
306 if (print_fd == 0)
307 {
308 if (!backendWaitLoop(snmp_fd, &(addrlist->addr), 1, backendNetworkSideCB))
309 return (CUPS_BACKEND_OK);
310 else if ((bytes = read(0, buffer, sizeof(buffer))) <= 0)
311 return (CUPS_BACKEND_OK);
312 }
313
314 /*
315 * Connect to the printer...
316 */
317
318 fprintf(stderr, "DEBUG: Connecting to %s:%d\n", hostname, port);
319 _cupsLangPrintFilter(stderr, "INFO", _("Connecting to printer."));
320
321 for (delay = 5;;)
322 {
323 if ((addr = httpAddrConnect(addrlist, &device_fd)) == NULL)
324 {
325 error = errno;
326 device_fd = -1;
327
328 if (getenv("CLASS") != NULL)
329 {
330 /*
331 * If the CLASS environment variable is set, the job was submitted
332 * to a class and not to a specific queue. In this case, we want
333 * to abort immediately so that the job can be requeued on the next
334 * available printer in the class.
335 */
336
337 _cupsLangPrintFilter(stderr, "INFO",
338 _("Unable to contact printer, queuing on next "
339 "printer in class."));
340
341 /*
342 * Sleep 5 seconds to keep the job from requeuing too rapidly...
343 */
344
345 sleep(5);
346
347 return (CUPS_BACKEND_FAILED);
348 }
349
350 fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(error));
351
352 if (error == ECONNREFUSED || error == EHOSTDOWN ||
353 error == EHOSTUNREACH)
354 {
355 if (contimeout && (time(NULL) - start_time) > contimeout)
356 {
357 _cupsLangPrintFilter(stderr, "ERROR",
358 _("The printer is not responding."));
359 return (CUPS_BACKEND_FAILED);
360 }
361
362 switch (error)
363 {
364 case EHOSTDOWN :
365 _cupsLangPrintFilter(stderr, "WARNING",
366 _("The printer may not exist or "
367 "is unavailable at this time."));
368 break;
369
370 case EHOSTUNREACH :
371 _cupsLangPrintFilter(stderr, "WARNING",
372 _("The printer is unreachable at this "
373 "time."));
374 break;
375
376 case ECONNREFUSED :
377 default :
378 _cupsLangPrintFilter(stderr, "WARNING",
379 _("The printer is in use."));
380 break;
381 }
382
383 sleep((unsigned)delay);
384
385 if (delay < 30)
386 delay += 5;
387 }
388 else
389 {
390 _cupsLangPrintFilter(stderr, "ERROR",
391 _("The printer is not responding."));
392 sleep(30);
393 }
394 }
395 else
396 break;
397 }
398
399 fputs("STATE: -connecting-to-device\n", stderr);
400 _cupsLangPrintFilter(stderr, "INFO", _("Connected to printer."));
401
402 fprintf(stderr, "DEBUG: Connected to %s:%d...\n",
403 httpAddrString(&(addr->addr), addrname, sizeof(addrname)),
404 httpAddrPort(&(addr->addr)));
405
406 /*
407 * Print everything...
408 */
409
410 tbytes = 0;
411
412 if (bytes > 0)
413 tbytes += write(device_fd, buffer, (size_t)bytes);
414
415 while (copies > 0 && tbytes >= 0)
416 {
417 copies --;
418
419 if (print_fd != 0)
420 {
421 fputs("PAGE: 1 1\n", stderr);
422 lseek(print_fd, 0, SEEK_SET);
423 }
424
425 tbytes = backendRunLoop(print_fd, device_fd, snmp_fd, &(addrlist->addr), 1,
426 0, backendNetworkSideCB);
427
428 if (print_fd != 0 && tbytes >= 0)
429 _cupsLangPrintFilter(stderr, "INFO", _("Print file sent."));
430 }
431
432 fputs("STATE: +cups-waiting-for-job-completed\n", stderr);
433
434 if (waiteof)
435 {
436 /*
437 * Shutdown the socket and wait for the other end to finish...
438 */
439
440 _cupsLangPrintFilter(stderr, "INFO", _("Waiting for printer to finish."));
441
442 shutdown(device_fd, 1);
443
444 while (wait_bc(device_fd, 90) > 0);
445 }
446
447 /*
448 * Collect the final page count as needed...
449 */
450
451 if (have_supplies &&
452 !backendSNMPSupplies(snmp_fd, &(addrlist->addr), &page_count, NULL) &&
453 page_count > start_count)
454 fprintf(stderr, "PAGE: total %d\n", page_count - start_count);
455
456 /*
457 * Close the socket connection...
458 */
459
460 close(device_fd);
461
462 httpAddrFreeList(addrlist);
463
464 /*
465 * Close the input file and return...
466 */
467
468 if (print_fd != 0)
469 close(print_fd);
470
471 return (CUPS_BACKEND_OK);
472 }
473
474
475 /*
476 * 'wait_bc()' - Wait for back-channel data...
477 */
478
479 static ssize_t /* O - # bytes read or -1 on error */
480 wait_bc(int device_fd, /* I - Socket */
481 int secs) /* I - Seconds to wait */
482 {
483 struct timeval timeout; /* Timeout for select() */
484 fd_set input; /* Input set for select() */
485 ssize_t bytes; /* Number of back-channel bytes read */
486 char buffer[1024]; /* Back-channel buffer */
487
488
489 /*
490 * Wait up to "secs" seconds for backchannel data...
491 */
492
493 timeout.tv_sec = secs;
494 timeout.tv_usec = 0;
495
496 FD_ZERO(&input);
497 FD_SET(device_fd, &input);
498
499 if (select(device_fd + 1, &input, NULL, NULL, &timeout) > 0)
500 {
501 /*
502 * Grab the data coming back and spit it out to stderr...
503 */
504
505 if ((bytes = read(device_fd, buffer, sizeof(buffer))) > 0)
506 {
507 fprintf(stderr, "DEBUG: Received %d bytes of back-channel data\n",
508 (int)bytes);
509 cupsBackChannelWrite(buffer, (size_t)bytes, 1.0);
510 }
511
512 return (bytes);
513 }
514 else
515 return (-1);
516 }
517
518
519 /*
520 * End of "$Id$".
521 */