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