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