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