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