]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/dest.c
2affdb22cd57b3152a5d67d1396efd3fd335857c
[thirdparty/cups.git] / cups / dest.c
1 /*
2 * "$Id$"
3 *
4 * User-defined destination (and option) support for CUPS.
5 *
6 * Copyright 2007-2015 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products.
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 * which should have been included with this file. If this file is
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-private.h"
23 #include <sys/stat.h>
24
25 #ifdef HAVE_NOTIFY_H
26 # include <notify.h>
27 #endif /* HAVE_NOTIFY_H */
28
29 #ifdef HAVE_POLL
30 # include <poll.h>
31 #endif /* HAVE_POLL */
32
33 #ifdef HAVE_DNSSD
34 # include <dns_sd.h>
35 #endif /* HAVE_DNSSD */
36
37 #ifdef HAVE_AVAHI
38 # include <avahi-client/client.h>
39 # include <avahi-client/lookup.h>
40 # include <avahi-common/simple-watch.h>
41 # include <avahi-common/domain.h>
42 # include <avahi-common/error.h>
43 # include <avahi-common/malloc.h>
44 #define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
45 #endif /* HAVE_AVAHI */
46
47
48 /*
49 * Constants...
50 */
51
52 #ifdef __APPLE__
53 # include <SystemConfiguration/SystemConfiguration.h>
54 # define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
55 # define kDefaultPaperIDKey CFSTR("DefaultPaperID")
56 # define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
57 # define kLocationNetworkKey CFSTR("Network")
58 # define kLocationPrinterIDKey CFSTR("PrinterID")
59 # define kUseLastPrinter CFSTR("UseLastPrinter")
60 #endif /* __APPLE__ */
61
62
63 /*
64 * Types...
65 */
66
67 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
68 typedef enum _cups_dnssd_state_e /* Enumerated device state */
69 {
70 _CUPS_DNSSD_NEW,
71 _CUPS_DNSSD_QUERY,
72 _CUPS_DNSSD_PENDING,
73 _CUPS_DNSSD_ACTIVE,
74 _CUPS_DNSSD_LOCAL,
75 _CUPS_DNSSD_INCOMPATIBLE,
76 _CUPS_DNSSD_ERROR
77 } _cups_dnssd_state_t;
78
79 typedef struct _cups_dnssd_data_s /* Enumeration data */
80 {
81 # ifdef HAVE_DNSSD
82 DNSServiceRef main_ref; /* Main service reference */
83 # else /* HAVE_AVAHI */
84 AvahiSimplePoll *simple_poll; /* Polling interface */
85 AvahiClient *client; /* Client information */
86 int got_data; /* Did we get data? */
87 # endif /* HAVE_DNSSD */
88 cups_dest_cb_t cb; /* Callback */
89 void *user_data; /* User data pointer */
90 cups_ptype_t type, /* Printer type filter */
91 mask; /* Printer type mask */
92 cups_array_t *devices; /* Devices found so far */
93 } _cups_dnssd_data_t;
94
95 typedef struct _cups_dnssd_device_s /* Enumerated device */
96 {
97 _cups_dnssd_state_t state; /* State of device listing */
98 # ifdef HAVE_DNSSD
99 DNSServiceRef ref; /* Service reference for query */
100 # else /* HAVE_AVAHI */
101 AvahiRecordBrowser *ref; /* Browser for query */
102 # endif /* HAVE_DNSSD */
103 char *domain, /* Domain name */
104 *fullName, /* Full name */
105 *regtype; /* Registration type */
106 cups_ptype_t type; /* Device registration type */
107 cups_dest_t dest; /* Destination record */
108 } _cups_dnssd_device_t;
109
110 typedef struct _cups_dnssd_resolve_s /* Data for resolving URI */
111 {
112 int *cancel; /* Pointer to "cancel" variable */
113 struct timeval end_time; /* Ending time */
114 } _cups_dnssd_resolve_t;
115 #endif /* HAVE_DNSSD */
116
117
118 /*
119 * Local functions...
120 */
121
122 #ifdef __APPLE__
123 static CFArrayRef appleCopyLocations(void);
124 static CFStringRef appleCopyNetwork(void);
125 static char *appleGetPaperSize(char *name, int namesize);
126 static CFStringRef appleGetPrinter(CFArrayRef locations,
127 CFStringRef network, CFIndex *locindex);
128 #endif /* __APPLE__ */
129 static cups_dest_t *cups_add_dest(const char *name, const char *instance,
130 int *num_dests, cups_dest_t **dests);
131 #ifdef __BLOCKS__
132 static int cups_block_cb(cups_dest_block_t block, unsigned flags,
133 cups_dest_t *dest);
134 #endif /* __BLOCKS__ */
135 static int cups_compare_dests(cups_dest_t *a, cups_dest_t *b);
136 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
137 # ifdef HAVE_DNSSD
138 static void cups_dnssd_browse_cb(DNSServiceRef sdRef,
139 DNSServiceFlags flags,
140 uint32_t interfaceIndex,
141 DNSServiceErrorType errorCode,
142 const char *serviceName,
143 const char *regtype,
144 const char *replyDomain,
145 void *context);
146 # else /* HAVE_AVAHI */
147 static void cups_dnssd_browse_cb(AvahiServiceBrowser *browser,
148 AvahiIfIndex interface,
149 AvahiProtocol protocol,
150 AvahiBrowserEvent event,
151 const char *serviceName,
152 const char *regtype,
153 const char *replyDomain,
154 AvahiLookupResultFlags flags,
155 void *context);
156 static void cups_dnssd_client_cb(AvahiClient *client,
157 AvahiClientState state,
158 void *context);
159 # endif /* HAVE_DNSSD */
160 static int cups_dnssd_compare_devices(_cups_dnssd_device_t *a,
161 _cups_dnssd_device_t *b);
162 static void cups_dnssd_free_device(_cups_dnssd_device_t *device,
163 _cups_dnssd_data_t *data);
164 static _cups_dnssd_device_t *
165 cups_dnssd_get_device(_cups_dnssd_data_t *data,
166 const char *serviceName,
167 const char *regtype,
168 const char *replyDomain);
169 # ifdef HAVE_DNSSD
170 static void cups_dnssd_local_cb(DNSServiceRef sdRef,
171 DNSServiceFlags flags,
172 uint32_t interfaceIndex,
173 DNSServiceErrorType errorCode,
174 const char *serviceName,
175 const char *regtype,
176 const char *replyDomain,
177 void *context);
178 static void cups_dnssd_query_cb(DNSServiceRef sdRef,
179 DNSServiceFlags flags,
180 uint32_t interfaceIndex,
181 DNSServiceErrorType errorCode,
182 const char *fullName,
183 uint16_t rrtype, uint16_t rrclass,
184 uint16_t rdlen, const void *rdata,
185 uint32_t ttl, void *context);
186 # else /* HAVE_AVAHI */
187 static int cups_dnssd_poll_cb(struct pollfd *pollfds,
188 unsigned int num_pollfds,
189 int timeout, void *context);
190 static void cups_dnssd_query_cb(AvahiRecordBrowser *browser,
191 AvahiIfIndex interface,
192 AvahiProtocol protocol,
193 AvahiBrowserEvent event,
194 const char *name, uint16_t rrclass,
195 uint16_t rrtype, const void *rdata,
196 size_t rdlen,
197 AvahiLookupResultFlags flags,
198 void *context);
199 # endif /* HAVE_DNSSD */
200 static const char *cups_dnssd_resolve(cups_dest_t *dest, const char *uri,
201 int msec, int *cancel,
202 cups_dest_cb_t cb, void *user_data);
203 static int cups_dnssd_resolve_cb(void *context);
204 static void cups_dnssd_unquote(char *dst, const char *src,
205 size_t dstsize);
206 #endif /* HAVE_DNSSD || HAVE_AVAHI */
207 static int cups_find_dest(const char *name, const char *instance,
208 int num_dests, cups_dest_t *dests, int prev,
209 int *rdiff);
210 static char *cups_get_default(const char *filename, char *namebuf,
211 size_t namesize, const char **instance);
212 static int cups_get_dests(const char *filename, const char *match_name,
213 const char *match_inst, int user_default_set,
214 int num_dests, cups_dest_t **dests);
215 static char *cups_make_string(ipp_attribute_t *attr, char *buffer,
216 size_t bufsize);
217
218
219 /*
220 * 'cupsAddDest()' - Add a destination to the list of destinations.
221 *
222 * This function cannot be used to add a new class or printer queue,
223 * it only adds a new container of saved options for the named
224 * destination or instance.
225 *
226 * If the named destination already exists, the destination list is
227 * returned unchanged. Adding a new instance of a destination creates
228 * a copy of that destination's options.
229 *
230 * Use the @link cupsSaveDests@ function to save the updated list of
231 * destinations to the user's lpoptions file.
232 */
233
234 int /* O - New number of destinations */
235 cupsAddDest(const char *name, /* I - Destination name */
236 const char *instance, /* I - Instance name or @code NULL@ for none/primary */
237 int num_dests, /* I - Number of destinations */
238 cups_dest_t **dests) /* IO - Destinations */
239 {
240 int i; /* Looping var */
241 cups_dest_t *dest; /* Destination pointer */
242 cups_dest_t *parent = NULL; /* Parent destination */
243 cups_option_t *doption, /* Current destination option */
244 *poption; /* Current parent option */
245
246
247 if (!name || !dests)
248 return (0);
249
250 if (!cupsGetDest(name, instance, num_dests, *dests))
251 {
252 if (instance && !cupsGetDest(name, NULL, num_dests, *dests))
253 return (num_dests);
254
255 if ((dest = cups_add_dest(name, instance, &num_dests, dests)) == NULL)
256 return (num_dests);
257
258 /*
259 * Find the base dest again now the array has been realloc'd.
260 */
261
262 parent = cupsGetDest(name, NULL, num_dests, *dests);
263
264 if (instance && parent && parent->num_options > 0)
265 {
266 /*
267 * Copy options from parent...
268 */
269
270 dest->options = calloc(sizeof(cups_option_t), (size_t)parent->num_options);
271
272 if (dest->options)
273 {
274 dest->num_options = parent->num_options;
275
276 for (i = dest->num_options, doption = dest->options,
277 poption = parent->options;
278 i > 0;
279 i --, doption ++, poption ++)
280 {
281 doption->name = _cupsStrRetain(poption->name);
282 doption->value = _cupsStrRetain(poption->value);
283 }
284 }
285 }
286 }
287
288 return (num_dests);
289 }
290
291
292 #ifdef __APPLE__
293 /*
294 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
295 */
296
297 CFStringRef /* O - Default paper ID */
298 _cupsAppleCopyDefaultPaperID(void)
299 {
300 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey,
301 kCUPSPrintingPrefs));
302 }
303
304
305 /*
306 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
307 */
308
309 CFStringRef /* O - Default printer name */
310 _cupsAppleCopyDefaultPrinter(void)
311 {
312 CFStringRef network; /* Network location */
313 CFArrayRef locations; /* Location array */
314 CFStringRef locprinter; /* Current printer */
315
316
317 /*
318 * Use location-based defaults only if "use last printer" is selected in the
319 * system preferences...
320 */
321
322 if (!_cupsAppleGetUseLastPrinter())
323 {
324 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
325 "default.");
326 return (NULL);
327 }
328
329 /*
330 * Get the current location...
331 */
332
333 if ((network = appleCopyNetwork()) == NULL)
334 {
335 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
336 "network.");
337 return (NULL);
338 }
339
340 /*
341 * Lookup the network in the preferences...
342 */
343
344 if ((locations = appleCopyLocations()) == NULL)
345 {
346 /*
347 * Missing or bad location array, so no location-based default...
348 */
349
350 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
351 "printer array.");
352
353 CFRelease(network);
354
355 return (NULL);
356 }
357
358 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
359 (int)CFArrayGetCount(locations)));
360
361 if ((locprinter = appleGetPrinter(locations, network, NULL)) != NULL)
362 CFRetain(locprinter);
363
364 CFRelease(network);
365 CFRelease(locations);
366
367 return (locprinter);
368 }
369
370
371 /*
372 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
373 */
374
375 int /* O - 1 to use last printer, 0 otherwise */
376 _cupsAppleGetUseLastPrinter(void)
377 {
378 Boolean uselast, /* Use last printer preference value */
379 uselast_set; /* Valid is set? */
380
381
382 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
383 return (0);
384
385 uselast = CFPreferencesGetAppBooleanValue(kUseLastPrinter,
386 kCUPSPrintingPrefs,
387 &uselast_set);
388 if (!uselast_set)
389 return (1);
390 else
391 return (uselast);
392 }
393
394
395 /*
396 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
397 */
398
399 void
400 _cupsAppleSetDefaultPaperID(
401 CFStringRef name) /* I - New paper ID */
402 {
403 CFPreferencesSetAppValue(kDefaultPaperIDKey, name, kCUPSPrintingPrefs);
404 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
405 notify_post("com.apple.printerPrefsChange");
406 }
407
408
409 /*
410 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
411 */
412
413 void
414 _cupsAppleSetDefaultPrinter(
415 CFStringRef name) /* I - Default printer/class name */
416 {
417 CFStringRef network; /* Current network */
418 CFArrayRef locations; /* Old locations array */
419 CFIndex locindex; /* Index in locations array */
420 CFStringRef locprinter; /* Current printer */
421 CFMutableArrayRef newlocations; /* New locations array */
422 CFMutableDictionaryRef newlocation; /* New location */
423
424
425 /*
426 * Get the current location...
427 */
428
429 if ((network = appleCopyNetwork()) == NULL)
430 {
431 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
432 return;
433 }
434
435 /*
436 * Lookup the network in the preferences...
437 */
438
439 if ((locations = appleCopyLocations()) != NULL)
440 locprinter = appleGetPrinter(locations, network, &locindex);
441 else
442 {
443 locprinter = NULL;
444 locindex = -1;
445 }
446
447 if (!locprinter || CFStringCompare(locprinter, name, 0) != kCFCompareEqualTo)
448 {
449 /*
450 * Need to change the locations array...
451 */
452
453 if (locations)
454 {
455 newlocations = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0,
456 locations);
457
458 if (locprinter)
459 CFArrayRemoveValueAtIndex(newlocations, locindex);
460 }
461 else
462 newlocations = CFArrayCreateMutable(kCFAllocatorDefault, 0,
463 &kCFTypeArrayCallBacks);
464
465 newlocation = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
466 &kCFTypeDictionaryKeyCallBacks,
467 &kCFTypeDictionaryValueCallBacks);
468
469 if (newlocation && newlocations)
470 {
471 /*
472 * Put the new location at the front of the array...
473 */
474
475 CFDictionaryAddValue(newlocation, kLocationNetworkKey, network);
476 CFDictionaryAddValue(newlocation, kLocationPrinterIDKey, name);
477 CFArrayInsertValueAtIndex(newlocations, 0, newlocation);
478
479 /*
480 * Limit the number of locations to 10...
481 */
482
483 while (CFArrayGetCount(newlocations) > 10)
484 CFArrayRemoveValueAtIndex(newlocations, 10);
485
486 /*
487 * Push the changes out...
488 */
489
490 CFPreferencesSetAppValue(kLastUsedPrintersKey, newlocations,
491 kCUPSPrintingPrefs);
492 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
493 notify_post("com.apple.printerPrefsChange");
494 }
495
496 if (newlocations)
497 CFRelease(newlocations);
498
499 if (newlocation)
500 CFRelease(newlocation);
501 }
502
503 if (locations)
504 CFRelease(locations);
505
506 CFRelease(network);
507 }
508
509
510 /*
511 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
512 */
513
514 void
515 _cupsAppleSetUseLastPrinter(
516 int uselast) /* O - 1 to use last printer, 0 otherwise */
517 {
518 CFPreferencesSetAppValue(kUseLastPrinter,
519 uselast ? kCFBooleanTrue : kCFBooleanFalse,
520 kCUPSPrintingPrefs);
521 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
522 notify_post("com.apple.printerPrefsChange");
523 }
524 #endif /* __APPLE__ */
525
526
527 /*
528 * 'cupsConnectDest()' - Connect to the server for a destination.
529 *
530 * Connect to the destination, returning a new http_t connection object and
531 * optionally the resource path to use for the destination. These calls will
532 * block until a connection is made, the timeout expires, the integer pointed
533 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
534 * The caller is responsible for calling httpClose() on the returned object.
535 *
536 * @since CUPS 1.6/OS X 10.8@
537 */
538
539 http_t * /* O - Connection to server or @code NULL@ */
540 cupsConnectDest(
541 cups_dest_t *dest, /* I - Destination */
542 unsigned flags, /* I - Connection flags */
543 int msec, /* I - Timeout in milliseconds */
544 int *cancel, /* I - Pointer to "cancel" variable */
545 char *resource, /* I - Resource buffer */
546 size_t resourcesize, /* I - Size of resource buffer */
547 cups_dest_cb_t cb, /* I - Callback function */
548 void *user_data) /* I - User data pointer */
549 {
550 const char *uri; /* Printer URI */
551 char scheme[32], /* URI scheme */
552 userpass[256], /* Username and password (unused) */
553 hostname[256], /* Hostname */
554 tempresource[1024]; /* Temporary resource buffer */
555 int port; /* Port number */
556 char portstr[16]; /* Port number string */
557 http_encryption_t encryption; /* Encryption to use */
558 http_addrlist_t *addrlist; /* Address list for server */
559 http_t *http; /* Connection to server */
560
561
562 /*
563 * Range check input...
564 */
565
566 if (!dest)
567 {
568 if (resource)
569 *resource = '\0';
570
571 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
572 return (NULL);
573 }
574
575 if (!resource || resourcesize < 1)
576 {
577 resource = tempresource;
578 resourcesize = sizeof(tempresource);
579 }
580
581 /*
582 * Grab the printer URI...
583 */
584
585 if ((uri = cupsGetOption("printer-uri-supported", dest->num_options,
586 dest->options)) == NULL)
587 {
588 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(ENOENT), 0);
589
590 if (cb)
591 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
592 dest);
593
594 return (NULL);
595 }
596
597 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
598 if (strstr(uri, "._tcp"))
599 {
600 if ((uri = cups_dnssd_resolve(dest, uri, msec, cancel, cb,
601 user_data)) == NULL)
602 return (NULL);
603 }
604 #endif /* HAVE_DNSSD || HAVE_AVAHI */
605
606 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
607 userpass, sizeof(userpass), hostname, sizeof(hostname),
608 &port, resource, (int)resourcesize) < HTTP_URI_STATUS_OK)
609 {
610 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
611
612 if (cb)
613 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
614 dest);
615
616 return (NULL);
617 }
618
619 /*
620 * Lookup the address for the server...
621 */
622
623 if (cb)
624 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING,
625 dest);
626
627 snprintf(portstr, sizeof(portstr), "%d", port);
628
629 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portstr)) == NULL)
630 {
631 if (cb)
632 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
633 dest);
634
635 return (NULL);
636 }
637
638 if (cancel && *cancel)
639 {
640 httpAddrFreeList(addrlist);
641
642 if (cb)
643 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CANCELED,
644 dest);
645
646 return (NULL);
647 }
648
649 /*
650 * Create the HTTP object pointing to the server referenced by the URI...
651 */
652
653 if (!strcmp(scheme, "ipps") || port == 443)
654 encryption = HTTP_ENCRYPTION_ALWAYS;
655 else
656 encryption = HTTP_ENCRYPTION_IF_REQUESTED;
657
658 http = httpConnect2(hostname, port, addrlist, AF_UNSPEC, encryption, 1, 0,
659 NULL);
660 httpAddrFreeList(addrlist);
661
662 /*
663 * Connect if requested...
664 */
665
666 if (flags & CUPS_DEST_FLAGS_UNCONNECTED)
667 {
668 if (cb)
669 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED, dest);
670 }
671 else
672 {
673 if (cb)
674 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING,
675 dest);
676
677 if (!httpReconnect2(http, msec, cancel) && cb)
678 {
679 if (cancel && *cancel)
680 (*cb)(user_data,
681 CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING, dest);
682 else
683 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
684 dest);
685 }
686 else if (cb)
687 (*cb)(user_data, CUPS_DEST_FLAGS_NONE, dest);
688 }
689
690 return (http);
691 }
692
693
694 #ifdef __BLOCKS__
695 /*
696 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
697 *
698 * Connect to the destination, returning a new http_t connection object and
699 * optionally the resource path to use for the destination. These calls will
700 * block until a connection is made, the timeout expires, the integer pointed
701 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
702 * The caller is responsible for calling httpClose() on the returned object.
703 *
704 * @since CUPS 1.6/OS X 10.8@
705 */
706
707 http_t * /* O - Connection to server or @code NULL@ */
708 cupsConnectDestBlock(
709 cups_dest_t *dest, /* I - Destination */
710 unsigned flags, /* I - Connection flags */
711 int msec, /* I - Timeout in milliseconds */
712 int *cancel, /* I - Pointer to "cancel" variable */
713 char *resource, /* I - Resource buffer */
714 size_t resourcesize, /* I - Size of resource buffer */
715 cups_dest_block_t block) /* I - Callback block */
716 {
717 return (cupsConnectDest(dest, flags, msec, cancel, resource, resourcesize,
718 (cups_dest_cb_t)cups_block_cb, (void *)block));
719 }
720 #endif /* __BLOCKS__ */
721
722
723 /*
724 * 'cupsCopyDest()' - Copy a destination.
725 *
726 * Make a copy of the destination to an array of destinations (or just a single
727 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
728 * for calling cupsFreeDests() on the returned object(s).
729 *
730 * @since CUPS 1.6/OS X 10.8@
731 */
732
733 int
734 cupsCopyDest(cups_dest_t *dest,
735 int num_dests,
736 cups_dest_t **dests)
737 {
738 int i; /* Looping var */
739 cups_dest_t *new_dest; /* New destination pointer */
740 cups_option_t *new_option, /* Current destination option */
741 *option; /* Current parent option */
742
743
744 /*
745 * Range check input...
746 */
747
748 if (!dest || num_dests < 0 || !dests)
749 return (num_dests);
750
751 /*
752 * See if the destination already exists...
753 */
754
755 if ((new_dest = cupsGetDest(dest->name, dest->instance, num_dests,
756 *dests)) != NULL)
757 {
758 /*
759 * Protect against copying destination to itself...
760 */
761
762 if (new_dest == dest)
763 return (num_dests);
764
765 /*
766 * Otherwise, free the options...
767 */
768
769 cupsFreeOptions(new_dest->num_options, new_dest->options);
770
771 new_dest->num_options = 0;
772 new_dest->options = NULL;
773 }
774 else
775 new_dest = cups_add_dest(dest->name, dest->instance, &num_dests, dests);
776
777 if (new_dest)
778 {
779 if ((new_dest->options = calloc(sizeof(cups_option_t), (size_t)dest->num_options)) == NULL)
780 return (cupsRemoveDest(dest->name, dest->instance, num_dests, dests));
781
782 new_dest->num_options = dest->num_options;
783
784 for (i = dest->num_options, option = dest->options,
785 new_option = new_dest->options;
786 i > 0;
787 i --, option ++, new_option ++)
788 {
789 new_option->name = _cupsStrRetain(option->name);
790 new_option->value = _cupsStrRetain(option->value);
791 }
792 }
793
794 return (num_dests);
795 }
796
797
798 /*
799 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
800 *
801 * Destinations are enumerated from one or more sources. The callback function
802 * receives the @code user_data@ pointer, destination name, instance, number of
803 * options, and options which can be used as input to the @link cupsAddDest@
804 * function. The function must return 1 to continue enumeration or 0 to stop.
805 *
806 * Enumeration happens on the current thread and does not return until all
807 * destinations have been enumerated or the callback function returns 0.
808 *
809 * @since CUPS 1.6/OS X 10.8@
810 */
811
812 int /* O - 1 on success, 0 on failure */
813 cupsEnumDests(
814 unsigned flags, /* I - Enumeration flags */
815 int msec, /* I - Timeout in milliseconds,
816 * -1 for indefinite */
817 int *cancel, /* I - Pointer to "cancel" variable */
818 cups_ptype_t type, /* I - Printer type bits */
819 cups_ptype_t mask, /* I - Mask for printer type bits */
820 cups_dest_cb_t cb, /* I - Callback function */
821 void *user_data) /* I - User data */
822 {
823 int i, /* Looping var */
824 num_dests; /* Number of destinations */
825 cups_dest_t *dests = NULL, /* Destinations */
826 *dest; /* Current destination */
827 const char *defprinter; /* Default printer */
828 char name[1024], /* Copy of printer name */
829 *instance, /* Pointer to instance name */
830 *user_default; /* User default printer */
831 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
832 int count, /* Number of queries started */
833 remaining; /* Remainder of timeout */
834 _cups_dnssd_data_t data; /* Data for callback */
835 _cups_dnssd_device_t *device; /* Current device */
836 # ifdef HAVE_DNSSD
837 int nfds, /* Number of files responded */
838 main_fd; /* File descriptor for lookups */
839 DNSServiceRef ipp_ref, /* IPP browser */
840 local_ipp_ref; /* Local IPP browser */
841 # ifdef HAVE_SSL
842 DNSServiceRef ipps_ref, /* IPPS browser */
843 local_ipps_ref; /* Local IPPS browser */
844 # endif /* HAVE_SSL */
845 # ifdef HAVE_POLL
846 struct pollfd pfd; /* Polling data */
847 # else
848 fd_set input; /* Input set for select() */
849 struct timeval timeout; /* Timeout for select() */
850 # endif /* HAVE_POLL */
851 # else /* HAVE_AVAHI */
852 int error; /* Error value */
853 AvahiServiceBrowser *ipp_ref; /* IPP browser */
854 # ifdef HAVE_SSL
855 AvahiServiceBrowser *ipps_ref; /* IPPS browser */
856 # endif /* HAVE_SSL */
857 # endif /* HAVE_DNSSD */
858 #endif /* HAVE_DNSSD || HAVE_AVAHI */
859
860 /*
861 * Range check input...
862 */
863
864 (void)flags;
865
866 if (!cb)
867 return (0);
868
869 /*
870 * Get the list of local printers and pass them to the callback function...
871 */
872
873 num_dests = _cupsGetDests(CUPS_HTTP_DEFAULT, IPP_OP_CUPS_GET_PRINTERS, NULL,
874 &dests, type, mask | CUPS_PRINTER_3D);
875
876 if ((user_default = _cupsUserDefault(name, sizeof(name))) != NULL)
877 defprinter = name;
878 else if ((defprinter = cupsGetDefault2(CUPS_HTTP_DEFAULT)) != NULL)
879 {
880 strlcpy(name, defprinter, sizeof(name));
881 defprinter = name;
882 }
883
884 if (defprinter)
885 {
886 /*
887 * Separate printer and instance name...
888 */
889
890 if ((instance = strchr(name, '/')) != NULL)
891 *instance++ = '\0';
892
893 /*
894 * Lookup the printer and instance and make it the default...
895 */
896
897 if ((dest = cupsGetDest(name, instance, num_dests, dests)) != NULL)
898 dest->is_default = 1;
899 }
900
901 for (i = num_dests, dest = dests;
902 i > 0 && (!cancel || !*cancel);
903 i --, dest ++)
904 if (!(*cb)(user_data, i > 1 ? CUPS_DEST_FLAGS_MORE : CUPS_DEST_FLAGS_NONE,
905 dest))
906 break;
907
908 cupsFreeDests(num_dests, dests);
909
910 if (i > 0 || msec == 0)
911 return (1);
912
913 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
914 /*
915 * Get Bonjour-shared printers...
916 */
917
918 data.type = type;
919 data.mask = mask;
920 data.cb = cb;
921 data.user_data = user_data;
922 data.devices = cupsArrayNew3((cups_array_func_t)cups_dnssd_compare_devices, NULL, NULL, 0, NULL, (cups_afree_func_t)cups_dnssd_free_device);
923
924 # ifdef HAVE_DNSSD
925 if (DNSServiceCreateConnection(&data.main_ref) != kDNSServiceErr_NoError)
926 return (0);
927
928 main_fd = DNSServiceRefSockFD(data.main_ref);
929
930 ipp_ref = data.main_ref;
931 DNSServiceBrowse(&ipp_ref, kDNSServiceFlagsShareConnection, 0,
932 "_ipp._tcp", NULL,
933 (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data);
934
935 local_ipp_ref = data.main_ref;
936 DNSServiceBrowse(&local_ipp_ref, kDNSServiceFlagsShareConnection,
937 kDNSServiceInterfaceIndexLocalOnly,
938 "_ipp._tcp", NULL,
939 (DNSServiceBrowseReply)cups_dnssd_local_cb, &data);
940
941 # ifdef HAVE_SSL
942 ipps_ref = data.main_ref;
943 DNSServiceBrowse(&ipps_ref, kDNSServiceFlagsShareConnection, 0,
944 "_ipps._tcp", NULL,
945 (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data);
946
947 local_ipps_ref = data.main_ref;
948 DNSServiceBrowse(&local_ipps_ref, kDNSServiceFlagsShareConnection,
949 kDNSServiceInterfaceIndexLocalOnly,
950 "_ipps._tcp", NULL,
951 (DNSServiceBrowseReply)cups_dnssd_local_cb, &data);
952 # endif /* HAVE_SSL */
953
954 # else /* HAVE_AVAHI */
955 if ((data.simple_poll = avahi_simple_poll_new()) == NULL)
956 {
957 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
958 return (1);
959 }
960
961 avahi_simple_poll_set_func(data.simple_poll, cups_dnssd_poll_cb, &data);
962
963 data.client = avahi_client_new(avahi_simple_poll_get(data.simple_poll),
964 0, cups_dnssd_client_cb, &data,
965 &error);
966 if (!data.client)
967 {
968 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
969 avahi_simple_poll_free(data.simple_poll);
970 return (1);
971 }
972
973 ipp_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC,
974 AVAHI_PROTO_UNSPEC, "_ipp._tcp", NULL,
975 0, cups_dnssd_browse_cb, &data);
976 # ifdef HAVE_SSL
977 ipps_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC,
978 AVAHI_PROTO_UNSPEC, "_ipps._tcp", NULL,
979 0, cups_dnssd_browse_cb, &data);
980 # endif /* HAVE_SSL */
981 # endif /* HAVE_DNSSD */
982
983 if (msec < 0)
984 remaining = INT_MAX;
985 else
986 remaining = msec;
987
988 while (remaining > 0 && (!cancel || !*cancel))
989 {
990 /*
991 * Check for input...
992 */
993
994 # ifdef HAVE_DNSSD
995 # ifdef HAVE_POLL
996 pfd.fd = main_fd;
997 pfd.events = POLLIN;
998
999 nfds = poll(&pfd, 1, remaining > 250 ? 250 : remaining);
1000
1001 # else
1002 FD_ZERO(&input);
1003 FD_SET(main_fd, &input);
1004
1005 timeout.tv_sec = 0;
1006 timeout.tv_usec = remaining > 250 ? 250000 : remaining * 1000;
1007
1008 nfds = select(main_fd + 1, &input, NULL, NULL, &timeout);
1009 # endif /* HAVE_POLL */
1010
1011 if (nfds > 0)
1012 DNSServiceProcessResult(data.main_ref);
1013 else if (nfds == 0)
1014 remaining -= 250;
1015
1016 # else /* HAVE_AVAHI */
1017 data.got_data = 0;
1018
1019 if ((error = avahi_simple_poll_iterate(data.simple_poll, 250)) > 0)
1020 {
1021 /*
1022 * We've been told to exit the loop. Perhaps the connection to
1023 * Avahi failed.
1024 */
1025
1026 break;
1027 }
1028
1029 if (!data.got_data)
1030 remaining -= 250;
1031 # endif /* HAVE_DNSSD */
1032
1033 for (device = (_cups_dnssd_device_t *)cupsArrayFirst(data.devices),
1034 count = 0;
1035 device;
1036 device = (_cups_dnssd_device_t *)cupsArrayNext(data.devices))
1037 {
1038 if (device->ref)
1039 count ++;
1040
1041 if (!device->ref && device->state == _CUPS_DNSSD_NEW)
1042 {
1043 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device->fullName));
1044
1045 # ifdef HAVE_DNSSD
1046 device->ref = data.main_ref;
1047
1048 if (DNSServiceQueryRecord(&(device->ref),
1049 kDNSServiceFlagsShareConnection,
1050 0, device->fullName,
1051 kDNSServiceType_TXT,
1052 kDNSServiceClass_IN,
1053 (DNSServiceQueryRecordReply)cups_dnssd_query_cb,
1054 &data) == kDNSServiceErr_NoError)
1055 {
1056 count ++;
1057 }
1058 else
1059 {
1060 device->ref = 0;
1061 device->state = _CUPS_DNSSD_ERROR;
1062
1063 DEBUG_puts("1cupsEnumDests: Query failed.");
1064 }
1065
1066 # else /* HAVE_AVAHI */
1067 if ((device->ref = avahi_record_browser_new(data.client,
1068 AVAHI_IF_UNSPEC,
1069 AVAHI_PROTO_UNSPEC,
1070 device->fullName,
1071 AVAHI_DNS_CLASS_IN,
1072 AVAHI_DNS_TYPE_TXT,
1073 0,
1074 cups_dnssd_query_cb,
1075 &data)) != NULL)
1076 {
1077 count ++;
1078 }
1079 else
1080 {
1081 device->state = _CUPS_DNSSD_ERROR;
1082
1083 DEBUG_printf(("1cupsEnumDests: Query failed: %s",
1084 avahi_strerror(avahi_client_errno(data.client))));
1085 }
1086 # endif /* HAVE_DNSSD */
1087 }
1088 else if (device->ref && device->state == _CUPS_DNSSD_PENDING)
1089 {
1090 if ((device->type & mask) == type)
1091 {
1092 if (!(*cb)(user_data, CUPS_DEST_FLAGS_NONE, &device->dest))
1093 {
1094 remaining = -1;
1095 break;
1096 }
1097 }
1098
1099 device->state = _CUPS_DNSSD_ACTIVE;
1100 }
1101 }
1102 }
1103
1104 cupsArrayDelete(data.devices);
1105
1106 # ifdef HAVE_DNSSD
1107 DNSServiceRefDeallocate(ipp_ref);
1108 DNSServiceRefDeallocate(local_ipp_ref);
1109
1110 # ifdef HAVE_SSL
1111 DNSServiceRefDeallocate(ipp_ref);
1112 DNSServiceRefDeallocate(local_ipp_ref);
1113 # endif /* HAVE_SSL */
1114
1115 DNSServiceRefDeallocate(data.main_ref);
1116
1117 # else /* HAVE_AVAHI */
1118 avahi_service_browser_free(ipp_ref);
1119 # ifdef HAVE_SSL
1120 avahi_service_browser_free(ipps_ref);
1121 # endif /* HAVE_SSL */
1122
1123 avahi_client_free(data.client);
1124 avahi_simple_poll_free(data.simple_poll);
1125 # endif /* HAVE_DNSSD */
1126 #endif /* HAVE_DNSSD || HAVE_DNSSD */
1127
1128 return (1);
1129 }
1130
1131
1132 # ifdef __BLOCKS__
1133 /*
1134 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1135 *
1136 * Destinations are enumerated from one or more sources. The block receives the
1137 * destination name, instance, number of options, and options which can be used
1138 * as input to the @link cupsAddDest@ function. The block must return 1 to
1139 * continue enumeration or 0 to stop.
1140 *
1141 * Enumeration happens on the current thread and does not return until all
1142 * destinations have been enumerated or the block returns 0.
1143 *
1144 * @since CUPS 1.6/OS X 10.8@
1145 */
1146
1147 int /* O - 1 on success, 0 on failure */
1148 cupsEnumDestsBlock(
1149 unsigned flags, /* I - Enumeration flags */
1150 int timeout, /* I - Timeout in milliseconds, 0 for indefinite */
1151 int *cancel, /* I - Pointer to "cancel" variable */
1152 cups_ptype_t type, /* I - Printer type bits */
1153 cups_ptype_t mask, /* I - Mask for printer type bits */
1154 cups_dest_block_t block) /* I - Block */
1155 {
1156 return (cupsEnumDests(flags, timeout, cancel, type, mask,
1157 (cups_dest_cb_t)cups_block_cb, (void *)block));
1158 }
1159 # endif /* __BLOCKS__ */
1160
1161
1162 /*
1163 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1164 */
1165
1166 void
1167 cupsFreeDests(int num_dests, /* I - Number of destinations */
1168 cups_dest_t *dests) /* I - Destinations */
1169 {
1170 int i; /* Looping var */
1171 cups_dest_t *dest; /* Current destination */
1172
1173
1174 if (num_dests == 0 || dests == NULL)
1175 return;
1176
1177 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
1178 {
1179 _cupsStrFree(dest->name);
1180 _cupsStrFree(dest->instance);
1181
1182 cupsFreeOptions(dest->num_options, dest->options);
1183 }
1184
1185 free(dests);
1186 }
1187
1188
1189 /*
1190 * 'cupsGetDest()' - Get the named destination from the list.
1191 *
1192 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1193 * list of supported destinations for the current user.
1194 */
1195
1196 cups_dest_t * /* O - Destination pointer or @code NULL@ */
1197 cupsGetDest(const char *name, /* I - Destination name or @code NULL@ for the default destination */
1198 const char *instance, /* I - Instance name or @code NULL@ */
1199 int num_dests, /* I - Number of destinations */
1200 cups_dest_t *dests) /* I - Destinations */
1201 {
1202 int diff, /* Result of comparison */
1203 match; /* Matching index */
1204
1205
1206 if (num_dests <= 0 || !dests)
1207 return (NULL);
1208
1209 if (!name)
1210 {
1211 /*
1212 * NULL name for default printer.
1213 */
1214
1215 while (num_dests > 0)
1216 {
1217 if (dests->is_default)
1218 return (dests);
1219
1220 num_dests --;
1221 dests ++;
1222 }
1223 }
1224 else
1225 {
1226 /*
1227 * Lookup name and optionally the instance...
1228 */
1229
1230 match = cups_find_dest(name, instance, num_dests, dests, -1, &diff);
1231
1232 if (!diff)
1233 return (dests + match);
1234 }
1235
1236 return (NULL);
1237 }
1238
1239
1240 /*
1241 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1242 */
1243
1244 const char * /* O - Printer URI */
1245 _cupsGetDestResource(
1246 cups_dest_t *dest, /* I - Destination */
1247 char *resource, /* I - Resource buffer */
1248 size_t resourcesize) /* I - Size of resource buffer */
1249 {
1250 const char *uri; /* Printer URI */
1251 char scheme[32], /* URI scheme */
1252 userpass[256], /* Username and password (unused) */
1253 hostname[256]; /* Hostname */
1254 int port; /* Port number */
1255
1256
1257 /*
1258 * Range check input...
1259 */
1260
1261 if (!dest || !resource || resourcesize < 1)
1262 {
1263 if (resource)
1264 *resource = '\0';
1265
1266 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
1267 return (NULL);
1268 }
1269
1270 /*
1271 * Grab the printer URI...
1272 */
1273
1274 if ((uri = cupsGetOption("printer-uri-supported", dest->num_options,
1275 dest->options)) == NULL)
1276 {
1277 if (resource)
1278 *resource = '\0';
1279
1280 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(ENOENT), 0);
1281
1282 return (NULL);
1283 }
1284
1285 #ifdef HAVE_DNSSD
1286 if (strstr(uri, "._tcp"))
1287 {
1288 if ((uri = cups_dnssd_resolve(dest, uri, 5000, NULL, NULL, NULL)) == NULL)
1289 return (NULL);
1290 }
1291 #endif /* HAVE_DNSSD */
1292
1293 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
1294 userpass, sizeof(userpass), hostname, sizeof(hostname),
1295 &port, resource, (int)resourcesize) < HTTP_URI_STATUS_OK)
1296 {
1297 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
1298
1299 return (NULL);
1300 }
1301
1302 return (uri);
1303 }
1304
1305
1306 /*
1307 * 'cupsGetDestWithURI()' - Get a destination associated with a URI.
1308 *
1309 * "name" is the desired name for the printer. If @code NULL@, a name will be
1310 * created using the URI.
1311 *
1312 * "uri" is the "ipp" or "ipps" URI for the printer.
1313 *
1314 * @since CUPS 2.0/OS X 10.10@
1315 */
1316
1317 cups_dest_t * /* O - Destination or @code NULL@ */
1318 cupsGetDestWithURI(const char *name, /* I - Desired printer name or @code NULL@ */
1319 const char *uri) /* I - URI for the printer */
1320 {
1321 cups_dest_t *dest; /* New destination */
1322 char temp[1024], /* Temporary string */
1323 scheme[256], /* Scheme from URI */
1324 userpass[256], /* Username:password from URI */
1325 hostname[256], /* Hostname from URI */
1326 resource[1024], /* Resource path from URI */
1327 *ptr; /* Pointer into string */
1328 int port; /* Port number from URI */
1329
1330
1331 /*
1332 * Range check input...
1333 */
1334
1335 if (!uri)
1336 {
1337 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
1338 return (NULL);
1339 }
1340
1341 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK ||
1342 (strncmp(uri, "ipp://", 6) && strncmp(uri, "ipps://", 7)))
1343 {
1344 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
1345
1346 return (NULL);
1347 }
1348
1349 if (!name)
1350 {
1351 /*
1352 * Create the name from the URI...
1353 */
1354
1355 if (strstr(hostname, "._tcp"))
1356 {
1357 /*
1358 * Use the service instance name...
1359 */
1360
1361 if ((ptr = strchr(hostname, '.')) != NULL)
1362 *ptr = '\0';
1363
1364 name = hostname;
1365 }
1366 else if (!strncmp(resource, "/classes/", 9))
1367 {
1368 snprintf(temp, sizeof(temp), "%s @ %s", resource + 9, hostname);
1369 name = temp;
1370 }
1371 else if (!strncmp(resource, "/printers/", 10))
1372 {
1373 snprintf(temp, sizeof(temp), "%s @ %s", resource + 10, hostname);
1374 name = temp;
1375 }
1376 else
1377 {
1378 name = hostname;
1379 }
1380 }
1381
1382 /*
1383 * Create the destination...
1384 */
1385
1386 if ((dest = calloc(1, sizeof(cups_dest_t))) == NULL)
1387 {
1388 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
1389 return (NULL);
1390 }
1391
1392 dest->name = _cupsStrAlloc(name);
1393 dest->num_options = cupsAddOption("printer-uri-supported", uri, dest->num_options, &(dest->options));
1394 dest->num_options = cupsAddOption("printer-info", name, dest->num_options, &(dest->options));
1395
1396 return (dest);
1397 }
1398
1399
1400 /*
1401 * '_cupsGetDests()' - Get destinations from a server.
1402 *
1403 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1404 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1405 * a known printer.
1406 *
1407 * "name" is the name of an existing printer and is only used when "op" is
1408 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1409 *
1410 * "dest" is initialized to point to the array of destinations.
1411 *
1412 * 0 is returned if there are no printers, no default printer, or the named
1413 * printer does not exist, respectively.
1414 *
1415 * Free the memory used by the destination array using the @link cupsFreeDests@
1416 * function.
1417 *
1418 * Note: On OS X this function also gets the default paper from the system
1419 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1420 * options array for each destination that supports it.
1421 */
1422
1423 int /* O - Number of destinations */
1424 _cupsGetDests(http_t *http, /* I - Connection to server or
1425 * @code CUPS_HTTP_DEFAULT@ */
1426 ipp_op_t op, /* I - IPP operation */
1427 const char *name, /* I - Name of destination */
1428 cups_dest_t **dests, /* IO - Destinations */
1429 cups_ptype_t type, /* I - Printer type bits */
1430 cups_ptype_t mask) /* I - Printer type mask */
1431 {
1432 int num_dests = 0; /* Number of destinations */
1433 cups_dest_t *dest; /* Current destination */
1434 ipp_t *request, /* IPP Request */
1435 *response; /* IPP Response */
1436 ipp_attribute_t *attr; /* Current attribute */
1437 const char *printer_name; /* printer-name attribute */
1438 char uri[1024]; /* printer-uri value */
1439 int num_options; /* Number of options */
1440 cups_option_t *options; /* Options */
1441 #ifdef __APPLE__
1442 char media_default[41]; /* Default paper size */
1443 #endif /* __APPLE__ */
1444 char optname[1024], /* Option name */
1445 value[2048], /* Option value */
1446 *ptr; /* Pointer into name/value */
1447 static const char * const pattrs[] = /* Attributes we're interested in */
1448 {
1449 "auth-info-required",
1450 "device-uri",
1451 "job-sheets-default",
1452 "marker-change-time",
1453 "marker-colors",
1454 "marker-high-levels",
1455 "marker-levels",
1456 "marker-low-levels",
1457 "marker-message",
1458 "marker-names",
1459 "marker-types",
1460 #ifdef __APPLE__
1461 "media-supported",
1462 #endif /* __APPLE__ */
1463 "printer-commands",
1464 "printer-defaults",
1465 "printer-info",
1466 "printer-is-accepting-jobs",
1467 "printer-is-shared",
1468 "printer-location",
1469 "printer-make-and-model",
1470 "printer-mandatory-job-attributes",
1471 "printer-name",
1472 "printer-state",
1473 "printer-state-change-time",
1474 "printer-state-reasons",
1475 "printer-type",
1476 "printer-uri-supported"
1477 };
1478
1479
1480 #ifdef __APPLE__
1481 /*
1482 * Get the default paper size...
1483 */
1484
1485 appleGetPaperSize(media_default, sizeof(media_default));
1486 #endif /* __APPLE__ */
1487
1488 /*
1489 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1490 * require the following attributes:
1491 *
1492 * attributes-charset
1493 * attributes-natural-language
1494 * requesting-user-name
1495 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1496 */
1497
1498 request = ippNewRequest(op);
1499
1500 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1501 "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
1502 NULL, pattrs);
1503
1504 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1505 "requesting-user-name", NULL, cupsUser());
1506
1507 if (name && op != IPP_OP_CUPS_GET_DEFAULT)
1508 {
1509 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
1510 "localhost", ippPort(), "/printers/%s", name);
1511 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
1512 uri);
1513 }
1514 else if (mask)
1515 {
1516 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type", (int)type);
1517 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type-mask", (int)mask);
1518 }
1519
1520 /*
1521 * Do the request and get back a response...
1522 */
1523
1524 if ((response = cupsDoRequest(http, request, "/")) != NULL)
1525 {
1526 for (attr = response->attrs; attr != NULL; attr = attr->next)
1527 {
1528 /*
1529 * Skip leading attributes until we hit a printer...
1530 */
1531
1532 while (attr != NULL && attr->group_tag != IPP_TAG_PRINTER)
1533 attr = attr->next;
1534
1535 if (attr == NULL)
1536 break;
1537
1538 /*
1539 * Pull the needed attributes from this printer...
1540 */
1541
1542 printer_name = NULL;
1543 num_options = 0;
1544 options = NULL;
1545
1546 for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
1547 {
1548 if (attr->value_tag != IPP_TAG_INTEGER &&
1549 attr->value_tag != IPP_TAG_ENUM &&
1550 attr->value_tag != IPP_TAG_BOOLEAN &&
1551 attr->value_tag != IPP_TAG_TEXT &&
1552 attr->value_tag != IPP_TAG_TEXTLANG &&
1553 attr->value_tag != IPP_TAG_NAME &&
1554 attr->value_tag != IPP_TAG_NAMELANG &&
1555 attr->value_tag != IPP_TAG_KEYWORD &&
1556 attr->value_tag != IPP_TAG_RANGE &&
1557 attr->value_tag != IPP_TAG_URI)
1558 continue;
1559
1560 if (!strcmp(attr->name, "auth-info-required") ||
1561 !strcmp(attr->name, "device-uri") ||
1562 !strcmp(attr->name, "marker-change-time") ||
1563 !strcmp(attr->name, "marker-colors") ||
1564 !strcmp(attr->name, "marker-high-levels") ||
1565 !strcmp(attr->name, "marker-levels") ||
1566 !strcmp(attr->name, "marker-low-levels") ||
1567 !strcmp(attr->name, "marker-message") ||
1568 !strcmp(attr->name, "marker-names") ||
1569 !strcmp(attr->name, "marker-types") ||
1570 !strcmp(attr->name, "printer-commands") ||
1571 !strcmp(attr->name, "printer-info") ||
1572 !strcmp(attr->name, "printer-is-shared") ||
1573 !strcmp(attr->name, "printer-make-and-model") ||
1574 !strcmp(attr->name, "printer-mandatory-job-attributes") ||
1575 !strcmp(attr->name, "printer-state") ||
1576 !strcmp(attr->name, "printer-state-change-time") ||
1577 !strcmp(attr->name, "printer-type") ||
1578 !strcmp(attr->name, "printer-is-accepting-jobs") ||
1579 !strcmp(attr->name, "printer-location") ||
1580 !strcmp(attr->name, "printer-state-reasons") ||
1581 !strcmp(attr->name, "printer-uri-supported"))
1582 {
1583 /*
1584 * Add a printer description attribute...
1585 */
1586
1587 num_options = cupsAddOption(attr->name,
1588 cups_make_string(attr, value,
1589 sizeof(value)),
1590 num_options, &options);
1591 }
1592 #ifdef __APPLE__
1593 else if (!strcmp(attr->name, "media-supported"))
1594 {
1595 /*
1596 * See if we can set a default media size...
1597 */
1598
1599 int i; /* Looping var */
1600
1601 for (i = 0; i < attr->num_values; i ++)
1602 if (!_cups_strcasecmp(media_default, attr->values[i].string.text))
1603 {
1604 num_options = cupsAddOption("media", media_default, num_options,
1605 &options);
1606 break;
1607 }
1608 }
1609 #endif /* __APPLE__ */
1610 else if (!strcmp(attr->name, "printer-name") &&
1611 attr->value_tag == IPP_TAG_NAME)
1612 printer_name = attr->values[0].string.text;
1613 else if (strncmp(attr->name, "notify-", 7) &&
1614 (attr->value_tag == IPP_TAG_BOOLEAN ||
1615 attr->value_tag == IPP_TAG_ENUM ||
1616 attr->value_tag == IPP_TAG_INTEGER ||
1617 attr->value_tag == IPP_TAG_KEYWORD ||
1618 attr->value_tag == IPP_TAG_NAME ||
1619 attr->value_tag == IPP_TAG_RANGE) &&
1620 (ptr = strstr(attr->name, "-default")) != NULL)
1621 {
1622 /*
1623 * Add a default option...
1624 */
1625
1626 strlcpy(optname, attr->name, sizeof(optname));
1627 optname[ptr - attr->name] = '\0';
1628
1629 if (_cups_strcasecmp(optname, "media") ||
1630 !cupsGetOption("media", num_options, options))
1631 num_options = cupsAddOption(optname,
1632 cups_make_string(attr, value,
1633 sizeof(value)),
1634 num_options, &options);
1635 }
1636 }
1637
1638 /*
1639 * See if we have everything needed...
1640 */
1641
1642 if (!printer_name)
1643 {
1644 cupsFreeOptions(num_options, options);
1645
1646 if (attr == NULL)
1647 break;
1648 else
1649 continue;
1650 }
1651
1652 if ((dest = cups_add_dest(printer_name, NULL, &num_dests, dests)) != NULL)
1653 {
1654 dest->num_options = num_options;
1655 dest->options = options;
1656 }
1657 else
1658 cupsFreeOptions(num_options, options);
1659
1660 if (attr == NULL)
1661 break;
1662 }
1663
1664 ippDelete(response);
1665 }
1666
1667 /*
1668 * Return the count...
1669 */
1670
1671 return (num_dests);
1672 }
1673
1674
1675 /*
1676 * 'cupsGetDests()' - Get the list of destinations from the default server.
1677 *
1678 * Starting with CUPS 1.2, the returned list of destinations include the
1679 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1680 * printer-make-and-model, printer-state, printer-state-change-time,
1681 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1682 * adds the marker-change-time, marker-colors, marker-high-levels,
1683 * marker-levels, marker-low-levels, marker-message, marker-names,
1684 * marker-types, and printer-commands attributes as well.
1685 *
1686 * Use the @link cupsFreeDests@ function to free the destination list and
1687 * the @link cupsGetDest@ function to find a particular destination.
1688 */
1689
1690 int /* O - Number of destinations */
1691 cupsGetDests(cups_dest_t **dests) /* O - Destinations */
1692 {
1693 return (cupsGetDests2(CUPS_HTTP_DEFAULT, dests));
1694 }
1695
1696
1697 /*
1698 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1699 *
1700 * Starting with CUPS 1.2, the returned list of destinations include the
1701 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1702 * printer-make-and-model, printer-state, printer-state-change-time,
1703 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1704 * adds the marker-change-time, marker-colors, marker-high-levels,
1705 * marker-levels, marker-low-levels, marker-message, marker-names,
1706 * marker-types, and printer-commands attributes as well.
1707 *
1708 * Use the @link cupsFreeDests@ function to free the destination list and
1709 * the @link cupsGetDest@ function to find a particular destination.
1710 *
1711 * @since CUPS 1.1.21/OS X 10.4@
1712 */
1713
1714 int /* O - Number of destinations */
1715 cupsGetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1716 cups_dest_t **dests) /* O - Destinations */
1717 {
1718 int num_dests; /* Number of destinations */
1719 cups_dest_t *dest; /* Destination pointer */
1720 const char *home; /* HOME environment variable */
1721 char filename[1024]; /* Local ~/.cups/lpoptions file */
1722 const char *defprinter; /* Default printer */
1723 char name[1024], /* Copy of printer name */
1724 *instance, /* Pointer to instance name */
1725 *user_default; /* User default printer */
1726 int num_reals; /* Number of real queues */
1727 cups_dest_t *reals; /* Real queues */
1728 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1729
1730
1731 /*
1732 * Range check the input...
1733 */
1734
1735 if (!dests)
1736 {
1737 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad NULL dests pointer"), 1);
1738 return (0);
1739 }
1740
1741 /*
1742 * Grab the printers and classes...
1743 */
1744
1745 *dests = (cups_dest_t *)0;
1746 num_dests = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, dests, 0, CUPS_PRINTER_3D);
1747
1748 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
1749 {
1750 cupsFreeDests(num_dests, *dests);
1751 *dests = (cups_dest_t *)0;
1752 return (0);
1753 }
1754
1755 /*
1756 * Make a copy of the "real" queues for a later sanity check...
1757 */
1758
1759 if (num_dests > 0)
1760 {
1761 num_reals = num_dests;
1762 reals = calloc((size_t)num_reals, sizeof(cups_dest_t));
1763
1764 if (reals)
1765 memcpy(reals, *dests, (size_t)num_reals * sizeof(cups_dest_t));
1766 else
1767 num_reals = 0;
1768 }
1769 else
1770 {
1771 num_reals = 0;
1772 reals = NULL;
1773 }
1774
1775 /*
1776 * Grab the default destination...
1777 */
1778
1779 if ((user_default = _cupsUserDefault(name, sizeof(name))) != NULL)
1780 defprinter = name;
1781 else if ((defprinter = cupsGetDefault2(http)) != NULL)
1782 {
1783 strlcpy(name, defprinter, sizeof(name));
1784 defprinter = name;
1785 }
1786
1787 if (defprinter)
1788 {
1789 /*
1790 * Separate printer and instance name...
1791 */
1792
1793 if ((instance = strchr(name, '/')) != NULL)
1794 *instance++ = '\0';
1795
1796 /*
1797 * Lookup the printer and instance and make it the default...
1798 */
1799
1800 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) != NULL)
1801 dest->is_default = 1;
1802 }
1803 else
1804 instance = NULL;
1805
1806 /*
1807 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1808 */
1809
1810 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
1811 num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL,
1812 num_dests, dests);
1813
1814 if ((home = getenv("HOME")) != NULL)
1815 {
1816 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1817
1818 num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL,
1819 num_dests, dests);
1820 }
1821
1822 /*
1823 * Validate the current default destination - this prevents old
1824 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1825 * pointing to a non-existent printer or class...
1826 */
1827
1828 if (num_reals)
1829 {
1830 /*
1831 * See if we have a default printer...
1832 */
1833
1834 if ((dest = cupsGetDest(NULL, NULL, num_dests, *dests)) != NULL)
1835 {
1836 /*
1837 * Have a default; see if it is real...
1838 */
1839
1840 if (!cupsGetDest(dest->name, NULL, num_reals, reals))
1841 {
1842 /*
1843 * Remove the non-real printer from the list, since we don't want jobs
1844 * going to an unexpected printer... (<rdar://problem/14216472>)
1845 */
1846
1847 num_dests = cupsRemoveDest(dest->name, dest->instance, num_dests,
1848 dests);
1849 }
1850 }
1851
1852 /*
1853 * Free memory...
1854 */
1855
1856 free(reals);
1857 }
1858
1859 /*
1860 * Return the number of destinations...
1861 */
1862
1863 if (num_dests > 0)
1864 _cupsSetError(IPP_STATUS_OK, NULL, 0);
1865
1866 return (num_dests);
1867 }
1868
1869
1870 /*
1871 * 'cupsGetNamedDest()' - Get options for the named destination.
1872 *
1873 * This function is optimized for retrieving a single destination and should
1874 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1875 * know the name of the destination or want to print to the default destination.
1876 * If @code NULL@ is returned, the destination does not exist or there is no
1877 * default destination.
1878 *
1879 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1880 * server will be used.
1881 *
1882 * If "name" is @code NULL@, the default printer for the current user will be
1883 * returned.
1884 *
1885 * The returned destination must be freed using @link cupsFreeDests@ with a
1886 * "num_dests" value of 1.
1887 *
1888 * @since CUPS 1.4/OS X 10.6@
1889 */
1890
1891 cups_dest_t * /* O - Destination or @code NULL@ */
1892 cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1893 const char *name, /* I - Destination name or @code NULL@ for the default destination */
1894 const char *instance) /* I - Instance name or @code NULL@ */
1895 {
1896 cups_dest_t *dest; /* Destination */
1897 char filename[1024], /* Path to lpoptions */
1898 defname[256]; /* Default printer name */
1899 const char *home = getenv("HOME"); /* Home directory */
1900 int set_as_default = 0; /* Set returned destination as default */
1901 ipp_op_t op = IPP_OP_GET_PRINTER_ATTRIBUTES;
1902 /* IPP operation to get server ops */
1903 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1904
1905
1906 /*
1907 * If "name" is NULL, find the default destination...
1908 */
1909
1910 if (!name)
1911 {
1912 set_as_default = 1;
1913 name = _cupsUserDefault(defname, sizeof(defname));
1914
1915 if (name)
1916 {
1917 char *ptr; /* Temporary pointer... */
1918
1919 if ((ptr = strchr(defname, '/')) != NULL)
1920 {
1921 *ptr++ = '\0';
1922 instance = ptr;
1923 }
1924 else
1925 instance = NULL;
1926 }
1927 else if (home)
1928 {
1929 /*
1930 * No default in the environment, try the user's lpoptions files...
1931 */
1932
1933 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1934
1935 name = cups_get_default(filename, defname, sizeof(defname), &instance);
1936 }
1937
1938 if (!name)
1939 {
1940 /*
1941 * Still not there? Try the system lpoptions file...
1942 */
1943
1944 snprintf(filename, sizeof(filename), "%s/lpoptions",
1945 cg->cups_serverroot);
1946 name = cups_get_default(filename, defname, sizeof(defname), &instance);
1947 }
1948
1949 if (!name)
1950 {
1951 /*
1952 * No locally-set default destination, ask the server...
1953 */
1954
1955 op = IPP_OP_CUPS_GET_DEFAULT;
1956 }
1957 }
1958
1959 /*
1960 * Get the printer's attributes...
1961 */
1962
1963 if (!_cupsGetDests(http, op, name, &dest, 0, CUPS_PRINTER_3D))
1964 return (NULL);
1965
1966 if (instance)
1967 dest->instance = _cupsStrAlloc(instance);
1968
1969 if (set_as_default)
1970 dest->is_default = 1;
1971
1972 /*
1973 * Then add local options...
1974 */
1975
1976 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
1977 cups_get_dests(filename, name, instance, 1, 1, &dest);
1978
1979 if (home)
1980 {
1981 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1982
1983 cups_get_dests(filename, name, instance, 1, 1, &dest);
1984 }
1985
1986 /*
1987 * Return the result...
1988 */
1989
1990 return (dest);
1991 }
1992
1993
1994 /*
1995 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1996 *
1997 * Removing a destination/instance does not delete the class or printer
1998 * queue, merely the lpoptions for that destination/instance. Use the
1999 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2000 * options for the user.
2001 *
2002 * @since CUPS 1.3/OS X 10.5@
2003 */
2004
2005 int /* O - New number of destinations */
2006 cupsRemoveDest(const char *name, /* I - Destination name */
2007 const char *instance, /* I - Instance name or @code NULL@ */
2008 int num_dests, /* I - Number of destinations */
2009 cups_dest_t **dests) /* IO - Destinations */
2010 {
2011 int i; /* Index into destinations */
2012 cups_dest_t *dest; /* Pointer to destination */
2013
2014
2015 /*
2016 * Find the destination...
2017 */
2018
2019 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
2020 return (num_dests);
2021
2022 /*
2023 * Free memory...
2024 */
2025
2026 _cupsStrFree(dest->name);
2027 _cupsStrFree(dest->instance);
2028 cupsFreeOptions(dest->num_options, dest->options);
2029
2030 /*
2031 * Remove the destination from the array...
2032 */
2033
2034 num_dests --;
2035
2036 i = (int)(dest - *dests);
2037
2038 if (i < num_dests)
2039 memmove(dest, dest + 1, (size_t)(num_dests - i) * sizeof(cups_dest_t));
2040
2041 return (num_dests);
2042 }
2043
2044
2045 /*
2046 * 'cupsSetDefaultDest()' - Set the default destination.
2047 *
2048 * @since CUPS 1.3/OS X 10.5@
2049 */
2050
2051 void
2052 cupsSetDefaultDest(
2053 const char *name, /* I - Destination name */
2054 const char *instance, /* I - Instance name or @code NULL@ */
2055 int num_dests, /* I - Number of destinations */
2056 cups_dest_t *dests) /* I - Destinations */
2057 {
2058 int i; /* Looping var */
2059 cups_dest_t *dest; /* Current destination */
2060
2061
2062 /*
2063 * Range check input...
2064 */
2065
2066 if (!name || num_dests <= 0 || !dests)
2067 return;
2068
2069 /*
2070 * Loop through the array and set the "is_default" flag for the matching
2071 * destination...
2072 */
2073
2074 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2075 dest->is_default = !_cups_strcasecmp(name, dest->name) &&
2076 ((!instance && !dest->instance) ||
2077 (instance && dest->instance &&
2078 !_cups_strcasecmp(instance, dest->instance)));
2079 }
2080
2081
2082 /*
2083 * 'cupsSetDests()' - Save the list of destinations for the default server.
2084 *
2085 * This function saves the destinations to /etc/cups/lpoptions when run
2086 * as root and ~/.cups/lpoptions when run as a normal user.
2087 */
2088
2089 void
2090 cupsSetDests(int num_dests, /* I - Number of destinations */
2091 cups_dest_t *dests) /* I - Destinations */
2092 {
2093 cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
2094 }
2095
2096
2097 /*
2098 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2099 *
2100 * This function saves the destinations to /etc/cups/lpoptions when run
2101 * as root and ~/.cups/lpoptions when run as a normal user.
2102 *
2103 * @since CUPS 1.1.21/OS X 10.4@
2104 */
2105
2106 int /* O - 0 on success, -1 on error */
2107 cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2108 int num_dests, /* I - Number of destinations */
2109 cups_dest_t *dests) /* I - Destinations */
2110 {
2111 int i, j; /* Looping vars */
2112 int wrote; /* Wrote definition? */
2113 cups_dest_t *dest; /* Current destination */
2114 cups_option_t *option; /* Current option */
2115 _ipp_option_t *match; /* Matching attribute for option */
2116 FILE *fp; /* File pointer */
2117 #ifndef WIN32
2118 const char *home; /* HOME environment variable */
2119 #endif /* WIN32 */
2120 char filename[1024]; /* lpoptions file */
2121 int num_temps; /* Number of temporary destinations */
2122 cups_dest_t *temps = NULL, /* Temporary destinations */
2123 *temp; /* Current temporary dest */
2124 const char *val; /* Value of temporary option */
2125 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2126
2127
2128 /*
2129 * Range check the input...
2130 */
2131
2132 if (!num_dests || !dests)
2133 return (-1);
2134
2135 /*
2136 * Get the server destinations...
2137 */
2138
2139 num_temps = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &temps, 0, CUPS_PRINTER_3D);
2140
2141 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
2142 {
2143 cupsFreeDests(num_temps, temps);
2144 return (-1);
2145 }
2146
2147 /*
2148 * Figure out which file to write to...
2149 */
2150
2151 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2152
2153 #ifndef WIN32
2154 if (getuid())
2155 {
2156 /*
2157 * Merge in server defaults...
2158 */
2159
2160 num_temps = cups_get_dests(filename, NULL, NULL, 0, num_temps, &temps);
2161
2162 /*
2163 * Point to user defaults...
2164 */
2165
2166 if ((home = getenv("HOME")) != NULL)
2167 {
2168 /*
2169 * Create ~/.cups subdirectory...
2170 */
2171
2172 snprintf(filename, sizeof(filename), "%s/.cups", home);
2173 if (access(filename, 0))
2174 mkdir(filename, 0700);
2175
2176 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2177 }
2178 }
2179 #endif /* !WIN32 */
2180
2181 /*
2182 * Try to open the file...
2183 */
2184
2185 if ((fp = fopen(filename, "w")) == NULL)
2186 {
2187 cupsFreeDests(num_temps, temps);
2188 return (-1);
2189 }
2190
2191 #ifndef WIN32
2192 /*
2193 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2194 * file...
2195 */
2196
2197 if (!getuid())
2198 fchmod(fileno(fp), 0644);
2199 #endif /* !WIN32 */
2200
2201 /*
2202 * Write each printer; each line looks like:
2203 *
2204 * Dest name[/instance] options
2205 * Default name[/instance] options
2206 */
2207
2208 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2209 if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
2210 {
2211 if (dest->is_default)
2212 {
2213 fprintf(fp, "Default %s", dest->name);
2214 if (dest->instance)
2215 fprintf(fp, "/%s", dest->instance);
2216
2217 wrote = 1;
2218 }
2219 else
2220 wrote = 0;
2221
2222 if ((temp = cupsGetDest(dest->name, dest->instance, num_temps, temps)) == NULL)
2223 temp = cupsGetDest(dest->name, NULL, num_temps, temps);
2224
2225 for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
2226 {
2227 /*
2228 * See if this option is a printer attribute; if so, skip it...
2229 */
2230
2231 if ((match = _ippFindOption(option->name)) != NULL &&
2232 match->group_tag == IPP_TAG_PRINTER)
2233 continue;
2234
2235 /*
2236 * See if the server/global options match these; if so, don't
2237 * write 'em.
2238 */
2239
2240 if (temp &&
2241 (val = cupsGetOption(option->name, temp->num_options,
2242 temp->options)) != NULL &&
2243 !_cups_strcasecmp(val, option->value))
2244 continue;
2245
2246 /*
2247 * Options don't match, write to the file...
2248 */
2249
2250 if (!wrote)
2251 {
2252 fprintf(fp, "Dest %s", dest->name);
2253 if (dest->instance)
2254 fprintf(fp, "/%s", dest->instance);
2255 wrote = 1;
2256 }
2257
2258 if (option->value[0])
2259 {
2260 if (strchr(option->value, ' ') ||
2261 strchr(option->value, '\\') ||
2262 strchr(option->value, '\"') ||
2263 strchr(option->value, '\''))
2264 {
2265 /*
2266 * Quote the value...
2267 */
2268
2269 fprintf(fp, " %s=\"", option->name);
2270
2271 for (val = option->value; *val; val ++)
2272 {
2273 if (strchr("\"\'\\", *val))
2274 putc('\\', fp);
2275
2276 putc(*val, fp);
2277 }
2278
2279 putc('\"', fp);
2280 }
2281 else
2282 {
2283 /*
2284 * Store the literal value...
2285 */
2286
2287 fprintf(fp, " %s=%s", option->name, option->value);
2288 }
2289 }
2290 else
2291 fprintf(fp, " %s", option->name);
2292 }
2293
2294 if (wrote)
2295 fputs("\n", fp);
2296 }
2297
2298 /*
2299 * Free the temporary destinations and close the file...
2300 */
2301
2302 cupsFreeDests(num_temps, temps);
2303
2304 fclose(fp);
2305
2306 #ifdef __APPLE__
2307 /*
2308 * Set the default printer for this location - this allows command-line
2309 * and GUI applications to share the same default destination...
2310 */
2311
2312 if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
2313 {
2314 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault,
2315 dest->name,
2316 kCFStringEncodingUTF8);
2317 /* Default printer name */
2318
2319 if (name)
2320 {
2321 _cupsAppleSetDefaultPrinter(name);
2322 CFRelease(name);
2323 }
2324 }
2325 #endif /* __APPLE__ */
2326
2327 #ifdef HAVE_NOTIFY_POST
2328 /*
2329 * Send a notification so that MacOS X applications can know about the
2330 * change, too.
2331 */
2332
2333 notify_post("com.apple.printerListChange");
2334 #endif /* HAVE_NOTIFY_POST */
2335
2336 return (0);
2337 }
2338
2339
2340 /*
2341 * '_cupsUserDefault()' - Get the user default printer from environment
2342 * variables and location information.
2343 */
2344
2345 char * /* O - Default printer or NULL */
2346 _cupsUserDefault(char *name, /* I - Name buffer */
2347 size_t namesize) /* I - Size of name buffer */
2348 {
2349 const char *env; /* LPDEST or PRINTER env variable */
2350 #ifdef __APPLE__
2351 CFStringRef locprinter; /* Last printer as this location */
2352 #endif /* __APPLE__ */
2353
2354
2355 if ((env = getenv("LPDEST")) == NULL)
2356 if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
2357 env = NULL;
2358
2359 if (env)
2360 {
2361 strlcpy(name, env, namesize);
2362 return (name);
2363 }
2364
2365 #ifdef __APPLE__
2366 /*
2367 * Use location-based defaults if "use last printer" is selected in the
2368 * system preferences...
2369 */
2370
2371 if ((locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
2372 {
2373 CFStringGetCString(locprinter, name, (CFIndex)namesize, kCFStringEncodingUTF8);
2374 CFRelease(locprinter);
2375 }
2376 else
2377 name[0] = '\0';
2378
2379 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
2380
2381 return (*name ? name : NULL);
2382
2383 #else
2384 /*
2385 * No location-based defaults on this platform...
2386 */
2387
2388 name[0] = '\0';
2389 return (NULL);
2390 #endif /* __APPLE__ */
2391 }
2392
2393
2394 #ifdef __APPLE__
2395 /*
2396 * 'appleCopyLocations()' - Copy the location history array.
2397 */
2398
2399 static CFArrayRef /* O - Location array or NULL */
2400 appleCopyLocations(void)
2401 {
2402 CFArrayRef locations; /* Location array */
2403
2404
2405 /*
2406 * Look up the location array in the preferences...
2407 */
2408
2409 if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
2410 kCUPSPrintingPrefs)) == NULL)
2411 return (NULL);
2412
2413 if (CFGetTypeID(locations) != CFArrayGetTypeID())
2414 {
2415 CFRelease(locations);
2416 return (NULL);
2417 }
2418
2419 return (locations);
2420 }
2421
2422
2423 /*
2424 * 'appleCopyNetwork()' - Get the network ID for the current location.
2425 */
2426
2427 static CFStringRef /* O - Network ID */
2428 appleCopyNetwork(void)
2429 {
2430 SCDynamicStoreRef dynamicStore; /* System configuration data */
2431 CFStringRef key; /* Current network configuration key */
2432 CFDictionaryRef ip_dict; /* Network configuration data */
2433 CFStringRef network = NULL; /* Current network ID */
2434
2435
2436 if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
2437 NULL)) != NULL)
2438 {
2439 /*
2440 * First use the IPv6 router address, if available, since that will generally
2441 * be a globally-unique link-local address.
2442 */
2443
2444 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2445 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
2446 {
2447 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2448 {
2449 if ((network = CFDictionaryGetValue(ip_dict,
2450 kSCPropNetIPv6Router)) != NULL)
2451 CFRetain(network);
2452
2453 CFRelease(ip_dict);
2454 }
2455
2456 CFRelease(key);
2457 }
2458
2459 /*
2460 * If that doesn't work, try the IPv4 router address. This isn't as unique
2461 * and will likely be a 10.x.y.z or 192.168.y.z address...
2462 */
2463
2464 if (!network)
2465 {
2466 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2467 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
2468 {
2469 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2470 {
2471 if ((network = CFDictionaryGetValue(ip_dict,
2472 kSCPropNetIPv4Router)) != NULL)
2473 CFRetain(network);
2474
2475 CFRelease(ip_dict);
2476 }
2477
2478 CFRelease(key);
2479 }
2480 }
2481
2482 CFRelease(dynamicStore);
2483 }
2484
2485 return (network);
2486 }
2487
2488
2489 /*
2490 * 'appleGetPaperSize()' - Get the default paper size.
2491 */
2492
2493 static char * /* O - Default paper size */
2494 appleGetPaperSize(char *name, /* I - Paper size name buffer */
2495 int namesize) /* I - Size of buffer */
2496 {
2497 CFStringRef defaultPaperID; /* Default paper ID */
2498 pwg_media_t *pwgmedia; /* PWG media size */
2499
2500
2501 defaultPaperID = _cupsAppleCopyDefaultPaperID();
2502 if (!defaultPaperID ||
2503 CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
2504 !CFStringGetCString(defaultPaperID, name, namesize,
2505 kCFStringEncodingUTF8))
2506 name[0] = '\0';
2507 else if ((pwgmedia = pwgMediaForLegacy(name)) != NULL)
2508 strlcpy(name, pwgmedia->pwg, namesize);
2509
2510 if (defaultPaperID)
2511 CFRelease(defaultPaperID);
2512
2513 return (name);
2514 }
2515
2516
2517 /*
2518 * 'appleGetPrinter()' - Get a printer from the history array.
2519 */
2520
2521 static CFStringRef /* O - Printer name or NULL */
2522 appleGetPrinter(CFArrayRef locations, /* I - Location array */
2523 CFStringRef network, /* I - Network name */
2524 CFIndex *locindex) /* O - Index in array */
2525 {
2526 CFIndex i, /* Looping var */
2527 count; /* Number of locations */
2528 CFDictionaryRef location; /* Current location */
2529 CFStringRef locnetwork, /* Current network */
2530 locprinter; /* Current printer */
2531
2532
2533 for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
2534 if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
2535 CFGetTypeID(location) == CFDictionaryGetTypeID())
2536 {
2537 if ((locnetwork = CFDictionaryGetValue(location,
2538 kLocationNetworkKey)) != NULL &&
2539 CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
2540 CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
2541 (locprinter = CFDictionaryGetValue(location,
2542 kLocationPrinterIDKey)) != NULL &&
2543 CFGetTypeID(locprinter) == CFStringGetTypeID())
2544 {
2545 if (locindex)
2546 *locindex = i;
2547
2548 return (locprinter);
2549 }
2550 }
2551
2552 return (NULL);
2553 }
2554 #endif /* __APPLE__ */
2555
2556
2557 /*
2558 * 'cups_add_dest()' - Add a destination to the array.
2559 *
2560 * Unlike cupsAddDest(), this function does not check for duplicates.
2561 */
2562
2563 static cups_dest_t * /* O - New destination */
2564 cups_add_dest(const char *name, /* I - Name of destination */
2565 const char *instance, /* I - Instance or NULL */
2566 int *num_dests, /* IO - Number of destinations */
2567 cups_dest_t **dests) /* IO - Destinations */
2568 {
2569 int insert, /* Insertion point */
2570 diff; /* Result of comparison */
2571 cups_dest_t *dest; /* Destination pointer */
2572
2573
2574 /*
2575 * Add new destination...
2576 */
2577
2578 if (*num_dests == 0)
2579 dest = malloc(sizeof(cups_dest_t));
2580 else
2581 dest = realloc(*dests, sizeof(cups_dest_t) * (size_t)(*num_dests + 1));
2582
2583 if (!dest)
2584 return (NULL);
2585
2586 *dests = dest;
2587
2588 /*
2589 * Find where to insert the destination...
2590 */
2591
2592 if (*num_dests == 0)
2593 insert = 0;
2594 else
2595 {
2596 insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
2597 &diff);
2598
2599 if (diff > 0)
2600 insert ++;
2601 }
2602
2603 /*
2604 * Move the array elements as needed...
2605 */
2606
2607 if (insert < *num_dests)
2608 memmove(*dests + insert + 1, *dests + insert, (size_t)(*num_dests - insert) * sizeof(cups_dest_t));
2609
2610 (*num_dests) ++;
2611
2612 /*
2613 * Initialize the destination...
2614 */
2615
2616 dest = *dests + insert;
2617 dest->name = _cupsStrAlloc(name);
2618 dest->instance = _cupsStrAlloc(instance);
2619 dest->is_default = 0;
2620 dest->num_options = 0;
2621 dest->options = (cups_option_t *)0;
2622
2623 return (dest);
2624 }
2625
2626
2627 # ifdef __BLOCKS__
2628 /*
2629 * 'cups_block_cb()' - Enumeration callback for block API.
2630 */
2631
2632 static int /* O - 1 to continue, 0 to stop */
2633 cups_block_cb(
2634 cups_dest_block_t block, /* I - Block */
2635 unsigned flags, /* I - Destination flags */
2636 cups_dest_t *dest) /* I - Destination */
2637 {
2638 return ((block)(flags, dest));
2639 }
2640 # endif /* __BLOCKS__ */
2641
2642
2643 /*
2644 * 'cups_compare_dests()' - Compare two destinations.
2645 */
2646
2647 static int /* O - Result of comparison */
2648 cups_compare_dests(cups_dest_t *a, /* I - First destination */
2649 cups_dest_t *b) /* I - Second destination */
2650 {
2651 int diff; /* Difference */
2652
2653
2654 if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
2655 return (diff);
2656 else if (a->instance && b->instance)
2657 return (_cups_strcasecmp(a->instance, b->instance));
2658 else
2659 return ((a->instance && !b->instance) - (!a->instance && b->instance));
2660 }
2661
2662
2663 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2664 # ifdef HAVE_DNSSD
2665 /*
2666 * 'cups_dnssd_browse_cb()' - Browse for printers.
2667 */
2668
2669 static void
2670 cups_dnssd_browse_cb(
2671 DNSServiceRef sdRef, /* I - Service reference */
2672 DNSServiceFlags flags, /* I - Option flags */
2673 uint32_t interfaceIndex, /* I - Interface number */
2674 DNSServiceErrorType errorCode, /* I - Error, if any */
2675 const char *serviceName, /* I - Name of service/device */
2676 const char *regtype, /* I - Type of service */
2677 const char *replyDomain, /* I - Service domain */
2678 void *context) /* I - Enumeration data */
2679 {
2680 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2681 /* Enumeration data */
2682
2683
2684 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2685 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2686 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2687 sdRef, flags, interfaceIndex, errorCode, serviceName, regtype,
2688 replyDomain, context));
2689
2690 /*
2691 * Don't do anything on error...
2692 */
2693
2694 if (errorCode != kDNSServiceErr_NoError)
2695 return;
2696
2697 /*
2698 * Get the device...
2699 */
2700
2701 cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
2702 }
2703
2704
2705 # else /* HAVE_AVAHI */
2706 /*
2707 * 'cups_dnssd_browse_cb()' - Browse for printers.
2708 */
2709
2710 static void
2711 cups_dnssd_browse_cb(
2712 AvahiServiceBrowser *browser, /* I - Browser */
2713 AvahiIfIndex interface, /* I - Interface index (unused) */
2714 AvahiProtocol protocol, /* I - Network protocol (unused) */
2715 AvahiBrowserEvent event, /* I - What happened */
2716 const char *name, /* I - Service name */
2717 const char *type, /* I - Registration type */
2718 const char *domain, /* I - Domain */
2719 AvahiLookupResultFlags flags, /* I - Flags */
2720 void *context) /* I - Devices array */
2721 {
2722 #ifdef DEBUG
2723 AvahiClient *client = avahi_service_browser_get_client(browser);
2724 /* Client information */
2725 #endif /* DEBUG */
2726 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2727 /* Enumeration data */
2728
2729
2730 (void)interface;
2731 (void)protocol;
2732 (void)context;
2733
2734 switch (event)
2735 {
2736 case AVAHI_BROWSER_FAILURE:
2737 DEBUG_printf(("cups_dnssd_browse_cb: %s",
2738 avahi_strerror(avahi_client_errno(client))));
2739 avahi_simple_poll_quit(data->simple_poll);
2740 break;
2741
2742 case AVAHI_BROWSER_NEW:
2743 /*
2744 * This object is new on the network.
2745 */
2746
2747 if (flags & AVAHI_LOOKUP_RESULT_LOCAL)
2748 {
2749 /*
2750 * This comes from the local machine so ignore it.
2751 */
2752
2753 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".",
2754 name));
2755 }
2756 else
2757 {
2758 /*
2759 * Create a device entry for it if it doesn't yet exist.
2760 */
2761
2762 cups_dnssd_get_device(data, name, type, domain);
2763 }
2764 break;
2765
2766 case AVAHI_BROWSER_REMOVE:
2767 case AVAHI_BROWSER_ALL_FOR_NOW:
2768 case AVAHI_BROWSER_CACHE_EXHAUSTED:
2769 break;
2770 }
2771 }
2772
2773
2774 /*
2775 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2776 */
2777
2778 static void
2779 cups_dnssd_client_cb(
2780 AvahiClient *client, /* I - Client information (unused) */
2781 AvahiClientState state, /* I - Current state */
2782 void *context) /* I - User data (unused) */
2783 {
2784 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2785 /* Enumeration data */
2786
2787
2788 (void)client;
2789
2790 /*
2791 * If the connection drops, quit.
2792 */
2793
2794 if (state == AVAHI_CLIENT_FAILURE)
2795 {
2796 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2797 avahi_simple_poll_quit(data->simple_poll);
2798 }
2799 }
2800 # endif /* HAVE_DNSSD */
2801
2802
2803 /*
2804 * 'cups_dnssd_compare_device()' - Compare two devices.
2805 */
2806
2807 static int /* O - Result of comparison */
2808 cups_dnssd_compare_devices(
2809 _cups_dnssd_device_t *a, /* I - First device */
2810 _cups_dnssd_device_t *b) /* I - Second device */
2811 {
2812 return (strcmp(a->dest.name, b->dest.name));
2813 }
2814
2815
2816 /*
2817 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2818 */
2819
2820 static void
2821 cups_dnssd_free_device(
2822 _cups_dnssd_device_t *device, /* I - Device */
2823 _cups_dnssd_data_t *data) /* I - Enumeration data */
2824 {
2825 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device,
2826 device->dest.name, data));
2827
2828 # ifdef HAVE_DNSSD
2829 if (device->ref)
2830 DNSServiceRefDeallocate(device->ref);
2831 # else /* HAVE_AVAHI */
2832 if (device->ref)
2833 avahi_record_browser_free(device->ref);
2834 # endif /* HAVE_DNSSD */
2835
2836 _cupsStrFree(device->domain);
2837 _cupsStrFree(device->fullName);
2838 _cupsStrFree(device->regtype);
2839 _cupsStrFree(device->dest.name);
2840
2841 cupsFreeOptions(device->dest.num_options, device->dest.options);
2842
2843 free(device);
2844 }
2845
2846
2847 /*
2848 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2849 */
2850
2851 static _cups_dnssd_device_t * /* O - Device */
2852 cups_dnssd_get_device(
2853 _cups_dnssd_data_t *data, /* I - Enumeration data */
2854 const char *serviceName, /* I - Service name */
2855 const char *regtype, /* I - Registration type */
2856 const char *replyDomain) /* I - Domain name */
2857 {
2858 _cups_dnssd_device_t key, /* Search key */
2859 *device; /* Device */
2860 char fullName[kDNSServiceMaxDomainName];
2861 /* Full name for query */
2862
2863
2864 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2865 "regtype=\"%s\", replyDomain=\"%s\")", data, serviceName,
2866 regtype, replyDomain));
2867
2868 /*
2869 * See if this is an existing device...
2870 */
2871
2872 key.dest.name = (char *)serviceName;
2873
2874 if ((device = cupsArrayFind(data->devices, &key)) != NULL)
2875 {
2876 /*
2877 * Yes, see if we need to do anything with this...
2878 */
2879
2880 int update = 0; /* Non-zero if we need to update */
2881
2882 if (!_cups_strcasecmp(replyDomain, "local.") &&
2883 _cups_strcasecmp(device->domain, replyDomain))
2884 {
2885 /*
2886 * Update the "global" listing to use the .local domain name instead.
2887 */
2888
2889 _cupsStrFree(device->domain);
2890 device->domain = _cupsStrAlloc(replyDomain);
2891
2892 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2893 "domain.", device->dest.name));
2894
2895 update = 1;
2896 }
2897
2898 if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
2899 _cups_strcasecmp(device->regtype, regtype))
2900 {
2901 /*
2902 * Prefer IPPS over IPP.
2903 */
2904
2905 _cupsStrFree(device->regtype);
2906 device->regtype = _cupsStrAlloc(regtype);
2907
2908 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2909 device->dest.name));
2910
2911 update = 1;
2912 }
2913
2914 if (!update)
2915 {
2916 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2917 device->dest.name));
2918 return (device);
2919 }
2920 }
2921 else
2922 {
2923 /*
2924 * No, add the device...
2925 */
2926
2927 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2928 "'%s'.", serviceName,
2929 !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
2930 replyDomain));
2931
2932 device = calloc(sizeof(_cups_dnssd_device_t), 1);
2933 device->dest.name = _cupsStrAlloc(serviceName);
2934 device->domain = _cupsStrAlloc(replyDomain);
2935 device->regtype = _cupsStrAlloc(regtype);
2936
2937 cupsArrayAdd(data->devices, device);
2938 }
2939
2940 /*
2941 * Set the "full name" of this service, which is used for queries...
2942 */
2943
2944 # ifdef HAVE_DNSSD
2945 DNSServiceConstructFullName(fullName, device->dest.name, device->regtype,
2946 device->domain);
2947 # else /* HAVE_AVAHI */
2948 avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName,
2949 regtype, replyDomain);
2950 # endif /* HAVE_DNSSD */
2951
2952 _cupsStrFree(device->fullName);
2953 device->fullName = _cupsStrAlloc(fullName);
2954
2955 if (device->ref)
2956 {
2957 # ifdef HAVE_DNSSD
2958 DNSServiceRefDeallocate(device->ref);
2959 # else /* HAVE_AVAHI */
2960 avahi_record_browser_free(device->ref);
2961 # endif /* HAVE_DNSSD */
2962
2963 device->ref = 0;
2964 }
2965
2966 if (device->state == _CUPS_DNSSD_ACTIVE)
2967 {
2968 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
2969 device->state = _CUPS_DNSSD_NEW;
2970 }
2971
2972 return (device);
2973 }
2974
2975
2976 # ifdef HAVE_DNSSD
2977 /*
2978 * 'cups_dnssd_local_cb()' - Browse for local printers.
2979 */
2980
2981 static void
2982 cups_dnssd_local_cb(
2983 DNSServiceRef sdRef, /* I - Service reference */
2984 DNSServiceFlags flags, /* I - Option flags */
2985 uint32_t interfaceIndex, /* I - Interface number */
2986 DNSServiceErrorType errorCode, /* I - Error, if any */
2987 const char *serviceName, /* I - Name of service/device */
2988 const char *regtype, /* I - Type of service */
2989 const char *replyDomain, /* I - Service domain */
2990 void *context) /* I - Devices array */
2991 {
2992 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2993 /* Enumeration data */
2994 _cups_dnssd_device_t *device; /* Device */
2995
2996
2997 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
2998 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2999 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
3000 sdRef, flags, interfaceIndex, errorCode, serviceName,
3001 regtype, replyDomain, context));
3002
3003 /*
3004 * Only process "add" data...
3005 */
3006
3007 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3008 return;
3009
3010 /*
3011 * Get the device...
3012 */
3013
3014 device = cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
3015
3016 /*
3017 * Hide locally-registered devices...
3018 */
3019
3020 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3021 serviceName));
3022
3023 if (device->ref)
3024 {
3025 DNSServiceRefDeallocate(device->ref);
3026 device->ref = 0;
3027 }
3028
3029 if (device->state == _CUPS_DNSSD_ACTIVE)
3030 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3031
3032 device->state = _CUPS_DNSSD_LOCAL;
3033 }
3034 # endif /* HAVE_DNSSD */
3035
3036
3037 # ifdef HAVE_AVAHI
3038 /*
3039 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3040 *
3041 * Note: This function is needed because avahi_simple_poll_iterate is broken
3042 * and always uses a timeout of 0 (!) milliseconds.
3043 * (Avahi Ticket #364)
3044 */
3045
3046 static int /* O - Number of file descriptors matching */
3047 cups_dnssd_poll_cb(
3048 struct pollfd *pollfds, /* I - File descriptors */
3049 unsigned int num_pollfds, /* I - Number of file descriptors */
3050 int timeout, /* I - Timeout in milliseconds (unused) */
3051 void *context) /* I - User data (unused) */
3052 {
3053 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3054 /* Enumeration data */
3055 int val; /* Return value */
3056
3057
3058 (void)timeout;
3059
3060 val = poll(pollfds, num_pollfds, 250);
3061
3062 if (val < 0)
3063 {
3064 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
3065 }
3066 else if (val > 0)
3067 data->got_data = 1;
3068
3069 return (val);
3070 }
3071 # endif /* HAVE_AVAHI */
3072
3073
3074 /*
3075 * 'cups_dnssd_query_cb()' - Process query data.
3076 */
3077
3078 # ifdef HAVE_DNSSD
3079 static void
3080 cups_dnssd_query_cb(
3081 DNSServiceRef sdRef, /* I - Service reference */
3082 DNSServiceFlags flags, /* I - Data flags */
3083 uint32_t interfaceIndex, /* I - Interface */
3084 DNSServiceErrorType errorCode, /* I - Error, if any */
3085 const char *fullName, /* I - Full service name */
3086 uint16_t rrtype, /* I - Record type */
3087 uint16_t rrclass, /* I - Record class */
3088 uint16_t rdlen, /* I - Length of record data */
3089 const void *rdata, /* I - Record data */
3090 uint32_t ttl, /* I - Time-to-live */
3091 void *context) /* I - Enumeration data */
3092 {
3093 # else /* HAVE_AVAHI */
3094 static void
3095 cups_dnssd_query_cb(
3096 AvahiRecordBrowser *browser, /* I - Record browser */
3097 AvahiIfIndex interfaceIndex,
3098 /* I - Interface index (unused) */
3099 AvahiProtocol protocol, /* I - Network protocol (unused) */
3100 AvahiBrowserEvent event, /* I - What happened? */
3101 const char *fullName, /* I - Service name */
3102 uint16_t rrclass, /* I - Record class */
3103 uint16_t rrtype, /* I - Record type */
3104 const void *rdata, /* I - TXT record */
3105 size_t rdlen, /* I - Length of TXT record */
3106 AvahiLookupResultFlags flags, /* I - Flags */
3107 void *context) /* I - Enumeration data */
3108 {
3109 # ifdef DEBUG
3110 AvahiClient *client = avahi_record_browser_get_client(browser);
3111 /* Client information */
3112 # endif /* DEBUG */
3113 # endif /* HAVE_DNSSD */
3114 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3115 /* Enumeration data */
3116 char name[1024], /* Service name */
3117 *ptr; /* Pointer into string */
3118 _cups_dnssd_device_t dkey, /* Search key */
3119 *device; /* Device */
3120
3121
3122 # ifdef HAVE_DNSSD
3123 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
3124 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
3125 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
3126 "context=%p)", sdRef, flags, interfaceIndex, errorCode,
3127 fullName, rrtype, rrclass, rdlen, rdata, ttl, context));
3128
3129 /*
3130 * Only process "add" data...
3131 */
3132
3133 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3134 return;
3135
3136 # else /* HAVE_AVAHI */
3137 DEBUG_printf(("5cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, "
3138 "protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, "
3139 "rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)",
3140 browser, interfaceIndex, protocol, event, fullName, rrclass,
3141 rrtype, rdata, (unsigned)rdlen, flags, context));
3142
3143 /*
3144 * Only process "add" data...
3145 */
3146
3147 if (event != AVAHI_BROWSER_NEW)
3148 {
3149 if (event == AVAHI_BROWSER_FAILURE)
3150 DEBUG_printf(("cups_dnssd_query_cb: %s",
3151 avahi_strerror(avahi_client_errno(client))));
3152
3153 return;
3154 }
3155 # endif /* HAVE_DNSSD */
3156
3157 /*
3158 * Lookup the service in the devices array.
3159 */
3160
3161 dkey.dest.name = name;
3162
3163 cups_dnssd_unquote(name, fullName, sizeof(name));
3164
3165 if ((ptr = strstr(name, "._")) != NULL)
3166 *ptr = '\0';
3167
3168 if ((device = cupsArrayFind(data->devices, &dkey)) != NULL)
3169 {
3170 /*
3171 * Found it, pull out the make and model from the TXT record and save it...
3172 */
3173
3174 const uint8_t *txt, /* Pointer into data */
3175 *txtnext, /* Next key/value pair */
3176 *txtend; /* End of entire TXT record */
3177 uint8_t txtlen; /* Length of current key/value pair */
3178 char key[256], /* Key string */
3179 value[256], /* Value string */
3180 make_and_model[512],
3181 /* Manufacturer and model */
3182 model[256], /* Model */
3183 uriname[1024], /* Name for URI */
3184 uri[1024]; /* Printer URI */
3185 cups_ptype_t type = CUPS_PRINTER_REMOTE | CUPS_PRINTER_BW;
3186 /* Printer type */
3187 int saw_printer_type = 0;
3188 /* Did we see a printer-type key? */
3189
3190 device->state = _CUPS_DNSSD_PENDING;
3191 make_and_model[0] = '\0';
3192
3193 strlcpy(model, "Unknown", sizeof(model));
3194
3195 for (txt = rdata, txtend = txt + rdlen;
3196 txt < txtend;
3197 txt = txtnext)
3198 {
3199 /*
3200 * Read a key/value pair starting with an 8-bit length. Since the
3201 * length is 8 bits and the size of the key/value buffers is 256, we
3202 * don't need to check for overflow...
3203 */
3204
3205 txtlen = *txt++;
3206
3207 if (!txtlen || (txt + txtlen) > txtend)
3208 break;
3209
3210 txtnext = txt + txtlen;
3211
3212 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
3213 *ptr++ = (char)*txt;
3214 *ptr = '\0';
3215
3216 if (txt < txtnext && *txt == '=')
3217 {
3218 txt ++;
3219
3220 if (txt < txtnext)
3221 memcpy(value, txt, (size_t)(txtnext - txt));
3222 value[txtnext - txt] = '\0';
3223
3224 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
3225 }
3226 else
3227 {
3228 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
3229 continue;
3230 }
3231
3232 if (!_cups_strcasecmp(key, "usb_MFG") ||
3233 !_cups_strcasecmp(key, "usb_MANU") ||
3234 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
3235 strlcpy(make_and_model, value, sizeof(make_and_model));
3236 else if (!_cups_strcasecmp(key, "usb_MDL") ||
3237 !_cups_strcasecmp(key, "usb_MODEL"))
3238 strlcpy(model, value, sizeof(model));
3239 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
3240 {
3241 if (value[0] == '(')
3242 {
3243 /*
3244 * Strip parenthesis...
3245 */
3246
3247 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
3248 *ptr = '\0';
3249
3250 strlcpy(model, value + 1, sizeof(model));
3251 }
3252 else
3253 strlcpy(model, value, sizeof(model));
3254 }
3255 else if (!_cups_strcasecmp(key, "ty"))
3256 {
3257 strlcpy(model, value, sizeof(model));
3258
3259 if ((ptr = strchr(model, ',')) != NULL)
3260 *ptr = '\0';
3261 }
3262 else if (!_cups_strcasecmp(key, "note"))
3263 device->dest.num_options = cupsAddOption("printer-location", value,
3264 device->dest.num_options,
3265 &device->dest.options);
3266 else if (!_cups_strcasecmp(key, "pdl"))
3267 {
3268 /*
3269 * Look for PDF-capable printers; only PDF-capable printers are shown.
3270 */
3271
3272 const char *start, *next; /* Pointer into value */
3273 int have_pdf = 0; /* Have PDF? */
3274
3275 for (start = value; start && *start; start = next)
3276 {
3277 if (!_cups_strncasecmp(start, "application/pdf", 15) &&
3278 (!start[15] || start[15] == ','))
3279 {
3280 have_pdf = 1;
3281 break;
3282 }
3283
3284 if ((next = strchr(start, ',')) != NULL)
3285 next ++;
3286 }
3287
3288 if (!have_pdf)
3289 device->state = _CUPS_DNSSD_INCOMPATIBLE;
3290 }
3291 else if (!_cups_strcasecmp(key, "printer-type"))
3292 {
3293 /*
3294 * Value is either NNNN or 0xXXXX
3295 */
3296
3297 saw_printer_type = 1;
3298 type = (cups_ptype_t)strtol(value, NULL, 0);
3299 }
3300 else if (!saw_printer_type)
3301 {
3302 if (!_cups_strcasecmp(key, "air") &&
3303 !_cups_strcasecmp(value, "t"))
3304 type |= CUPS_PRINTER_AUTHENTICATED;
3305 else if (!_cups_strcasecmp(key, "bind") &&
3306 !_cups_strcasecmp(value, "t"))
3307 type |= CUPS_PRINTER_BIND;
3308 else if (!_cups_strcasecmp(key, "collate") &&
3309 !_cups_strcasecmp(value, "t"))
3310 type |= CUPS_PRINTER_COLLATE;
3311 else if (!_cups_strcasecmp(key, "color") &&
3312 !_cups_strcasecmp(value, "t"))
3313 type |= CUPS_PRINTER_COLOR;
3314 else if (!_cups_strcasecmp(key, "copies") &&
3315 !_cups_strcasecmp(value, "t"))
3316 type |= CUPS_PRINTER_COPIES;
3317 else if (!_cups_strcasecmp(key, "duplex") &&
3318 !_cups_strcasecmp(value, "t"))
3319 type |= CUPS_PRINTER_DUPLEX;
3320 else if (!_cups_strcasecmp(key, "fax") &&
3321 !_cups_strcasecmp(value, "t"))
3322 type |= CUPS_PRINTER_MFP;
3323 else if (!_cups_strcasecmp(key, "papercustom") &&
3324 !_cups_strcasecmp(value, "t"))
3325 type |= CUPS_PRINTER_VARIABLE;
3326 else if (!_cups_strcasecmp(key, "papermax"))
3327 {
3328 if (!_cups_strcasecmp(value, "legal-a4"))
3329 type |= CUPS_PRINTER_SMALL;
3330 else if (!_cups_strcasecmp(value, "isoc-a2"))
3331 type |= CUPS_PRINTER_MEDIUM;
3332 else if (!_cups_strcasecmp(value, ">isoc-a2"))
3333 type |= CUPS_PRINTER_LARGE;
3334 }
3335 else if (!_cups_strcasecmp(key, "punch") &&
3336 !_cups_strcasecmp(value, "t"))
3337 type |= CUPS_PRINTER_PUNCH;
3338 else if (!_cups_strcasecmp(key, "scan") &&
3339 !_cups_strcasecmp(value, "t"))
3340 type |= CUPS_PRINTER_MFP;
3341 else if (!_cups_strcasecmp(key, "sort") &&
3342 !_cups_strcasecmp(value, "t"))
3343 type |= CUPS_PRINTER_SORT;
3344 else if (!_cups_strcasecmp(key, "staple") &&
3345 !_cups_strcasecmp(value, "t"))
3346 type |= CUPS_PRINTER_STAPLE;
3347 }
3348 }
3349
3350 /*
3351 * Save the printer-xxx values...
3352 */
3353
3354 device->dest.num_options = cupsAddOption("printer-info", name,
3355 device->dest.num_options,
3356 &device->dest.options);
3357
3358 if (make_and_model[0])
3359 {
3360 strlcat(make_and_model, " ", sizeof(make_and_model));
3361 strlcat(make_and_model, model, sizeof(make_and_model));
3362
3363 device->dest.num_options = cupsAddOption("printer-make-and-model",
3364 make_and_model,
3365 device->dest.num_options,
3366 &device->dest.options);
3367 }
3368 else
3369 device->dest.num_options = cupsAddOption("printer-make-and-model",
3370 model,
3371 device->dest.num_options,
3372 &device->dest.options);
3373
3374 device->type = type;
3375 snprintf(value, sizeof(value), "%u", type);
3376 device->dest.num_options = cupsAddOption("printer-type", value,
3377 device->dest.num_options,
3378 &device->dest.options);
3379
3380 /*
3381 * Save the URI...
3382 */
3383
3384 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
3385 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
3386 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
3387 NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
3388
3389 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri));
3390
3391 device->dest.num_options = cupsAddOption("printer-uri-supported", uri,
3392 device->dest.num_options,
3393 &device->dest.options);
3394 }
3395 else
3396 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3397 fullName));
3398 }
3399
3400
3401 /*
3402 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3403 */
3404
3405 static const char * /* O - Resolved URI or NULL */
3406 cups_dnssd_resolve(
3407 cups_dest_t *dest, /* I - Destination */
3408 const char *uri, /* I - Current printer URI */
3409 int msec, /* I - Time in milliseconds */
3410 int *cancel, /* I - Pointer to "cancel" variable */
3411 cups_dest_cb_t cb, /* I - Callback */
3412 void *user_data) /* I - User data for callback */
3413 {
3414 char tempuri[1024]; /* Temporary URI buffer */
3415 _cups_dnssd_resolve_t resolve; /* Resolve data */
3416
3417
3418 /*
3419 * Resolve the URI...
3420 */
3421
3422 resolve.cancel = cancel;
3423 gettimeofday(&resolve.end_time, NULL);
3424 if (msec > 0)
3425 {
3426 resolve.end_time.tv_sec += msec / 1000;
3427 resolve.end_time.tv_usec += (msec % 1000) * 1000;
3428
3429 while (resolve.end_time.tv_usec >= 1000000)
3430 {
3431 resolve.end_time.tv_sec ++;
3432 resolve.end_time.tv_usec -= 1000000;
3433 }
3434 }
3435 else
3436 resolve.end_time.tv_sec += 75;
3437
3438 if (cb)
3439 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING,
3440 dest);
3441
3442 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri),
3443 _HTTP_RESOLVE_FQDN, cups_dnssd_resolve_cb,
3444 &resolve)) == NULL)
3445 {
3446 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1);
3447
3448 if (cb)
3449 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
3450 dest);
3451
3452 return (NULL);
3453 }
3454
3455 /*
3456 * Save the resolved URI...
3457 */
3458
3459 dest->num_options = cupsAddOption("printer-uri-supported", uri,
3460 dest->num_options, &dest->options);
3461
3462 return (cupsGetOption("printer-uri-supported", dest->num_options,
3463 dest->options));
3464 }
3465
3466
3467 /*
3468 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3469 */
3470
3471 static int /* O - 1 to continue, 0 to stop */
3472 cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
3473 {
3474 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
3475 /* Resolve data */
3476 struct timeval curtime; /* Current time */
3477
3478
3479 /*
3480 * If the cancel variable is set, return immediately.
3481 */
3482
3483 if (*resolve->cancel)
3484 return (0);
3485
3486 /*
3487 * Otherwise check the end time...
3488 */
3489
3490 gettimeofday(&curtime, NULL);
3491
3492 return (curtime.tv_sec > resolve->end_time.tv_sec ||
3493 (curtime.tv_sec == resolve->end_time.tv_sec &&
3494 curtime.tv_usec > resolve->end_time.tv_usec));
3495 }
3496
3497
3498 /*
3499 * 'cups_dnssd_unquote()' - Unquote a name string.
3500 */
3501
3502 static void
3503 cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3504 const char *src, /* I - Source string */
3505 size_t dstsize) /* I - Size of destination buffer */
3506 {
3507 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3508
3509
3510 while (*src && dst < dstend)
3511 {
3512 if (*src == '\\')
3513 {
3514 src ++;
3515 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3516 isdigit(src[2] & 255))
3517 {
3518 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3519 src += 3;
3520 }
3521 else
3522 *dst++ = *src++;
3523 }
3524 else
3525 *dst++ = *src ++;
3526 }
3527
3528 *dst = '\0';
3529 }
3530 #endif /* HAVE_DNSSD */
3531
3532
3533 /*
3534 * 'cups_find_dest()' - Find a destination using a binary search.
3535 */
3536
3537 static int /* O - Index of match */
3538 cups_find_dest(const char *name, /* I - Destination name */
3539 const char *instance, /* I - Instance or NULL */
3540 int num_dests, /* I - Number of destinations */
3541 cups_dest_t *dests, /* I - Destinations */
3542 int prev, /* I - Previous index */
3543 int *rdiff) /* O - Difference of match */
3544 {
3545 int left, /* Low mark for binary search */
3546 right, /* High mark for binary search */
3547 current, /* Current index */
3548 diff; /* Result of comparison */
3549 cups_dest_t key; /* Search key */
3550
3551
3552 key.name = (char *)name;
3553 key.instance = (char *)instance;
3554
3555 if (prev >= 0)
3556 {
3557 /*
3558 * Start search on either side of previous...
3559 */
3560
3561 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3562 (diff < 0 && prev == 0) ||
3563 (diff > 0 && prev == (num_dests - 1)))
3564 {
3565 *rdiff = diff;
3566 return (prev);
3567 }
3568 else if (diff < 0)
3569 {
3570 /*
3571 * Start with previous on right side...
3572 */
3573
3574 left = 0;
3575 right = prev;
3576 }
3577 else
3578 {
3579 /*
3580 * Start wih previous on left side...
3581 */
3582
3583 left = prev;
3584 right = num_dests - 1;
3585 }
3586 }
3587 else
3588 {
3589 /*
3590 * Start search in the middle...
3591 */
3592
3593 left = 0;
3594 right = num_dests - 1;
3595 }
3596
3597 do
3598 {
3599 current = (left + right) / 2;
3600 diff = cups_compare_dests(&key, dests + current);
3601
3602 if (diff == 0)
3603 break;
3604 else if (diff < 0)
3605 right = current;
3606 else
3607 left = current;
3608 }
3609 while ((right - left) > 1);
3610
3611 if (diff != 0)
3612 {
3613 /*
3614 * Check the last 1 or 2 elements...
3615 */
3616
3617 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
3618 current = left;
3619 else
3620 {
3621 diff = cups_compare_dests(&key, dests + right);
3622 current = right;
3623 }
3624 }
3625
3626 /*
3627 * Return the closest destination and the difference...
3628 */
3629
3630 *rdiff = diff;
3631
3632 return (current);
3633 }
3634
3635
3636 /*
3637 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3638 */
3639
3640 static char * /* O - Default destination or NULL */
3641 cups_get_default(const char *filename, /* I - File to read */
3642 char *namebuf, /* I - Name buffer */
3643 size_t namesize, /* I - Size of name buffer */
3644 const char **instance) /* I - Instance */
3645 {
3646 cups_file_t *fp; /* lpoptions file */
3647 char line[8192], /* Line from file */
3648 *value, /* Value for line */
3649 *nameptr; /* Pointer into name */
3650 int linenum; /* Current line */
3651
3652
3653 *namebuf = '\0';
3654
3655 if ((fp = cupsFileOpen(filename, "r")) != NULL)
3656 {
3657 linenum = 0;
3658
3659 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3660 {
3661 if (!_cups_strcasecmp(line, "default") && value)
3662 {
3663 strlcpy(namebuf, value, namesize);
3664
3665 if ((nameptr = strchr(namebuf, ' ')) != NULL)
3666 *nameptr = '\0';
3667 if ((nameptr = strchr(namebuf, '\t')) != NULL)
3668 *nameptr = '\0';
3669
3670 if ((nameptr = strchr(namebuf, '/')) != NULL)
3671 *nameptr++ = '\0';
3672
3673 *instance = nameptr;
3674 break;
3675 }
3676 }
3677
3678 cupsFileClose(fp);
3679 }
3680
3681 return (*namebuf ? namebuf : NULL);
3682 }
3683
3684
3685 /*
3686 * 'cups_get_dests()' - Get destinations from a file.
3687 */
3688
3689 static int /* O - Number of destinations */
3690 cups_get_dests(
3691 const char *filename, /* I - File to read from */
3692 const char *match_name, /* I - Destination name we want */
3693 const char *match_inst, /* I - Instance name we want */
3694 int user_default_set, /* I - User default printer set? */
3695 int num_dests, /* I - Number of destinations */
3696 cups_dest_t **dests) /* IO - Destinations */
3697 {
3698 int i; /* Looping var */
3699 cups_dest_t *dest; /* Current destination */
3700 cups_file_t *fp; /* File pointer */
3701 char line[8192], /* Line from file */
3702 *lineptr, /* Pointer into line */
3703 *name, /* Name of destination/option */
3704 *instance; /* Instance of destination */
3705 int linenum; /* Current line number */
3706
3707
3708 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
3709 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
3710 "dests=%p)", filename, match_name, match_inst,
3711 user_default_set, num_dests, dests));
3712
3713 /*
3714 * Try to open the file...
3715 */
3716
3717 if ((fp = cupsFileOpen(filename, "r")) == NULL)
3718 return (num_dests);
3719
3720 /*
3721 * Read each printer; each line looks like:
3722 *
3723 * Dest name[/instance] options
3724 * Default name[/instance] options
3725 */
3726
3727 linenum = 0;
3728
3729 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
3730 {
3731 /*
3732 * See what type of line it is...
3733 */
3734
3735 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3736 linenum, line, lineptr));
3737
3738 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
3739 {
3740 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3741 continue;
3742 }
3743
3744 name = lineptr;
3745
3746 /*
3747 * Search for an instance...
3748 */
3749
3750 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
3751 lineptr ++;
3752
3753 if (*lineptr == '/')
3754 {
3755 /*
3756 * Found an instance...
3757 */
3758
3759 *lineptr++ = '\0';
3760 instance = lineptr;
3761
3762 /*
3763 * Search for an instance...
3764 */
3765
3766 while (!isspace(*lineptr & 255) && *lineptr)
3767 lineptr ++;
3768 }
3769 else
3770 instance = NULL;
3771
3772 if (*lineptr)
3773 *lineptr++ = '\0';
3774
3775 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
3776 instance));
3777
3778 /*
3779 * See if the primary instance of the destination exists; if not,
3780 * ignore this entry and move on...
3781 */
3782
3783 if (match_name)
3784 {
3785 if (_cups_strcasecmp(name, match_name) ||
3786 (!instance && match_inst) ||
3787 (instance && !match_inst) ||
3788 (instance && _cups_strcasecmp(instance, match_inst)))
3789 continue;
3790
3791 dest = *dests;
3792 }
3793 else if (cupsGetDest(name, NULL, num_dests, *dests) == NULL)
3794 {
3795 DEBUG_puts("9cups_get_dests: Not found!");
3796 continue;
3797 }
3798 else
3799 {
3800 /*
3801 * Add the destination...
3802 */
3803
3804 num_dests = cupsAddDest(name, instance, num_dests, dests);
3805
3806 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
3807 {
3808 /*
3809 * Out of memory!
3810 */
3811
3812 DEBUG_puts("9cups_get_dests: Out of memory!");
3813 break;
3814 }
3815 }
3816
3817 /*
3818 * Add options until we hit the end of the line...
3819 */
3820
3821 dest->num_options = cupsParseOptions(lineptr, dest->num_options,
3822 &(dest->options));
3823
3824 /*
3825 * If we found what we were looking for, stop now...
3826 */
3827
3828 if (match_name)
3829 break;
3830
3831 /*
3832 * Set this as default if needed...
3833 */
3834
3835 if (!user_default_set && !_cups_strcasecmp(line, "default"))
3836 {
3837 DEBUG_puts("9cups_get_dests: Setting as default...");
3838
3839 for (i = 0; i < num_dests; i ++)
3840 (*dests)[i].is_default = 0;
3841
3842 dest->is_default = 1;
3843 }
3844 }
3845
3846 /*
3847 * Close the file and return...
3848 */
3849
3850 cupsFileClose(fp);
3851
3852 return (num_dests);
3853 }
3854
3855
3856 /*
3857 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3858 * attribute.
3859 */
3860
3861 static char * /* O - New string */
3862 cups_make_string(
3863 ipp_attribute_t *attr, /* I - Attribute to convert */
3864 char *buffer, /* I - Buffer */
3865 size_t bufsize) /* I - Size of buffer */
3866 {
3867 int i; /* Looping var */
3868 char *ptr, /* Pointer into buffer */
3869 *end, /* Pointer to end of buffer */
3870 *valptr; /* Pointer into string attribute */
3871
3872
3873 /*
3874 * Return quickly if we have a single string value...
3875 */
3876
3877 if (attr->num_values == 1 &&
3878 attr->value_tag != IPP_TAG_INTEGER &&
3879 attr->value_tag != IPP_TAG_ENUM &&
3880 attr->value_tag != IPP_TAG_BOOLEAN &&
3881 attr->value_tag != IPP_TAG_RANGE)
3882 return (attr->values[0].string.text);
3883
3884 /*
3885 * Copy the values to the string, separating with commas and escaping strings
3886 * as needed...
3887 */
3888
3889 end = buffer + bufsize - 1;
3890
3891 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
3892 {
3893 if (i)
3894 *ptr++ = ',';
3895
3896 switch (attr->value_tag)
3897 {
3898 case IPP_TAG_INTEGER :
3899 case IPP_TAG_ENUM :
3900 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].integer);
3901 break;
3902
3903 case IPP_TAG_BOOLEAN :
3904 if (attr->values[i].boolean)
3905 strlcpy(ptr, "true", (size_t)(end - ptr + 1));
3906 else
3907 strlcpy(ptr, "false", (size_t)(end - ptr + 1));
3908 break;
3909
3910 case IPP_TAG_RANGE :
3911 if (attr->values[i].range.lower == attr->values[i].range.upper)
3912 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].range.lower);
3913 else
3914 snprintf(ptr, (size_t)(end - ptr + 1), "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper);
3915 break;
3916
3917 default :
3918 for (valptr = attr->values[i].string.text;
3919 *valptr && ptr < end;)
3920 {
3921 if (strchr(" \t\n\\\'\"", *valptr))
3922 {
3923 if (ptr >= (end - 1))
3924 break;
3925
3926 *ptr++ = '\\';
3927 }
3928
3929 *ptr++ = *valptr++;
3930 }
3931
3932 *ptr = '\0';
3933 break;
3934 }
3935
3936 ptr += strlen(ptr);
3937 }
3938
3939 *ptr = '\0';
3940
3941 return (buffer);
3942 }
3943
3944
3945 /*
3946 * End of "$Id$".
3947 */