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