]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/dirsvc.c
Merge changes from CUPS 1.5svn-r9491.
[thirdparty/cups.git] / scheduler / dirsvc.c
1 /*
2 * "$Id: dirsvc.c 7933 2008-09-11 00:44:58Z mike $"
3 *
4 * Directory services routines for the CUPS scheduler.
5 *
6 * Copyright 2007-2010 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
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 * Contents:
16 *
17 * cupsdDeregisterPrinter() - Stop sending broadcast information for a local
18 * printer and remove any pending references to
19 * remote printers.
20 * cupsdLoadRemoteCache() - Load the remote printer cache.
21 * cupsdRegisterPrinter() - Start sending broadcast information for a
22 * printer or update the broadcast contents.
23 * cupsdRestartPolling() - Restart polling servers as needed.
24 * cupsdSaveRemoteCache() - Save the remote printer cache.
25 * cupsdSendBrowseList() - Send new browsing information as necessary.
26 * ldap_rebind_proc() - Callback function for LDAP rebind
27 * ldap_connect() - Start new LDAP connection
28 * ldap_reconnect() - Reconnect to LDAP Server
29 * ldap_disconnect() - Disconnect from LDAP Server
30 * cupsdStartBrowsing() - Start sending and receiving broadcast
31 * information.
32 * cupsdStartPolling() - Start polling servers as needed.
33 * cupsdStopBrowsing() - Stop sending and receiving broadcast
34 * information.
35 * cupsdStopPolling() - Stop polling servers as needed.
36 * cupsdUpdateDNSSDName() - Update the computer name we use for
37 * browsing...
38 * cupsdUpdateLDAPBrowse() - Scan for new printers via LDAP...
39 * cupsdUpdateSLPBrowse() - Get browsing information via SLP.
40 * dequote() - Remote quotes from a string.
41 * dnssdAddAlias() - Add a DNS-SD alias name.
42 * dnssdBuildTxtRecord() - Build a TXT record from printer info.
43 * dnssdComparePrinters() - Compare the registered names of two printers.
44 * dnssdDeregisterPrinter() - Stop sending broadcast information for a
45 * printer.
46 * dnssdPackTxtRecord() - Pack an array of key/value pairs into the TXT
47 * record format.
48 * dnssdRegisterCallback() - DNSServiceRegister callback.
49 * dnssdRegisterPrinter() - Start sending broadcast information for a
50 * printer or update the broadcast contents.
51 * dnssdStop() - Stop all DNS-SD registrations.
52 * dnssdUpdate() - Handle DNS-SD queries.
53 * get_auth_info_required() - Get the auth-info-required value to advertise.
54 * get_hostconfig() - Get an /etc/hostconfig service setting.
55 * is_local_queue() - Determine whether the URI points at a local
56 * queue.
57 * process_browse_data() - Process new browse data.
58 * process_implicit_classes() - Create/update implicit classes as needed.
59 * send_cups_browse() - Send new browsing information using the CUPS
60 * protocol.
61 * ldap_search_rec() - LDAP Search with reconnect
62 * ldap_freeres() - Free LDAPMessage
63 * ldap_getval_char() - Get first LDAP value and convert to string
64 * send_ldap_ou() - Send LDAP ou registrations.
65 * send_ldap_browse() - Send LDAP printer registrations.
66 * ldap_dereg_printer() - Delete printer from directory
67 * ldap_dereg_ou() - Remove the organizational unit.
68 * send_slp_browse() - Register the specified printer with SLP.
69 * slp_attr_callback() - SLP attribute callback
70 * slp_dereg_printer() - SLPDereg() the specified printer
71 * slp_get_attr() - Get an attribute from an SLP registration.
72 * slp_reg_callback() - Empty SLPRegReport.
73 * slp_url_callback() - SLP service url callback
74 * update_cups_browse() - Update the browse lists using the CUPS
75 * protocol.
76 * update_lpd() - Update the LPD configuration as needed.
77 * update_polling() - Read status messages from the poll daemons.
78 * update_smb() - Update the SMB configuration as needed.
79 */
80
81 /*
82 * Include necessary headers...
83 */
84
85 #include "cupsd.h"
86 #include <grp.h>
87
88 #ifdef HAVE_DNSSD
89 # include <dns_sd.h>
90 # ifdef __APPLE__
91 # include <nameser.h>
92 # ifdef HAVE_COREFOUNDATION
93 # include <CoreFoundation/CoreFoundation.h>
94 # endif /* HAVE_COREFOUNDATION */
95 # ifdef HAVE_SYSTEMCONFIGURATION
96 # include <SystemConfiguration/SystemConfiguration.h>
97 # endif /* HAVE_SYSTEMCONFIGURATION */
98 # endif /* __APPLE__ */
99 #endif /* HAVE_DNSSD */
100
101
102 /*
103 * Local functions...
104 */
105
106 static char *dequote(char *d, const char *s, int dlen);
107 static char *get_auth_info_required(cupsd_printer_t *p, char *buffer,
108 size_t bufsize);
109 #ifdef __APPLE__
110 static int get_hostconfig(const char *name);
111 #endif /* __APPLE__ */
112 static int is_local_queue(const char *uri, char *host, int hostlen,
113 char *resource, int resourcelen);
114 static void process_browse_data(const char *uri, const char *host,
115 const char *resource, cups_ptype_t type,
116 ipp_pstate_t state, const char *location,
117 const char *info, const char *make_model,
118 int num_attrs, cups_option_t *attrs);
119 static void process_implicit_classes(void);
120 static void send_cups_browse(cupsd_printer_t *p);
121 #ifdef HAVE_LDAP
122 static LDAP *ldap_connect(void);
123 static LDAP *ldap_reconnect(void);
124 static void ldap_disconnect(LDAP *ld);
125 static int ldap_search_rec(LDAP *ld, char *base, int scope,
126 char *filter, char *attrs[],
127 int attrsonly, LDAPMessage **res);
128 static int ldap_getval_firststring(LDAP *ld, LDAPMessage *entry,
129 char *attr, char *retval,
130 unsigned long maxsize);
131 static void ldap_freeres(LDAPMessage *entry);
132 static void send_ldap_ou(char *ou, char *basedn, char *descstring);
133 static void send_ldap_browse(cupsd_printer_t *p);
134 static void ldap_dereg_printer(cupsd_printer_t *p);
135 static void ldap_dereg_ou(char *ou, char *basedn);
136 # ifdef HAVE_LDAP_REBIND_PROC
137 # if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
138 static int ldap_rebind_proc(LDAP *RebindLDAPHandle,
139 LDAP_CONST char *refsp,
140 ber_tag_t request,
141 ber_int_t msgid,
142 void *params);
143 # else
144 static int ldap_rebind_proc(LDAP *RebindLDAPHandle,
145 char **dnp,
146 char **passwdp,
147 int *authmethodp,
148 int freeit,
149 void *arg);
150 # endif /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
151 # endif /* HAVE_LDAP_REBIND_PROC */
152 #endif /* HAVE_LDAP */
153 #ifdef HAVE_LIBSLP
154 static void send_slp_browse(cupsd_printer_t *p);
155 #endif /* HAVE_LIBSLP */
156 static void update_cups_browse(void);
157 static void update_lpd(int onoff);
158 static void update_polling(void);
159 static void update_smb(int onoff);
160
161
162 #ifdef HAVE_DNSSD
163 # ifdef HAVE_COREFOUNDATION
164 static void dnssdAddAlias(const void *key, const void *value,
165 void *context);
166 # endif /* HAVE_COREFOUNDATION */
167 static char *dnssdBuildTxtRecord(int *txt_len, cupsd_printer_t *p,
168 int for_lpd);
169 static int dnssdComparePrinters(cupsd_printer_t *a, cupsd_printer_t *b);
170 static void dnssdDeregisterPrinter(cupsd_printer_t *p);
171 static char *dnssdPackTxtRecord(int *txt_len, char *keyvalue[][2],
172 int count);
173 static void dnssdRegisterCallback(DNSServiceRef sdRef,
174 DNSServiceFlags flags,
175 DNSServiceErrorType errorCode,
176 const char *name, const char *regtype,
177 const char *domain, void *context);
178 static void dnssdRegisterPrinter(cupsd_printer_t *p);
179 static void dnssdStop(void);
180 static void dnssdUpdate(void);
181 #endif /* HAVE_DNSSD */
182
183 #ifdef HAVE_LDAP
184 static const char * const ldap_attrs[] =/* CUPS LDAP attributes */
185 {
186 "printerDescription",
187 "printerLocation",
188 "printerMakeAndModel",
189 "printerType",
190 "printerURI",
191 NULL
192 };
193 #endif /* HAVE_LDAP */
194
195 #ifdef HAVE_LIBSLP
196 /*
197 * SLP definitions...
198 */
199
200 /*
201 * SLP service name for CUPS...
202 */
203
204 # define SLP_CUPS_SRVTYPE "service:printer"
205 # define SLP_CUPS_SRVLEN 15
206
207
208 /*
209 * Printer service URL structure
210 */
211
212 typedef struct _slpsrvurl_s /**** SLP URL list ****/
213 {
214 struct _slpsrvurl_s *next; /* Next URL in list */
215 char url[HTTP_MAX_URI];
216 /* URL */
217 } slpsrvurl_t;
218
219
220 /*
221 * Local functions...
222 */
223
224 static SLPBoolean slp_attr_callback(SLPHandle hslp, const char *attrlist,
225 SLPError errcode, void *cookie);
226 static void slp_dereg_printer(cupsd_printer_t *p);
227 static int slp_get_attr(const char *attrlist, const char *tag,
228 char **valbuf);
229 static void slp_reg_callback(SLPHandle hslp, SLPError errcode,
230 void *cookie);
231 static SLPBoolean slp_url_callback(SLPHandle hslp, const char *srvurl,
232 unsigned short lifetime,
233 SLPError errcode, void *cookie);
234 #endif /* HAVE_LIBSLP */
235
236
237 /*
238 * 'cupsdDeregisterPrinter()' - Stop sending broadcast information for a
239 * local printer and remove any pending
240 * references to remote printers.
241 */
242
243 void
244 cupsdDeregisterPrinter(
245 cupsd_printer_t *p, /* I - Printer to register */
246 int removeit) /* I - Printer being permanently removed */
247 {
248 /*
249 * Only deregister if browsing is enabled and it's a local printer...
250 */
251
252 cupsdLogMessage(CUPSD_LOG_DEBUG,
253 "cupsdDeregisterPrinter(p=%p(%s), removeit=%d)", p, p->name,
254 removeit);
255
256 if (!Browsing || !p->shared ||
257 (p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
258 CUPS_PRINTER_SCANNER)))
259 return;
260
261 /*
262 * Announce the deletion...
263 */
264
265 if ((BrowseLocalProtocols & BROWSE_CUPS) && BrowseSocket >= 0)
266 {
267 cups_ptype_t savedtype = p->type; /* Saved printer type */
268
269 p->type |= CUPS_PRINTER_DELETE;
270
271 send_cups_browse(p);
272
273 p->type = savedtype;
274 }
275
276 #ifdef HAVE_LIBSLP
277 if (BrowseLocalProtocols & BROWSE_SLP)
278 slp_dereg_printer(p);
279 #endif /* HAVE_LIBSLP */
280
281 #ifdef HAVE_LDAP
282 if (BrowseLocalProtocols & BROWSE_LDAP)
283 ldap_dereg_printer(p);
284 #endif /* HAVE_LDAP */
285
286 #ifdef HAVE_DNSSD
287 if (removeit && (BrowseLocalProtocols & BROWSE_DNSSD) && DNSSDRef)
288 dnssdDeregisterPrinter(p);
289 #endif /* HAVE_DNSSD */
290 }
291
292
293 /*
294 * 'cupsdLoadRemoteCache()' - Load the remote printer cache.
295 */
296
297 void
298 cupsdLoadRemoteCache(void)
299 {
300 int i; /* Looping var */
301 cups_file_t *fp; /* remote.cache file */
302 int linenum; /* Current line number */
303 char line[4096], /* Line from file */
304 *value, /* Pointer to value */
305 *valueptr, /* Pointer into value */
306 scheme[32], /* Scheme portion of URI */
307 username[64], /* Username portion of URI */
308 host[HTTP_MAX_HOST],
309 /* Hostname portion of URI */
310 resource[HTTP_MAX_URI];
311 /* Resource portion of URI */
312 int port; /* Port number */
313 cupsd_printer_t *p; /* Current printer */
314 time_t now; /* Current time */
315
316
317 /*
318 * Don't load the cache if the remote protocols are disabled...
319 */
320
321 if (!Browsing)
322 {
323 cupsdLogMessage(CUPSD_LOG_DEBUG,
324 "cupsdLoadRemoteCache: Not loading remote cache.");
325 return;
326 }
327
328 /*
329 * Open the remote.cache file...
330 */
331
332 snprintf(line, sizeof(line), "%s/remote.cache", CacheDir);
333 if ((fp = cupsFileOpen(line, "r")) == NULL)
334 return;
335
336 /*
337 * Read printer configurations until we hit EOF...
338 */
339
340 linenum = 0;
341 p = NULL;
342 now = time(NULL);
343
344 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
345 {
346 /*
347 * Decode the directive...
348 */
349
350 if (!strcasecmp(line, "<Printer") ||
351 !strcasecmp(line, "<DefaultPrinter"))
352 {
353 /*
354 * <Printer name> or <DefaultPrinter name>
355 */
356
357 if (p == NULL && value)
358 {
359 /*
360 * Add the printer and a base file type...
361 */
362
363 cupsdLogMessage(CUPSD_LOG_DEBUG,
364 "cupsdLoadRemoteCache: Loading printer %s...", value);
365
366 if ((p = cupsdFindDest(value)) != NULL)
367 {
368 if (p->type & CUPS_PRINTER_CLASS)
369 {
370 cupsdLogMessage(CUPSD_LOG_WARN,
371 "Cached remote printer \"%s\" conflicts with "
372 "existing class!",
373 value);
374 p = NULL;
375 continue;
376 }
377 }
378 else
379 p = cupsdAddPrinter(value);
380
381 p->accepting = 1;
382 p->state = IPP_PRINTER_IDLE;
383 p->type |= CUPS_PRINTER_REMOTE | CUPS_PRINTER_DISCOVERED;
384 p->browse_time = now;
385 p->browse_expire = now + BrowseTimeout;
386
387 /*
388 * Set the default printer as needed...
389 */
390
391 if (!strcasecmp(line, "<DefaultPrinter"))
392 DefaultPrinter = p;
393 }
394 else
395 {
396 cupsdLogMessage(CUPSD_LOG_ERROR,
397 "Syntax error on line %d of remote.cache.", linenum);
398 break;
399 }
400 }
401 else if (!strcasecmp(line, "<Class") ||
402 !strcasecmp(line, "<DefaultClass"))
403 {
404 /*
405 * <Class name> or <DefaultClass name>
406 */
407
408 if (p == NULL && value)
409 {
410 /*
411 * Add the printer and a base file type...
412 */
413
414 cupsdLogMessage(CUPSD_LOG_DEBUG,
415 "cupsdLoadRemoteCache: Loading class %s...", value);
416
417 if ((p = cupsdFindDest(value)) != NULL)
418 p->type = CUPS_PRINTER_CLASS;
419 else
420 p = cupsdAddClass(value);
421
422 p->accepting = 1;
423 p->state = IPP_PRINTER_IDLE;
424 p->type |= CUPS_PRINTER_REMOTE | CUPS_PRINTER_DISCOVERED;
425 p->browse_time = now;
426 p->browse_expire = now + BrowseTimeout;
427
428 /*
429 * Set the default printer as needed...
430 */
431
432 if (!strcasecmp(line, "<DefaultClass"))
433 DefaultPrinter = p;
434 }
435 else
436 {
437 cupsdLogMessage(CUPSD_LOG_ERROR,
438 "Syntax error on line %d of remote.cache.", linenum);
439 break;
440 }
441 }
442 else if (!strcasecmp(line, "</Printer>") ||
443 !strcasecmp(line, "</Class>"))
444 {
445 if (p != NULL)
446 {
447 /*
448 * Close out the current printer...
449 */
450
451 cupsdSetPrinterAttrs(p);
452
453 p = NULL;
454 }
455 else
456 cupsdLogMessage(CUPSD_LOG_ERROR,
457 "Syntax error on line %d of remote.cache.", linenum);
458 }
459 else if (!p)
460 {
461 cupsdLogMessage(CUPSD_LOG_ERROR,
462 "Syntax error on line %d of remote.cache.", linenum);
463 }
464 else if (!strcasecmp(line, "Info"))
465 {
466 if (value)
467 cupsdSetString(&p->info, value);
468 }
469 else if (!strcasecmp(line, "MakeModel"))
470 {
471 if (value)
472 cupsdSetString(&p->make_model, value);
473 }
474 else if (!strcasecmp(line, "Location"))
475 {
476 if (value)
477 cupsdSetString(&p->location, value);
478 }
479 else if (!strcasecmp(line, "DeviceURI"))
480 {
481 if (value)
482 {
483 httpSeparateURI(HTTP_URI_CODING_ALL, value, scheme, sizeof(scheme),
484 username, sizeof(username), host, sizeof(host), &port,
485 resource, sizeof(resource));
486
487 cupsdSetString(&p->hostname, host);
488 cupsdSetString(&p->uri, value);
489 cupsdSetDeviceURI(p, value);
490 }
491 else
492 cupsdLogMessage(CUPSD_LOG_ERROR,
493 "Syntax error on line %d of remote.cache.", linenum);
494 }
495 else if (!strcasecmp(line, "Option") && value)
496 {
497 /*
498 * Option name value
499 */
500
501 for (valueptr = value; *valueptr && !isspace(*valueptr & 255); valueptr ++);
502
503 if (!*valueptr)
504 cupsdLogMessage(CUPSD_LOG_ERROR,
505 "Syntax error on line %d of remote.cache.", linenum);
506 else
507 {
508 for (; *valueptr && isspace(*valueptr & 255); *valueptr++ = '\0');
509
510 p->num_options = cupsAddOption(value, valueptr, p->num_options,
511 &(p->options));
512 }
513 }
514 else if (!strcasecmp(line, "Reason"))
515 {
516 if (value)
517 {
518 for (i = 0 ; i < p->num_reasons; i ++)
519 if (!strcmp(value, p->reasons[i]))
520 break;
521
522 if (i >= p->num_reasons &&
523 p->num_reasons < (int)(sizeof(p->reasons) / sizeof(p->reasons[0])))
524 {
525 p->reasons[p->num_reasons] = _cupsStrAlloc(value);
526 p->num_reasons ++;
527 }
528 }
529 else
530 cupsdLogMessage(CUPSD_LOG_ERROR,
531 "Syntax error on line %d of remote.cache.", linenum);
532 }
533 else if (!strcasecmp(line, "State"))
534 {
535 /*
536 * Set the initial queue state...
537 */
538
539 if (value && !strcasecmp(value, "idle"))
540 p->state = IPP_PRINTER_IDLE;
541 else if (value && !strcasecmp(value, "stopped"))
542 {
543 p->state = IPP_PRINTER_STOPPED;
544 cupsdSetPrinterReasons(p, "+paused");
545 }
546 else
547 cupsdLogMessage(CUPSD_LOG_ERROR,
548 "Syntax error on line %d of remote.cache.", linenum);
549 }
550 else if (!strcasecmp(line, "StateMessage"))
551 {
552 /*
553 * Set the initial queue state message...
554 */
555
556 if (value)
557 strlcpy(p->state_message, value, sizeof(p->state_message));
558 }
559 else if (!strcasecmp(line, "Accepting"))
560 {
561 /*
562 * Set the initial accepting state...
563 */
564
565 if (value &&
566 (!strcasecmp(value, "yes") ||
567 !strcasecmp(value, "on") ||
568 !strcasecmp(value, "true")))
569 p->accepting = 1;
570 else if (value &&
571 (!strcasecmp(value, "no") ||
572 !strcasecmp(value, "off") ||
573 !strcasecmp(value, "false")))
574 p->accepting = 0;
575 else
576 cupsdLogMessage(CUPSD_LOG_ERROR,
577 "Syntax error on line %d of remote.cache.", linenum);
578 }
579 else if (!strcasecmp(line, "Type"))
580 {
581 if (value)
582 p->type = atoi(value);
583 else
584 cupsdLogMessage(CUPSD_LOG_ERROR,
585 "Syntax error on line %d of remote.cache.", linenum);
586 }
587 else if (!strcasecmp(line, "BrowseTime"))
588 {
589 if (value)
590 {
591 time_t t = atoi(value);
592
593 if (t > p->browse_expire)
594 p->browse_expire = t;
595 }
596 else
597 cupsdLogMessage(CUPSD_LOG_ERROR,
598 "Syntax error on line %d of remote.cache.", linenum);
599 }
600 else if (!strcasecmp(line, "JobSheets"))
601 {
602 /*
603 * Set the initial job sheets...
604 */
605
606 if (value)
607 {
608 for (valueptr = value; *valueptr && !isspace(*valueptr & 255); valueptr ++);
609
610 if (*valueptr)
611 *valueptr++ = '\0';
612
613 cupsdSetString(&p->job_sheets[0], value);
614
615 while (isspace(*valueptr & 255))
616 valueptr ++;
617
618 if (*valueptr)
619 {
620 for (value = valueptr; *valueptr && !isspace(*valueptr & 255); valueptr ++);
621
622 if (*valueptr)
623 *valueptr = '\0';
624
625 cupsdSetString(&p->job_sheets[1], value);
626 }
627 }
628 else
629 cupsdLogMessage(CUPSD_LOG_ERROR,
630 "Syntax error on line %d of remote.cache.", linenum);
631 }
632 else if (!strcasecmp(line, "AllowUser"))
633 {
634 if (value)
635 {
636 p->deny_users = 0;
637 cupsdAddString(&(p->users), value);
638 }
639 else
640 cupsdLogMessage(CUPSD_LOG_ERROR,
641 "Syntax error on line %d of remote.cache.", linenum);
642 }
643 else if (!strcasecmp(line, "DenyUser"))
644 {
645 if (value)
646 {
647 p->deny_users = 1;
648 cupsdAddString(&(p->users), value);
649 }
650 else
651 cupsdLogMessage(CUPSD_LOG_ERROR,
652 "Syntax error on line %d of remote.cache.", linenum);
653 }
654 else
655 {
656 /*
657 * Something else we don't understand...
658 */
659
660 cupsdLogMessage(CUPSD_LOG_ERROR,
661 "Unknown configuration directive %s on line %d of remote.cache.",
662 line, linenum);
663 }
664 }
665
666 cupsFileClose(fp);
667
668 /*
669 * Do auto-classing if needed...
670 */
671
672 process_implicit_classes();
673 }
674
675
676 /*
677 * 'cupsdRegisterPrinter()' - Start sending broadcast information for a
678 * printer or update the broadcast contents.
679 */
680
681 void
682 cupsdRegisterPrinter(cupsd_printer_t *p)/* I - Printer */
683 {
684 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdRegisterPrinter(p=%p(%s))", p,
685 p->name);
686
687 if (!Browsing || !BrowseLocalProtocols ||
688 (p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
689 CUPS_PRINTER_SCANNER)))
690 return;
691
692 #ifdef HAVE_LIBSLP
693 /* if (BrowseLocalProtocols & BROWSE_SLP)
694 slpRegisterPrinter(p); */
695 #endif /* HAVE_LIBSLP */
696
697 #ifdef HAVE_DNSSD
698 if ((BrowseLocalProtocols & BROWSE_DNSSD) && DNSSDRef)
699 dnssdRegisterPrinter(p);
700 #endif /* HAVE_DNSSD */
701 }
702
703
704 /*
705 * 'cupsdRestartPolling()' - Restart polling servers as needed.
706 */
707
708 void
709 cupsdRestartPolling(void)
710 {
711 int i; /* Looping var */
712 cupsd_dirsvc_poll_t *pollp; /* Current polling server */
713
714
715 for (i = 0, pollp = Polled; i < NumPolled; i ++, pollp ++)
716 if (pollp->pid)
717 kill(pollp->pid, SIGHUP);
718 }
719
720
721 /*
722 * 'cupsdSaveRemoteCache()' - Save the remote printer cache.
723 */
724
725 void
726 cupsdSaveRemoteCache(void)
727 {
728 int i; /* Looping var */
729 cups_file_t *fp; /* printers.conf file */
730 char temp[1024], /* Temporary string */
731 value[2048], /* Value string */
732 *name; /* Current user name */
733 cupsd_printer_t *printer; /* Current printer class */
734 time_t curtime; /* Current time */
735 struct tm *curdate; /* Current date */
736 cups_option_t *option; /* Current option */
737
738
739 /*
740 * Create the remote.cache file...
741 */
742
743 snprintf(temp, sizeof(temp), "%s/remote.cache", CacheDir);
744
745 if ((fp = cupsFileOpen(temp, "w")) == NULL)
746 {
747 cupsdLogMessage(CUPSD_LOG_ERROR,
748 "Unable to save remote.cache - %s", strerror(errno));
749 return;
750 }
751 else
752 cupsdLogMessage(CUPSD_LOG_DEBUG, "Saving remote.cache...");
753
754 /*
755 * Restrict access to the file...
756 */
757
758 fchown(cupsFileNumber(fp), getuid(), Group);
759 fchmod(cupsFileNumber(fp), ConfigFilePerm);
760
761 /*
762 * Write a small header to the file...
763 */
764
765 curtime = time(NULL);
766 curdate = localtime(&curtime);
767 strftime(temp, sizeof(temp) - 1, "%Y-%m-%d %H:%M", curdate);
768
769 cupsFilePuts(fp, "# Remote cache file for " CUPS_SVERSION "\n");
770 cupsFilePrintf(fp, "# Written by cupsd on %s\n", temp);
771
772 /*
773 * Write each local printer known to the system...
774 */
775
776 for (printer = (cupsd_printer_t *)cupsArrayFirst(Printers);
777 printer;
778 printer = (cupsd_printer_t *)cupsArrayNext(Printers))
779 {
780 /*
781 * Skip local destinations...
782 */
783
784 if (!(printer->type & CUPS_PRINTER_DISCOVERED))
785 continue;
786
787 /*
788 * Write printers as needed...
789 */
790
791 if (printer == DefaultPrinter)
792 cupsFilePuts(fp, "<Default");
793 else
794 cupsFilePutChar(fp, '<');
795
796 if (printer->type & CUPS_PRINTER_CLASS)
797 cupsFilePrintf(fp, "Class %s>\n", printer->name);
798 else
799 cupsFilePrintf(fp, "Printer %s>\n", printer->name);
800
801 cupsFilePrintf(fp, "BrowseTime %d\n", (int)printer->browse_expire);
802
803 if (printer->info)
804 cupsFilePutConf(fp, "Info", printer->info);
805
806 if (printer->location)
807 cupsFilePutConf(fp, "Location", printer->location);
808
809 if (printer->make_model)
810 cupsFilePutConf(fp, "MakeModel", printer->make_model);
811
812 cupsFilePutConf(fp, "DeviceURI", printer->device_uri);
813
814 if (printer->state == IPP_PRINTER_STOPPED)
815 cupsFilePuts(fp, "State Stopped\n");
816 else
817 cupsFilePuts(fp, "State Idle\n");
818
819 for (i = 0; i < printer->num_reasons; i ++)
820 cupsFilePutConf(fp, "Reason", printer->reasons[i]);
821
822 cupsFilePrintf(fp, "Type %d\n", printer->type);
823
824 if (printer->accepting)
825 cupsFilePuts(fp, "Accepting Yes\n");
826 else
827 cupsFilePuts(fp, "Accepting No\n");
828
829 snprintf(value, sizeof(value), "%s %s", printer->job_sheets[0],
830 printer->job_sheets[1]);
831 cupsFilePutConf(fp, "JobSheets", value);
832
833 for (name = (char *)cupsArrayFirst(printer->users);
834 name;
835 name = (char *)cupsArrayNext(printer->users))
836 cupsFilePutConf(fp, printer->deny_users ? "DenyUser" : "AllowUser", name);
837
838 for (i = printer->num_options, option = printer->options;
839 i > 0;
840 i --, option ++)
841 {
842 snprintf(value, sizeof(value), "%s %s", option->name, option->value);
843 cupsFilePutConf(fp, "Option", value);
844 }
845
846 if (printer->type & CUPS_PRINTER_CLASS)
847 cupsFilePuts(fp, "</Class>\n");
848 else
849 cupsFilePuts(fp, "</Printer>\n");
850 }
851
852 cupsFileClose(fp);
853 }
854
855
856 /*
857 * 'cupsdSendBrowseList()' - Send new browsing information as necessary.
858 */
859
860 void
861 cupsdSendBrowseList(void)
862 {
863 int count; /* Number of dests to update */
864 cupsd_printer_t *p; /* Current printer */
865 time_t ut, /* Minimum update time */
866 to; /* Timeout time */
867
868
869 if (!Browsing || !Printers)
870 return;
871
872 /*
873 * Compute the update and timeout times...
874 */
875
876 to = time(NULL);
877 ut = to - BrowseInterval;
878
879 /*
880 * Figure out how many printers need an update...
881 */
882
883 if (BrowseInterval > 0 && BrowseLocalProtocols)
884 {
885 int max_count; /* Maximum number to update */
886
887
888 /*
889 * Throttle the number of printers we'll be updating this time
890 * around based on the number of queues that need updating and
891 * the maximum number of queues to update each second...
892 */
893
894 max_count = 2 * cupsArrayCount(Printers) / BrowseInterval + 1;
895
896 for (count = 0, p = (cupsd_printer_t *)cupsArrayFirst(Printers);
897 count < max_count && p != NULL;
898 p = (cupsd_printer_t *)cupsArrayNext(Printers))
899 if (!(p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
900 CUPS_PRINTER_SCANNER)) &&
901 p->shared && p->browse_time < ut)
902 count ++;
903
904 /*
905 * Loop through all of the printers and send local updates as needed...
906 */
907
908 if (BrowseNext)
909 p = (cupsd_printer_t *)cupsArrayFind(Printers, BrowseNext);
910 else
911 p = (cupsd_printer_t *)cupsArrayFirst(Printers);
912
913 for (;
914 count > 0;
915 p = (cupsd_printer_t *)cupsArrayNext(Printers))
916 {
917 /*
918 * Check for wraparound...
919 */
920
921 if (!p)
922 p = (cupsd_printer_t *)cupsArrayFirst(Printers);
923
924 if (!p)
925 break;
926 else if ((p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
927 CUPS_PRINTER_SCANNER)) ||
928 !p->shared)
929 continue;
930 else if (p->browse_time < ut)
931 {
932 /*
933 * Need to send an update...
934 */
935
936 count --;
937
938 p->browse_time = time(NULL);
939
940 if ((BrowseLocalProtocols & BROWSE_CUPS) && BrowseSocket >= 0)
941 send_cups_browse(p);
942
943 #ifdef HAVE_LIBSLP
944 if (BrowseLocalProtocols & BROWSE_SLP)
945 send_slp_browse(p);
946 #endif /* HAVE_LIBSLP */
947
948 #ifdef HAVE_LDAP
949 if (BrowseLocalProtocols & BROWSE_LDAP)
950 send_ldap_browse(p);
951 #endif /* HAVE_LDAP */
952 }
953 }
954
955 /*
956 * Save where we left off so that all printers get updated...
957 */
958
959 BrowseNext = p;
960 }
961
962 /*
963 * Loop through all of the printers and timeout old printers as needed...
964 */
965
966 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
967 p;
968 p = (cupsd_printer_t *)cupsArrayNext(Printers))
969 {
970 /*
971 * If this is a remote queue, see if it needs to be timed out...
972 */
973
974 if ((p->type & CUPS_PRINTER_DISCOVERED) &&
975 !(p->type & CUPS_PRINTER_IMPLICIT) &&
976 p->browse_expire < to)
977 {
978 cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, p, NULL,
979 "%s \'%s\' deleted by directory services (timeout).",
980 (p->type & CUPS_PRINTER_CLASS) ? "Class" : "Printer",
981 p->name);
982
983 cupsdLogMessage(CUPSD_LOG_DEBUG,
984 "Remote destination \"%s\" has timed out; "
985 "deleting it...",
986 p->name);
987
988 cupsArraySave(Printers);
989 cupsdDeletePrinter(p, 1);
990 cupsArrayRestore(Printers);
991 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
992 }
993 }
994 }
995
996
997 #ifdef HAVE_LDAP_REBIND_PROC
998 # if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
999 /*
1000 * 'ldap_rebind_proc()' - Callback function for LDAP rebind
1001 */
1002
1003 static int /* O - Result code */
1004 ldap_rebind_proc(
1005 LDAP *RebindLDAPHandle, /* I - LDAP handle */
1006 LDAP_CONST char *refsp, /* I - ??? */
1007 ber_tag_t request, /* I - ??? */
1008 ber_int_t msgid, /* I - ??? */
1009 void *params) /* I - ??? */
1010 {
1011 int rc; /* Result code */
1012 # if LDAP_API_VERSION > 3000
1013 struct berval bval; /* Bind value */
1014 # endif /* LDAP_API_VERSION > 3000 */
1015
1016 /*
1017 * Bind to new LDAP server...
1018 */
1019
1020 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_rebind_proc: Rebind to %s", refsp);
1021
1022 # if LDAP_API_VERSION > 3000
1023 bval.bv_val = BrowseLDAPPassword;
1024 bval.bv_len = (BrowseLDAPPassword == NULL) ? 0 : strlen(BrowseLDAPPassword);
1025
1026 rc = ldap_sasl_bind_s(RebindLDAPHandle, BrowseLDAPBindDN, LDAP_SASL_SIMPLE,
1027 &bval, NULL, NULL, NULL);
1028 # else
1029 rc = ldap_bind_s(RebindLDAPHandle, BrowseLDAPBindDN, BrowseLDAPPassword,
1030 LDAP_AUTH_SIMPLE);
1031 # endif /* LDAP_API_VERSION > 3000 */
1032
1033 return (rc);
1034 }
1035
1036
1037 # else /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
1038 /*
1039 * 'ldap_rebind_proc()' - Callback function for LDAP rebind
1040 */
1041
1042 static int /* O - Result code */
1043 ldap_rebind_proc(
1044 LDAP *RebindLDAPHandle, /* I - LDAP handle */
1045 char **dnp, /* I - ??? */
1046 char **passwdp, /* I - ??? */
1047 int *authmethodp, /* I - ??? */
1048 int freeit, /* I - ??? */
1049 void *arg) /* I - ??? */
1050 {
1051 switch (freeit)
1052 {
1053 case 1:
1054 /*
1055 * Free current values...
1056 */
1057
1058 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_rebind_proc: Free values...");
1059
1060 if (dnp && *dnp)
1061 free(*dnp);
1062
1063 if (passwdp && *passwdp)
1064 free(*passwdp);
1065 break;
1066
1067 case 0:
1068 /*
1069 * Return credentials for LDAP referal...
1070 */
1071
1072 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1073 "ldap_rebind_proc: Return necessary values...");
1074
1075 *dnp = strdup(BrowseLDAPBindDN);
1076 *passwdp = strdup(BrowseLDAPPassword);
1077 *authmethodp = LDAP_AUTH_SIMPLE;
1078 break;
1079
1080 default:
1081 /*
1082 * Should never happen...
1083 */
1084
1085 cupsdLogMessage(CUPSD_LOG_ERROR,
1086 "LDAP rebind has been called with wrong freeit value!");
1087 break;
1088 }
1089
1090 return (LDAP_SUCCESS);
1091 }
1092 # endif /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
1093 #endif /* HAVE_LDAP_REBIND_PROC */
1094
1095
1096 #ifdef HAVE_LDAP
1097 /*
1098 * 'ldap_connect()' - Start new LDAP connection
1099 */
1100
1101 static LDAP * /* O - LDAP handle */
1102 ldap_connect(void)
1103 {
1104 int rc; /* LDAP API status */
1105 int version = 3; /* LDAP version */
1106 struct berval bv = {0, ""}; /* SASL bind value */
1107 LDAP *TempBrowseLDAPHandle=NULL;
1108 /* Temporary LDAP Handle */
1109 # if defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP)
1110 int ldap_ssl = 0; /* LDAP SSL indicator */
1111 int ssl_err = 0; /* LDAP SSL error value */
1112 # endif /* defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP) */
1113
1114
1115 # ifdef HAVE_OPENLDAP
1116 # ifdef HAVE_LDAP_SSL
1117 /*
1118 * Set the certificate file to use for encrypted LDAP sessions...
1119 */
1120
1121 if (BrowseLDAPCACertFile)
1122 {
1123 cupsdLogMessage(CUPSD_LOG_DEBUG,
1124 "ldap_connect: Setting CA certificate file \"%s\"",
1125 BrowseLDAPCACertFile);
1126
1127 if ((rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE,
1128 (void *)BrowseLDAPCACertFile)) != LDAP_SUCCESS)
1129 cupsdLogMessage(CUPSD_LOG_ERROR,
1130 "Unable to set CA certificate file for LDAP "
1131 "connections: %d - %s", rc, ldap_err2string(rc));
1132 }
1133 # endif /* HAVE_LDAP_SSL */
1134
1135 /*
1136 * Initialize OPENLDAP connection...
1137 * LDAP stuff currently only supports ldapi EXTERNAL SASL binds...
1138 */
1139
1140 if (!BrowseLDAPServer || !strcasecmp(BrowseLDAPServer, "localhost"))
1141 rc = ldap_initialize(&TempBrowseLDAPHandle, "ldapi:///");
1142 else
1143 rc = ldap_initialize(&TempBrowseLDAPHandle, BrowseLDAPServer);
1144
1145 # else /* HAVE_OPENLDAP */
1146
1147 int ldap_port = 0; /* LDAP port */
1148 char ldap_protocol[11], /* LDAP protocol */
1149 ldap_host[255]; /* LDAP host */
1150
1151 /*
1152 * Split LDAP URI into its components...
1153 */
1154
1155 if (!BrowseLDAPServer)
1156 {
1157 cupsdLogMessage(CUPSD_LOG_ERROR, "BrowseLDAPServer not configured!");
1158 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1159 BrowseLocalProtocols &= ~BROWSE_LDAP;
1160 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1161 return (NULL);
1162 }
1163
1164 sscanf(BrowseLDAPServer, "%10[^:]://%254[^:/]:%d", ldap_protocol, ldap_host,
1165 &ldap_port);
1166
1167 if (!strcmp(ldap_protocol, "ldap"))
1168 ldap_ssl = 0;
1169 else if (!strcmp(ldap_protocol, "ldaps"))
1170 ldap_ssl = 1;
1171 else
1172 {
1173 cupsdLogMessage(CUPSD_LOG_ERROR, "Unrecognized LDAP protocol (%s)!",
1174 ldap_protocol);
1175 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1176 BrowseLocalProtocols &= ~BROWSE_LDAP;
1177 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1178 return (NULL);
1179 }
1180
1181 if (ldap_port == 0)
1182 {
1183 if (ldap_ssl)
1184 ldap_port = LDAPS_PORT;
1185 else
1186 ldap_port = LDAP_PORT;
1187 }
1188
1189 cupsdLogMessage(CUPSD_LOG_DEBUG, "ldap_connect: PROT:%s HOST:%s PORT:%d",
1190 ldap_protocol, ldap_host, ldap_port);
1191
1192 /*
1193 * Initialize LDAP connection...
1194 */
1195
1196 if (!ldap_ssl)
1197 {
1198 if ((TempBrowseLDAPHandle = ldap_init(ldap_host, ldap_port)) == NULL)
1199 rc = LDAP_OPERATIONS_ERROR;
1200 else
1201 rc = LDAP_SUCCESS;
1202
1203 # ifdef HAVE_LDAP_SSL
1204 }
1205 else
1206 {
1207 /*
1208 * Initialize SSL LDAP connection...
1209 */
1210
1211 if (BrowseLDAPCACertFile)
1212 {
1213 rc = ldapssl_client_init(BrowseLDAPCACertFile, (void *)NULL);
1214 if (rc != LDAP_SUCCESS)
1215 {
1216 cupsdLogMessage(CUPSD_LOG_ERROR,
1217 "Failed to initialize LDAP SSL client!");
1218 rc = LDAP_OPERATIONS_ERROR;
1219 }
1220 else
1221 {
1222 if ((TempBrowseLDAPHandle = ldapssl_init(ldap_host, ldap_port,
1223 1)) == NULL)
1224 rc = LDAP_OPERATIONS_ERROR;
1225 else
1226 rc = LDAP_SUCCESS;
1227 }
1228 }
1229 else
1230 {
1231 cupsdLogMessage(CUPSD_LOG_ERROR,
1232 "LDAP SSL certificate file/database not configured!");
1233 rc = LDAP_OPERATIONS_ERROR;
1234 }
1235
1236 # else /* HAVE_LDAP_SSL */
1237
1238 /*
1239 * Return error, because client libraries doesn't support SSL
1240 */
1241
1242 cupsdLogMessage(CUPSD_LOG_ERROR,
1243 "LDAP client libraries do not support SSL");
1244 rc = LDAP_OPERATIONS_ERROR;
1245
1246 # endif /* HAVE_LDAP_SSL */
1247 }
1248 # endif /* HAVE_OPENLDAP */
1249
1250 /*
1251 * Check return code from LDAP initialize...
1252 */
1253
1254 if (rc != LDAP_SUCCESS)
1255 {
1256 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to initialize LDAP!");
1257
1258 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
1259 cupsdLogMessage(CUPSD_LOG_ERROR, "Temporarily disabling LDAP browsing...");
1260 else
1261 {
1262 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1263
1264 BrowseLocalProtocols &= ~BROWSE_LDAP;
1265 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1266 }
1267
1268 ldap_disconnect(TempBrowseLDAPHandle);
1269
1270 return (NULL);
1271 }
1272
1273 /*
1274 * Upgrade LDAP version...
1275 */
1276
1277 if (ldap_set_option(TempBrowseLDAPHandle, LDAP_OPT_PROTOCOL_VERSION,
1278 (const void *)&version) != LDAP_SUCCESS)
1279 {
1280 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to set LDAP protocol version %d!",
1281 version);
1282 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1283
1284 BrowseLocalProtocols &= ~BROWSE_LDAP;
1285 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1286 ldap_disconnect(TempBrowseLDAPHandle);
1287
1288 return (NULL);
1289 }
1290
1291 /*
1292 * Register LDAP rebind procedure...
1293 */
1294
1295 # ifdef HAVE_LDAP_REBIND_PROC
1296 # if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1297
1298 rc = ldap_set_rebind_proc(TempBrowseLDAPHandle, &ldap_rebind_proc,
1299 (void *)NULL);
1300 if (rc != LDAP_SUCCESS)
1301 cupsdLogMessage(CUPSD_LOG_ERROR,
1302 "Setting LDAP rebind function failed with status %d: %s",
1303 rc, ldap_err2string(rc));
1304
1305 # else
1306
1307 ldap_set_rebind_proc(TempBrowseLDAPHandle, &ldap_rebind_proc, (void *)NULL);
1308
1309 # endif /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
1310 # endif /* HAVE_LDAP_REBIND_PROC */
1311
1312 /*
1313 * Start LDAP bind...
1314 */
1315
1316 # if LDAP_API_VERSION > 3000
1317 struct berval bval;
1318 bval.bv_val = BrowseLDAPPassword;
1319 bval.bv_len = (BrowseLDAPPassword == NULL) ? 0 : strlen(BrowseLDAPPassword);
1320
1321 if (!BrowseLDAPServer || !strcasecmp(BrowseLDAPServer, "localhost"))
1322 rc = ldap_sasl_bind_s(TempBrowseLDAPHandle, NULL, "EXTERNAL", &bv, NULL,
1323 NULL, NULL);
1324 else
1325 rc = ldap_sasl_bind_s(TempBrowseLDAPHandle, BrowseLDAPBindDN, LDAP_SASL_SIMPLE, &bval, NULL, NULL, NULL);
1326
1327 # else
1328 rc = ldap_bind_s(TempBrowseLDAPHandle, BrowseLDAPBindDN,
1329 BrowseLDAPPassword, LDAP_AUTH_SIMPLE);
1330 # endif /* LDAP_API_VERSION > 3000 */
1331
1332 if (rc != LDAP_SUCCESS)
1333 {
1334 cupsdLogMessage(CUPSD_LOG_ERROR, "LDAP bind failed with error %d: %s",
1335 rc, ldap_err2string(rc));
1336
1337 # if defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP)
1338 if (ldap_ssl && (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR))
1339 {
1340 ssl_err = PORT_GetError();
1341 if (ssl_err != 0)
1342 cupsdLogMessage(CUPSD_LOG_ERROR, "LDAP SSL error %d: %s", ssl_err,
1343 ldapssl_err2string(ssl_err));
1344 }
1345 # endif /* defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP) */
1346
1347 ldap_disconnect(TempBrowseLDAPHandle);
1348
1349 return (NULL);
1350 }
1351
1352 cupsdLogMessage(CUPSD_LOG_INFO, "LDAP connection established");
1353
1354 return (TempBrowseLDAPHandle);
1355 }
1356
1357
1358 /*
1359 * 'ldap_reconnect()' - Reconnect to LDAP Server
1360 */
1361
1362 static LDAP * /* O - New LDAP handle */
1363 ldap_reconnect(void)
1364 {
1365 LDAP *TempBrowseLDAPHandle = NULL; /* Temp Handle to LDAP server */
1366
1367
1368 /*
1369 * Get a new LDAP Handle and replace the global Handle
1370 * if the new connection was successful.
1371 */
1372
1373 cupsdLogMessage(CUPSD_LOG_INFO, "Try LDAP reconnect...");
1374
1375 TempBrowseLDAPHandle = ldap_connect();
1376
1377 if (TempBrowseLDAPHandle != NULL)
1378 {
1379 if (BrowseLDAPHandle != NULL)
1380 ldap_disconnect(BrowseLDAPHandle);
1381
1382 BrowseLDAPHandle = TempBrowseLDAPHandle;
1383 }
1384
1385 return (BrowseLDAPHandle);
1386 }
1387
1388
1389 /*
1390 * 'ldap_disconnect()' - Disconnect from LDAP Server
1391 */
1392
1393 static void
1394 ldap_disconnect(LDAP *ld) /* I - LDAP handle */
1395 {
1396 int rc; /* Return code */
1397
1398
1399 /*
1400 * Close LDAP handle...
1401 */
1402
1403 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
1404 rc = ldap_unbind_ext_s(ld, NULL, NULL);
1405 # else
1406 rc = ldap_unbind_s(ld);
1407 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
1408
1409 if (rc != LDAP_SUCCESS)
1410 cupsdLogMessage(CUPSD_LOG_ERROR,
1411 "Unbind from LDAP server failed with status %d: %s",
1412 rc, ldap_err2string(rc));
1413 }
1414 #endif /* HAVE_LDAP */
1415
1416
1417 /*
1418 * 'cupsdStartBrowsing()' - Start sending and receiving broadcast information.
1419 */
1420
1421 void
1422 cupsdStartBrowsing(void)
1423 {
1424 int val; /* Socket option value */
1425 struct sockaddr_in addr; /* Broadcast address */
1426 cupsd_printer_t *p; /* Current printer */
1427
1428
1429 BrowseNext = NULL;
1430
1431 if (!Browsing || !(BrowseLocalProtocols | BrowseRemoteProtocols))
1432 return;
1433
1434 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_CUPS)
1435 {
1436 if (BrowseSocket < 0)
1437 {
1438 /*
1439 * Create the broadcast socket...
1440 */
1441
1442 if ((BrowseSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1443 {
1444 cupsdLogMessage(CUPSD_LOG_ERROR,
1445 "Unable to create broadcast socket - %s.",
1446 strerror(errno));
1447 BrowseLocalProtocols &= ~BROWSE_CUPS;
1448 BrowseRemoteProtocols &= ~BROWSE_CUPS;
1449
1450 if (FatalErrors & CUPSD_FATAL_BROWSE)
1451 cupsdEndProcess(getpid(), 0);
1452 }
1453 }
1454
1455 if (BrowseSocket >= 0)
1456 {
1457 /*
1458 * Bind the socket to browse port...
1459 */
1460
1461 memset(&addr, 0, sizeof(addr));
1462 addr.sin_addr.s_addr = htonl(INADDR_ANY);
1463 addr.sin_family = AF_INET;
1464 addr.sin_port = htons(BrowsePort);
1465
1466 if (bind(BrowseSocket, (struct sockaddr *)&addr, sizeof(addr)))
1467 {
1468 cupsdLogMessage(CUPSD_LOG_ERROR,
1469 "Unable to bind broadcast socket - %s.",
1470 strerror(errno));
1471
1472 #ifdef WIN32
1473 closesocket(BrowseSocket);
1474 #else
1475 close(BrowseSocket);
1476 #endif /* WIN32 */
1477
1478 BrowseSocket = -1;
1479 BrowseLocalProtocols &= ~BROWSE_CUPS;
1480 BrowseRemoteProtocols &= ~BROWSE_CUPS;
1481
1482 if (FatalErrors & CUPSD_FATAL_BROWSE)
1483 cupsdEndProcess(getpid(), 0);
1484 }
1485 }
1486
1487 if (BrowseSocket >= 0)
1488 {
1489 /*
1490 * Set the "broadcast" flag...
1491 */
1492
1493 val = 1;
1494 if (setsockopt(BrowseSocket, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)))
1495 {
1496 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to set broadcast mode - %s.",
1497 strerror(errno));
1498
1499 #ifdef WIN32
1500 closesocket(BrowseSocket);
1501 #else
1502 close(BrowseSocket);
1503 #endif /* WIN32 */
1504
1505 BrowseSocket = -1;
1506 BrowseLocalProtocols &= ~BROWSE_CUPS;
1507 BrowseRemoteProtocols &= ~BROWSE_CUPS;
1508
1509 if (FatalErrors & CUPSD_FATAL_BROWSE)
1510 cupsdEndProcess(getpid(), 0);
1511 }
1512 }
1513
1514 if (BrowseSocket >= 0)
1515 {
1516 /*
1517 * Close the socket on exec...
1518 */
1519
1520 fcntl(BrowseSocket, F_SETFD, fcntl(BrowseSocket, F_GETFD) | FD_CLOEXEC);
1521
1522 /*
1523 * Finally, add the socket to the input selection set as needed...
1524 */
1525
1526 if (BrowseRemoteProtocols & BROWSE_CUPS)
1527 {
1528 /*
1529 * We only listen if we want remote printers...
1530 */
1531
1532 cupsdAddSelect(BrowseSocket, (cupsd_selfunc_t)update_cups_browse,
1533 NULL, NULL);
1534 }
1535 }
1536 }
1537 else
1538 BrowseSocket = -1;
1539
1540 #ifdef HAVE_DNSSD
1541 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_DNSSD)
1542 {
1543 DNSServiceErrorType error; /* Error from service creation */
1544 cupsd_listener_t *lis; /* Current listening socket */
1545
1546
1547 /*
1548 * First create a "master" connection for all registrations...
1549 */
1550
1551 if ((error = DNSServiceCreateConnection(&DNSSDRef))
1552 != kDNSServiceErr_NoError)
1553 {
1554 cupsdLogMessage(CUPSD_LOG_ERROR,
1555 "Unable to create master DNS-SD reference: %d", error);
1556
1557 if (FatalErrors & CUPSD_FATAL_BROWSE)
1558 cupsdEndProcess(getpid(), 0);
1559 }
1560 else
1561 {
1562 /*
1563 * Add the master connection to the select list...
1564 */
1565
1566 int fd = DNSServiceRefSockFD(DNSSDRef);
1567
1568 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
1569
1570 cupsdAddSelect(fd, (cupsd_selfunc_t)dnssdUpdate, NULL, NULL);
1571
1572 /*
1573 * Then get the port we use for registrations. If we are not listening
1574 * on any non-local ports, there is no sense sharing local printers via
1575 * Bonjour...
1576 */
1577
1578 DNSSDPort = 0;
1579
1580 for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
1581 lis;
1582 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
1583 {
1584 if (httpAddrLocalhost(&(lis->address)))
1585 continue;
1586
1587 if (lis->address.addr.sa_family == AF_INET)
1588 {
1589 DNSSDPort = ntohs(lis->address.ipv4.sin_port);
1590 break;
1591 }
1592 else if (lis->address.addr.sa_family == AF_INET6)
1593 {
1594 DNSSDPort = ntohs(lis->address.ipv6.sin6_port);
1595 break;
1596 }
1597 }
1598
1599 /*
1600 * Create an array to track the printers we share...
1601 */
1602
1603 if (BrowseRemoteProtocols & BROWSE_DNSSD)
1604 DNSSDPrinters = cupsArrayNew((cups_array_func_t)dnssdComparePrinters,
1605 NULL);
1606
1607 /*
1608 * Set the computer name and register the web interface...
1609 */
1610
1611 cupsdUpdateDNSSDName();
1612 }
1613 }
1614 #endif /* HAVE_DNSSD */
1615
1616 #ifdef HAVE_LIBSLP
1617 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_SLP)
1618 {
1619 /*
1620 * Open SLP handle...
1621 */
1622
1623 if (SLPOpen("en", SLP_FALSE, &BrowseSLPHandle) != SLP_OK)
1624 {
1625 cupsdLogMessage(CUPSD_LOG_ERROR,
1626 "Unable to open an SLP handle; disabling SLP browsing!");
1627 BrowseLocalProtocols &= ~BROWSE_SLP;
1628 BrowseRemoteProtocols &= ~BROWSE_SLP;
1629 BrowseSLPHandle = NULL;
1630
1631 if (FatalErrors & CUPSD_FATAL_BROWSE)
1632 cupsdEndProcess(getpid(), 0);
1633 }
1634
1635 BrowseSLPRefresh = 0;
1636 }
1637 else
1638 BrowseSLPHandle = NULL;
1639 #endif /* HAVE_LIBSLP */
1640
1641 #ifdef HAVE_LDAP
1642 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_LDAP)
1643 {
1644 if (!BrowseLDAPDN)
1645 {
1646 cupsdLogMessage(CUPSD_LOG_ERROR,
1647 "Need to set BrowseLDAPDN to use LDAP browsing!");
1648 BrowseLocalProtocols &= ~BROWSE_LDAP;
1649 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1650
1651 if (FatalErrors & CUPSD_FATAL_BROWSE)
1652 cupsdEndProcess(getpid(), 0);
1653 }
1654 else
1655 {
1656 /*
1657 * Open LDAP handle...
1658 */
1659
1660 if ((BrowseLDAPHandle = ldap_connect()) == NULL &&
1661 (FatalErrors & CUPSD_FATAL_BROWSE))
1662 cupsdEndProcess(getpid(), 0);
1663 }
1664
1665 BrowseLDAPRefresh = 0;
1666 }
1667 #endif /* HAVE_LDAP */
1668
1669 /*
1670 * Enable LPD and SMB printer sharing as needed through external programs...
1671 */
1672
1673 if (BrowseLocalProtocols & BROWSE_LPD)
1674 update_lpd(1);
1675
1676 if (BrowseLocalProtocols & BROWSE_SMB)
1677 update_smb(1);
1678
1679 /*
1680 * Register the individual printers
1681 */
1682
1683 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1684 p;
1685 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1686 if (!(p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
1687 CUPS_PRINTER_SCANNER)))
1688 cupsdRegisterPrinter(p);
1689 }
1690
1691
1692 /*
1693 * 'cupsdStartPolling()' - Start polling servers as needed.
1694 */
1695
1696 void
1697 cupsdStartPolling(void)
1698 {
1699 int i; /* Looping var */
1700 cupsd_dirsvc_poll_t *pollp; /* Current polling server */
1701 char polld[1024]; /* Poll daemon path */
1702 char sport[255]; /* Server port */
1703 char bport[255]; /* Browser port */
1704 char interval[255]; /* Poll interval */
1705 int statusfds[2]; /* Status pipe */
1706 char *argv[6]; /* Arguments */
1707 char *envp[100]; /* Environment */
1708
1709
1710 /*
1711 * Don't do anything if we aren't polling...
1712 */
1713
1714 if (NumPolled == 0 || BrowseSocket < 0)
1715 {
1716 PollPipe = -1;
1717 PollStatusBuffer = NULL;
1718 return;
1719 }
1720
1721 /*
1722 * Setup string arguments for polld, port and interval options.
1723 */
1724
1725 snprintf(polld, sizeof(polld), "%s/daemon/cups-polld", ServerBin);
1726
1727 sprintf(bport, "%d", BrowsePort);
1728
1729 if (BrowseInterval)
1730 sprintf(interval, "%d", BrowseInterval);
1731 else
1732 strcpy(interval, "30");
1733
1734 argv[0] = "cups-polld";
1735 argv[2] = sport;
1736 argv[3] = interval;
1737 argv[4] = bport;
1738 argv[5] = NULL;
1739
1740 cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
1741
1742 /*
1743 * Create a pipe that receives the status messages from each
1744 * polling daemon...
1745 */
1746
1747 if (cupsdOpenPipe(statusfds))
1748 {
1749 cupsdLogMessage(CUPSD_LOG_ERROR,
1750 "Unable to create polling status pipes - %s.",
1751 strerror(errno));
1752 PollPipe = -1;
1753 PollStatusBuffer = NULL;
1754 return;
1755 }
1756
1757 PollPipe = statusfds[0];
1758 PollStatusBuffer = cupsdStatBufNew(PollPipe, "[Poll]");
1759
1760 /*
1761 * Run each polling daemon, redirecting stderr to the polling pipe...
1762 */
1763
1764 for (i = 0, pollp = Polled; i < NumPolled; i ++, pollp ++)
1765 {
1766 sprintf(sport, "%d", pollp->port);
1767
1768 argv[1] = pollp->hostname;
1769
1770 if (cupsdStartProcess(polld, argv, envp, -1, -1, statusfds[1], -1, -1,
1771 0, DefaultProfile, NULL, &(pollp->pid)) < 0)
1772 {
1773 cupsdLogMessage(CUPSD_LOG_ERROR,
1774 "cupsdStartPolling: Unable to fork polling daemon - %s",
1775 strerror(errno));
1776 pollp->pid = 0;
1777 break;
1778 }
1779 else
1780 cupsdLogMessage(CUPSD_LOG_DEBUG,
1781 "cupsdStartPolling: Started polling daemon for %s:%d, pid = %d",
1782 pollp->hostname, pollp->port, pollp->pid);
1783 }
1784
1785 close(statusfds[1]);
1786
1787 /*
1788 * Finally, add the pipe to the input selection set...
1789 */
1790
1791 cupsdAddSelect(PollPipe, (cupsd_selfunc_t)update_polling, NULL, NULL);
1792 }
1793
1794
1795 /*
1796 * 'cupsdStopBrowsing()' - Stop sending and receiving broadcast information.
1797 */
1798
1799 void
1800 cupsdStopBrowsing(void)
1801 {
1802 cupsd_printer_t *p; /* Current printer */
1803
1804
1805 if (!Browsing || !(BrowseLocalProtocols | BrowseRemoteProtocols))
1806 return;
1807
1808 /*
1809 * De-register the individual printers
1810 */
1811
1812 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1813 p;
1814 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1815 if (!(p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
1816 CUPS_PRINTER_SCANNER)))
1817 cupsdDeregisterPrinter(p, 1);
1818
1819 /*
1820 * Shut down browsing sockets...
1821 */
1822
1823 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_CUPS) &&
1824 BrowseSocket >= 0)
1825 {
1826 /*
1827 * Close the socket and remove it from the input selection set.
1828 */
1829
1830 #ifdef WIN32
1831 closesocket(BrowseSocket);
1832 #else
1833 close(BrowseSocket);
1834 #endif /* WIN32 */
1835
1836 cupsdRemoveSelect(BrowseSocket);
1837 BrowseSocket = -1;
1838 }
1839
1840 #ifdef HAVE_DNSSD
1841 if ((BrowseLocalProtocols & BROWSE_DNSSD) && DNSSDRef)
1842 dnssdStop();
1843 #endif /* HAVE_DNSSD */
1844
1845 #ifdef HAVE_LIBSLP
1846 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_SLP) &&
1847 BrowseSLPHandle)
1848 {
1849 /*
1850 * Close SLP handle...
1851 */
1852
1853 SLPClose(BrowseSLPHandle);
1854 BrowseSLPHandle = NULL;
1855 }
1856 #endif /* HAVE_LIBSLP */
1857
1858 #ifdef HAVE_LDAP
1859 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_LDAP) &&
1860 BrowseLDAPHandle)
1861 {
1862 ldap_dereg_ou(ServerName, BrowseLDAPDN);
1863 ldap_disconnect(BrowseLDAPHandle);
1864 BrowseLDAPHandle = NULL;
1865 }
1866 #endif /* HAVE_OPENLDAP */
1867
1868 /*
1869 * Disable LPD and SMB printer sharing as needed through external programs...
1870 */
1871
1872 if (BrowseLocalProtocols & BROWSE_LPD)
1873 update_lpd(0);
1874
1875 if (BrowseLocalProtocols & BROWSE_SMB)
1876 update_smb(0);
1877 }
1878
1879
1880 /*
1881 * 'cupsdStopPolling()' - Stop polling servers as needed.
1882 */
1883
1884 void
1885 cupsdStopPolling(void)
1886 {
1887 int i; /* Looping var */
1888 cupsd_dirsvc_poll_t *pollp; /* Current polling server */
1889
1890
1891 if (PollPipe >= 0)
1892 {
1893 cupsdStatBufDelete(PollStatusBuffer);
1894 close(PollPipe);
1895
1896 cupsdRemoveSelect(PollPipe);
1897
1898 PollPipe = -1;
1899 PollStatusBuffer = NULL;
1900 }
1901
1902 for (i = 0, pollp = Polled; i < NumPolled; i ++, pollp ++)
1903 if (pollp->pid)
1904 cupsdEndProcess(pollp->pid, 0);
1905 }
1906
1907
1908 #ifdef HAVE_DNSSD
1909 /*
1910 * 'cupsdUpdateDNSSDName()' - Update the computer name we use for browsing...
1911 */
1912
1913 void
1914 cupsdUpdateDNSSDName(void)
1915 {
1916 DNSServiceErrorType error; /* Error from service creation */
1917 char webif[1024]; /* Web interface share name */
1918 # ifdef HAVE_SYSTEMCONFIGURATION
1919 SCDynamicStoreRef sc; /* Context for dynamic store */
1920 CFDictionaryRef btmm; /* Back-to-My-Mac domains */
1921 CFStringEncoding nameEncoding; /* Encoding of computer name */
1922 CFStringRef nameRef; /* Host name CFString */
1923 char nameBuffer[1024]; /* C-string buffer */
1924 # endif /* HAVE_SYSTEMCONFIGURATION */
1925
1926
1927 /*
1928 * Only share the web interface and printers when non-local listening is
1929 * enabled...
1930 */
1931
1932
1933 if (!DNSSDPort)
1934 return;
1935
1936 /*
1937 * Get the computer name as a c-string...
1938 */
1939
1940 # ifdef HAVE_SYSTEMCONFIGURATION
1941 sc = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("cupsd"), NULL, NULL);
1942
1943 if (sc)
1944 {
1945 /*
1946 * Get the computer name from the dynamic store...
1947 */
1948
1949 cupsdClearString(&DNSSDComputerName);
1950
1951 if ((nameRef = SCDynamicStoreCopyComputerName(sc, &nameEncoding)) != NULL)
1952 {
1953 if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer),
1954 kCFStringEncodingUTF8))
1955 {
1956 cupsdLogMessage(CUPSD_LOG_DEBUG,
1957 "Dynamic store computer name is \"%s\".", nameBuffer);
1958 cupsdSetString(&DNSSDComputerName, nameBuffer);
1959 }
1960
1961 CFRelease(nameRef);
1962 }
1963
1964 if (!DNSSDComputerName)
1965 {
1966 /*
1967 * Use the ServerName instead...
1968 */
1969
1970 cupsdLogMessage(CUPSD_LOG_DEBUG,
1971 "Using ServerName \"%s\" as computer name.", ServerName);
1972 cupsdSetString(&DNSSDComputerName, ServerName);
1973 }
1974
1975 /*
1976 * Get the local hostname from the dynamic store...
1977 */
1978
1979 cupsdClearString(&DNSSDHostName);
1980
1981 if ((nameRef = SCDynamicStoreCopyLocalHostName(sc)) != NULL)
1982 {
1983 if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer),
1984 kCFStringEncodingUTF8))
1985 {
1986 cupsdLogMessage(CUPSD_LOG_DEBUG,
1987 "Dynamic store host name is \"%s\".", nameBuffer);
1988 cupsdSetString(&DNSSDHostName, nameBuffer);
1989 }
1990
1991 CFRelease(nameRef);
1992 }
1993
1994 if (!DNSSDHostName)
1995 {
1996 /*
1997 * Use the ServerName instead...
1998 */
1999
2000 cupsdLogMessage(CUPSD_LOG_DEBUG,
2001 "Using ServerName \"%s\" as host name.", ServerName);
2002 cupsdSetString(&DNSSDHostName, ServerName);
2003 }
2004
2005 /*
2006 * Get any Back-to-My-Mac domains and add them as aliases...
2007 */
2008
2009 cupsdFreeAliases(DNSSDAlias);
2010 DNSSDAlias = NULL;
2011
2012 btmm = SCDynamicStoreCopyValue(sc, CFSTR("Setup:/Network/BackToMyMac"));
2013 if (btmm && CFGetTypeID(btmm) == CFDictionaryGetTypeID())
2014 {
2015 cupsdLogMessage(CUPSD_LOG_DEBUG, "%d Back to My Mac aliases to add.",
2016 (int)CFDictionaryGetCount(btmm));
2017 CFDictionaryApplyFunction(btmm, dnssdAddAlias, NULL);
2018 }
2019 else if (btmm)
2020 cupsdLogMessage(CUPSD_LOG_ERROR,
2021 "Bad Back to My Mac data in dynamic store!");
2022 else
2023 cupsdLogMessage(CUPSD_LOG_DEBUG, "No Back to My Mac aliases to add.");
2024
2025 if (btmm)
2026 CFRelease(btmm);
2027
2028 CFRelease(sc);
2029 }
2030 else
2031 # endif /* HAVE_SYSTEMCONFIGURATION */
2032 {
2033 cupsdSetString(&DNSSDComputerName, ServerName);
2034 cupsdSetString(&DNSSDHostName, ServerName);
2035 }
2036
2037 /*
2038 * Then (re)register the web interface if enabled...
2039 */
2040
2041 if (BrowseWebIF)
2042 {
2043 if (DNSSDComputerName)
2044 snprintf(webif, sizeof(webif), "CUPS @ %s", DNSSDComputerName);
2045 else
2046 strlcpy(webif, "CUPS Web Interface", sizeof(webif));
2047
2048 if (WebIFRef)
2049 DNSServiceRefDeallocate(WebIFRef);
2050
2051 WebIFRef = DNSSDRef;
2052 if ((error = DNSServiceRegister(&WebIFRef,
2053 kDNSServiceFlagsShareConnection,
2054 0, webif, "_http._tcp", NULL,
2055 NULL, htons(DNSSDPort), 7,
2056 "\006path=/", dnssdRegisterCallback,
2057 NULL)) != kDNSServiceErr_NoError)
2058 cupsdLogMessage(CUPSD_LOG_ERROR,
2059 "DNS-SD web interface registration failed: %d", error);
2060 }
2061 }
2062 #endif /* HAVE_DNSSD */
2063
2064
2065 #ifdef HAVE_LDAP
2066 /*
2067 * 'cupsdUpdateLDAPBrowse()' - Scan for new printers via LDAP...
2068 */
2069
2070 void
2071 cupsdUpdateLDAPBrowse(void)
2072 {
2073 char uri[HTTP_MAX_URI], /* Printer URI */
2074 host[HTTP_MAX_URI], /* Hostname */
2075 resource[HTTP_MAX_URI], /* Resource path */
2076 location[1024], /* Printer location */
2077 info[1024], /* Printer information */
2078 make_model[1024], /* Printer make and model */
2079 type_num[30]; /* Printer type number */
2080 int type; /* Printer type */
2081 int rc; /* LDAP status */
2082 int limit; /* Size limit */
2083 LDAPMessage *res, /* LDAP search results */
2084 *e; /* Current entry from search */
2085
2086 cupsdLogMessage(CUPSD_LOG_DEBUG2, "UpdateLDAPBrowse: %s", ServerName);
2087
2088 BrowseLDAPRefresh = time(NULL) + BrowseInterval;
2089
2090 /*
2091 * Reconnect if LDAP Handle is invalid...
2092 */
2093
2094 if (! BrowseLDAPHandle)
2095 {
2096 ldap_reconnect();
2097 return;
2098 }
2099
2100 /*
2101 * Search for cups printers in LDAP directory...
2102 */
2103
2104 rc = ldap_search_rec(BrowseLDAPHandle, BrowseLDAPDN, LDAP_SCOPE_SUBTREE,
2105 "(objectclass=cupsPrinter)", (char **)ldap_attrs, 0, &res);
2106
2107 /*
2108 * If ldap search was successfull then exit function
2109 * and temporary disable LDAP updates...
2110 */
2111
2112 if (rc != LDAP_SUCCESS)
2113 {
2114 if (BrowseLDAPUpdate && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR)))
2115 {
2116 BrowseLDAPUpdate = FALSE;
2117 cupsdLogMessage(CUPSD_LOG_INFO,
2118 "LDAP update temporary disabled");
2119 }
2120 return;
2121 }
2122
2123 /*
2124 * If LDAP updates were disabled, we will reenable them...
2125 */
2126
2127 if (! BrowseLDAPUpdate)
2128 {
2129 BrowseLDAPUpdate = TRUE;
2130 cupsdLogMessage(CUPSD_LOG_INFO,
2131 "LDAP update enabled");
2132 }
2133
2134 /*
2135 * Count LDAP entries and return if no entry exist...
2136 */
2137
2138 limit = ldap_count_entries(BrowseLDAPHandle, res);
2139 cupsdLogMessage(CUPSD_LOG_DEBUG2, "LDAP search returned %d entries", limit);
2140 if (limit < 1)
2141 {
2142 ldap_freeres(res);
2143 return;
2144 }
2145
2146 /*
2147 * Loop through the available printers...
2148 */
2149
2150 for (e = ldap_first_entry(BrowseLDAPHandle, res);
2151 e;
2152 e = ldap_next_entry(BrowseLDAPHandle, e))
2153 {
2154 /*
2155 * Get the required values from this entry...
2156 */
2157
2158 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2159 "printerDescription", info, sizeof(info)) == -1)
2160 continue;
2161
2162 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2163 "printerLocation", location, sizeof(location)) == -1)
2164 continue;
2165
2166 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2167 "printerMakeAndModel", make_model, sizeof(make_model)) == -1)
2168 continue;
2169
2170 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2171 "printerType", type_num, sizeof(type_num)) == -1)
2172 continue;
2173
2174 type = atoi(type_num);
2175
2176 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2177 "printerURI", uri, sizeof(uri)) == -1)
2178 continue;
2179
2180 /*
2181 * Process the entry as browse data...
2182 */
2183
2184 if (!is_local_queue(uri, host, sizeof(host), resource, sizeof(resource)))
2185 process_browse_data(uri, host, resource, type, IPP_PRINTER_IDLE,
2186 location, info, make_model, 0, NULL);
2187
2188 }
2189
2190 ldap_freeres(res);
2191 }
2192 #endif /* HAVE_LDAP */
2193
2194
2195 #ifdef HAVE_LIBSLP
2196 /*
2197 * 'cupsdUpdateSLPBrowse()' - Get browsing information via SLP.
2198 */
2199
2200 void
2201 cupsdUpdateSLPBrowse(void)
2202 {
2203 slpsrvurl_t *s, /* Temporary list of service URLs */
2204 *next; /* Next service in list */
2205 cupsd_printer_t p; /* Printer information */
2206 const char *uri; /* Pointer to printer URI */
2207 char host[HTTP_MAX_URI], /* Host portion of URI */
2208 resource[HTTP_MAX_URI]; /* Resource portion of URI */
2209
2210
2211 /*
2212 * Reset the refresh time...
2213 */
2214
2215 BrowseSLPRefresh = time(NULL) + BrowseInterval;
2216
2217 /*
2218 * Poll for remote printers using SLP...
2219 */
2220
2221 s = NULL;
2222
2223 SLPFindSrvs(BrowseSLPHandle, SLP_CUPS_SRVTYPE, "", "",
2224 slp_url_callback, &s);
2225
2226 /*
2227 * Loop through the list of available printers...
2228 */
2229
2230 for (; s; s = next)
2231 {
2232 /*
2233 * Save the "next" pointer...
2234 */
2235
2236 next = s->next;
2237
2238 /*
2239 * Load a cupsd_printer_t structure with the SLP service attributes...
2240 */
2241
2242 SLPFindAttrs(BrowseSLPHandle, s->url, "", "", slp_attr_callback, &p);
2243
2244 /*
2245 * Process this printer entry...
2246 */
2247
2248 uri = s->url + SLP_CUPS_SRVLEN + 1;
2249
2250 if (!strncmp(uri, "http://", 7) || !strncmp(uri, "ipp://", 6))
2251 {
2252 /*
2253 * Pull the URI apart to see if this is a local or remote printer...
2254 */
2255
2256 if (!is_local_queue(uri, host, sizeof(host), resource, sizeof(resource)))
2257 process_browse_data(uri, host, resource, p.type, IPP_PRINTER_IDLE,
2258 p.location, p.info, p.make_model, 0, NULL);
2259 }
2260
2261 /*
2262 * Free this listing...
2263 */
2264
2265 cupsdClearString(&p.info);
2266 cupsdClearString(&p.location);
2267 cupsdClearString(&p.make_model);
2268
2269 free(s);
2270 }
2271 }
2272 #endif /* HAVE_LIBSLP */
2273
2274
2275 /*
2276 * 'dequote()' - Remote quotes from a string.
2277 */
2278
2279 static char * /* O - Dequoted string */
2280 dequote(char *d, /* I - Destination string */
2281 const char *s, /* I - Source string */
2282 int dlen) /* I - Destination length */
2283 {
2284 char *dptr; /* Pointer into destination */
2285
2286
2287 if (s)
2288 {
2289 for (dptr = d, dlen --; *s && dlen > 0; s ++)
2290 if (*s != '\"')
2291 {
2292 *dptr++ = *s;
2293 dlen --;
2294 }
2295
2296 *dptr = '\0';
2297 }
2298 else
2299 *d = '\0';
2300
2301 return (d);
2302 }
2303
2304
2305 #ifdef HAVE_DNSSD
2306 # ifdef HAVE_COREFOUNDATION
2307 /*
2308 * 'dnssdAddAlias()' - Add a DNS-SD alias name.
2309 */
2310
2311 static void
2312 dnssdAddAlias(const void *key, /* I - Key */
2313 const void *value, /* I - Value (domain) */
2314 void *context) /* I - Unused */
2315 {
2316 char valueStr[1024], /* Domain string */
2317 hostname[1024]; /* Complete hostname */
2318
2319
2320 (void)context;
2321
2322 if (CFGetTypeID((CFStringRef)value) == CFStringGetTypeID() &&
2323 CFStringGetCString((CFStringRef)value, valueStr, sizeof(valueStr),
2324 kCFStringEncodingUTF8))
2325 {
2326 snprintf(hostname, sizeof(hostname), "%s.%s", DNSSDHostName, valueStr);
2327 if (!DNSSDAlias)
2328 DNSSDAlias = cupsArrayNew(NULL, NULL);
2329
2330 cupsdAddAlias(DNSSDAlias, hostname);
2331 cupsdLogMessage(CUPSD_LOG_DEBUG, "Added Back to My Mac ServerAlias %s",
2332 hostname);
2333 }
2334 else
2335 cupsdLogMessage(CUPSD_LOG_ERROR,
2336 "Bad Back to My Mac domain in dynamic store!");
2337 }
2338 # endif /* HAVE_COREFOUNDATION */
2339
2340
2341 /*
2342 * 'dnssdBuildTxtRecord()' - Build a TXT record from printer info.
2343 */
2344
2345 static char * /* O - TXT record */
2346 dnssdBuildTxtRecord(
2347 int *txt_len, /* O - TXT record length */
2348 cupsd_printer_t *p, /* I - Printer information */
2349 int for_lpd) /* I - 1 = LPD, 0 = IPP */
2350 {
2351 int i; /* Looping var */
2352 char admin_hostname[256], /* .local hostname for admin page */
2353 adminurl_str[256], /* URL for the admin page */
2354 type_str[32], /* Type to string buffer */
2355 state_str[32], /* State to string buffer */
2356 rp_str[1024], /* Queue name string buffer */
2357 air_str[1024], /* auth-info-required string buffer */
2358 *keyvalue[32][2]; /* Table of key/value pairs */
2359
2360
2361 /*
2362 * Load up the key value pairs...
2363 */
2364
2365 i = 0;
2366
2367 keyvalue[i ][0] = "txtvers";
2368 keyvalue[i++][1] = "1";
2369
2370 keyvalue[i ][0] = "qtotal";
2371 keyvalue[i++][1] = "1";
2372
2373 keyvalue[i ][0] = "rp";
2374 keyvalue[i++][1] = rp_str;
2375 if (for_lpd)
2376 strlcpy(rp_str, p->name, sizeof(rp_str));
2377 else
2378 snprintf(rp_str, sizeof(rp_str), "%s/%s",
2379 (p->type & CUPS_PRINTER_CLASS) ? "classes" : "printers", p->name);
2380
2381 keyvalue[i ][0] = "ty";
2382 keyvalue[i++][1] = p->make_model ? p->make_model : "Unknown";
2383
2384 snprintf(admin_hostname, sizeof(admin_hostname), "%s.local", DNSSDHostName);
2385 httpAssembleURIf(HTTP_URI_CODING_ALL, adminurl_str, sizeof(adminurl_str),
2386 "http", NULL, admin_hostname, DNSSDPort, "/%s/%s",
2387 (p->type & CUPS_PRINTER_CLASS) ? "classes" : "printers",
2388 p->name);
2389 keyvalue[i ][0] = "adminurl";
2390 keyvalue[i++][1] = adminurl_str;
2391
2392 keyvalue[i ][0] = "note";
2393 keyvalue[i++][1] = p->location ? p->location : "";
2394
2395 keyvalue[i ][0] = "priority";
2396 keyvalue[i++][1] = for_lpd ? "100" : "0";
2397
2398 keyvalue[i ][0] = "product";
2399 keyvalue[i++][1] = p->product ? p->product : "Unknown";
2400
2401 snprintf(type_str, sizeof(type_str), "0x%X", p->type | CUPS_PRINTER_REMOTE);
2402 snprintf(state_str, sizeof(state_str), "%d", p->state);
2403
2404 keyvalue[i ][0] = "printer-state";
2405 keyvalue[i++][1] = state_str;
2406
2407 keyvalue[i ][0] = "printer-type";
2408 keyvalue[i++][1] = type_str;
2409
2410 keyvalue[i ][0] = "Transparent";
2411 keyvalue[i++][1] = "T";
2412
2413 keyvalue[i ][0] = "Binary";
2414 keyvalue[i++][1] = "T";
2415
2416 keyvalue[i ][0] = "Fax";
2417 keyvalue[i++][1] = (p->type & CUPS_PRINTER_FAX) ? "T" : "F";
2418
2419 keyvalue[i ][0] = "Color";
2420 keyvalue[i++][1] = (p->type & CUPS_PRINTER_COLOR) ? "T" : "F";
2421
2422 keyvalue[i ][0] = "Duplex";
2423 keyvalue[i++][1] = (p->type & CUPS_PRINTER_DUPLEX) ? "T" : "F";
2424
2425 keyvalue[i ][0] = "Staple";
2426 keyvalue[i++][1] = (p->type & CUPS_PRINTER_STAPLE) ? "T" : "F";
2427
2428 keyvalue[i ][0] = "Copies";
2429 keyvalue[i++][1] = (p->type & CUPS_PRINTER_COPIES) ? "T" : "F";
2430
2431 keyvalue[i ][0] = "Collate";
2432 keyvalue[i++][1] = (p->type & CUPS_PRINTER_COLLATE) ? "T" : "F";
2433
2434 keyvalue[i ][0] = "Punch";
2435 keyvalue[i++][1] = (p->type & CUPS_PRINTER_PUNCH) ? "T" : "F";
2436
2437 keyvalue[i ][0] = "Bind";
2438 keyvalue[i++][1] = (p->type & CUPS_PRINTER_BIND) ? "T" : "F";
2439
2440 keyvalue[i ][0] = "Sort";
2441 keyvalue[i++][1] = (p->type & CUPS_PRINTER_SORT) ? "T" : "F";
2442
2443 keyvalue[i ][0] = "Scan";
2444 keyvalue[i++][1] = (p->type & CUPS_PRINTER_MFP) ? "T" : "F";
2445
2446 keyvalue[i ][0] = "pdl";
2447 keyvalue[i++][1] = p->pdl ? p->pdl : "application/postscript";
2448
2449 if (get_auth_info_required(p, air_str, sizeof(air_str)))
2450 {
2451 keyvalue[i ][0] = "air";
2452 keyvalue[i++][1] = air_str;
2453 }
2454
2455 /*
2456 * Then pack them into a proper txt record...
2457 */
2458
2459 return (dnssdPackTxtRecord(txt_len, keyvalue, i));
2460 }
2461
2462
2463 /*
2464 * 'dnssdComparePrinters()' - Compare the registered names of two printers.
2465 */
2466
2467 static int /* O - Result of comparison */
2468 dnssdComparePrinters(cupsd_printer_t *a,/* I - First printer */
2469 cupsd_printer_t *b)/* I - Second printer */
2470 {
2471 return (strcasecmp(a->reg_name, b->reg_name));
2472 }
2473
2474
2475 /*
2476 * 'dnssdDeregisterPrinter()' - Stop sending broadcast information for a
2477 * printer.
2478 */
2479
2480 static void
2481 dnssdDeregisterPrinter(
2482 cupsd_printer_t *p) /* I - Printer */
2483 {
2484 cupsdLogMessage(CUPSD_LOG_DEBUG2, "dnssdDeregisterPrinter(%s)", p->name);
2485
2486 /*
2487 * Closing the socket deregisters the service
2488 */
2489
2490 if (p->ipp_ref)
2491 {
2492 DNSServiceRefDeallocate(p->ipp_ref);
2493 p->ipp_ref = NULL;
2494 }
2495
2496 if (p->ipp_txt)
2497 {
2498 /*
2499 * p->ipp_txt is malloc'd, not _cupsStrAlloc'd...
2500 */
2501
2502 free(p->ipp_txt);
2503 p->ipp_txt = NULL;
2504 }
2505
2506 if (p->printer_ref)
2507 {
2508 DNSServiceRefDeallocate(p->printer_ref);
2509 p->printer_ref = NULL;
2510 }
2511
2512 if (p->printer_txt)
2513 {
2514 /*
2515 * p->printer_txt is malloc'd, not _cupsStrAlloc'd...
2516 */
2517
2518 free(p->printer_txt);
2519 p->printer_txt = NULL;
2520 }
2521
2522 /*
2523 * Remove the printer from the array of DNS-SD printers, then clear the
2524 * registered name...
2525 */
2526
2527 cupsArrayRemove(DNSSDPrinters, p);
2528 cupsdClearString(&p->reg_name);
2529 }
2530
2531
2532 /*
2533 * 'dnssdPackTxtRecord()' - Pack an array of key/value pairs into the
2534 * TXT record format.
2535 */
2536
2537 static char * /* O - TXT record */
2538 dnssdPackTxtRecord(int *txt_len, /* O - TXT record length */
2539 char *keyvalue[][2], /* I - Table of key value pairs */
2540 int count) /* I - Items in table */
2541 {
2542 int i; /* Looping var */
2543 int length; /* Length of TXT record */
2544 int length2; /* Length of value */
2545 char *txtRecord; /* TXT record buffer */
2546 char *cursor; /* Looping pointer */
2547
2548
2549 /*
2550 * Calculate the buffer size
2551 */
2552
2553 for (length = i = 0; i < count; i++)
2554 length += 1 + strlen(keyvalue[i][0]) +
2555 (keyvalue[i][1] ? 1 + strlen(keyvalue[i][1]) : 0);
2556
2557 /*
2558 * Allocate and fill it
2559 */
2560
2561 txtRecord = malloc(length);
2562 if (txtRecord)
2563 {
2564 *txt_len = length;
2565
2566 for (cursor = txtRecord, i = 0; i < count; i++)
2567 {
2568 /*
2569 * Drop in the p-string style length byte followed by the data
2570 */
2571
2572 length = strlen(keyvalue[i][0]);
2573 length2 = keyvalue[i][1] ? 1 + strlen(keyvalue[i][1]) : 0;
2574
2575 *cursor++ = (unsigned char)(length + length2);
2576
2577 memcpy(cursor, keyvalue[i][0], length);
2578 cursor += length;
2579
2580 if (length2)
2581 {
2582 length2 --;
2583 *cursor++ = '=';
2584 memcpy(cursor, keyvalue[i][1], length2);
2585 cursor += length2;
2586 }
2587 }
2588 }
2589
2590 return (txtRecord);
2591 }
2592
2593
2594 /*
2595 * 'dnssdRegisterCallback()' - DNSServiceRegister callback.
2596 */
2597
2598 static void
2599 dnssdRegisterCallback(
2600 DNSServiceRef sdRef, /* I - DNS Service reference */
2601 DNSServiceFlags flags, /* I - Reserved for future use */
2602 DNSServiceErrorType errorCode, /* I - Error code */
2603 const char *name, /* I - Service name */
2604 const char *regtype, /* I - Service type */
2605 const char *domain, /* I - Domain. ".local" for now */
2606 void *context) /* I - User-defined context */
2607 {
2608 cupsd_printer_t *p = (cupsd_printer_t *)context;
2609 /* Current printer */
2610
2611
2612 cupsdLogMessage(CUPSD_LOG_DEBUG2, "dnssdRegisterCallback(%s, %s) for %s (%s)",
2613 name, regtype, p ? p->name : "Web Interface",
2614 p ? (p->reg_name ? p->reg_name : "(null)") : "NA");
2615
2616 if (errorCode)
2617 {
2618 cupsdLogMessage(CUPSD_LOG_ERROR,
2619 "DNSServiceRegister failed with error %d", (int)errorCode);
2620 return;
2621 }
2622 else if (p && (!p->reg_name || strcasecmp(name, p->reg_name)))
2623 {
2624 cupsdLogMessage(CUPSD_LOG_INFO, "Using service name \"%s\" for \"%s\"",
2625 name, p->name);
2626
2627 cupsArrayRemove(DNSSDPrinters, p);
2628 cupsdSetString(&p->reg_name, name);
2629 cupsArrayAdd(DNSSDPrinters, p);
2630
2631 LastEvent |= CUPSD_EVENT_PRINTER_MODIFIED;
2632 }
2633 }
2634
2635
2636 /*
2637 * 'dnssdRegisterPrinter()' - Start sending broadcast information for a printer
2638 * or update the broadcast contents.
2639 */
2640
2641 static void
2642 dnssdRegisterPrinter(cupsd_printer_t *p)/* I - Printer */
2643 {
2644 DNSServiceErrorType se; /* dnssd errors */
2645 char *ipp_txt, /* IPP TXT record buffer */
2646 *printer_txt, /* LPD TXT record buffer */
2647 name[1024], /* Service name */
2648 *nameptr; /* Pointer into name */
2649 int ipp_len, /* IPP TXT record length */
2650 printer_len, /* LPD TXT record length */
2651 printer_port; /* LPD port number */
2652 const char *regtype; /* Registration type */
2653
2654
2655 cupsdLogMessage(CUPSD_LOG_DEBUG2, "dnssdRegisterPrinter(%s) %s", p->name,
2656 !p->ipp_ref ? "new" : "update");
2657
2658 /*
2659 * If per-printer sharing was just disabled make sure we're not
2660 * registered before returning.
2661 */
2662
2663 if (!p->shared)
2664 {
2665 dnssdDeregisterPrinter(p);
2666 return;
2667 }
2668
2669 /*
2670 * The registered name takes the form of "<printer-info> @ <computer name>"...
2671 */
2672
2673 if (p->info && strlen(p->info) > 0)
2674 {
2675 if (DNSSDComputerName)
2676 snprintf(name, sizeof(name), "%s @ %s", p->info, DNSSDComputerName);
2677 else
2678 strlcpy(name, p->info, sizeof(name));
2679 }
2680 else if (DNSSDComputerName)
2681 snprintf(name, sizeof(name), "%s @ %s", p->name, DNSSDComputerName);
2682 else
2683 strlcpy(name, p->name, sizeof(name));
2684
2685 /*
2686 * If an existing printer was renamed, unregister it and start over...
2687 */
2688
2689 if (p->reg_name && strcmp(p->reg_name, name))
2690 dnssdDeregisterPrinter(p);
2691
2692 if (!p->reg_name)
2693 {
2694 cupsdSetString(&p->reg_name, name);
2695 cupsArrayAdd(DNSSDPrinters, p);
2696 }
2697
2698 /*
2699 * Register IPP and (optionally) LPD...
2700 */
2701
2702 ipp_len = 0; /* anti-compiler-warning-code */
2703 ipp_txt = dnssdBuildTxtRecord(&ipp_len, p, 0);
2704
2705 if (p->ipp_ref &&
2706 (ipp_len != p->ipp_len || memcmp(ipp_txt, p->ipp_txt, ipp_len)))
2707 {
2708 /*
2709 * Update the existing registration...
2710 */
2711
2712 /* A TTL of 0 means use record's original value (Radar 3176248) */
2713 if ((se = DNSServiceUpdateRecord(p->ipp_ref, NULL, 0, ipp_len, ipp_txt,
2714 0)) == kDNSServiceErr_NoError)
2715 {
2716 if (p->ipp_txt)
2717 free(p->ipp_txt);
2718
2719 p->ipp_txt = ipp_txt;
2720 p->ipp_len = ipp_len;
2721 ipp_txt = NULL;
2722 }
2723 else
2724 {
2725 /*
2726 * Failed to update record, lets close this reference and move on...
2727 */
2728
2729 cupsdLogMessage(CUPSD_LOG_ERROR,
2730 "Unable to update IPP DNS-SD record for %s - %d", p->name,
2731 se);
2732
2733 DNSServiceRefDeallocate(p->ipp_ref);
2734 p->ipp_ref = NULL;
2735 }
2736 }
2737
2738 if (!p->ipp_ref)
2739 {
2740 /*
2741 * Initial registration. Use the _fax subtype for fax queues...
2742 */
2743
2744 regtype = (p->type & CUPS_PRINTER_FAX) ? "_fax-ipp._tcp" :
2745 "_ipp._tcp,_cups";
2746
2747 cupsdLogMessage(CUPSD_LOG_DEBUG,
2748 "Registering DNS-SD printer %s with name \"%s\" and "
2749 "type \"%s\"", p->name, name, regtype);
2750
2751 /*
2752 * Register the queue, dropping characters as needed until we succeed...
2753 */
2754
2755 nameptr = name + strlen(name);
2756
2757 do
2758 {
2759 p->ipp_ref = DNSSDRef;
2760 if ((se = DNSServiceRegister(&p->ipp_ref, kDNSServiceFlagsShareConnection,
2761 0, name, regtype, NULL, NULL,
2762 htons(DNSSDPort), ipp_len, ipp_txt,
2763 dnssdRegisterCallback,
2764 p)) == kDNSServiceErr_BadParam)
2765 {
2766 /*
2767 * Name is too long, drop trailing characters, taking into account
2768 * UTF-8 encoding...
2769 */
2770
2771 nameptr --;
2772
2773 while (nameptr > name && (*nameptr & 0xc0) == 0x80)
2774 nameptr --;
2775
2776 if (nameptr > name)
2777 *nameptr = '\0';
2778 }
2779 }
2780 while (se == kDNSServiceErr_BadParam && nameptr > name);
2781
2782 if (se == kDNSServiceErr_NoError)
2783 {
2784 p->ipp_txt = ipp_txt;
2785 p->ipp_len = ipp_len;
2786 ipp_txt = NULL;
2787 }
2788 else
2789 cupsdLogMessage(CUPSD_LOG_WARN,
2790 "DNS-SD IPP registration of \"%s\" failed: %d",
2791 p->name, se);
2792 }
2793
2794 if (ipp_txt)
2795 free(ipp_txt);
2796
2797 if (BrowseLocalProtocols & BROWSE_LPD)
2798 {
2799 printer_len = 0; /* anti-compiler-warning-code */
2800 printer_port = 515;
2801 printer_txt = dnssdBuildTxtRecord(&printer_len, p, 1);
2802 }
2803 else
2804 {
2805 printer_len = 0;
2806 printer_port = 0;
2807 printer_txt = NULL;
2808 }
2809
2810 if (p->printer_ref &&
2811 (printer_len != p->printer_len ||
2812 memcmp(printer_txt, p->printer_txt, printer_len)))
2813 {
2814 /*
2815 * Update the existing registration...
2816 */
2817
2818 /* A TTL of 0 means use record's original value (Radar 3176248) */
2819 if ((se = DNSServiceUpdateRecord(p->printer_ref, NULL, 0, printer_len,
2820 printer_txt,
2821 0)) == kDNSServiceErr_NoError)
2822 {
2823 if (p->printer_txt)
2824 free(p->printer_txt);
2825
2826 p->printer_txt = printer_txt;
2827 p->printer_len = printer_len;
2828 printer_txt = NULL;
2829 }
2830 else
2831 {
2832 /*
2833 * Failed to update record, lets close this reference and move on...
2834 */
2835
2836 cupsdLogMessage(CUPSD_LOG_ERROR,
2837 "Unable to update LPD DNS-SD record for %s - %d",
2838 p->name, se);
2839
2840 DNSServiceRefDeallocate(p->printer_ref);
2841 p->printer_ref = NULL;
2842 }
2843 }
2844
2845 if (!p->printer_ref)
2846 {
2847 /*
2848 * Initial registration...
2849 */
2850
2851 cupsdLogMessage(CUPSD_LOG_DEBUG,
2852 "Registering DNS-SD printer %s with name \"%s\" and "
2853 "type \"_printer._tcp\"", p->name, name);
2854
2855 p->printer_ref = DNSSDRef;
2856 if ((se = DNSServiceRegister(&p->printer_ref,
2857 kDNSServiceFlagsShareConnection,
2858 0, name, "_printer._tcp", NULL, NULL,
2859 htons(printer_port), printer_len, printer_txt,
2860 dnssdRegisterCallback,
2861 p)) == kDNSServiceErr_NoError)
2862 {
2863 p->printer_txt = printer_txt;
2864 p->printer_len = printer_len;
2865 printer_txt = NULL;
2866 }
2867 else
2868 cupsdLogMessage(CUPSD_LOG_WARN,
2869 "DNS-SD LPD registration of \"%s\" failed: %d",
2870 p->name, se);
2871 }
2872
2873 if (printer_txt)
2874 free(printer_txt);
2875 }
2876
2877
2878 /*
2879 * 'dnssdStop()' - Stop all DNS-SD registrations.
2880 */
2881
2882 static void
2883 dnssdStop(void)
2884 {
2885 cupsd_printer_t *p; /* Current printer */
2886
2887
2888 /*
2889 * De-register the individual printers
2890 */
2891
2892 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
2893 p;
2894 p = (cupsd_printer_t *)cupsArrayNext(Printers))
2895 dnssdDeregisterPrinter(p);
2896
2897 /*
2898 * Shutdown the rest of the service refs...
2899 */
2900
2901 if (WebIFRef)
2902 {
2903 DNSServiceRefDeallocate(WebIFRef);
2904 WebIFRef = NULL;
2905 }
2906
2907 if (RemoteRef)
2908 {
2909 DNSServiceRefDeallocate(RemoteRef);
2910 RemoteRef = NULL;
2911 }
2912
2913 cupsdRemoveSelect(DNSServiceRefSockFD(DNSSDRef));
2914
2915 DNSServiceRefDeallocate(DNSSDRef);
2916 DNSSDRef = NULL;
2917
2918 cupsArrayDelete(DNSSDPrinters);
2919 DNSSDPrinters = NULL;
2920
2921 DNSSDPort = 0;
2922 }
2923
2924
2925 /*
2926 * 'dnssdUpdate()' - Handle DNS-SD queries.
2927 */
2928
2929 static void
2930 dnssdUpdate(void)
2931 {
2932 DNSServiceErrorType sdErr; /* Service discovery error */
2933
2934
2935 if ((sdErr = DNSServiceProcessResult(DNSSDRef)) != kDNSServiceErr_NoError)
2936 {
2937 cupsdLogMessage(CUPSD_LOG_ERROR,
2938 "DNS Service Discovery registration error %d!",
2939 sdErr);
2940 dnssdStop();
2941 }
2942 }
2943 #endif /* HAVE_DNSSD */
2944
2945
2946 /*
2947 * 'get_auth_info_required()' - Get the auth-info-required value to advertise.
2948 */
2949
2950 static char * /* O - String or NULL if none */
2951 get_auth_info_required(
2952 cupsd_printer_t *p, /* I - Printer */
2953 char *buffer, /* I - Value buffer */
2954 size_t bufsize) /* I - Size of value buffer */
2955 {
2956 cupsd_location_t *auth; /* Pointer to authentication element */
2957 char resource[1024]; /* Printer/class resource path */
2958
2959
2960 /*
2961 * If auth-info-required is set for this printer, return that...
2962 */
2963
2964 if (p->num_auth_info_required > 0 && strcmp(p->auth_info_required[0], "none"))
2965 {
2966 int i; /* Looping var */
2967 char *bufptr; /* Pointer into buffer */
2968
2969 for (i = 0, bufptr = buffer; i < p->num_auth_info_required; i ++)
2970 {
2971 if (bufptr >= (buffer + bufsize - 2))
2972 break;
2973
2974 if (i)
2975 *bufptr++ = ',';
2976
2977 strlcpy(bufptr, p->auth_info_required[i], bufsize - (bufptr - buffer));
2978 bufptr += strlen(bufptr);
2979 }
2980
2981 return (buffer);
2982 }
2983
2984 /*
2985 * Figure out the authentication data requirements to advertise...
2986 */
2987
2988 if (p->type & CUPS_PRINTER_CLASS)
2989 snprintf(resource, sizeof(resource), "/classes/%s", p->name);
2990 else
2991 snprintf(resource, sizeof(resource), "/printers/%s", p->name);
2992
2993 if ((auth = cupsdFindBest(resource, HTTP_POST)) == NULL ||
2994 auth->type == CUPSD_AUTH_NONE)
2995 auth = cupsdFindPolicyOp(p->op_policy_ptr, IPP_PRINT_JOB);
2996
2997 if (auth)
2998 {
2999 int auth_type; /* Authentication type */
3000
3001 if ((auth_type = auth->type) == CUPSD_AUTH_DEFAULT)
3002 auth_type = DefaultAuthType;
3003
3004 switch (auth_type)
3005 {
3006 case CUPSD_AUTH_NONE :
3007 return (NULL);
3008
3009 case CUPSD_AUTH_NEGOTIATE :
3010 strlcpy(buffer, "negotiate", bufsize);
3011 break;
3012
3013 default :
3014 strlcpy(buffer, "username,password", bufsize);
3015 break;
3016 }
3017
3018 return (buffer);
3019 }
3020
3021 return (NULL);
3022 }
3023
3024
3025 #ifdef __APPLE__
3026 /*
3027 * 'get_hostconfig()' - Get an /etc/hostconfig service setting.
3028 */
3029
3030 static int /* O - 1 for YES or AUTOMATIC, 0 for NO */
3031 get_hostconfig(const char *name) /* I - Name of service */
3032 {
3033 cups_file_t *fp; /* Hostconfig file */
3034 char line[1024], /* Line from file */
3035 *ptr; /* Pointer to value */
3036 int state = 1; /* State of service */
3037
3038
3039 /*
3040 * Try opening the /etc/hostconfig file; if we can't open it, assume that
3041 * the service is enabled/auto.
3042 */
3043
3044 if ((fp = cupsFileOpen("/etc/hostconfig", "r")) != NULL)
3045 {
3046 /*
3047 * Read lines from the file until we find the service...
3048 */
3049
3050 while (cupsFileGets(fp, line, sizeof(line)))
3051 {
3052 if (line[0] == '#' || (ptr = strchr(line, '=')) == NULL)
3053 continue;
3054
3055 *ptr++ = '\0';
3056
3057 if (!strcasecmp(line, name))
3058 {
3059 /*
3060 * Found the service, see if it is set to "-NO-"...
3061 */
3062
3063 if (!strncasecmp(ptr, "-NO-", 4))
3064 state = 0;
3065 break;
3066 }
3067 }
3068
3069 cupsFileClose(fp);
3070 }
3071
3072 return (state);
3073 }
3074 #endif /* __APPLE__ */
3075
3076
3077 /*
3078 * 'is_local_queue()' - Determine whether the URI points at a local queue.
3079 */
3080
3081 static int /* O - 1 = local, 0 = remote, -1 = bad URI */
3082 is_local_queue(const char *uri, /* I - Printer URI */
3083 char *host, /* O - Host string */
3084 int hostlen, /* I - Length of host buffer */
3085 char *resource, /* O - Resource string */
3086 int resourcelen) /* I - Length of resource buffer */
3087 {
3088 char scheme[32], /* Scheme portion of URI */
3089 username[HTTP_MAX_URI]; /* Username portion of URI */
3090 int port; /* Port portion of URI */
3091 cupsd_netif_t *iface; /* Network interface */
3092
3093
3094 /*
3095 * Pull the URI apart to see if this is a local or remote printer...
3096 */
3097
3098 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
3099 username, sizeof(username), host, hostlen, &port,
3100 resource, resourcelen) < HTTP_URI_OK)
3101 return (-1);
3102
3103 DEBUG_printf(("host=\"%s\", ServerName=\"%s\"\n", host, ServerName));
3104
3105 /*
3106 * Check for local server addresses...
3107 */
3108
3109 if (!strcasecmp(host, ServerName) && port == LocalPort)
3110 return (1);
3111
3112 cupsdNetIFUpdate();
3113
3114 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
3115 iface;
3116 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
3117 if (!strcasecmp(host, iface->hostname) && port == iface->port)
3118 return (1);
3119
3120 /*
3121 * If we get here, the printer is remote...
3122 */
3123
3124 return (0);
3125 }
3126
3127
3128 /*
3129 * 'process_browse_data()' - Process new browse data.
3130 */
3131
3132 static void
3133 process_browse_data(
3134 const char *uri, /* I - URI of printer/class */
3135 const char *host, /* I - Hostname */
3136 const char *resource, /* I - Resource path */
3137 cups_ptype_t type, /* I - Printer type */
3138 ipp_pstate_t state, /* I - Printer state */
3139 const char *location, /* I - Printer location */
3140 const char *info, /* I - Printer information */
3141 const char *make_model, /* I - Printer make and model */
3142 int num_attrs, /* I - Number of attributes */
3143 cups_option_t *attrs) /* I - Attributes */
3144 {
3145 int i; /* Looping var */
3146 int update; /* Update printer attributes? */
3147 char finaluri[HTTP_MAX_URI], /* Final URI for printer */
3148 name[IPP_MAX_NAME], /* Name of printer */
3149 newname[IPP_MAX_NAME], /* New name of printer */
3150 *hptr, /* Pointer into hostname */
3151 *sptr; /* Pointer into ServerName */
3152 const char *shortname; /* Short queue name (queue) */
3153 char local_make_model[IPP_MAX_NAME];
3154 /* Local make and model */
3155 cupsd_printer_t *p; /* Printer information */
3156 const char *ipp_options, /* ipp-options value */
3157 *lease_duration; /* lease-duration value */
3158 int is_class; /* Is this queue a class? */
3159
3160
3161 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3162 "process_browse_data(uri=\"%s\", host=\"%s\", "
3163 "resource=\"%s\", type=%x, state=%d, location=\"%s\", "
3164 "info=\"%s\", make_model=\"%s\", num_attrs=%d, attrs=%p)",
3165 uri, host, resource, type, state,
3166 location ? location : "(nil)", info ? info : "(nil)",
3167 make_model ? make_model : "(nil)", num_attrs, attrs);
3168
3169 /*
3170 * Determine if the URI contains any illegal characters in it...
3171 */
3172
3173 if (strncmp(uri, "ipp://", 6) || !host[0] ||
3174 (strncmp(resource, "/printers/", 10) &&
3175 strncmp(resource, "/classes/", 9)))
3176 {
3177 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad printer URI in browse data: %s", uri);
3178 return;
3179 }
3180
3181 if (strchr(resource, '?') ||
3182 (!strncmp(resource, "/printers/", 10) && strchr(resource + 10, '/')) ||
3183 (!strncmp(resource, "/classes/", 9) && strchr(resource + 9, '/')))
3184 {
3185 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad resource in browse data: %s",
3186 resource);
3187 return;
3188 }
3189
3190 /*
3191 * OK, this isn't a local printer; add any remote options...
3192 */
3193
3194 ipp_options = cupsGetOption("ipp-options", num_attrs, attrs);
3195
3196 if (BrowseRemoteOptions)
3197 {
3198 if (BrowseRemoteOptions[0] == '?')
3199 {
3200 /*
3201 * Override server-supplied options...
3202 */
3203
3204 snprintf(finaluri, sizeof(finaluri), "%s%s", uri, BrowseRemoteOptions);
3205 }
3206 else if (ipp_options)
3207 {
3208 /*
3209 * Combine the server and local options...
3210 */
3211
3212 snprintf(finaluri, sizeof(finaluri), "%s?%s+%s", uri, ipp_options,
3213 BrowseRemoteOptions);
3214 }
3215 else
3216 {
3217 /*
3218 * Just use the local options...
3219 */
3220
3221 snprintf(finaluri, sizeof(finaluri), "%s?%s", uri, BrowseRemoteOptions);
3222 }
3223
3224 uri = finaluri;
3225 }
3226 else if (ipp_options)
3227 {
3228 /*
3229 * Just use the server-supplied options...
3230 */
3231
3232 snprintf(finaluri, sizeof(finaluri), "%s?%s", uri, ipp_options);
3233 uri = finaluri;
3234 }
3235
3236 /*
3237 * See if we already have it listed in the Printers list, and add it if not...
3238 */
3239
3240 type |= CUPS_PRINTER_REMOTE | CUPS_PRINTER_DISCOVERED;
3241 type &= ~CUPS_PRINTER_IMPLICIT;
3242 update = 0;
3243 hptr = strchr(host, '.');
3244 sptr = strchr(ServerName, '.');
3245 is_class = type & CUPS_PRINTER_CLASS;
3246
3247 if (!ServerNameIsIP && sptr != NULL && hptr != NULL)
3248 {
3249 /*
3250 * Strip the common domain name components...
3251 */
3252
3253 while (hptr != NULL)
3254 {
3255 if (!strcasecmp(hptr, sptr))
3256 {
3257 *hptr = '\0';
3258 break;
3259 }
3260 else
3261 hptr = strchr(hptr + 1, '.');
3262 }
3263 }
3264
3265 if (is_class)
3266 {
3267 /*
3268 * Remote destination is a class...
3269 */
3270
3271 if (!strncmp(resource, "/classes/", 9))
3272 snprintf(name, sizeof(name), "%s@%s", resource + 9, host);
3273 else
3274 return;
3275
3276 shortname = resource + 9;
3277 }
3278 else
3279 {
3280 /*
3281 * Remote destination is a printer...
3282 */
3283
3284 if (!strncmp(resource, "/printers/", 10))
3285 snprintf(name, sizeof(name), "%s@%s", resource + 10, host);
3286 else
3287 return;
3288
3289 shortname = resource + 10;
3290 }
3291
3292 if (hptr && !*hptr)
3293 *hptr = '.'; /* Resource FQDN */
3294
3295 if ((p = cupsdFindDest(name)) == NULL && BrowseShortNames)
3296 {
3297 /*
3298 * Long name doesn't exist, try short name...
3299 */
3300
3301 cupsdLogMessage(CUPSD_LOG_DEBUG, "process_browse_data: %s not found...",
3302 name);
3303
3304 if ((p = cupsdFindDest(shortname)) == NULL)
3305 {
3306 /*
3307 * Short name doesn't exist, use it for this shared queue.
3308 */
3309
3310 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_browse_data: %s not found...",
3311 shortname);
3312 strlcpy(name, shortname, sizeof(name));
3313 }
3314 else
3315 {
3316 /*
3317 * Short name exists...
3318 */
3319
3320 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3321 "process_browse_data: %s found, type=%x, hostname=%s...",
3322 shortname, p->type, p->hostname ? p->hostname : "(nil)");
3323
3324 if (p->type & CUPS_PRINTER_IMPLICIT)
3325 p = NULL; /* Don't replace implicit classes */
3326 else if (p->hostname && strcasecmp(p->hostname, host))
3327 {
3328 /*
3329 * Short name exists but is for a different host. If this is a remote
3330 * queue, rename it and use the long name...
3331 */
3332
3333 if (p->type & CUPS_PRINTER_REMOTE)
3334 {
3335 cupsdLogMessage(CUPSD_LOG_DEBUG,
3336 "Renamed remote %s \"%s\" to \"%s@%s\"...",
3337 is_class ? "class" : "printer", p->name, p->name,
3338 p->hostname);
3339 cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, p, NULL,
3340 "%s \'%s\' deleted by directory services.",
3341 is_class ? "Class" : "Printer", p->name);
3342
3343 snprintf(newname, sizeof(newname), "%s@%s", p->name, p->hostname);
3344 cupsdRenamePrinter(p, newname);
3345
3346 cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED, p, NULL,
3347 "%s \'%s\' added by directory services.",
3348 is_class ? "Class" : "Printer", p->name);
3349 }
3350
3351 /*
3352 * Force creation with long name...
3353 */
3354
3355 p = NULL;
3356 }
3357 }
3358 }
3359 else if (p)
3360 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3361 "process_browse_data: %s found, type=%x, hostname=%s...",
3362 name, p->type, p->hostname ? p->hostname : "(nil)");
3363
3364 if (!p)
3365 {
3366 /*
3367 * Queue doesn't exist; add it...
3368 */
3369
3370 if (is_class)
3371 p = cupsdAddClass(name);
3372 else
3373 p = cupsdAddPrinter(name);
3374
3375 if (!p)
3376 return;
3377
3378 cupsdClearString(&(p->hostname));
3379
3380 cupsdLogMessage(CUPSD_LOG_DEBUG, "Added remote %s \"%s\"...",
3381 is_class ? "class" : "printer", name);
3382
3383 cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED, p, NULL,
3384 "%s \'%s\' added by directory services.",
3385 is_class ? "Class" : "Printer", name);
3386
3387 /*
3388 * Force the URI to point to the real server...
3389 */
3390
3391 p->type = type & ~CUPS_PRINTER_REJECTING;
3392 p->accepting = 1;
3393
3394 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
3395 }
3396
3397 if (!p->hostname)
3398 {
3399 /*
3400 * Hostname not set, so this must be a cached remote printer
3401 * that was created for a pending print job...
3402 */
3403
3404 cupsdSetString(&p->hostname, host);
3405 cupsdSetString(&p->uri, uri);
3406 cupsdSetString(&p->device_uri, uri);
3407 update = 1;
3408
3409 cupsdMarkDirty(CUPSD_DIRTY_REMOTE);
3410 }
3411
3412 /*
3413 * Update the state...
3414 */
3415
3416 p->state = state;
3417 p->browse_time = time(NULL);
3418
3419 if ((lease_duration = cupsGetOption("lease-duration", num_attrs,
3420 attrs)) != NULL)
3421 {
3422 /*
3423 * Grab the lease-duration for the browse data; anything less then 1
3424 * second or more than 1 week gets the default BrowseTimeout...
3425 */
3426
3427 i = atoi(lease_duration);
3428 if (i < 1 || i > 604800)
3429 i = BrowseTimeout;
3430
3431 p->browse_expire = p->browse_time + i;
3432 }
3433 else
3434 p->browse_expire = p->browse_time + BrowseTimeout;
3435
3436 if (type & CUPS_PRINTER_REJECTING)
3437 {
3438 type &= ~CUPS_PRINTER_REJECTING;
3439
3440 if (p->accepting)
3441 {
3442 update = 1;
3443 p->accepting = 0;
3444 }
3445 }
3446 else if (!p->accepting)
3447 {
3448 update = 1;
3449 p->accepting = 1;
3450 }
3451
3452 if (p->type != type)
3453 {
3454 p->type = type;
3455 update = 1;
3456 }
3457
3458 if (location && (!p->location || strcmp(p->location, location)))
3459 {
3460 cupsdSetString(&p->location, location);
3461 update = 1;
3462 }
3463
3464 if (info && (!p->info || strcmp(p->info, info)))
3465 {
3466 cupsdSetString(&p->info, info);
3467 update = 1;
3468
3469 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3470 }
3471
3472 if (!make_model || !make_model[0])
3473 {
3474 if (is_class)
3475 snprintf(local_make_model, sizeof(local_make_model),
3476 "Remote Class on %s", host);
3477 else
3478 snprintf(local_make_model, sizeof(local_make_model),
3479 "Remote Printer on %s", host);
3480 }
3481 else
3482 snprintf(local_make_model, sizeof(local_make_model),
3483 "%s on %s", make_model, host);
3484
3485 if (!p->make_model || strcmp(p->make_model, local_make_model))
3486 {
3487 cupsdSetString(&p->make_model, local_make_model);
3488 update = 1;
3489 }
3490
3491 if (p->num_options)
3492 {
3493 if (!update && !(type & CUPS_PRINTER_DELETE))
3494 {
3495 /*
3496 * See if we need to update the attributes...
3497 */
3498
3499 if (p->num_options != num_attrs)
3500 update = 1;
3501 else
3502 {
3503 for (i = 0; i < num_attrs; i ++)
3504 if (strcmp(attrs[i].name, p->options[i].name) ||
3505 (!attrs[i].value != !p->options[i].value) ||
3506 (attrs[i].value && strcmp(attrs[i].value, p->options[i].value)))
3507 {
3508 update = 1;
3509 break;
3510 }
3511 }
3512 }
3513
3514 /*
3515 * Free the old options...
3516 */
3517
3518 cupsFreeOptions(p->num_options, p->options);
3519 }
3520
3521 p->num_options = num_attrs;
3522 p->options = attrs;
3523
3524 if (type & CUPS_PRINTER_DELETE)
3525 {
3526 cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, p, NULL,
3527 "%s \'%s\' deleted by directory services.",
3528 is_class ? "Class" : "Printer", p->name);
3529
3530 cupsdExpireSubscriptions(p, NULL);
3531
3532 cupsdDeletePrinter(p, 1);
3533 cupsdUpdateImplicitClasses();
3534 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3535 }
3536 else if (update)
3537 {
3538 cupsdSetPrinterAttrs(p);
3539 cupsdUpdateImplicitClasses();
3540 }
3541
3542 /*
3543 * See if we have a default printer... If not, make the first network
3544 * default printer the default.
3545 */
3546
3547 if (DefaultPrinter == NULL && Printers != NULL && UseNetworkDefault)
3548 {
3549 /*
3550 * Find the first network default printer and use it...
3551 */
3552
3553 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
3554 p;
3555 p = (cupsd_printer_t *)cupsArrayNext(Printers))
3556 if (p->type & CUPS_PRINTER_DEFAULT)
3557 {
3558 DefaultPrinter = p;
3559 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3560 break;
3561 }
3562 }
3563
3564 /*
3565 * Do auto-classing if needed...
3566 */
3567
3568 process_implicit_classes();
3569 }
3570
3571
3572 /*
3573 * 'process_implicit_classes()' - Create/update implicit classes as needed.
3574 */
3575
3576 static void
3577 process_implicit_classes(void)
3578 {
3579 int i; /* Looping var */
3580 int update; /* Update printer attributes? */
3581 char name[IPP_MAX_NAME], /* Name of printer */
3582 *hptr; /* Pointer into hostname */
3583 cupsd_printer_t *p, /* Printer information */
3584 *pclass, /* Printer class */
3585 *first; /* First printer in class */
3586 int offset, /* Offset of name */
3587 len; /* Length of name */
3588
3589
3590 if (!ImplicitClasses || !Printers)
3591 return;
3592
3593 /*
3594 * Loop through all available printers and create classes as needed...
3595 */
3596
3597 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers), len = 0, offset = 0,
3598 update = 0, pclass = NULL, first = NULL;
3599 p != NULL;
3600 p = (cupsd_printer_t *)cupsArrayNext(Printers))
3601 {
3602 /*
3603 * Skip implicit classes...
3604 */
3605
3606 if (p->type & CUPS_PRINTER_IMPLICIT)
3607 {
3608 len = 0;
3609 continue;
3610 }
3611
3612 /*
3613 * If len == 0, get the length of this printer name up to the "@"
3614 * sign (if any).
3615 */
3616
3617 cupsArraySave(Printers);
3618
3619 if (len > 0 &&
3620 !strncasecmp(p->name, name + offset, len) &&
3621 (p->name[len] == '\0' || p->name[len] == '@'))
3622 {
3623 /*
3624 * We have more than one printer with the same name; see if
3625 * we have a class, and if this printer is a member...
3626 */
3627
3628 if (pclass && strcasecmp(pclass->name, name))
3629 {
3630 if (update)
3631 cupsdSetPrinterAttrs(pclass);
3632
3633 update = 0;
3634 pclass = NULL;
3635 }
3636
3637 if (!pclass && (pclass = cupsdFindDest(name)) == NULL)
3638 {
3639 /*
3640 * Need to add the class...
3641 */
3642
3643 pclass = cupsdAddPrinter(name);
3644 cupsArrayAdd(ImplicitPrinters, pclass);
3645
3646 pclass->type |= CUPS_PRINTER_IMPLICIT;
3647 pclass->accepting = 1;
3648 pclass->state = IPP_PRINTER_IDLE;
3649
3650 cupsdSetString(&pclass->location, p->location);
3651 cupsdSetString(&pclass->info, p->info);
3652
3653 cupsdSetString(&pclass->job_sheets[0], p->job_sheets[0]);
3654 cupsdSetString(&pclass->job_sheets[1], p->job_sheets[1]);
3655
3656 update = 1;
3657
3658 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3659
3660 cupsdLogMessage(CUPSD_LOG_DEBUG, "Added implicit class \"%s\"...",
3661 name);
3662 cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED, p, NULL,
3663 "Implicit class \'%s\' added by directory services.",
3664 name);
3665 }
3666
3667 if (first != NULL)
3668 {
3669 for (i = 0; i < pclass->num_printers; i ++)
3670 if (pclass->printers[i] == first)
3671 break;
3672
3673 if (i >= pclass->num_printers)
3674 {
3675 first->in_implicit_class = 1;
3676 cupsdAddPrinterToClass(pclass, first);
3677 }
3678
3679 first = NULL;
3680 }
3681
3682 for (i = 0; i < pclass->num_printers; i ++)
3683 if (pclass->printers[i] == p)
3684 break;
3685
3686 if (i >= pclass->num_printers)
3687 {
3688 p->in_implicit_class = 1;
3689 cupsdAddPrinterToClass(pclass, p);
3690 update = 1;
3691 }
3692 }
3693 else
3694 {
3695 /*
3696 * First time around; just get name length and mark it as first
3697 * in the list...
3698 */
3699
3700 if ((hptr = strchr(p->name, '@')) != NULL)
3701 len = hptr - p->name;
3702 else
3703 len = strlen(p->name);
3704
3705 if (len >= sizeof(name))
3706 {
3707 /*
3708 * If the printer name length somehow is greater than we normally allow,
3709 * skip this printer...
3710 */
3711
3712 len = 0;
3713 cupsArrayRestore(Printers);
3714 continue;
3715 }
3716
3717 strncpy(name, p->name, len);
3718 name[len] = '\0';
3719 offset = 0;
3720
3721 if ((first = (hptr ? cupsdFindDest(name) : p)) != NULL &&
3722 !(first->type & CUPS_PRINTER_IMPLICIT))
3723 {
3724 /*
3725 * Can't use same name as a local printer; add "Any" to the
3726 * front of the name, unless we have explicitly disabled
3727 * the "ImplicitAnyClasses"...
3728 */
3729
3730 if (ImplicitAnyClasses && len < (sizeof(name) - 4))
3731 {
3732 /*
3733 * Add "Any" to the class name...
3734 */
3735
3736 strcpy(name, "Any");
3737 strncpy(name + 3, p->name, len);
3738 name[len + 3] = '\0';
3739 offset = 3;
3740 }
3741 else
3742 {
3743 /*
3744 * Don't create an implicit class if we have a local printer
3745 * with the same name...
3746 */
3747
3748 len = 0;
3749 cupsArrayRestore(Printers);
3750 continue;
3751 }
3752 }
3753
3754 first = p;
3755 }
3756
3757 cupsArrayRestore(Printers);
3758 }
3759
3760 /*
3761 * Update the last printer class as needed...
3762 */
3763
3764 if (pclass && update)
3765 cupsdSetPrinterAttrs(pclass);
3766 }
3767
3768
3769 /*
3770 * 'send_cups_browse()' - Send new browsing information using the CUPS
3771 * protocol.
3772 */
3773
3774 static void
3775 send_cups_browse(cupsd_printer_t *p) /* I - Printer to send */
3776 {
3777 int i; /* Looping var */
3778 cups_ptype_t type; /* Printer type */
3779 cupsd_dirsvc_addr_t *b; /* Browse address */
3780 int bytes; /* Length of packet */
3781 char packet[1453], /* Browse data packet */
3782 uri[1024], /* Printer URI */
3783 location[1024], /* printer-location */
3784 info[1024], /* printer-info */
3785 make_model[1024],
3786 /* printer-make-and-model */
3787 air[1024]; /* auth-info-required */
3788 cupsd_netif_t *iface; /* Network interface */
3789
3790
3791 /*
3792 * Figure out the printer type value...
3793 */
3794
3795 type = p->type | CUPS_PRINTER_REMOTE;
3796
3797 if (!p->accepting)
3798 type |= CUPS_PRINTER_REJECTING;
3799
3800 if (p == DefaultPrinter)
3801 type |= CUPS_PRINTER_DEFAULT;
3802
3803 /*
3804 * Remove quotes from printer-info, printer-location, and
3805 * printer-make-and-model attributes...
3806 */
3807
3808 dequote(location, p->location, sizeof(location));
3809 dequote(info, p->info, sizeof(info));
3810
3811 if (p->make_model)
3812 dequote(make_model, p->make_model, sizeof(make_model));
3813 else if (p->type & CUPS_PRINTER_CLASS)
3814 {
3815 if (p->num_printers > 0 && p->printers[0]->make_model)
3816 strlcpy(make_model, p->printers[0]->make_model, sizeof(make_model));
3817 else
3818 strlcpy(make_model, "Local Printer Class", sizeof(make_model));
3819 }
3820 else if (p->raw)
3821 strlcpy(make_model, "Local Raw Printer", sizeof(make_model));
3822 else
3823 strlcpy(make_model, "Local System V Printer", sizeof(make_model));
3824
3825 if (get_auth_info_required(p, packet, sizeof(packet)))
3826 snprintf(air, sizeof(air), " auth-info-required=%s", packet);
3827 else
3828 air[0] = '\0';
3829
3830 /*
3831 * Send a packet to each browse address...
3832 */
3833
3834 for (i = NumBrowsers, b = Browsers; i > 0; i --, b ++)
3835 if (b->iface[0])
3836 {
3837 /*
3838 * Send the browse packet to one or more interfaces...
3839 */
3840
3841 if (!strcmp(b->iface, "*"))
3842 {
3843 /*
3844 * Send to all local interfaces...
3845 */
3846
3847 cupsdNetIFUpdate();
3848
3849 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
3850 iface;
3851 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
3852 {
3853 /*
3854 * Only send to local, IPv4 interfaces...
3855 */
3856
3857 if (!iface->is_local || !iface->port ||
3858 iface->address.addr.sa_family != AF_INET)
3859 continue;
3860
3861 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
3862 iface->hostname, iface->port,
3863 (p->type & CUPS_PRINTER_CLASS) ? "/classes/%s" :
3864 "/printers/%s",
3865 p->name);
3866 snprintf(packet, sizeof(packet), "%x %x %s \"%s\" \"%s\" \"%s\" %s%s\n",
3867 type, p->state, uri, location, info, make_model,
3868 p->browse_attrs ? p->browse_attrs : "", air);
3869
3870 bytes = strlen(packet);
3871
3872 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3873 "cupsdSendBrowseList: (%d bytes to \"%s\") %s", bytes,
3874 iface->name, packet);
3875
3876 iface->broadcast.ipv4.sin_port = htons(BrowsePort);
3877
3878 sendto(BrowseSocket, packet, bytes, 0,
3879 (struct sockaddr *)&(iface->broadcast),
3880 httpAddrLength(&(iface->broadcast)));
3881 }
3882 }
3883 else if ((iface = cupsdNetIFFind(b->iface)) != NULL)
3884 {
3885 /*
3886 * Send to the named interface using the IPv4 address...
3887 */
3888
3889 while (iface)
3890 if (strcmp(b->iface, iface->name))
3891 {
3892 iface = NULL;
3893 break;
3894 }
3895 else if (iface->address.addr.sa_family == AF_INET && iface->port)
3896 break;
3897 else
3898 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList);
3899
3900 if (iface)
3901 {
3902 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
3903 iface->hostname, iface->port,
3904 (p->type & CUPS_PRINTER_CLASS) ? "/classes/%s" :
3905 "/printers/%s",
3906 p->name);
3907 snprintf(packet, sizeof(packet),
3908 "%x %x %s \"%s\" \"%s\" \"%s\" %s%s\n",
3909 type, p->state, uri, location, info, make_model,
3910 p->browse_attrs ? p->browse_attrs : "", air);
3911
3912 bytes = strlen(packet);
3913
3914 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3915 "cupsdSendBrowseList: (%d bytes to \"%s\") %s", bytes,
3916 iface->name, packet);
3917
3918 iface->broadcast.ipv4.sin_port = htons(BrowsePort);
3919
3920 sendto(BrowseSocket, packet, bytes, 0,
3921 (struct sockaddr *)&(iface->broadcast),
3922 httpAddrLength(&(iface->broadcast)));
3923 }
3924 }
3925 }
3926 else
3927 {
3928 /*
3929 * Send the browse packet to the indicated address using
3930 * the default server name...
3931 */
3932
3933 snprintf(packet, sizeof(packet), "%x %x %s \"%s\" \"%s\" \"%s\" %s%s\n",
3934 type, p->state, p->uri, location, info, make_model,
3935 p->browse_attrs ? p->browse_attrs : "", air);
3936
3937 bytes = strlen(packet);
3938 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3939 "cupsdSendBrowseList: (%d bytes) %s", bytes, packet);
3940
3941 if (sendto(BrowseSocket, packet, bytes, 0,
3942 (struct sockaddr *)&(b->to),
3943 httpAddrLength(&(b->to))) <= 0)
3944 {
3945 /*
3946 * Unable to send browse packet, so remove this address from the
3947 * list...
3948 */
3949
3950 cupsdLogMessage(CUPSD_LOG_ERROR,
3951 "cupsdSendBrowseList: sendto failed for browser "
3952 "%d - %s.",
3953 (int)(b - Browsers + 1), strerror(errno));
3954
3955 if (i > 1)
3956 memmove(b, b + 1, (i - 1) * sizeof(cupsd_dirsvc_addr_t));
3957
3958 b --;
3959 NumBrowsers --;
3960 }
3961 }
3962 }
3963
3964
3965 #ifdef HAVE_LDAP
3966 /*
3967 * 'ldap_search_rec()' - LDAP Search with reconnect
3968 */
3969
3970 static int /* O - Return code */
3971 ldap_search_rec(LDAP *ld, /* I - LDAP handler */
3972 char *base, /* I - Base dn */
3973 int scope, /* I - LDAP search scope */
3974 char *filter, /* I - Filter string */
3975 char *attrs[], /* I - Requested attributes */
3976 int attrsonly, /* I - Return only attributes? */
3977 LDAPMessage **res) /* I - LDAP handler */
3978 {
3979 int rc; /* Return code */
3980 LDAP *ldr; /* LDAP handler after reconnect */
3981
3982
3983 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
3984 rc = ldap_search_ext_s(ld, base, scope, filter, attrs, attrsonly, NULL, NULL,
3985 NULL, LDAP_NO_LIMIT, res);
3986 # else
3987 rc = ldap_search_s(ld, base, scope, filter, attrs, attrsonly, res);
3988 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
3989
3990 /*
3991 * If we have a connection problem try again...
3992 */
3993
3994 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
3995 {
3996 cupsdLogMessage(CUPSD_LOG_ERROR,
3997 "LDAP search failed with status %d: %s",
3998 rc, ldap_err2string(rc));
3999 cupsdLogMessage(CUPSD_LOG_INFO,
4000 "We try the LDAP search once again after reconnecting to "
4001 "the server");
4002 ldap_freeres(*res);
4003 ldr = ldap_reconnect();
4004
4005 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4006 rc = ldap_search_ext_s(ldr, base, scope, filter, attrs, attrsonly, NULL,
4007 NULL, NULL, LDAP_NO_LIMIT, res);
4008 # else
4009 rc = ldap_search_s(ldr, base, scope, filter, attrs, attrsonly, res);
4010 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4011 }
4012
4013 if (rc == LDAP_NO_SUCH_OBJECT)
4014 cupsdLogMessage(CUPSD_LOG_DEBUG,
4015 "ldap_search_rec: LDAP entry/object not found");
4016 else if (rc != LDAP_SUCCESS)
4017 cupsdLogMessage(CUPSD_LOG_ERROR,
4018 "ldap_search_rec: LDAP search failed with status %d: %s",
4019 rc, ldap_err2string(rc));
4020
4021 if (rc != LDAP_SUCCESS)
4022 ldap_freeres(*res);
4023
4024 return (rc);
4025 }
4026
4027
4028 /*
4029 * 'ldap_freeres()' - Free LDAPMessage
4030 */
4031
4032 static void
4033 ldap_freeres(LDAPMessage *entry) /* I - LDAP handler */
4034 {
4035 int rc; /* Return value */
4036
4037
4038 rc = ldap_msgfree(entry);
4039 if (rc == -1)
4040 cupsdLogMessage(CUPSD_LOG_WARN, "Can't free LDAPMessage!");
4041 else if (rc == 0)
4042 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Freeing LDAPMessage was unnecessary");
4043 }
4044
4045
4046 /*
4047 * 'ldap_getval_char()' - Get first LDAP value and convert to string
4048 */
4049
4050 static int /* O - Return code */
4051 ldap_getval_firststring(
4052 LDAP *ld, /* I - LDAP handler */
4053 LDAPMessage *entry, /* I - LDAP message or search result */
4054 char *attr, /* I - the wanted attribute */
4055 char *retval, /* O - String to return */
4056 unsigned long maxsize) /* I - Max string size */
4057 {
4058 char *dn; /* LDAP DN */
4059 int rc = 0; /* Return code */
4060 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4061 struct berval **bval; /* LDAP value array */
4062 unsigned long size; /* String size */
4063
4064
4065 /*
4066 * Get value from LDAPMessage...
4067 */
4068
4069 if ((bval = ldap_get_values_len(ld, entry, attr)) == NULL)
4070 {
4071 rc = -1;
4072 dn = ldap_get_dn(ld, entry);
4073 cupsdLogMessage(CUPSD_LOG_WARN,
4074 "Failed to get LDAP value %s for %s!",
4075 attr, dn);
4076 ldap_memfree(dn);
4077 }
4078 else
4079 {
4080 /*
4081 * Check size and copy value into our string...
4082 */
4083
4084 size = maxsize;
4085 if (size < (bval[0]->bv_len + 1))
4086 {
4087 rc = -1;
4088 dn = ldap_get_dn(ld, entry);
4089 cupsdLogMessage(CUPSD_LOG_WARN,
4090 "Attribute %s is too big! (dn: %s)",
4091 attr, dn);
4092 ldap_memfree(dn);
4093 }
4094 else
4095 size = bval[0]->bv_len + 1;
4096
4097 strlcpy(retval, bval[0]->bv_val, size);
4098 ldap_value_free_len(bval);
4099 }
4100 # else
4101 char **value; /* LDAP value */
4102
4103 /*
4104 * Get value from LDAPMessage...
4105 */
4106
4107 if ((value = (char **)ldap_get_values(ld, entry, attr)) == NULL)
4108 {
4109 rc = -1;
4110 dn = ldap_get_dn(ld, entry);
4111 cupsdLogMessage(CUPSD_LOG_WARN, "Failed to get LDAP value %s for %s!",
4112 attr, dn);
4113 ldap_memfree(dn);
4114 }
4115 else
4116 {
4117 strlcpy(retval, *value, maxsize);
4118 ldap_value_free(value);
4119 }
4120 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4121
4122 return (rc);
4123 }
4124
4125
4126 /*
4127 * 'send_ldap_ou()' - Send LDAP ou registrations.
4128 */
4129
4130 static void
4131 send_ldap_ou(char *ou, /* I - Servername/ou to register */
4132 char *basedn, /* I - Our base dn */
4133 char *descstring) /* I - Description for ou */
4134 {
4135 int i; /* Looping var... */
4136 LDAPMod mods[3]; /* The 3 attributes we will be adding */
4137 LDAPMod *pmods[4]; /* Pointers to the 3 attributes + NULL */
4138 LDAPMessage *res, /* Search result token */
4139 *e; /* Current entry from search */
4140 int rc; /* LDAP status */
4141 int rcmod; /* LDAP status for modifications */
4142 char dn[1024], /* DN of the organizational unit we are adding */
4143 *desc[2], /* Change records */
4144 *ou_value[2];
4145 char old_desc[1024]; /* Old description */
4146 static const char * const objectClass_values[] =
4147 { /* The 2 objectClass's we use in */
4148 "top", /* our LDAP entries */
4149 "organizationalUnit",
4150 NULL
4151 };
4152 static const char * const ou_attrs[] =/* CUPS LDAP attributes */
4153 {
4154 "description",
4155 NULL
4156 };
4157
4158
4159 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_ou: %s", ou);
4160
4161 /*
4162 * Reconnect if LDAP Handle is invalid...
4163 */
4164
4165 if (!BrowseLDAPHandle)
4166 {
4167 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4168 "send_ldap_ou: LDAP Handle is invalid. Try reconnecting...");
4169 ldap_reconnect();
4170 return;
4171 }
4172
4173 /*
4174 * Prepare ldap search...
4175 */
4176
4177 snprintf(dn, sizeof(dn), "ou=%s, %s", ou, basedn);
4178 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_ou: dn=\"%s\"", dn);
4179
4180 ou_value[0] = ou;
4181 ou_value[1] = NULL;
4182 desc[0] = descstring;
4183 desc[1] = NULL;
4184
4185 mods[0].mod_type = "ou";
4186 mods[0].mod_values = ou_value;
4187 mods[1].mod_type = "description";
4188 mods[1].mod_values = desc;
4189 mods[2].mod_type = "objectClass";
4190 mods[2].mod_values = (char **)objectClass_values;
4191
4192 rc = ldap_search_rec(BrowseLDAPHandle, dn, LDAP_SCOPE_BASE, NULL,
4193 (char **)ou_attrs, 0, &res);
4194
4195 /*
4196 * If ldap search was not successfull then exit function...
4197 */
4198
4199 if (rc != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT)
4200 return;
4201
4202 /*
4203 * Check if we need to insert or update the LDAP entry...
4204 */
4205
4206 if (ldap_count_entries(BrowseLDAPHandle, res) > 0 &&
4207 rc != LDAP_NO_SUCH_OBJECT)
4208 {
4209 /*
4210 * Printserver has already been registered, check if
4211 * modification is required...
4212 */
4213
4214 e = ldap_first_entry(BrowseLDAPHandle, res);
4215
4216 /*
4217 * Get the required values from this entry...
4218 */
4219
4220 if (ldap_getval_firststring(BrowseLDAPHandle, e, "description", old_desc,
4221 sizeof(old_desc)) == -1)
4222 old_desc[0] = '\0';
4223
4224 /*
4225 * Check if modification is required...
4226 */
4227
4228 if ( strcmp(desc[0], old_desc) == 0 )
4229 {
4230 /*
4231 * LDAP entry for the printer exists.
4232 * Printer has already been registered,
4233 * no modifications required...
4234 */
4235 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4236 "send_ldap_ou: No updates required for %s", ou);
4237 }
4238 else
4239 {
4240
4241 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4242 "send_ldap_ou: Replace entry for %s", ou);
4243
4244 for (i = 0; i < 3; i ++)
4245 {
4246 pmods[i] = mods + i;
4247 pmods[i]->mod_op = LDAP_MOD_REPLACE;
4248 }
4249 pmods[i] = NULL;
4250
4251 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4252 if ((rcmod = ldap_modify_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4253 NULL)) != LDAP_SUCCESS)
4254 # else
4255 if ((rcmod = ldap_modify_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4256 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4257 {
4258 cupsdLogMessage(CUPSD_LOG_ERROR,
4259 "LDAP modify for %s failed with status %d: %s",
4260 ou, rcmod, ldap_err2string(rcmod));
4261 if (rcmod == LDAP_SERVER_DOWN)
4262 ldap_reconnect();
4263 }
4264 }
4265 }
4266 else
4267 {
4268 /*
4269 * Printserver has never been registered,
4270 * add registration...
4271 */
4272
4273 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4274 "send_ldap_ou: Add entry for %s", ou);
4275
4276 for (i = 0; i < 3; i ++)
4277 {
4278 pmods[i] = mods + i;
4279 pmods[i]->mod_op = LDAP_MOD_ADD;
4280 }
4281 pmods[i] = NULL;
4282
4283 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4284 if ((rcmod = ldap_add_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4285 NULL)) != LDAP_SUCCESS)
4286 # else
4287 if ((rcmod = ldap_add_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4288 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4289 {
4290 cupsdLogMessage(CUPSD_LOG_ERROR,
4291 "LDAP add for %s failed with status %d: %s",
4292 ou, rcmod, ldap_err2string(rcmod));
4293 if (rcmod == LDAP_SERVER_DOWN)
4294 ldap_reconnect();
4295 }
4296 }
4297
4298 if (rc == LDAP_SUCCESS)
4299 ldap_freeres(res);
4300 }
4301
4302
4303 /*
4304 * 'send_ldap_browse()' - Send LDAP printer registrations.
4305 */
4306
4307 static void
4308 send_ldap_browse(cupsd_printer_t *p) /* I - Printer to register */
4309 {
4310 int i; /* Looping var... */
4311 LDAPMod mods[7]; /* The 7 attributes we will be adding */
4312 LDAPMod *pmods[8]; /* Pointers to the 7 attributes + NULL */
4313 LDAPMessage *res, /* Search result token */
4314 *e; /* Current entry from search */
4315 char *cn_value[2], /* Change records */
4316 *uri[2],
4317 *info[2],
4318 *location[2],
4319 *make_model[2],
4320 *type[2],
4321 typestring[255], /* String to hold printer-type */
4322 dn[1024]; /* DN of the printer we are adding */
4323 int rc; /* LDAP status */
4324 int rcmod; /* LDAP status for modifications */
4325 char old_uri[HTTP_MAX_URI], /* Printer URI */
4326 old_location[1024], /* Printer location */
4327 old_info[1024], /* Printer information */
4328 old_make_model[1024], /* Printer make and model */
4329 old_type_string[30]; /* Temporary type number */
4330 int old_type; /* Printer type */
4331 static const char * const objectClass_values[] =
4332 { /* The 3 objectClass's we use in */
4333 "top", /* our LDAP entries */
4334 "device",
4335 "cupsPrinter",
4336 NULL
4337 };
4338
4339
4340 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_browse: %s", p->name);
4341
4342 /*
4343 * Exit function if LDAP updates has been disabled...
4344 */
4345
4346 if (!BrowseLDAPUpdate)
4347 {
4348 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4349 "send_ldap_browse: Updates temporary disabled; "
4350 "skipping...");
4351 return;
4352 }
4353
4354 /*
4355 * Reconnect if LDAP Handle is invalid...
4356 */
4357
4358 if (!BrowseLDAPHandle)
4359 {
4360 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4361 "send_ldap_browse: LDAP Handle is invalid. Try "
4362 "reconnecting...");
4363 ldap_reconnect();
4364 return;
4365 }
4366
4367 /*
4368 * Everything in ldap is ** so we fudge around it...
4369 */
4370
4371 sprintf(typestring, "%u", p->type);
4372
4373 cn_value[0] = p->name;
4374 cn_value[1] = NULL;
4375 info[0] = p->info ? p->info : "Unknown";
4376 info[1] = NULL;
4377 location[0] = p->location ? p->location : "Unknown";
4378 location[1] = NULL;
4379 make_model[0] = p->make_model ? p->make_model : "Unknown";
4380 make_model[1] = NULL;
4381 type[0] = typestring;
4382 type[1] = NULL;
4383 uri[0] = p->uri;
4384 uri[1] = NULL;
4385
4386 /*
4387 * Get ldap entry for printer ...
4388 */
4389
4390 snprintf(dn, sizeof(dn), "cn=%s, ou=%s, %s", p->name, ServerName,
4391 BrowseLDAPDN);
4392 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_browse: dn=\"%s\"", dn);
4393
4394 rc = ldap_search_rec(BrowseLDAPHandle, dn, LDAP_SCOPE_BASE, NULL,
4395 (char **)ldap_attrs, 0, &res);
4396
4397 /*
4398 * If ldap search was not successfull then exit function
4399 * and temporary disable LDAP updates...
4400 */
4401
4402 if (rc != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT)
4403 {
4404 if (BrowseLDAPUpdate &&
4405 (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR))
4406 {
4407 BrowseLDAPUpdate = FALSE;
4408 cupsdLogMessage(CUPSD_LOG_INFO,
4409 "LDAP update temporary disabled");
4410 }
4411
4412 return;
4413 }
4414
4415 /*
4416 * Fill modification array...
4417 */
4418
4419 mods[0].mod_type = "cn";
4420 mods[0].mod_values = cn_value;
4421 mods[1].mod_type = "printerDescription";
4422 mods[1].mod_values = info;
4423 mods[2].mod_type = "printerURI";
4424 mods[2].mod_values = uri;
4425 mods[3].mod_type = "printerLocation";
4426 mods[3].mod_values = location;
4427 mods[4].mod_type = "printerMakeAndModel";
4428 mods[4].mod_values = make_model;
4429 mods[5].mod_type = "printerType";
4430 mods[5].mod_values = type;
4431 mods[6].mod_type = "objectClass";
4432 mods[6].mod_values = (char **)objectClass_values;
4433
4434 /*
4435 * Check if we need to insert or update the LDAP entry...
4436 */
4437
4438 if (ldap_count_entries(BrowseLDAPHandle, res) > 0 &&
4439 rc != LDAP_NO_SUCH_OBJECT)
4440 {
4441 /*
4442 * Printer has already been registered, check if
4443 * modification is required...
4444 */
4445
4446 e = ldap_first_entry(BrowseLDAPHandle, res);
4447
4448 /*
4449 * Get the required values from this entry...
4450 */
4451
4452 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerDescription",
4453 old_info, sizeof(old_info)) == -1)
4454 old_info[0] = '\0';
4455
4456 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerLocation",
4457 old_location, sizeof(old_location)) == -1)
4458 old_info[0] = '\0';
4459
4460 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerMakeAndModel",
4461 old_make_model, sizeof(old_make_model)) == -1)
4462 old_info[0] = '\0';
4463
4464 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerType",
4465 old_type_string, sizeof(old_type_string)) == -1)
4466 old_info[0] = '\0';
4467
4468 old_type = atoi(old_type_string);
4469
4470 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerURI", old_uri,
4471 sizeof(old_uri)) == -1)
4472 old_info[0] = '\0';
4473
4474 /*
4475 * Check if modification is required...
4476 */
4477
4478 if (!strcmp(info[0], old_info) && !strcmp(uri[0], old_uri) &&
4479 !strcmp(location[0], old_location) &&
4480 !strcmp(make_model[0], old_make_model) && p->type == old_type)
4481 {
4482 /*
4483 * LDAP entry for the printer exists. Printer has already been registered,
4484 * no modifications required...
4485 */
4486
4487 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4488 "send_ldap_browse: No updates required for %s", p->name);
4489 }
4490 else
4491 {
4492 /*
4493 * LDAP entry for the printer exists. Printer has already been registered,
4494 * modify the current registration...
4495 */
4496
4497 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4498 "send_ldap_browse: Replace entry for %s", p->name);
4499
4500 for (i = 0; i < 7; i ++)
4501 {
4502 pmods[i] = mods + i;
4503 pmods[i]->mod_op = LDAP_MOD_REPLACE;
4504 }
4505 pmods[i] = NULL;
4506
4507 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4508 if ((rcmod = ldap_modify_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4509 NULL)) != LDAP_SUCCESS)
4510 # else
4511 if ((rcmod = ldap_modify_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4512 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4513 {
4514 cupsdLogMessage(CUPSD_LOG_ERROR,
4515 "LDAP modify for %s failed with status %d: %s",
4516 p->name, rcmod, ldap_err2string(rcmod));
4517 if (rcmod == LDAP_SERVER_DOWN)
4518 ldap_reconnect();
4519 }
4520 }
4521 }
4522 else
4523 {
4524 /*
4525 * No LDAP entry exists for the printer. Printer has never been registered,
4526 * add the current registration...
4527 */
4528
4529 send_ldap_ou(ServerName, BrowseLDAPDN, "CUPS Server");
4530
4531 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4532 "send_ldap_browse: Add entry for %s", p->name);
4533
4534 for (i = 0; i < 7; i ++)
4535 {
4536 pmods[i] = mods + i;
4537 pmods[i]->mod_op = LDAP_MOD_ADD;
4538 }
4539 pmods[i] = NULL;
4540
4541 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4542 if ((rcmod = ldap_add_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4543 NULL)) != LDAP_SUCCESS)
4544 # else
4545 if ((rcmod = ldap_add_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4546 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4547 {
4548 cupsdLogMessage(CUPSD_LOG_ERROR,
4549 "LDAP add for %s failed with status %d: %s",
4550 p->name, rcmod, ldap_err2string(rcmod));
4551 if (rcmod == LDAP_SERVER_DOWN)
4552 ldap_reconnect();
4553 }
4554 }
4555
4556 if (rc == LDAP_SUCCESS)
4557 ldap_freeres(res);
4558 }
4559
4560
4561 /*
4562 * 'ldap_dereg_printer()' - Delete printer from directory
4563 */
4564
4565 static void
4566 ldap_dereg_printer(cupsd_printer_t *p) /* I - Printer to deregister */
4567 {
4568 char dn[1024]; /* DN of the printer */
4569 int rc; /* LDAP status */
4570
4571
4572 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_printer: Remove entry for %s",
4573 p->name);
4574
4575 /*
4576 * Reconnect if LDAP Handle is invalid...
4577 */
4578
4579 if (!BrowseLDAPHandle)
4580 {
4581 ldap_reconnect();
4582 return;
4583 }
4584
4585 /*
4586 * Get dn for printer and delete LDAP entry...
4587 */
4588
4589 snprintf(dn, sizeof(dn), "cn=%s, ou=%s, %s", p->name, ServerName,
4590 BrowseLDAPDN);
4591 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_printer: dn=\"%s\"", dn);
4592
4593 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4594 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4595 NULL)) != LDAP_SUCCESS)
4596 # else
4597 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4598 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4599 {
4600 cupsdLogMessage(CUPSD_LOG_WARN,
4601 "LDAP delete for %s failed with status %d: %s",
4602 p->name, rc, ldap_err2string(rc));
4603
4604 /*
4605 * If we had a connection problem (connection timed out, etc.)
4606 * we should reconnect and try again to delete the entry...
4607 */
4608
4609 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
4610 {
4611 cupsdLogMessage(CUPSD_LOG_INFO,
4612 "Retry deleting LDAP entry for %s after a reconnect...", p->name);
4613 ldap_reconnect();
4614
4615 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4616 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4617 NULL)) != LDAP_SUCCESS)
4618 # else
4619 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4620 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4621 cupsdLogMessage(CUPSD_LOG_WARN,
4622 "LDAP delete for %s failed with status %d: %s",
4623 p->name, rc, ldap_err2string(rc));
4624 }
4625 }
4626 }
4627
4628
4629 /*
4630 * 'ldap_dereg_ou()' - Remove the organizational unit.
4631 */
4632
4633 static void
4634 ldap_dereg_ou(char *ou, /* I - Organizational unit (servername) */
4635 char *basedn) /* I - Dase dn */
4636 {
4637 char dn[1024]; /* DN of the printer */
4638 int rc; /* LDAP status */
4639
4640
4641 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_ou: Remove entry for %s", ou);
4642
4643 /*
4644 * Reconnect if LDAP Handle is invalid...
4645 */
4646
4647 if (!BrowseLDAPHandle)
4648 {
4649 ldap_reconnect();
4650 return;
4651 }
4652
4653 /*
4654 * Get dn for printer and delete LDAP entry...
4655 */
4656
4657 snprintf(dn, sizeof(dn), "ou=%s, %s", ou, basedn);
4658 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_ou: dn=\"%s\"", dn);
4659
4660 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4661 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4662 NULL)) != LDAP_SUCCESS)
4663 # else
4664 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4665 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4666 {
4667 cupsdLogMessage(CUPSD_LOG_WARN,
4668 "LDAP delete for %s failed with status %d: %s",
4669 ou, rc, ldap_err2string(rc));
4670
4671 /*
4672 * If we had a connection problem (connection timed out, etc.)
4673 * we should reconnect and try again to delete the entry...
4674 */
4675
4676 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
4677 {
4678 cupsdLogMessage(CUPSD_LOG_INFO,
4679 "Retry deleting LDAP entry for %s after a reconnect...", ou);
4680 ldap_reconnect();
4681 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4682 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4683 NULL)) != LDAP_SUCCESS)
4684 # else
4685 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4686 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4687 cupsdLogMessage(CUPSD_LOG_WARN,
4688 "LDAP delete for %s failed with status %d: %s",
4689 ou, rc, ldap_err2string(rc));
4690 }
4691 }
4692 }
4693 #endif /* HAVE_LDAP */
4694
4695
4696 #ifdef HAVE_LIBSLP
4697 /*
4698 * 'send_slp_browse()' - Register the specified printer with SLP.
4699 */
4700
4701 static void
4702 send_slp_browse(cupsd_printer_t *p) /* I - Printer to register */
4703 {
4704 char srvurl[HTTP_MAX_URI], /* Printer service URI */
4705 attrs[8192], /* Printer attributes */
4706 finishings[1024], /* Finishings to support */
4707 make_model[IPP_MAX_NAME * 2],
4708 /* Make and model, quoted */
4709 location[IPP_MAX_NAME * 2],
4710 /* Location, quoted */
4711 info[IPP_MAX_NAME * 2], /* Info, quoted */
4712 *src, /* Pointer to original string */
4713 *dst; /* Pointer to destination string */
4714 ipp_attribute_t *authentication; /* uri-authentication-supported value */
4715 SLPError error; /* SLP error, if any */
4716
4717
4718 cupsdLogMessage(CUPSD_LOG_DEBUG, "send_slp_browse(%p = \"%s\")", p,
4719 p->name);
4720
4721 /*
4722 * Make the SLP service URL that conforms to the IANA
4723 * 'printer:' template.
4724 */
4725
4726 snprintf(srvurl, sizeof(srvurl), SLP_CUPS_SRVTYPE ":%s", p->uri);
4727
4728 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Service URL = \"%s\"", srvurl);
4729
4730 /*
4731 * Figure out the finishings string...
4732 */
4733
4734 if (p->type & CUPS_PRINTER_STAPLE)
4735 strcpy(finishings, "staple");
4736 else
4737 finishings[0] = '\0';
4738
4739 if (p->type & CUPS_PRINTER_BIND)
4740 {
4741 if (finishings[0])
4742 strlcat(finishings, ",bind", sizeof(finishings));
4743 else
4744 strcpy(finishings, "bind");
4745 }
4746
4747 if (p->type & CUPS_PRINTER_PUNCH)
4748 {
4749 if (finishings[0])
4750 strlcat(finishings, ",punch", sizeof(finishings));
4751 else
4752 strcpy(finishings, "punch");
4753 }
4754
4755 if (p->type & CUPS_PRINTER_COVER)
4756 {
4757 if (finishings[0])
4758 strlcat(finishings, ",cover", sizeof(finishings));
4759 else
4760 strcpy(finishings, "cover");
4761 }
4762
4763 if (p->type & CUPS_PRINTER_SORT)
4764 {
4765 if (finishings[0])
4766 strlcat(finishings, ",sort", sizeof(finishings));
4767 else
4768 strcpy(finishings, "sort");
4769 }
4770
4771 if (!finishings[0])
4772 strcpy(finishings, "none");
4773
4774 /*
4775 * Quote any commas in the make and model, location, and info strings...
4776 */
4777
4778 for (src = p->make_model, dst = make_model;
4779 src && *src && dst < (make_model + sizeof(make_model) - 2);)
4780 {
4781 if (*src == ',' || *src == '\\' || *src == ')')
4782 *dst++ = '\\';
4783
4784 *dst++ = *src++;
4785 }
4786
4787 *dst = '\0';
4788
4789 if (!make_model[0])
4790 strcpy(make_model, "Unknown");
4791
4792 for (src = p->location, dst = location;
4793 src && *src && dst < (location + sizeof(location) - 2);)
4794 {
4795 if (*src == ',' || *src == '\\' || *src == ')')
4796 *dst++ = '\\';
4797
4798 *dst++ = *src++;
4799 }
4800
4801 *dst = '\0';
4802
4803 if (!location[0])
4804 strcpy(location, "Unknown");
4805
4806 for (src = p->info, dst = info;
4807 src && *src && dst < (info + sizeof(info) - 2);)
4808 {
4809 if (*src == ',' || *src == '\\' || *src == ')')
4810 *dst++ = '\\';
4811
4812 *dst++ = *src++;
4813 }
4814
4815 *dst = '\0';
4816
4817 if (!info[0])
4818 strcpy(info, "Unknown");
4819
4820 /*
4821 * Get the authentication value...
4822 */
4823
4824 authentication = ippFindAttribute(p->attrs, "uri-authentication-supported",
4825 IPP_TAG_KEYWORD);
4826
4827 /*
4828 * Make the SLP attribute string list that conforms to
4829 * the IANA 'printer:' template.
4830 */
4831
4832 snprintf(attrs, sizeof(attrs),
4833 "(printer-uri-supported=%s),"
4834 "(uri-authentication-supported=%s>),"
4835 #ifdef HAVE_SSL
4836 "(uri-security-supported=tls>),"
4837 #else
4838 "(uri-security-supported=none>),"
4839 #endif /* HAVE_SSL */
4840 "(printer-name=%s),"
4841 "(printer-location=%s),"
4842 "(printer-info=%s),"
4843 "(printer-more-info=%s),"
4844 "(printer-make-and-model=%s),"
4845 "(printer-type=%d),"
4846 "(charset-supported=utf-8),"
4847 "(natural-language-configured=%s),"
4848 "(natural-language-supported=de,en,es,fr,it),"
4849 "(color-supported=%s),"
4850 "(finishings-supported=%s),"
4851 "(sides-supported=one-sided%s),"
4852 "(multiple-document-jobs-supported=true)"
4853 "(ipp-versions-supported=1.0,1.1)",
4854 p->uri, authentication->values[0].string.text, p->name, location,
4855 info, p->uri, make_model, p->type, DefaultLanguage,
4856 p->type & CUPS_PRINTER_COLOR ? "true" : "false",
4857 finishings,
4858 p->type & CUPS_PRINTER_DUPLEX ?
4859 ",two-sided-long-edge,two-sided-short-edge" : "");
4860
4861 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Attributes = \"%s\"", attrs);
4862
4863 /*
4864 * Register the printer with the SLP server...
4865 */
4866
4867 error = SLPReg(BrowseSLPHandle, srvurl, BrowseTimeout,
4868 SLP_CUPS_SRVTYPE, attrs, SLP_TRUE, slp_reg_callback, 0);
4869
4870 if (error != SLP_OK)
4871 cupsdLogMessage(CUPSD_LOG_ERROR, "SLPReg of \"%s\" failed with status %d!", p->name,
4872 error);
4873 }
4874
4875
4876 /*
4877 * 'slp_attr_callback()' - SLP attribute callback
4878 */
4879
4880 static SLPBoolean /* O - SLP_TRUE for success */
4881 slp_attr_callback(
4882 SLPHandle hslp, /* I - SLP handle */
4883 const char *attrlist, /* I - Attribute list */
4884 SLPError errcode, /* I - Parsing status for this attr */
4885 void *cookie) /* I - Current printer */
4886 {
4887 char *tmp = 0; /* Temporary string */
4888 cupsd_printer_t *p = (cupsd_printer_t*)cookie;
4889 /* Current printer */
4890
4891
4892 (void)hslp; /* anti-compiler-warning-code */
4893
4894 /*
4895 * Bail if there was an error
4896 */
4897
4898 if (errcode != SLP_OK)
4899 return (SLP_TRUE);
4900
4901 /*
4902 * Parse the attrlist to obtain things needed to build CUPS browse packet
4903 */
4904
4905 memset(p, 0, sizeof(cupsd_printer_t));
4906
4907 if (slp_get_attr(attrlist, "(printer-location=", &(p->location)))
4908 return (SLP_FALSE);
4909 if (slp_get_attr(attrlist, "(printer-info=", &(p->info)))
4910 return (SLP_FALSE);
4911 if (slp_get_attr(attrlist, "(printer-make-and-model=", &(p->make_model)))
4912 return (SLP_FALSE);
4913 if (!slp_get_attr(attrlist, "(printer-type=", &tmp))
4914 p->type = atoi(tmp);
4915 else
4916 p->type = CUPS_PRINTER_REMOTE;
4917
4918 cupsdClearString(&tmp);
4919
4920 return (SLP_TRUE);
4921 }
4922
4923
4924 /*
4925 * 'slp_dereg_printer()' - SLPDereg() the specified printer
4926 */
4927
4928 static void
4929 slp_dereg_printer(cupsd_printer_t *p) /* I - Printer */
4930 {
4931 char srvurl[HTTP_MAX_URI]; /* Printer service URI */
4932
4933
4934 cupsdLogMessage(CUPSD_LOG_DEBUG, "slp_dereg_printer: printer=\"%s\"", p->name);
4935
4936 if (!(p->type & CUPS_PRINTER_REMOTE))
4937 {
4938 /*
4939 * Make the SLP service URL that conforms to the IANA
4940 * 'printer:' template.
4941 */
4942
4943 snprintf(srvurl, sizeof(srvurl), SLP_CUPS_SRVTYPE ":%s", p->uri);
4944
4945 /*
4946 * Deregister the printer...
4947 */
4948
4949 SLPDereg(BrowseSLPHandle, srvurl, slp_reg_callback, 0);
4950 }
4951 }
4952
4953
4954 /*
4955 * 'slp_get_attr()' - Get an attribute from an SLP registration.
4956 */
4957
4958 static int /* O - 0 on success */
4959 slp_get_attr(const char *attrlist, /* I - Attribute list string */
4960 const char *tag, /* I - Name of attribute */
4961 char **valbuf) /* O - Value */
4962 {
4963 char *ptr1, /* Pointer into string */
4964 *ptr2; /* ... */
4965
4966
4967 cupsdClearString(valbuf);
4968
4969 if ((ptr1 = strstr(attrlist, tag)) != NULL)
4970 {
4971 ptr1 += strlen(tag);
4972
4973 if ((ptr2 = strchr(ptr1,')')) != NULL)
4974 {
4975 /*
4976 * Copy the value...
4977 */
4978
4979 *valbuf = calloc(ptr2 - ptr1 + 1, 1);
4980 strncpy(*valbuf, ptr1, ptr2 - ptr1);
4981
4982 /*
4983 * Dequote the value...
4984 */
4985
4986 for (ptr1 = *valbuf; *ptr1; ptr1 ++)
4987 if (*ptr1 == '\\' && ptr1[1])
4988 _cups_strcpy(ptr1, ptr1 + 1);
4989
4990 return (0);
4991 }
4992 }
4993
4994 return (-1);
4995 }
4996
4997
4998 /*
4999 * 'slp_reg_callback()' - Empty SLPRegReport.
5000 */
5001
5002 static void
5003 slp_reg_callback(SLPHandle hslp, /* I - SLP handle */
5004 SLPError errcode, /* I - Error code, if any */
5005 void *cookie) /* I - App data */
5006 {
5007 (void)hslp;
5008 (void)errcode;
5009 (void)cookie;
5010
5011 return;
5012 }
5013
5014
5015 /*
5016 * 'slp_url_callback()' - SLP service url callback
5017 */
5018
5019 static SLPBoolean /* O - TRUE = OK, FALSE = error */
5020 slp_url_callback(
5021 SLPHandle hslp, /* I - SLP handle */
5022 const char *srvurl, /* I - URL of service */
5023 unsigned short lifetime, /* I - Life of service */
5024 SLPError errcode, /* I - Existing error code */
5025 void *cookie) /* I - Pointer to service list */
5026 {
5027 slpsrvurl_t *s, /* New service entry */
5028 **head; /* Pointer to head of entry */
5029
5030
5031 /*
5032 * Let the compiler know we won't be using these vars...
5033 */
5034
5035 (void)hslp;
5036 (void)lifetime;
5037
5038 /*
5039 * Bail if there was an error
5040 */
5041
5042 if (errcode != SLP_OK)
5043 return (SLP_TRUE);
5044
5045 /*
5046 * Grab the head of the list...
5047 */
5048
5049 head = (slpsrvurl_t**)cookie;
5050
5051 /*
5052 * Allocate a *temporary* slpsrvurl_t to hold this entry.
5053 */
5054
5055 if ((s = (slpsrvurl_t *)calloc(1, sizeof(slpsrvurl_t))) == NULL)
5056 return (SLP_FALSE);
5057
5058 /*
5059 * Copy the SLP service URL...
5060 */
5061
5062 strlcpy(s->url, srvurl, sizeof(s->url));
5063
5064 /*
5065 * Link the SLP service URL into the head of the list
5066 */
5067
5068 if (*head)
5069 s->next = *head;
5070
5071 *head = s;
5072
5073 return (SLP_TRUE);
5074 }
5075 #endif /* HAVE_LIBSLP */
5076
5077
5078 /*
5079 * 'update_cups_browse()' - Update the browse lists using the CUPS protocol.
5080 */
5081
5082 static void
5083 update_cups_browse(void)
5084 {
5085 int i; /* Looping var */
5086 int auth; /* Authorization status */
5087 int len; /* Length of name string */
5088 int bytes; /* Number of bytes left */
5089 char packet[1541], /* Broadcast packet */
5090 *pptr; /* Pointer into packet */
5091 socklen_t srclen; /* Length of source address */
5092 http_addr_t srcaddr; /* Source address */
5093 char srcname[1024]; /* Source hostname */
5094 unsigned address[4]; /* Source address */
5095 unsigned type; /* Printer type */
5096 unsigned state; /* Printer state */
5097 char uri[HTTP_MAX_URI], /* Printer URI */
5098 host[HTTP_MAX_URI], /* Host portion of URI */
5099 resource[HTTP_MAX_URI], /* Resource portion of URI */
5100 info[IPP_MAX_NAME], /* Information string */
5101 location[IPP_MAX_NAME], /* Location string */
5102 make_model[IPP_MAX_NAME];/* Make and model string */
5103 int num_attrs; /* Number of attributes */
5104 cups_option_t *attrs; /* Attributes */
5105
5106
5107 /*
5108 * Read a packet from the browse socket...
5109 */
5110
5111 srclen = sizeof(srcaddr);
5112 if ((bytes = recvfrom(BrowseSocket, packet, sizeof(packet) - 1, 0,
5113 (struct sockaddr *)&srcaddr, &srclen)) < 0)
5114 {
5115 /*
5116 * "Connection refused" is returned under Linux if the destination port
5117 * or address is unreachable from a previous sendto(); check for the
5118 * error here and ignore it for now...
5119 */
5120
5121 if (errno != ECONNREFUSED && errno != EAGAIN)
5122 {
5123 cupsdLogMessage(CUPSD_LOG_ERROR, "Browse recv failed - %s.",
5124 strerror(errno));
5125 cupsdLogMessage(CUPSD_LOG_ERROR, "CUPS browsing turned off.");
5126
5127 #ifdef WIN32
5128 closesocket(BrowseSocket);
5129 #else
5130 close(BrowseSocket);
5131 #endif /* WIN32 */
5132
5133 cupsdRemoveSelect(BrowseSocket);
5134 BrowseSocket = -1;
5135
5136 BrowseLocalProtocols &= ~BROWSE_CUPS;
5137 BrowseRemoteProtocols &= ~BROWSE_CUPS;
5138 }
5139
5140 return;
5141 }
5142
5143 packet[bytes] = '\0';
5144
5145 /*
5146 * If we're about to sleep, ignore incoming browse packets.
5147 */
5148
5149 if (Sleeping)
5150 return;
5151
5152 /*
5153 * Figure out where it came from...
5154 */
5155
5156 #ifdef AF_INET6
5157 if (srcaddr.addr.sa_family == AF_INET6)
5158 {
5159 address[0] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[0]);
5160 address[1] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[1]);
5161 address[2] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[2]);
5162 address[3] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[3]);
5163 }
5164 else
5165 #endif /* AF_INET6 */
5166 {
5167 address[0] = 0;
5168 address[1] = 0;
5169 address[2] = 0;
5170 address[3] = ntohl(srcaddr.ipv4.sin_addr.s_addr);
5171 }
5172
5173 if (HostNameLookups)
5174 httpAddrLookup(&srcaddr, srcname, sizeof(srcname));
5175 else
5176 httpAddrString(&srcaddr, srcname, sizeof(srcname));
5177
5178 len = strlen(srcname);
5179
5180 /*
5181 * Do ACL stuff...
5182 */
5183
5184 if (BrowseACL)
5185 {
5186 if (httpAddrLocalhost(&srcaddr) || !strcasecmp(srcname, "localhost"))
5187 {
5188 /*
5189 * Access from localhost (127.0.0.1) is always allowed...
5190 */
5191
5192 auth = CUPSD_AUTH_ALLOW;
5193 }
5194 else
5195 {
5196 /*
5197 * Do authorization checks on the domain/address...
5198 */
5199
5200 switch (BrowseACL->order_type)
5201 {
5202 default :
5203 auth = CUPSD_AUTH_DENY; /* anti-compiler-warning-code */
5204 break;
5205
5206 case CUPSD_AUTH_ALLOW : /* Order Deny,Allow */
5207 auth = CUPSD_AUTH_ALLOW;
5208
5209 if (cupsdCheckAuth(address, srcname, len, BrowseACL->deny))
5210 auth = CUPSD_AUTH_DENY;
5211
5212 if (cupsdCheckAuth(address, srcname, len, BrowseACL->allow))
5213 auth = CUPSD_AUTH_ALLOW;
5214 break;
5215
5216 case CUPSD_AUTH_DENY : /* Order Allow,Deny */
5217 auth = CUPSD_AUTH_DENY;
5218
5219 if (cupsdCheckAuth(address, srcname, len, BrowseACL->allow))
5220 auth = CUPSD_AUTH_ALLOW;
5221
5222 if (cupsdCheckAuth(address, srcname, len, BrowseACL->deny))
5223 auth = CUPSD_AUTH_DENY;
5224 break;
5225 }
5226 }
5227 }
5228 else
5229 auth = CUPSD_AUTH_ALLOW;
5230
5231 if (auth == CUPSD_AUTH_DENY)
5232 {
5233 cupsdLogMessage(CUPSD_LOG_DEBUG,
5234 "update_cups_browse: Refused %d bytes from %s", bytes,
5235 srcname);
5236 return;
5237 }
5238
5239 cupsdLogMessage(CUPSD_LOG_DEBUG2,
5240 "update_cups_browse: (%d bytes from %s) %s", bytes,
5241 srcname, packet);
5242
5243 /*
5244 * Parse packet...
5245 */
5246
5247 if (sscanf(packet, "%x%x%1023s", &type, &state, uri) < 3)
5248 {
5249 cupsdLogMessage(CUPSD_LOG_WARN,
5250 "update_cups_browse: Garbled browse packet - %s", packet);
5251 return;
5252 }
5253
5254 strcpy(location, "Location Unknown");
5255 strcpy(info, "No Information Available");
5256 make_model[0] = '\0';
5257 num_attrs = 0;
5258 attrs = NULL;
5259
5260 if ((pptr = strchr(packet, '\"')) != NULL)
5261 {
5262 /*
5263 * Have extended information; can't use sscanf for it because not all
5264 * sscanf's allow empty strings with %[^\"]...
5265 */
5266
5267 for (i = 0, pptr ++;
5268 i < (sizeof(location) - 1) && *pptr && *pptr != '\"';
5269 i ++, pptr ++)
5270 location[i] = *pptr;
5271
5272 if (i)
5273 location[i] = '\0';
5274
5275 if (*pptr == '\"')
5276 pptr ++;
5277
5278 while (*pptr && isspace(*pptr & 255))
5279 pptr ++;
5280
5281 if (*pptr == '\"')
5282 {
5283 for (i = 0, pptr ++;
5284 i < (sizeof(info) - 1) && *pptr && *pptr != '\"';
5285 i ++, pptr ++)
5286 info[i] = *pptr;
5287
5288 info[i] = '\0';
5289
5290 if (*pptr == '\"')
5291 pptr ++;
5292
5293 while (*pptr && isspace(*pptr & 255))
5294 pptr ++;
5295
5296 if (*pptr == '\"')
5297 {
5298 for (i = 0, pptr ++;
5299 i < (sizeof(make_model) - 1) && *pptr && *pptr != '\"';
5300 i ++, pptr ++)
5301 make_model[i] = *pptr;
5302
5303 if (*pptr == '\"')
5304 pptr ++;
5305
5306 make_model[i] = '\0';
5307
5308 if (*pptr)
5309 num_attrs = cupsParseOptions(pptr, num_attrs, &attrs);
5310 }
5311 }
5312 }
5313
5314 DEBUG_puts(packet);
5315 DEBUG_printf(("type=%x, state=%x, uri=\"%s\"\n"
5316 "location=\"%s\", info=\"%s\", make_model=\"%s\"\n",
5317 type, state, uri, location, info, make_model));
5318
5319 /*
5320 * Pull the URI apart to see if this is a local or remote printer...
5321 */
5322
5323 if (is_local_queue(uri, host, sizeof(host), resource, sizeof(resource)))
5324 {
5325 cupsFreeOptions(num_attrs, attrs);
5326 return;
5327 }
5328
5329 /*
5330 * Do relaying...
5331 */
5332
5333 for (i = 0; i < NumRelays; i ++)
5334 if (cupsdCheckAuth(address, srcname, len, Relays[i].from))
5335 if (sendto(BrowseSocket, packet, bytes, 0,
5336 (struct sockaddr *)&(Relays[i].to),
5337 httpAddrLength(&(Relays[i].to))) <= 0)
5338 {
5339 cupsdLogMessage(CUPSD_LOG_ERROR,
5340 "update_cups_browse: sendto failed for relay %d - %s.",
5341 i + 1, strerror(errno));
5342 cupsFreeOptions(num_attrs, attrs);
5343 return;
5344 }
5345
5346 /*
5347 * Process the browse data...
5348 */
5349
5350 process_browse_data(uri, host, resource, (cups_ptype_t)type,
5351 (ipp_pstate_t)state, location, info, make_model,
5352 num_attrs, attrs);
5353 }
5354
5355
5356 /*
5357 * 'update_lpd()' - Update the LPD configuration as needed.
5358 */
5359
5360 static void
5361 update_lpd(int onoff) /* - 1 = turn on, 0 = turn off */
5362 {
5363 if (!LPDConfigFile)
5364 return;
5365
5366 #ifdef __APPLE__
5367 /*
5368 * Allow /etc/hostconfig CUPS_LPD service setting to override cupsd.conf
5369 * setting for backwards-compatibility.
5370 */
5371
5372 if (onoff && !get_hostconfig("CUPS_LPD"))
5373 onoff = 0;
5374 #endif /* __APPLE__ */
5375
5376 if (!strncmp(LPDConfigFile, "xinetd:///", 10))
5377 {
5378 /*
5379 * Enable/disable LPD via the xinetd.d config file for cups-lpd...
5380 */
5381
5382 char newfile[1024]; /* New cups-lpd.N file */
5383 cups_file_t *ofp, /* Original file pointer */
5384 *nfp; /* New file pointer */
5385 char line[1024]; /* Line from file */
5386
5387
5388 snprintf(newfile, sizeof(newfile), "%s.N", LPDConfigFile + 9);
5389
5390 if ((ofp = cupsFileOpen(LPDConfigFile + 9, "r")) == NULL)
5391 {
5392 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open \"%s\" - %s",
5393 LPDConfigFile + 9, strerror(errno));
5394 return;
5395 }
5396
5397 if ((nfp = cupsFileOpen(newfile, "w")) == NULL)
5398 {
5399 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create \"%s\" - %s",
5400 newfile, strerror(errno));
5401 cupsFileClose(ofp);
5402 return;
5403 }
5404
5405 /*
5406 * Copy all of the lines from the cups-lpd file...
5407 */
5408
5409 while (cupsFileGets(ofp, line, sizeof(line)))
5410 {
5411 if (line[0] == '{')
5412 {
5413 cupsFilePrintf(nfp, "%s\n", line);
5414 snprintf(line, sizeof(line), "\tdisable = %s",
5415 onoff ? "no" : "yes");
5416 }
5417 else if (!strstr(line, "disable ="))
5418 cupsFilePrintf(nfp, "%s\n", line);
5419 }
5420
5421 cupsFileClose(nfp);
5422 cupsFileClose(ofp);
5423 rename(newfile, LPDConfigFile + 9);
5424 }
5425 #ifdef __APPLE__
5426 else if (!strncmp(LPDConfigFile, "launchd:///", 11))
5427 {
5428 /*
5429 * Enable/disable LPD via the launchctl command...
5430 */
5431
5432 char *argv[5], /* Arguments for command */
5433 *envp[MAX_ENV]; /* Environment for command */
5434 int pid; /* Process ID */
5435
5436
5437 cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
5438 argv[0] = (char *)"launchctl";
5439 argv[1] = (char *)(onoff ? "load" : "unload");
5440 argv[2] = (char *)"-w";
5441 argv[3] = LPDConfigFile + 10;
5442 argv[4] = NULL;
5443
5444 cupsdStartProcess("/bin/launchctl", argv, envp, -1, -1, -1, -1, -1, 1,
5445 NULL, NULL, &pid);
5446 }
5447 #endif /* __APPLE__ */
5448 else
5449 cupsdLogMessage(CUPSD_LOG_INFO, "Unknown LPDConfigFile scheme!");
5450 }
5451
5452
5453 /*
5454 * 'update_polling()' - Read status messages from the poll daemons.
5455 */
5456
5457 static void
5458 update_polling(void)
5459 {
5460 char *ptr, /* Pointer to end of line in buffer */
5461 message[1024]; /* Pointer to message text */
5462 int loglevel; /* Log level for message */
5463
5464
5465 while ((ptr = cupsdStatBufUpdate(PollStatusBuffer, &loglevel,
5466 message, sizeof(message))) != NULL)
5467 {
5468 if (loglevel == CUPSD_LOG_INFO)
5469 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
5470
5471 if (!strchr(PollStatusBuffer->buffer, '\n'))
5472 break;
5473 }
5474
5475 if (ptr == NULL && !PollStatusBuffer->bufused)
5476 {
5477 /*
5478 * All polling processes have died; stop polling...
5479 */
5480
5481 cupsdLogMessage(CUPSD_LOG_ERROR,
5482 "update_polling: all polling processes have exited!");
5483 cupsdStopPolling();
5484 }
5485 }
5486
5487
5488 /*
5489 * 'update_smb()' - Update the SMB configuration as needed.
5490 */
5491
5492 static void
5493 update_smb(int onoff) /* I - 1 = turn on, 0 = turn off */
5494 {
5495 if (!SMBConfigFile)
5496 return;
5497
5498 if (!strncmp(SMBConfigFile, "samba:///", 9))
5499 {
5500 /*
5501 * Enable/disable SMB via the specified smb.conf config file...
5502 */
5503
5504 char newfile[1024]; /* New smb.conf.N file */
5505 cups_file_t *ofp, /* Original file pointer */
5506 *nfp; /* New file pointer */
5507 char line[1024]; /* Line from file */
5508 int in_printers; /* In [printers] section? */
5509
5510
5511 snprintf(newfile, sizeof(newfile), "%s.N", SMBConfigFile + 8);
5512
5513 if ((ofp = cupsFileOpen(SMBConfigFile + 8, "r")) == NULL)
5514 {
5515 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open \"%s\" - %s",
5516 SMBConfigFile + 8, strerror(errno));
5517 return;
5518 }
5519
5520 if ((nfp = cupsFileOpen(newfile, "w")) == NULL)
5521 {
5522 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create \"%s\" - %s",
5523 newfile, strerror(errno));
5524 cupsFileClose(ofp);
5525 return;
5526 }
5527
5528 /*
5529 * Copy all of the lines from the smb.conf file...
5530 */
5531
5532 in_printers = 0;
5533
5534 while (cupsFileGets(ofp, line, sizeof(line)))
5535 {
5536 if (in_printers && strstr(line, "printable ="))
5537 snprintf(line, sizeof(line), " printable = %s",
5538 onoff ? "yes" : "no");
5539
5540 cupsFilePrintf(nfp, "%s\n", line);
5541
5542 if (line[0] == '[')
5543 in_printers = !strcmp(line, "[printers]");
5544 }
5545
5546 cupsFileClose(nfp);
5547 cupsFileClose(ofp);
5548 rename(newfile, SMBConfigFile + 8);
5549 }
5550 else
5551 cupsdLogMessage(CUPSD_LOG_INFO, "Unknown SMBConfigFile scheme!");
5552 }
5553
5554
5555 /*
5556 * End of "$Id: dirsvc.c 7933 2008-09-11 00:44:58Z mike $".
5557 */