]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/dest.c
Merge changes from CUPS 1.6svn-r10188, including changes for <rdar://problem/10127258...
[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
351//# ifdef DEBUG
352// CFStringGetCString(network, name, namesize, kCFStringEncodingUTF8);
353// DEBUG_printf(("2_cupsUserDefault: network=\"%s\"", name));
354//# endif /* DEBUG */
355
356 /*
357 * Lookup the network in the preferences...
358 */
359
360 if ((locations = appleCopyLocations()) == NULL)
361 {
362 /*
363 * Missing or bad location array, so no location-based default...
364 */
365
366 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
367 "printer array.");
368
369 CFRelease(network);
370
371 return (NULL);
372 }
88f9aafc 373
f14324a7
MS
374 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
375 (int)CFArrayGetCount(locations)));
376
377 if ((locprinter = appleGetPrinter(locations, network, NULL)) != NULL)
378 CFRetain(locprinter);
379
380 CFRelease(network);
381 CFRelease(locations);
382
383 return (locprinter);
c8fef167
MS
384}
385
386
387/*
388 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
389 */
390
391int /* O - 1 to use last printer, 0 otherwise */
392_cupsAppleGetUseLastPrinter(void)
393{
394 Boolean uselast, /* Use last printer preference value */
395 uselast_set; /* Valid is set? */
396
397
398 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
399 return (0);
400
f14324a7
MS
401 uselast = CFPreferencesGetAppBooleanValue(kUseLastPrinter,
402 kCUPSPrintingPrefs,
c8fef167 403 &uselast_set);
c8fef167
MS
404 if (!uselast_set)
405 return (1);
406 else
407 return (uselast);
408}
409
410
411/*
412 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
413 */
414
415void
416_cupsAppleSetDefaultPaperID(
417 CFStringRef name) /* I - New paper ID */
418{
f14324a7
MS
419 CFPreferencesSetAppValue(kDefaultPaperIDKey, name, kCUPSPrintingPrefs);
420 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
421 notify_post("com.apple.printerPrefsChange");
422}
423
424
425/*
426 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
427 */
428
429void
430_cupsAppleSetDefaultPrinter(
431 CFStringRef name) /* I - Default printer/class name */
432{
433 CFStringRef network; /* Current network */
434 CFArrayRef locations; /* Old locations array */
435 CFIndex locindex; /* Index in locations array */
436 CFStringRef locprinter; /* Current printer */
437 CFMutableArrayRef newlocations; /* New locations array */
438 CFMutableDictionaryRef newlocation; /* New location */
439
440
441 /*
442 * Get the current location...
443 */
444
445 if ((network = appleCopyNetwork()) == NULL)
446 {
447 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
448 return;
449 }
450
451 /*
452 * Lookup the network in the preferences...
453 */
454
455 if ((locations = appleCopyLocations()) != NULL)
456 locprinter = appleGetPrinter(locations, network, &locindex);
457 else
458 {
459 locprinter = NULL;
460 locindex = -1;
461 }
462
463 if (!locprinter || CFStringCompare(locprinter, name, 0) != kCFCompareEqualTo)
464 {
465 /*
466 * Need to change the locations array...
467 */
468
469 if (locations)
470 {
471 newlocations = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0,
472 locations);
473
474 if (locprinter)
475 CFArrayRemoveValueAtIndex(newlocations, locindex);
476 }
477 else
478 newlocations = CFArrayCreateMutable(kCFAllocatorDefault, 0,
479 &kCFTypeArrayCallBacks);
480
481 newlocation = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
482 &kCFTypeDictionaryKeyCallBacks,
483 &kCFTypeDictionaryValueCallBacks);
484
485 if (newlocation && newlocations)
486 {
487 /*
488 * Put the new location at the front of the array...
489 */
490
491 CFDictionaryAddValue(newlocation, kLocationNetworkKey, network);
492 CFDictionaryAddValue(newlocation, kLocationPrinterIDKey, name);
493 CFArrayInsertValueAtIndex(newlocations, 0, newlocation);
494
495 /*
496 * Limit the number of locations to 10...
497 */
498
499 while (CFArrayGetCount(newlocations) > 10)
500 CFArrayRemoveValueAtIndex(newlocations, 10);
501
502 /*
503 * Push the changes out...
504 */
505
506 CFPreferencesSetAppValue(kLastUsedPrintersKey, newlocations,
507 kCUPSPrintingPrefs);
508 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
509 notify_post("com.apple.printerPrefsChange");
510 }
511
512 if (newlocations)
513 CFRelease(newlocations);
514
515 if (newlocation)
516 CFRelease(newlocation);
517 }
518
519 if (locations)
520 CFRelease(locations);
521
522 CFRelease(network);
c8fef167
MS
523}
524
525
526/*
527 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
528 */
88f9aafc
MS
529
530void
c8fef167
MS
531_cupsAppleSetUseLastPrinter(
532 int uselast) /* O - 1 to use last printer, 0 otherwise */
533{
88f9aafc 534 CFPreferencesSetAppValue(kUseLastPrinter,
c8fef167 535 uselast ? kCFBooleanTrue : kCFBooleanFalse,
f14324a7
MS
536 kCUPSPrintingPrefs);
537 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
538 notify_post("com.apple.printerPrefsChange");
c8fef167
MS
539}
540#endif /* __APPLE__ */
541
542
9c80ffa2
MS
543/*
544 * 'cupsConnectDest()' - Connect to the server for a destination.
545 *
dcb445bc
MS
546 * Connect to the destination, returning a new http_t connection object and
547 * optionally the resource path to use for the destination. These calls will
548 * block until a connection is made, the timeout expires, the integer pointed
549 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
550 * The caller is responsible for calling httpClose() on the returned object.
551 *
9c80ffa2
MS
552 * @since CUPS 1.6@
553 */
554
555http_t * /* O - Connection to server or @code NULL@ */
dcb445bc
MS
556cupsConnectDest(
557 cups_dest_t *dest, /* I - Destination */
558 unsigned flags, /* I - Connection flags */
559 int msec, /* I - Timeout in milliseconds */
560 int *cancel, /* I - Pointer to "cancel" variable */
561 char *resource, /* I - Resource buffer */
562 size_t resourcesize, /* I - Size of resource buffer */
563 cups_dest_cb_t cb, /* I - Callback function */
564 void *user_data) /* I - User data pointer */
9c80ffa2 565{
dcb445bc
MS
566 const char *uri; /* Printer URI */
567 char scheme[32], /* URI scheme */
568 userpass[256], /* Username and password (unused) */
569 hostname[256], /* Hostname */
570 tempresource[1024]; /* Temporary resource buffer */
571 int port; /* Port number */
572 char portstr[16]; /* Port number string */
573 http_encryption_t encrypt; /* Encryption to use */
574 http_addrlist_t *addrlist; /* Address list for server */
575 http_t *http; /* Connection to server */
576
577
578 /*
579 * Range check input...
580 */
581
582 if (!dest)
583 {
584 if (resource)
585 *resource = '\0';
586
587 _cupsSetError(IPP_INTERNAL_ERROR, strerror(EINVAL), 0);
588 return (NULL);
589 }
590
591 if (!resource || resourcesize < 1)
592 {
593 resource = tempresource;
594 resourcesize = sizeof(tempresource);
595 }
596
597 /*
598 * Grab the printer URI...
599 */
600
601 if ((uri = cupsGetOption("printer-uri-supported", dest->num_options,
602 dest->options)) == NULL)
603 {
604 _cupsSetError(IPP_INTERNAL_ERROR, strerror(ENOENT), 0);
605
606 if (cb)
607 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
608 dest);
609
610 return (NULL);
611 }
612
613#ifdef HAVE_DNSSD
614 if (strstr(uri, "._tcp"))
615 {
616 if ((uri = cups_dnssd_resolve(dest, uri, msec, cancel, cb,
617 user_data)) == NULL)
618 return (NULL);
619 }
620#endif /* HAVE_DNSSD */
621
622 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
623 userpass, sizeof(userpass), hostname, sizeof(hostname),
624 &port, resource, resourcesize) < HTTP_URI_OK)
625 {
626 _cupsSetError(IPP_INTERNAL_ERROR, _("Bad printer URI."), 1);
627
628 if (cb)
629 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
630 dest);
631
632 return (NULL);
633 }
634
635 /*
636 * Lookup the address for the server...
637 */
638
639 if (cb)
640 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING,
641 dest);
642
643 snprintf(portstr, sizeof(portstr), "%d", port);
644
645 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portstr)) == NULL)
646 {
647 if (cb)
648 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
649 dest);
650
651 return (NULL);
652 }
653
654 if (cancel && *cancel)
655 {
656 httpAddrFreeList(addrlist);
657
658 if (cb)
659 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CANCELED,
660 dest);
661
662 return (NULL);
663 }
664
665 /*
666 * Create the HTTP object pointing to the server referenced by the URI...
667 */
668
669 if (!strcmp(scheme, "ipps") || port == 443)
670 encrypt = HTTP_ENCRYPT_ALWAYS;
671 else
672 encrypt = HTTP_ENCRYPT_IF_REQUESTED;
673
674 http = _httpCreate(hostname, port, addrlist, encrypt, AF_UNSPEC);
675
676 /*
677 * Connect if requested...
678 */
679
680 if (flags & CUPS_DEST_FLAGS_UNCONNECTED)
681 {
682 if (cb)
683 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED, dest);
684 }
685 else
686 {
687 if (cb)
688 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING,
689 dest);
690
691 if (!httpReconnect2(http, msec, cancel) && cb)
692 {
693 if (cancel && *cancel)
694 (*cb)(user_data,
695 CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING, dest);
696 else
697 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
698 dest);
699 }
700 else if (cb)
701 (*cb)(user_data, CUPS_DEST_FLAGS_NONE, dest);
702 }
703
704 return (http);
705}
706
707
708#ifdef __BLOCKS__
709/*
710 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
711 *
712 * Connect to the destination, returning a new http_t connection object and
713 * optionally the resource path to use for the destination. These calls will
714 * block until a connection is made, the timeout expires, the integer pointed
715 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
716 * The caller is responsible for calling httpClose() on the returned object.
717 *
718 * @since CUPS 1.6@
719 */
720
721http_t * /* O - Connection to server or @code NULL@ */
722cupsConnectDestBlock(
723 cups_dest_t *dest, /* I - Destination */
724 unsigned flags, /* I - Connection flags */
725 int msec, /* I - Timeout in milliseconds */
726 int *cancel, /* I - Pointer to "cancel" variable */
727 char *resource, /* I - Resource buffer */
728 size_t resourcesize, /* I - Size of resource buffer */
729 cups_dest_block_t block) /* I - Callback block */
730{
731 return (cupsConnectDest(dest, flags, msec, cancel, resource, resourcesize,
732 (cups_dest_cb_t)cups_block_cb, (void *)block));
733}
734#endif /* __BLOCKS__ */
735
736
737/*
738 * 'cupsCopyDest()' - Copy a destination.
739 *
740 * Make a copy of the destination to an array of destinations (or just a single
741 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
742 * for calling cupsFreeDests() on the returned object(s).
743 *
744 * @since CUPS 1.6@
745 */
746
747int
748cupsCopyDest(cups_dest_t *dest,
749 int num_dests,
750 cups_dest_t **dests)
751{
752 int i; /* Looping var */
753 cups_dest_t *new_dest; /* New destination pointer */
754 cups_option_t *new_option, /* Current destination option */
755 *option; /* Current parent option */
756
757
758 /*
759 * Range check input...
760 */
761
762 if (!dest || num_dests < 0 || !dests)
763 return (num_dests);
764
765 /*
766 * See if the destination already exists...
767 */
768
769 if ((new_dest = cupsGetDest(dest->name, dest->instance, num_dests,
770 *dests)) != NULL)
771 {
772 /*
773 * Protect against copying destination to itself...
774 */
775
776 if (new_dest == dest)
777 return (num_dests);
778
779 /*
780 * Otherwise, free the options...
781 */
782
783 cupsFreeOptions(new_dest->num_options, new_dest->options);
784
785 new_dest->num_options = 0;
786 new_dest->options = NULL;
787 }
788 else
789 new_dest = cups_add_dest(dest->name, dest->instance, &num_dests, dests);
790
791 if (new_dest)
792 {
793 if ((new_dest->options = calloc(sizeof(cups_option_t),
794 dest->num_options)) == NULL)
795 return (cupsRemoveDest(dest->name, dest->instance, num_dests, dests));
796
797 new_dest->num_options = dest->num_options;
798
799 for (i = dest->num_options, option = dest->options,
800 new_option = new_dest->options;
801 i > 0;
802 i --, option ++, new_option ++)
803 {
804 new_option->name = _cupsStrRetain(option->name);
805 new_option->value = _cupsStrRetain(option->value);
806 }
807 }
808
809 return (num_dests);
9c80ffa2
MS
810}
811
812
813/*
814 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
815 *
dcb445bc
MS
816 * Destinations are enumerated from one or more sources. The callback function
817 * receives the @code user_data@ pointer, destination name, instance, number of
818 * options, and options which can be used as input to the @link cupsAddDest@
819 * function. The function must return 1 to continue enumeration or 0 to stop.
9c80ffa2 820 *
dcb445bc
MS
821 * Enumeration happens on the current thread and does not return until all
822 * destinations have been enumerated or the callback function returns 0.
9c80ffa2
MS
823 *
824 * @since CUPS 1.6@
825 */
826
827int /* O - 1 on success, 0 on failure */
dcb445bc
MS
828cupsEnumDests(
829 unsigned flags, /* I - Enumeration flags */
830 int msec, /* I - Timeout in milliseconds,
831 * -1 for indefinite */
832 int *cancel, /* I - Pointer to "cancel" variable */
833 cups_ptype_t type, /* I - Printer type bits */
834 cups_ptype_t mask, /* I - Mask for printer type bits */
835 cups_dest_cb_t cb, /* I - Callback function */
836 void *user_data) /* I - User data */
9c80ffa2 837{
dcb445bc
MS
838 int i, /* Looping var */
839 num_dests; /* Number of destinations */
840 cups_dest_t *dests, /* Destinations */
841 *dest; /* Current destination */
842#ifdef HAVE_DNSSD
843 int nfds, /* Number of files responded */
844 count, /* Number of queries started */
845 remaining; /* Remainder of timeout */
846 _cups_dnssd_data_t data; /* Data for callback */
847 _cups_dnssd_device_t *device; /* Current device */
848 int main_fd; /* File descriptor for lookups */
849 DNSServiceRef ipp_ref, /* IPP browser */
850 local_ipp_ref; /* Local IPP browser */
851# ifdef HAVE_SSL
852 DNSServiceRef ipps_ref, /* IPPS browser */
853 local_ipps_ref; /* Local IPPS browser */
854# endif /* HAVE_SSL */
855# ifdef HAVE_POLL
856 struct pollfd pfd; /* Polling data */
857# else
858 fd_set input; /* Input set for select() */
859 struct timeval timeout; /* Timeout for select() */
860# endif /* HAVE_POLL */
861#endif /* HAVE_DNSSD */
862
863
864 /*
865 * Range check input...
866 */
867
868 if (!cb)
869 return (0);
870
871 /*
872 * Get the list of local printers and pass them to the callback function...
873 */
874
875 num_dests = _cupsGetDests(CUPS_HTTP_DEFAULT, CUPS_GET_PRINTERS, NULL, &dests,
876 type, mask);
877
878 for (i = num_dests, dest = dests;
879 i > 0 && (!cancel || !*cancel);
880 i --, dest ++)
881 if (!(*cb)(user_data, i > 1 ? CUPS_DEST_FLAGS_MORE : CUPS_DEST_FLAGS_NONE,
882 dest))
883 break;
884
885 cupsFreeDests(num_dests, dests);
886
887 if (i > 0 || msec == 0)
888 return (1);
889
890#ifdef HAVE_DNSSD
891 /*
892 * Get Bonjour-shared printers...
893 */
894
895 data.type = type;
896 data.mask = mask;
897 data.devices = cupsArrayNew3((cups_array_func_t)cups_dnssd_compare_devices,
898 NULL, NULL, 0, NULL,
899 (cups_afree_func_t)cups_dnssd_free_device);
900
901 if (DNSServiceCreateConnection(&data.main_ref) != kDNSServiceErr_NoError)
902 return (0);
903
904 main_fd = DNSServiceRefSockFD(data.main_ref);
905
906 ipp_ref = data.main_ref;
907 DNSServiceBrowse(&ipp_ref, kDNSServiceFlagsShareConnection, 0,
908 "_ipp._tcp,_cups", NULL, cups_dnssd_browse_cb, &data);
909
910 local_ipp_ref = data.main_ref;
911 DNSServiceBrowse(&local_ipp_ref, kDNSServiceFlagsShareConnection,
912 kDNSServiceInterfaceIndexLocalOnly,
913 "_ipp._tcp,_cups", NULL, cups_dnssd_local_cb, &data);
914
915# ifdef HAVE_SSL
916 ipps_ref = data.main_ref;
917 DNSServiceBrowse(&ipps_ref, kDNSServiceFlagsShareConnection, 0,
918 "_ipps._tcp,_cups", NULL, cups_dnssd_browse_cb, &data);
919
920 local_ipps_ref = data.main_ref;
921 DNSServiceBrowse(&local_ipps_ref, kDNSServiceFlagsShareConnection,
922 kDNSServiceInterfaceIndexLocalOnly,
923 "_ipps._tcp,_cups", NULL, cups_dnssd_local_cb, &data);
924# endif /* HAVE_SSL */
925
926 if (msec < 0)
927 remaining = INT_MAX;
928 else
929 remaining = msec;
930
931 while (remaining > 0 && (!cancel || !*cancel))
932 {
933 /*
934 * Check for input...
935 */
936
937# ifdef HAVE_POLL
938 pfd.fd = main_fd;
939 pfd.events = POLLIN;
940
941 nfds = poll(&pfd, 1, remaining > 250 ? 250 : remaining);
942
943# else
944 FD_ZERO(&input);
945 FD_SET(main_fd, &input);
946
947 timeout.tv_sec = 0;
948 timeout.tv_usec = remaining > 250 ? 250000 : remaining * 1000;
949
950 nfds = select(main_fd + 1, &input, NULL, NULL, &timeout);
951# endif /* HAVE_POLL */
952
953 if (nfds > 0)
954 DNSServiceProcessResult(data.main_ref);
955 else if (nfds == 0)
956 remaining -= 250;
957
958 for (device = (_cups_dnssd_device_t *)cupsArrayFirst(data.devices),
959 count = 0;
960 device;
961 device = (_cups_dnssd_device_t *)cupsArrayNext(data.devices))
962 {
963 if (device->ref)
964 count ++;
965
966 if (!device->ref && device->state == _CUPS_DNSSD_NEW)
967 {
968 device->ref = data.main_ref;
969
970 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device->fullName));
971
972 if (DNSServiceQueryRecord(&(device->ref),
973 kDNSServiceFlagsShareConnection,
974 0, device->fullName,
975 kDNSServiceType_TXT,
976 kDNSServiceClass_IN, cups_dnssd_query_cb,
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 */
1932 cups_dest_t *temps, /* Temporary destinations */
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 */
2799 cups_ptype_t type; /* Device type */
2800
2801 device->state = _CUPS_DNSSD_PENDING;
2802 make_and_model[0] = '\0';
2803 type = CUPS_PRINTER_REMOTE;
2804
2805 strcpy(model, "Unknown");
2806
2807 for (txt = rdata, txtend = txt + rdlen;
2808 txt < txtend;
2809 txt = txtnext)
2810 {
2811 /*
2812 * Read a key/value pair starting with an 8-bit length. Since the
2813 * length is 8 bits and the size of the key/value buffers is 256, we
2814 * don't need to check for overflow...
2815 */
2816
2817 txtlen = *txt++;
2818
2819 if (!txtlen || (txt + txtlen) > txtend)
2820 break;
2821
2822 txtnext = txt + txtlen;
2823
2824 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
2825 *ptr++ = *txt;
2826 *ptr = '\0';
2827
2828 if (txt < txtnext && *txt == '=')
2829 {
2830 txt ++;
2831
2832 if (txt < txtnext)
2833 memcpy(value, txt, txtnext - txt);
2834 value[txtnext - txt] = '\0';
2835
2836 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
2837 }
2838 else
2839 {
2840 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
2841 continue;
2842 }
2843
2844 if (!_cups_strcasecmp(key, "usb_MFG") ||
2845 !_cups_strcasecmp(key, "usb_MANU") ||
2846 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
2847 strcpy(make_and_model, value);
2848 else if (!_cups_strcasecmp(key, "usb_MDL") ||
2849 !_cups_strcasecmp(key, "usb_MODEL"))
2850 strcpy(model, value);
2851 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
2852 {
2853 if (value[0] == '(')
2854 {
2855 /*
2856 * Strip parenthesis...
2857 */
2858
2859 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
2860 *ptr = '\0';
2861
2862 strcpy(model, value + 1);
2863 }
2864 else
2865 strcpy(model, value);
2866 }
2867 else if (!_cups_strcasecmp(key, "ty"))
2868 {
2869 strcpy(model, value);
2870
2871 if ((ptr = strchr(model, ',')) != NULL)
2872 *ptr = '\0';
2873 }
2874 else if (!_cups_strcasecmp(key, "printer-type"))
2875 {
2876 device->dest.num_options = cupsAddOption("printer-type", value,
2877 device->dest.num_options,
2878 &device->dest.options);
2879 type = strtol(value, NULL, 0);
2880 }
2881 }
2882
2883 /*
2884 * Save the make-and-model...
2885 */
2886
2887 if (make_and_model[0])
2888 {
2889 strlcat(make_and_model, " ", sizeof(make_and_model));
2890 strlcat(make_and_model, model, sizeof(make_and_model));
2891
2892 device->dest.num_options = cupsAddOption("printer-make-and-model",
2893 make_and_model,
2894 device->dest.num_options,
2895 &device->dest.options);
2896 }
2897 else
2898 device->dest.num_options = cupsAddOption("printer-make-and-model",
2899 model,
2900 device->dest.num_options,
2901 &device->dest.options);
2902
2903 /*
2904 * Save the URI...
2905 */
2906
2907 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
2908 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
2909 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
2910 NULL, uriname, 0, "/cups");
2911
2912 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri));
2913
2914 device->dest.num_options = cupsAddOption("printer-uri-supported", uri,
2915 device->dest.num_options,
2916 &device->dest.options);
2917 }
2918 else
2919 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
2920 fullName));
2921}
2922
2923
2924/*
2925 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
2926 */
2927
2928static const char * /* O - Resolved URI or NULL */
2929cups_dnssd_resolve(
2930 cups_dest_t *dest, /* I - Destination */
2931 const char *uri, /* I - Current printer URI */
2932 int msec, /* I - Time in milliseconds */
2933 int *cancel, /* I - Pointer to "cancel" variable */
2934 cups_dest_cb_t cb, /* I - Callback */
2935 void *user_data) /* I - User data for callback */
2936{
2937 char tempuri[1024]; /* Temporary URI buffer */
2938 _cups_dnssd_resolve_t resolve; /* Resolve data */
2939
2940
2941 /*
2942 * Resolve the URI...
2943 */
2944
2945 resolve.cancel = cancel;
2946 gettimeofday(&resolve.end_time, NULL);
2947 if (msec > 0)
2948 {
2949 resolve.end_time.tv_sec += msec / 1000;
2950 resolve.end_time.tv_usec += (msec % 1000) * 1000;
2951
2952 while (resolve.end_time.tv_usec >= 1000000)
2953 {
2954 resolve.end_time.tv_sec ++;
2955 resolve.end_time.tv_usec -= 1000000;
2956 }
2957 }
2958 else
2959 resolve.end_time.tv_sec += 75;
2960
2961 if (cb)
2962 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING,
2963 dest);
2964
2965 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri),
2966 _HTTP_RESOLVE_FQDN, cups_dnssd_resolve_cb,
2967 &resolve)) == NULL)
2968 {
2969 _cupsSetError(IPP_INTERNAL_ERROR, _("Unable to resolve printer URI."), 1);
2970
2971 if (cb)
2972 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
2973 dest);
2974
2975 return (NULL);
2976 }
2977
2978 /*
2979 * Save the resolved URI...
2980 */
2981
2982 dest->num_options = cupsAddOption("printer-uri-supported", uri,
2983 dest->num_options, &dest->options);
2984
2985 return (cupsGetOption("printer-uri-supported", dest->num_options,
2986 dest->options));
2987}
2988
2989
2990/*
2991 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
2992 */
2993
2994static int /* O - 1 to continue, 0 to stop */
2995cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
2996{
2997 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
2998 /* Resolve data */
2999 struct timeval curtime; /* Current time */
3000
3001
3002 /*
3003 * If the cancel variable is set, return immediately.
3004 */
3005
3006 if (*resolve->cancel)
3007 return (0);
3008
3009 /*
3010 * Otherwise check the end time...
3011 */
3012
3013 gettimeofday(&curtime, NULL);
3014
3015 return (curtime.tv_sec > resolve->end_time.tv_sec ||
3016 (curtime.tv_sec == resolve->end_time.tv_sec &&
3017 curtime.tv_usec > resolve->end_time.tv_usec));
3018}
3019
3020
3021/*
3022 * 'cups_dnssd_unquote()' - Unquote a name string.
3023 */
3024
3025static void
3026cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3027 const char *src, /* I - Source string */
3028 size_t dstsize) /* I - Size of destination buffer */
3029{
3030 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3031
3032
3033 while (*src && dst < dstend)
3034 {
3035 if (*src == '\\')
3036 {
3037 src ++;
3038 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3039 isdigit(src[2] & 255))
3040 {
3041 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3042 src += 3;
3043 }
3044 else
3045 *dst++ = *src++;
3046 }
3047 else
3048 *dst++ = *src ++;
3049 }
3050
3051 *dst = '\0';
3052}
3053#endif /* HAVE_DNSSD */
3054
3055
426c6a59
MS
3056/*
3057 * 'cups_find_dest()' - Find a destination using a binary search.
3058 */
3059
3060static int /* O - Index of match */
3061cups_find_dest(const char *name, /* I - Destination name */
3062 const char *instance, /* I - Instance or NULL */
3063 int num_dests, /* I - Number of destinations */
3064 cups_dest_t *dests, /* I - Destinations */
3065 int prev, /* I - Previous index */
3066 int *rdiff) /* O - Difference of match */
3067{
3068 int left, /* Low mark for binary search */
3069 right, /* High mark for binary search */
3070 current, /* Current index */
3071 diff; /* Result of comparison */
3072 cups_dest_t key; /* Search key */
3073
3074
3075 key.name = (char *)name;
3076 key.instance = (char *)instance;
3077
3078 if (prev >= 0)
3079 {
3080 /*
3081 * Start search on either side of previous...
3082 */
3083
3084 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3085 (diff < 0 && prev == 0) ||
3086 (diff > 0 && prev == (num_dests - 1)))
3087 {
3088 *rdiff = diff;
3089 return (prev);
3090 }
3091 else if (diff < 0)
3092 {
3093 /*
3094 * Start with previous on right side...
3095 */
3096
3097 left = 0;
3098 right = prev;
3099 }
3100 else
3101 {
3102 /*
3103 * Start wih previous on left side...
3104 */
3105
3106 left = prev;
3107 right = num_dests - 1;
3108 }
3109 }
3110 else
3111 {
3112 /*
3113 * Start search in the middle...
3114 */
3115
3116 left = 0;
3117 right = num_dests - 1;
3118 }
3119
3120 do
3121 {
3122 current = (left + right) / 2;
3123 diff = cups_compare_dests(&key, dests + current);
3124
3125 if (diff == 0)
3126 break;
3127 else if (diff < 0)
3128 right = current;
3129 else
3130 left = current;
3131 }
3132 while ((right - left) > 1);
3133
3134 if (diff != 0)
3135 {
3136 /*
3137 * Check the last 1 or 2 elements...
3138 */
3139
3140 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
3141 current = left;
3142 else
3143 {
3144 diff = cups_compare_dests(&key, dests + right);
3145 current = right;
3146 }
3147 }
3148
3149 /*
3150 * Return the closest destination and the difference...
3151 */
3152
3153 *rdiff = diff;
3154
3155 return (current);
3156}
3157
3158
a4924f6c
MS
3159/*
3160 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3161 */
3162
080811b1 3163static char * /* O - Default destination or NULL */
a4924f6c
MS
3164cups_get_default(const char *filename, /* I - File to read */
3165 char *namebuf, /* I - Name buffer */
3166 size_t namesize, /* I - Size of name buffer */
3167 const char **instance) /* I - Instance */
3168{
3169 cups_file_t *fp; /* lpoptions file */
3170 char line[8192], /* Line from file */
3171 *value, /* Value for line */
3172 *nameptr; /* Pointer into name */
88f9aafc 3173 int linenum; /* Current line */
a4924f6c
MS
3174
3175
3176 *namebuf = '\0';
3177
3178 if ((fp = cupsFileOpen(filename, "r")) != NULL)
3179 {
3180 linenum = 0;
3181
3182 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3183 {
88f9aafc 3184 if (!_cups_strcasecmp(line, "default") && value)
a4924f6c
MS
3185 {
3186 strlcpy(namebuf, value, namesize);
3187
3188 if ((nameptr = strchr(namebuf, ' ')) != NULL)
3189 *nameptr = '\0';
3190 if ((nameptr = strchr(namebuf, '\t')) != NULL)
3191 *nameptr = '\0';
3192
3193 if ((nameptr = strchr(namebuf, '/')) != NULL)
3194 *nameptr++ = '\0';
3195
3196 *instance = nameptr;
3197 break;
3198 }
3199 }
3200
3201 cupsFileClose(fp);
3202 }
3203
3204 return (*namebuf ? namebuf : NULL);
3205}
3206
3207
ef416fc2 3208/*
3209 * 'cups_get_dests()' - Get destinations from a file.
3210 */
3211
3212static int /* O - Number of destinations */
38e73f87
MS
3213cups_get_dests(
3214 const char *filename, /* I - File to read from */
3215 const char *match_name, /* I - Destination name we want */
3216 const char *match_inst, /* I - Instance name we want */
3217 int user_default_set, /* I - User default printer set? */
3218 int num_dests, /* I - Number of destinations */
3219 cups_dest_t **dests) /* IO - Destinations */
ef416fc2 3220{
3221 int i; /* Looping var */
3222 cups_dest_t *dest; /* Current destination */
a4924f6c 3223 cups_file_t *fp; /* File pointer */
ef416fc2 3224 char line[8192], /* Line from file */
3225 *lineptr, /* Pointer into line */
3226 *name, /* Name of destination/option */
3227 *instance; /* Instance of destination */
a4924f6c 3228 int linenum; /* Current line number */
ef416fc2 3229
3230
e07d4801 3231 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
38e73f87 3232 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
e07d4801 3233 "dests=%p)", filename, match_name, match_inst,
38e73f87 3234 user_default_set, num_dests, dests));
a4924f6c
MS
3235
3236 /*
3237 * Try to open the file...
3238 */
3239
3240 if ((fp = cupsFileOpen(filename, "r")) == NULL)
3241 return (num_dests);
3242
ef416fc2 3243 /*
3244 * Read each printer; each line looks like:
3245 *
3246 * Dest name[/instance] options
3247 * Default name[/instance] options
3248 */
3249
a4924f6c
MS
3250 linenum = 0;
3251
3252 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
ef416fc2 3253 {
3254 /*
3255 * See what type of line it is...
3256 */
3257
e07d4801 3258 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
38e73f87 3259 linenum, line, lineptr));
ef416fc2 3260
88f9aafc 3261 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
a4924f6c 3262 {
e07d4801 3263 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
ef416fc2 3264 continue;
a4924f6c 3265 }
ef416fc2 3266
3267 name = lineptr;
3268
3269 /*
3270 * Search for an instance...
3271 */
3272
3273 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
3274 lineptr ++;
3275
ef416fc2 3276 if (*lineptr == '/')
3277 {
3278 /*
3279 * Found an instance...
3280 */
3281
3282 *lineptr++ = '\0';
3283 instance = lineptr;
3284
3285 /*
3286 * Search for an instance...
3287 */
3288
3289 while (!isspace(*lineptr & 255) && *lineptr)
3290 lineptr ++;
3291 }
3292 else
3293 instance = NULL;
3294
a4924f6c
MS
3295 if (*lineptr)
3296 *lineptr++ = '\0';
3297
e07d4801 3298 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
a4924f6c 3299 instance));
ef416fc2 3300
3301 /*
3302 * See if the primary instance of the destination exists; if not,
3303 * ignore this entry and move on...
3304 */
3305
a4924f6c
MS
3306 if (match_name)
3307 {
88f9aafc 3308 if (_cups_strcasecmp(name, match_name) ||
a4924f6c
MS
3309 (!instance && match_inst) ||
3310 (instance && !match_inst) ||
88f9aafc 3311 (instance && _cups_strcasecmp(instance, match_inst)))
a4924f6c 3312 continue;
ef416fc2 3313
a4924f6c
MS
3314 dest = *dests;
3315 }
3316 else if (cupsGetDest(name, NULL, num_dests, *dests) == NULL)
3317 {
e07d4801 3318 DEBUG_puts("9cups_get_dests: Not found!");
a4924f6c
MS
3319 continue;
3320 }
3321 else
ef416fc2 3322 {
3323 /*
a4924f6c 3324 * Add the destination...
ef416fc2 3325 */
3326
a4924f6c
MS
3327 num_dests = cupsAddDest(name, instance, num_dests, dests);
3328
3329 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
3330 {
3331 /*
3332 * Out of memory!
3333 */
3334
e07d4801 3335 DEBUG_puts("9cups_get_dests: Out of memory!");
a4924f6c
MS
3336 break;
3337 }
ef416fc2 3338 }
3339
3340 /*
3341 * Add options until we hit the end of the line...
3342 */
3343
3344 dest->num_options = cupsParseOptions(lineptr, dest->num_options,
3345 &(dest->options));
3346
a4924f6c
MS
3347 /*
3348 * If we found what we were looking for, stop now...
3349 */
3350
3351 if (match_name)
3352 break;
3353
ef416fc2 3354 /*
3355 * Set this as default if needed...
3356 */
3357
88f9aafc 3358 if (!user_default_set && !_cups_strcasecmp(line, "default"))
ef416fc2 3359 {
e07d4801 3360 DEBUG_puts("9cups_get_dests: Setting as default...");
a4924f6c 3361
ef416fc2 3362 for (i = 0; i < num_dests; i ++)
3363 (*dests)[i].is_default = 0;
3364
3365 dest->is_default = 1;
3366 }
3367 }
3368
3369 /*
3370 * Close the file and return...
3371 */
3372
88f9aafc 3373 cupsFileClose(fp);
ef416fc2 3374
3375 return (num_dests);
3376}
3377
3378
426c6a59
MS
3379/*
3380 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3381 * attribute.
3382 */
3383
3384static char * /* O - New string */
3385cups_make_string(
3386 ipp_attribute_t *attr, /* I - Attribute to convert */
3387 char *buffer, /* I - Buffer */
3388 size_t bufsize) /* I - Size of buffer */
3389{
3390 int i; /* Looping var */
3391 char *ptr, /* Pointer into buffer */
3392 *end, /* Pointer to end of buffer */
3393 *valptr; /* Pointer into string attribute */
3394
3395
3396 /*
3397 * Return quickly if we have a single string value...
3398 */
3399
3400 if (attr->num_values == 1 &&
3401 attr->value_tag != IPP_TAG_INTEGER &&
3402 attr->value_tag != IPP_TAG_ENUM &&
3403 attr->value_tag != IPP_TAG_BOOLEAN &&
3404 attr->value_tag != IPP_TAG_RANGE)
3405 return (attr->values[0].string.text);
3406
3407 /*
3408 * Copy the values to the string, separating with commas and escaping strings
3409 * as needed...
3410 */
3411
3412 end = buffer + bufsize - 1;
3413
3414 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
3415 {
3416 if (i)
3417 *ptr++ = ',';
3418
3419 switch (attr->value_tag)
3420 {
3421 case IPP_TAG_INTEGER :
3422 case IPP_TAG_ENUM :
3423 snprintf(ptr, end - ptr + 1, "%d", attr->values[i].integer);
3424 break;
3425
3426 case IPP_TAG_BOOLEAN :
3427 if (attr->values[i].boolean)
3428 strlcpy(ptr, "true", end - ptr + 1);
3429 else
3430 strlcpy(ptr, "false", end - ptr + 1);
3431 break;
3432
3433 case IPP_TAG_RANGE :
3434 if (attr->values[i].range.lower == attr->values[i].range.upper)
3435 snprintf(ptr, end - ptr + 1, "%d", attr->values[i].range.lower);
3436 else
3437 snprintf(ptr, end - ptr + 1, "%d-%d", attr->values[i].range.lower,
3438 attr->values[i].range.upper);
3439 break;
3440
3441 default :
3442 for (valptr = attr->values[i].string.text;
3443 *valptr && ptr < end;)
3444 {
3445 if (strchr(" \t\n\\\'\"", *valptr))
3446 {
3447 if (ptr >= (end - 1))
3448 break;
3449
3450 *ptr++ = '\\';
3451 }
3452
3453 *ptr++ = *valptr++;
3454 }
3455
3456 *ptr = '\0';
3457 break;
3458 }
3459
3460 ptr += strlen(ptr);
3461 }
3462
3463 *ptr = '\0';
3464
3465 return (buffer);
3466}
3467
3468
ef416fc2 3469/*
f14324a7 3470 * End of "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $".
ef416fc2 3471 */