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