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