]> git.ipfire.org Git - thirdparty/cups.git/blame - backend/snmp.c
Load cups into easysw/current.
[thirdparty/cups.git] / backend / snmp.c
CommitLineData
89d46774 1/*
bc44d920 2 * "$Id: snmp.c 6649 2007-07-11 21:46:42Z mike $"
89d46774 3 *
4 * SNMP discovery backend for the Common UNIX Printing System (CUPS).
5 *
bc44d920 6 * Copyright 2007 by Apple Inc.
c0e1af83 7 * Copyright 2006-2007 by Easy Software Products, all rights reserved.
89d46774 8 *
9 * These coded instructions, statements, and computer programs are the
bc44d920 10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
89d46774 12 * "LICENSE" which should have been included with this file. If this
bc44d920 13 * file is missing or damaged, see the license at "http://www.cups.org/".
89d46774 14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 *
17 * Contents:
18 *
19 * main() - Discover printers via SNMP.
20 * add_array() - Add a string to an array.
21 * add_cache() - Add a cached device...
b94498cf 22 * add_device_uri() - Add a device URI to the cache.
89d46774 23 * alarm_handler() - Handle alarm signals...
24 * asn1_decode_snmp() - Decode a SNMP packet.
25 * asn1_debug() - Decode an ASN1-encoded message.
26 * asn1_encode_snmp() - Encode a SNMP packet.
27 * asn1_get_integer() - Get an integer value.
28 * asn1_get_length() - Get a value length.
29 * asn1_get_oid() - Get an OID value.
30 * asn1_get_packed() - Get a packed integer value.
31 * asn1_get_string() - Get a string value.
32 * asn1_get_type() - Get a value type.
33 * asn1_set_integer() - Set an integer value.
34 * asn1_set_length() - Set a value length.
35 * asn1_set_oid() - Set an OID value.
36 * asn1_set_packed() - Set a packed integer value.
37 * asn1_size_integer() - Figure out the number of bytes needed for an
38 * integer value.
39 * asn1_size_length() - Figure out the number of bytes needed for a
40 * length value.
41 * asn1_size_oid() - Figure out the numebr of bytes needed for an
42 * OID value.
43 * asn1_size_packed() - Figure out the number of bytes needed for a
44 * packed integer value.
45 * compare_cache() - Compare two cache entries.
46 * debug_printf() - Display some debugging information.
47 * fix_make_model() - Fix common problems in the make-and-model
48 * string.
49 * free_array() - Free an array of strings.
50 * free_cache() - Free the array of cached devices.
51 * get_interface_addresses() - Get the broadcast address(es) associated
52 * with an interface.
53 * hex_debug() - Output hex debugging data...
d09495fa 54 * list_device() - List a device we found...
89d46774 55 * open_snmp_socket() - Open the SNMP broadcast socket.
56 * password_cb() - Handle authentication requests.
57 * probe_device() - Probe a device to discover whether it is a
58 * printer.
59 * read_snmp_conf() - Read the snmp.conf file.
60 * read_snmp_response() - Read and parse a SNMP response...
61 * run_time() - Return the total running time...
62 * scan_devices() - Scan for devices using SNMP.
63 * send_snmp_query() - Send an SNMP query packet.
64 * try_connect() - Try connecting on a port...
65 * update_cache() - Update a cached device...
66 */
67
68/*
69 * Include necessary headers.
70 */
71
89d46774 72#include <cups/http-private.h>
ed486911 73#include "backend-private.h"
89d46774 74#include <cups/array.h>
75#include <cups/file.h>
b94498cf 76#include <regex.h>
89d46774 77
78
79/*
80 * This backend implements SNMP printer discovery. It uses a broadcast-
b94498cf 81 * based approach to get SNMP response packets from potential printers,
82 * tries a mDNS lookup (Mac OS X only at present), a URI lookup based on
83 * the device description string, and finally a probe of port 9100
84 * (AppSocket) and 515 (LPD).
89d46774 85 *
86 * The current focus is on printers with internal network cards, although
87 * the code also works with many external print servers as well. Future
88 * versions will support scanning for vendor-specific SNMP OIDs and the
89 * new PWG Port Monitor MIB and not just the Host MIB OIDs.
90 *
91 * The backend reads the snmp.conf file from the CUPS_SERVERROOT directory
92 * which can contain comments, blank lines, or any number of the following
93 * directives:
94 *
95 * Address ip-address
96 * Address @LOCAL
97 * Address @IF(name)
98 * Community name
99 * DebugLevel N
b94498cf 100 * DeviceURI "regex pattern" uri
89d46774 101 * HostNameLookups on
102 * HostNameLookups off
b94498cf 103 * MaxRunTime N
89d46774 104 *
105 * The default is to use:
106 *
107 * Address @LOCAL
108 * Community public
109 * DebugLevel 0
110 * HostNameLookups off
b94498cf 111 * MaxRunTime 10
89d46774 112 *
113 * This backend is known to work with the following network printers and
114 * print servers:
115 *
116 * Axis OfficeBasic, 5400, 5600
117 * EPSON
118 * Genicom
119 * HP JetDirect
120 * Lexmark
121 * Sharp
122 * Tektronix
123 * Xerox
124 *
125 * It does not currently work with:
126 *
127 * DLink
128 * Linksys
129 * Netgear
130 * Okidata
131 *
132 * (for all of these, they do not support the Host MIB)
133 */
134
135/*
136 * Constants...
137 */
138
139#define SNMP_PORT 161 /* SNMP well-known port */
140#define SNMP_MAX_OID 64 /* Maximum number of OID numbers */
141#define SNMP_MAX_PACKET 1472 /* Maximum size of SNMP packet */
142#define SNMP_MAX_STRING 512 /* Maximum size of string */
143#define SNMP_VERSION_1 0 /* SNMPv1 */
144
145#define ASN1_END_OF_CONTENTS 0x00 /* End-of-contents */
146#define ASN1_BOOLEAN 0x01 /* BOOLEAN */
147#define ASN1_INTEGER 0x02 /* INTEGER or ENUMERATION */
148#define ASN1_BIT_STRING 0x03 /* BIT STRING */
149#define ASN1_OCTET_STRING 0x04 /* OCTET STRING */
150#define ASN1_NULL_VALUE 0x05 /* NULL VALUE */
151#define ASN1_OID 0x06 /* OBJECT IDENTIFIER */
152#define ASN1_SEQUENCE 0x30 /* SEQUENCE */
153#define ASN1_GET_REQUEST 0xa0 /* Get-Request-PDU */
154#define ASN1_GET_RESPONSE 0xa2 /* Get-Response-PDU */
155
156
157/*
158 * Types...
159 */
160
b94498cf 161typedef struct device_uri_s /**** DeviceURI values ****/
162{
163 regex_t re; /* Regular expression to match */
164 cups_array_t *uris; /* URIs */
165} device_uri_t;
166
89d46774 167typedef struct snmp_cache_s /**** SNMP scan cache ****/
168{
169 http_addr_t address; /* Address of device */
170 char *addrname, /* Name of device */
171 *uri, /* device-uri */
172 *id, /* device-id */
173 *make_and_model; /* device-make-and-model */
174} snmp_cache_t;
175
176typedef struct snmp_packet_s /**** SNMP packet ****/
177{
178 const char *error; /* Encode/decode error */
179 int version; /* Version number */
180 char community[SNMP_MAX_STRING];
181 /* Community name */
182 int request_type; /* Request type */
183 int request_id; /* request-id value */
184 int error_status; /* error-status value */
185 int error_index; /* error-index value */
186 int object_name[SNMP_MAX_OID];
187 /* object-name value */
188 int object_type; /* object-value type */
189 union
190 {
191 int boolean; /* Boolean value */
192 int integer; /* Integer value */
193 int oid[SNMP_MAX_OID]; /* OID value */
194 char string[SNMP_MAX_STRING];/* String value */
195 } object_value; /* object-value value */
196} snmp_packet_t;
197
198
d09495fa 199/*
200 * Private CUPS API to set the last error...
201 */
202
203extern void _cupsSetError(ipp_status_t status, const char *message);
204
205
89d46774 206/*
207 * Local functions...
208 */
209
210static char *add_array(cups_array_t *a, const char *s);
211static void add_cache(http_addr_t *addr, const char *addrname,
212 const char *uri, const char *id,
213 const char *make_and_model);
b94498cf 214static device_uri_t *add_device_uri(char *value);
89d46774 215static void alarm_handler(int sig);
216static int asn1_decode_snmp(unsigned char *buffer, size_t len,
217 snmp_packet_t *packet);
218static void asn1_debug(unsigned char *buffer, size_t len,
219 int indent);
220static int asn1_encode_snmp(unsigned char *buffer, size_t len,
221 snmp_packet_t *packet);
222static int asn1_get_integer(unsigned char **buffer,
223 unsigned char *bufend,
224 int length);
225static int asn1_get_oid(unsigned char **buffer,
226 unsigned char *bufend,
227 int length, int *oid, int oidsize);
228static int asn1_get_packed(unsigned char **buffer,
229 unsigned char *bufend);
230static char *asn1_get_string(unsigned char **buffer,
231 unsigned char *bufend,
232 int length, char *string,
233 int strsize);
234static int asn1_get_length(unsigned char **buffer,
235 unsigned char *bufend);
236static int asn1_get_type(unsigned char **buffer,
237 unsigned char *bufend);
238static void asn1_set_integer(unsigned char **buffer,
239 int integer);
240static void asn1_set_length(unsigned char **buffer,
241 int length);
242static void asn1_set_oid(unsigned char **buffer,
243 const int *oid);
244static void asn1_set_packed(unsigned char **buffer,
245 int integer);
246static int asn1_size_integer(int integer);
247static int asn1_size_length(int length);
248static int asn1_size_oid(const int *oid);
249static int asn1_size_packed(int integer);
250static int compare_cache(snmp_cache_t *a, snmp_cache_t *b);
251static void debug_printf(const char *format, ...);
252static void fix_make_model(char *make_model,
253 const char *old_make_model,
254 int make_model_size);
255static void free_array(cups_array_t *a);
256static void free_cache(void);
257static http_addrlist_t *get_interface_addresses(const char *ifname);
258static void hex_debug(unsigned char *buffer, size_t len);
d09495fa 259static void list_device(snmp_cache_t *cache);
89d46774 260static int open_snmp_socket(void);
261static const char *password_cb(const char *prompt);
262static void probe_device(snmp_cache_t *device);
263static void read_snmp_conf(const char *address);
264static void read_snmp_response(int fd);
265static double run_time(void);
266static void scan_devices(int fd);
267static void send_snmp_query(int fd, http_addr_t *addr, int version,
268 const char *community,
269 const unsigned request_id,
270 const int *oid);
271static int try_connect(http_addr_t *addr, const char *addrname,
272 int port);
273static void update_cache(snmp_cache_t *device, const char *uri,
274 const char *id, const char *make_model);
275
276
277/*
278 * Local globals...
279 */
280
281static cups_array_t *Addresses = NULL;
282static cups_array_t *Communities = NULL;
283static cups_array_t *Devices = NULL;
284static int DebugLevel = 0;
89d46774 285static int DeviceDescOID[] = { 1, 3, 6, 1, 2, 1, 25, 3,
286 2, 1, 3, 1, 0 };
89d46774 287static unsigned DeviceDescRequest;
b94498cf 288static int DeviceTypeOID[] = { 1, 3, 6, 1, 2, 1, 25, 3,
289 2, 1, 2, 1, 0 };
290static unsigned DeviceTypeRequest;
291static cups_array_t *DeviceURIs = NULL;
89d46774 292static int HostNameLookups = 0;
d09495fa 293static int MaxRunTime = 10;
89d46774 294static struct timeval StartTime;
295
296
297/*
298 * 'main()' - Discover printers via SNMP.
299 */
300
301int /* O - Exit status */
302main(int argc, /* I - Number of command-line arguments (6 or 7) */
303 char *argv[]) /* I - Command-line arguments */
304{
305 int fd; /* SNMP socket */
d09495fa 306#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
307 struct sigaction action; /* Actions for POSIX signals */
308#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
89d46774 309
310
311 /*
312 * Check command-line options...
313 */
314
315 if (argc > 2)
316 {
c0e1af83 317 fputs(_("Usage: snmp [host-or-ip-address]\n"), stderr);
89d46774 318 return (1);
319 }
320
321 /*
322 * Set the password callback for IPP operations...
323 */
324
325 cupsSetPasswordCB(password_cb);
326
d09495fa 327 /*
328 * Catch SIGALRM signals...
329 */
330
331#ifdef HAVE_SIGSET
332 sigset(SIGALRM, alarm_handler);
333#elif defined(HAVE_SIGACTION)
334 memset(&action, 0, sizeof(action));
335
336 sigemptyset(&action.sa_mask);
337 sigaddset(&action.sa_mask, SIGALRM);
338 action.sa_handler = alarm_handler;
339 sigaction(SIGALRM, &action, NULL);
340#else
341 signal(SIGALRM, alarm_handler);
342#endif /* HAVE_SIGSET */
343
89d46774 344 /*
345 * Open the SNMP socket...
346 */
347
348 if ((fd = open_snmp_socket()) < 0)
349 return (1);
350
351 /*
352 * Read the configuration file and any cache data...
353 */
354
355 read_snmp_conf(argv[1]);
356
357 Devices = cupsArrayNew((cups_array_func_t)compare_cache, NULL);
358
359 /*
360 * Scan for devices...
361 */
362
363 scan_devices(fd);
364
89d46774 365 /*
366 * Close, free, and return with no errors...
367 */
368
369 close(fd);
370
371 free_array(Addresses);
372 free_array(Communities);
373 free_cache();
374
375 return (0);
376}
377
378
379/*
380 * 'add_array()' - Add a string to an array.
381 */
382
383static char * /* O - New string */
384add_array(cups_array_t *a, /* I - Array */
385 const char *s) /* I - String to add */
386{
387 char *dups; /* New string */
388
389
390 dups = strdup(s);
391
392 cupsArrayAdd(a, dups);
393
394 return (dups);
395}
396
397
398/*
399 * 'add_cache()' - Add a cached device...
400 */
401
402static void
403add_cache(http_addr_t *addr, /* I - Device IP address */
404 const char *addrname, /* I - IP address or name string */
405 const char *uri, /* I - Device URI */
406 const char *id, /* I - 1284 device ID */
407 const char *make_and_model) /* I - Make and model */
408{
409 snmp_cache_t *temp; /* New device entry */
410
411
412 debug_printf("DEBUG: add_cache(addr=%p, addrname=\"%s\", uri=\"%s\", "
413 "id=\"%s\", make_and_model=\"%s\")\n",
d09495fa 414 addr, addrname, uri ? uri : "(null)", id ? id : "(null)",
89d46774 415 make_and_model ? make_and_model : "(null)");
416
417 temp = calloc(1, sizeof(snmp_cache_t));
418 memcpy(&(temp->address), addr, sizeof(temp->address));
419
420 temp->addrname = strdup(addrname);
421
422 if (uri)
423 temp->uri = strdup(uri);
424
425 if (id)
426 temp->id = strdup(id);
427
428 if (make_and_model)
429 temp->make_and_model = strdup(make_and_model);
430
431 cupsArrayAdd(Devices, temp);
d09495fa 432
433 if (uri)
434 list_device(temp);
89d46774 435}
436
437
b94498cf 438/*
439 * 'add_device_uri()' - Add a device URI to the cache.
440 *
441 * The value string is modified (chopped up) as needed.
442 */
443
444static device_uri_t * /* O - Device URI */
445add_device_uri(char *value) /* I - Value from snmp.conf */
446{
447 device_uri_t *device_uri; /* Device URI */
448 char *start; /* Start of value */
449
450
451 /*
452 * Allocate memory as needed...
453 */
454
455 if (!DeviceURIs)
456 DeviceURIs = cupsArrayNew(NULL, NULL);
457
458 if (!DeviceURIs)
459 return (NULL);
460
461 if ((device_uri = calloc(1, sizeof(device_uri_t))) == NULL)
462 return (NULL);
463
464 if ((device_uri->uris = cupsArrayNew(NULL, NULL)) == NULL)
465 {
466 free(device_uri);
467 return (NULL);
468 }
469
470 /*
471 * Scan the value string for the regular expression and URI(s)...
472 */
473
474 value ++; /* Skip leading " */
475
476 for (start = value; *value && *value != '\"'; value ++)
477 if (*value == '\\' && value[1])
478 _cups_strcpy(value, value + 1);
479
480 if (!*value)
481 {
482 fputs("ERROR: Missing end quote for DeviceURI!\n", stderr);
483
484 cupsArrayDelete(device_uri->uris);
485 free(device_uri);
486
487 return (NULL);
488 }
489
490 *value++ = '\0';
491
492 if (regcomp(&(device_uri->re), start, REG_EXTENDED | REG_ICASE))
493 {
494 fputs("ERROR: Bad regular expression for DeviceURI!\n", stderr);
495
496 cupsArrayDelete(device_uri->uris);
497 free(device_uri);
498
499 return (NULL);
500 }
501
502 while (*value)
503 {
504 while (isspace(*value & 255))
505 value ++;
506
507 if (!*value)
508 break;
509
510 for (start = value; *value && !isspace(*value & 255); value ++);
511
512 if (*value)
513 *value++ = '\0';
514
515 cupsArrayAdd(device_uri->uris, strdup(start));
516 }
517
518 /*
519 * Add the device URI to the list and return it...
520 */
521
522 cupsArrayAdd(DeviceURIs, device_uri);
523
524 return (device_uri);
525}
526
527
89d46774 528/*
529 * 'alarm_handler()' - Handle alarm signals...
530 */
531
532static void
533alarm_handler(int sig) /* I - Signal number */
534{
535 /*
536 * Do nothing...
537 */
538
539 (void)sig;
540
d09495fa 541#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
542 signal(SIGALRM, alarm_handler);
543#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
544
89d46774 545 if (DebugLevel)
546 write(2, "DEBUG: ALARM!\n", 14);
547}
548
549
550/*
551 * 'asn1_decode_snmp()' - Decode a SNMP packet.
552 */
553
554static int /* O - 0 on success, -1 on error */
555asn1_decode_snmp(unsigned char *buffer, /* I - Buffer */
556 size_t len, /* I - Size of buffer */
557 snmp_packet_t *packet) /* I - SNMP packet */
558{
559 unsigned char *bufptr, /* Pointer into the data */
560 *bufend; /* End of data */
561 int length; /* Length of value */
562
563
564 /*
565 * Initialize the decoding...
566 */
567
568 memset(packet, 0, sizeof(snmp_packet_t));
569
570 bufptr = buffer;
571 bufend = buffer + len;
572
573 if (asn1_get_type(&bufptr, bufend) != ASN1_SEQUENCE)
574 packet->error = "Packet does not start with SEQUENCE";
575 else if (asn1_get_length(&bufptr, bufend) == 0)
576 packet->error = "SEQUENCE uses indefinite length";
577 else if (asn1_get_type(&bufptr, bufend) != ASN1_INTEGER)
578 packet->error = "No version number";
579 else if ((length = asn1_get_length(&bufptr, bufend)) == 0)
580 packet->error = "Version uses indefinite length";
581 else if ((packet->version = asn1_get_integer(&bufptr, bufend, length))
582 != SNMP_VERSION_1)
583 packet->error = "Bad SNMP version number";
584 else if (asn1_get_type(&bufptr, bufend) != ASN1_OCTET_STRING)
585 packet->error = "No community name";
586 else if ((length = asn1_get_length(&bufptr, bufend)) == 0)
587 packet->error = "Community name uses indefinite length";
588 else
589 {
590 asn1_get_string(&bufptr, bufend, length, packet->community,
591 sizeof(packet->community));
592
593 if ((packet->request_type = asn1_get_type(&bufptr, bufend))
594 != ASN1_GET_RESPONSE)
595 packet->error = "Packet does not contain a Get-Response-PDU";
596 else if (asn1_get_length(&bufptr, bufend) == 0)
597 packet->error = "Get-Response-PDU uses indefinite length";
598 else if (asn1_get_type(&bufptr, bufend) != ASN1_INTEGER)
599 packet->error = "No request-id";
600 else if ((length = asn1_get_length(&bufptr, bufend)) == 0)
601 packet->error = "request-id uses indefinite length";
602 else
603 {
604 packet->request_id = asn1_get_integer(&bufptr, bufend, length);
605
606 if (asn1_get_type(&bufptr, bufend) != ASN1_INTEGER)
607 packet->error = "No error-status";
608 else if ((length = asn1_get_length(&bufptr, bufend)) == 0)
609 packet->error = "error-status uses indefinite length";
610 else
611 {
612 packet->error_status = asn1_get_integer(&bufptr, bufend, length);
613
614 if (asn1_get_type(&bufptr, bufend) != ASN1_INTEGER)
615 packet->error = "No error-index";
616 else if ((length = asn1_get_length(&bufptr, bufend)) == 0)
617 packet->error = "error-index uses indefinite length";
618 else
619 {
620 packet->error_index = asn1_get_integer(&bufptr, bufend, length);
621
622 if (asn1_get_type(&bufptr, bufend) != ASN1_SEQUENCE)
623 packet->error = "No variable-bindings SEQUENCE";
624 else if (asn1_get_length(&bufptr, bufend) == 0)
625 packet->error = "variable-bindings uses indefinite length";
626 else if (asn1_get_type(&bufptr, bufend) != ASN1_SEQUENCE)
627 packet->error = "No VarBind SEQUENCE";
628 else if (asn1_get_length(&bufptr, bufend) == 0)
629 packet->error = "VarBind uses indefinite length";
630 else if (asn1_get_type(&bufptr, bufend) != ASN1_OID)
631 packet->error = "No name OID";
632 else if ((length = asn1_get_length(&bufptr, bufend)) == 0)
633 packet->error = "Name OID uses indefinite length";
634 else
635 {
636 asn1_get_oid(&bufptr, bufend, length, packet->object_name,
637 SNMP_MAX_OID);
638
639 packet->object_type = asn1_get_type(&bufptr, bufend);
640
641 if ((length = asn1_get_length(&bufptr, bufend)) == 0 &&
642 packet->object_type != ASN1_NULL_VALUE &&
643 packet->object_type != ASN1_OCTET_STRING)
644 packet->error = "Value uses indefinite length";
645 else
646 {
647 switch (packet->object_type)
648 {
649 case ASN1_BOOLEAN :
650 packet->object_value.boolean =
651 asn1_get_integer(&bufptr, bufend, length);
652 break;
653
654 case ASN1_INTEGER :
655 packet->object_value.integer =
656 asn1_get_integer(&bufptr, bufend, length);
657 break;
658
659 case ASN1_NULL_VALUE :
660 break;
661
662 case ASN1_OCTET_STRING :
663 asn1_get_string(&bufptr, bufend, length,
664 packet->object_value.string,
665 SNMP_MAX_STRING);
666 break;
667
668 case ASN1_OID :
669 asn1_get_oid(&bufptr, bufend, length,
670 packet->object_value.oid, SNMP_MAX_OID);
671 break;
672
673 default :
674 packet->error = "Unsupported value type";
675 break;
676 }
677 }
678 }
679 }
680 }
681 }
682 }
683
684 return (packet->error ? -1 : 0);
685}
686
687
688/*
689 * 'asn1_debug()' - Decode an ASN1-encoded message.
690 */
691
692static void
693asn1_debug(unsigned char *buffer, /* I - Buffer */
694 size_t len, /* I - Length of buffer */
695 int indent) /* I - Indentation */
696{
697 int i; /* Looping var */
698 unsigned char *bufend; /* End of buffer */
699 int integer; /* Number value */
700 int oid[SNMP_MAX_OID]; /* OID value */
701 char string[SNMP_MAX_STRING];/* String value */
702 unsigned char value_type; /* Type of value */
703 int value_length; /* Length of value */
704
705
706 bufend = buffer + len;
707
708 while (buffer < bufend)
709 {
710 /*
711 * Get value type...
712 */
713
714 value_type = asn1_get_type(&buffer, bufend);
715 value_length = asn1_get_length(&buffer, bufend);
716
717 switch (value_type)
718 {
719 case ASN1_BOOLEAN :
720 integer = asn1_get_integer(&buffer, bufend, value_length);
721
722 fprintf(stderr, "DEBUG: %*sBOOLEAN %d bytes %d\n", indent, "",
723 value_length, integer);
724 break;
725
726 case ASN1_INTEGER :
727 integer = asn1_get_integer(&buffer, bufend, value_length);
728
729 fprintf(stderr, "DEBUG: %*sINTEGER %d bytes %d\n", indent, "",
730 value_length, integer);
731 break;
732
733 case ASN1_OCTET_STRING :
734 fprintf(stderr, "DEBUG: %*sOCTET STRING %d bytes \"%s\"\n", indent, "",
735 value_length, asn1_get_string(&buffer, bufend,
736 value_length, string,
737 sizeof(string)));
738 break;
739
740 case ASN1_NULL_VALUE :
741 fprintf(stderr, "DEBUG: %*sNULL VALUE %d bytes\n", indent, "",
742 value_length);
743
744 buffer += value_length;
745 break;
746
747 case ASN1_OID :
748 asn1_get_oid(&buffer, bufend, value_length, oid, SNMP_MAX_OID);
749
750 fprintf(stderr, "DEBUG: %*sOID %d bytes ", indent, "",
751 value_length);
752 for (i = 0; oid[i]; i ++)
753 fprintf(stderr, ".%d", oid[i]);
754 putc('\n', stderr);
755 break;
756
757 case ASN1_SEQUENCE :
758 fprintf(stderr, "DEBUG: %*sSEQUENCE %d bytes\n", indent, "",
759 value_length);
760 asn1_debug(buffer, value_length, indent + 4);
761
762 buffer += value_length;
763 break;
764
765 case ASN1_GET_REQUEST :
766 fprintf(stderr, "DEBUG: %*sGet-Request-PDU %d bytes\n", indent, "",
767 value_length);
768 asn1_debug(buffer, value_length, indent + 4);
769
770 buffer += value_length;
771 break;
772
773 case ASN1_GET_RESPONSE :
774 fprintf(stderr, "DEBUG: %*sGet-Response-PDU %d bytes\n", indent, "",
775 value_length);
776 asn1_debug(buffer, value_length, indent + 4);
777
778 buffer += value_length;
779 break;
780
781 default :
782 fprintf(stderr, "DEBUG: %*sUNKNOWN(%x) %d bytes\n", indent, "",
783 value_type, value_length);
784
785 buffer += value_length;
786 break;
787 }
788 }
789}
790
791
792/*
793 * 'asn1_encode_snmp()' - Encode a SNMP packet.
794 */
795
796static int /* O - Length on success, -1 on error */
797asn1_encode_snmp(unsigned char *buffer, /* I - Buffer */
798 size_t bufsize, /* I - Size of buffer */
799 snmp_packet_t *packet) /* I - SNMP packet */
800{
801 unsigned char *bufptr; /* Pointer into buffer */
802 int total, /* Total length */
803 msglen, /* Length of entire message */
804 commlen, /* Length of community string */
805 reqlen, /* Length of request */
806 listlen, /* Length of variable list */
807 varlen, /* Length of variable */
808 namelen, /* Length of object name OID */
809 valuelen; /* Length of object value */
810
811
812 /*
813 * Get the lengths of the community string, OID, and message...
814 */
815
816 namelen = asn1_size_oid(packet->object_name);
817
818 switch (packet->object_type)
819 {
820 case ASN1_NULL_VALUE :
821 valuelen = 0;
822 break;
823
824 case ASN1_BOOLEAN :
825 valuelen = asn1_size_integer(packet->object_value.boolean);
826 break;
827
828 case ASN1_INTEGER :
829 valuelen = asn1_size_integer(packet->object_value.integer);
830 break;
831
832 case ASN1_OCTET_STRING :
833 valuelen = strlen(packet->object_value.string);
834 break;
835
836 case ASN1_OID :
837 valuelen = asn1_size_oid(packet->object_value.oid);
838 break;
839
840 default :
841 packet->error = "Unknown object type";
842 return (-1);
843 }
844
845 varlen = 1 + asn1_size_length(namelen) + namelen +
846 1 + asn1_size_length(valuelen) + valuelen;
847 listlen = 1 + asn1_size_length(varlen) + varlen;
848 reqlen = 2 + asn1_size_integer(packet->request_id) +
849 2 + asn1_size_integer(packet->error_status) +
850 2 + asn1_size_integer(packet->error_index) +
851 1 + asn1_size_length(listlen) + listlen;
852 commlen = strlen(packet->community);
853 msglen = 2 + asn1_size_integer(packet->version) +
854 1 + asn1_size_length(commlen) + commlen +
855 1 + asn1_size_length(reqlen) + reqlen;
856 total = 1 + asn1_size_length(msglen) + msglen;
857
858 if (total > bufsize)
859 {
860 packet->error = "Message too large for buffer";
861 return (-1);
862 }
863
864 /*
865 * Then format the message...
866 */
867
868 bufptr = buffer;
869
870 *bufptr++ = ASN1_SEQUENCE; /* SNMPv1 message header */
871 asn1_set_length(&bufptr, msglen);
872
873 asn1_set_integer(&bufptr, packet->version);
874 /* version */
875
876 *bufptr++ = ASN1_OCTET_STRING; /* community */
877 asn1_set_length(&bufptr, commlen);
878 memcpy(bufptr, packet->community, commlen);
879 bufptr += commlen;
880
881 *bufptr++ = packet->request_type; /* Get-Request-PDU */
882 asn1_set_length(&bufptr, reqlen);
883
884 asn1_set_integer(&bufptr, packet->request_id);
885
886 asn1_set_integer(&bufptr, packet->error_status);
887
888 asn1_set_integer(&bufptr, packet->error_index);
889
890 *bufptr++ = ASN1_SEQUENCE; /* variable-bindings */
891 asn1_set_length(&bufptr, listlen);
892
893 *bufptr++ = ASN1_SEQUENCE; /* variable */
894 asn1_set_length(&bufptr, varlen);
895
896 asn1_set_oid(&bufptr, packet->object_name);
897 /* ObjectName */
898
899 switch (packet->object_type)
900 {
901 case ASN1_NULL_VALUE :
902 *bufptr++ = ASN1_NULL_VALUE; /* ObjectValue */
903 *bufptr++ = 0; /* Length */
904 break;
905
906 case ASN1_BOOLEAN :
907 asn1_set_integer(&bufptr, packet->object_value.boolean);
908 break;
909
910 case ASN1_INTEGER :
911 asn1_set_integer(&bufptr, packet->object_value.integer);
912 break;
913
914 case ASN1_OCTET_STRING :
915 *bufptr++ = ASN1_OCTET_STRING;
916 asn1_set_length(&bufptr, valuelen);
917 memcpy(bufptr, packet->object_value.string, valuelen);
918 bufptr += valuelen;
919 break;
920
921 case ASN1_OID :
922 asn1_set_oid(&bufptr, packet->object_value.oid);
923 break;
924 }
925
926 return (bufptr - buffer);
927}
928
929
930/*
931 * 'asn1_get_integer()' - Get an integer value.
932 */
933
934static int /* O - Integer value */
935asn1_get_integer(
936 unsigned char **buffer, /* IO - Pointer in buffer */
937 unsigned char *bufend, /* I - End of buffer */
938 int length) /* I - Length of value */
939{
940 int value; /* Integer value */
941
942
943 for (value = 0;
944 length > 0 && *buffer < bufend;
945 length --, (*buffer) ++)
946 value = (value << 8) | **buffer;
947
948 return (value);
949}
950
951
952/*
953 * 'asn1_get_length()' - Get a value length.
954 */
955
956static int /* O - Length */
957asn1_get_length(unsigned char **buffer, /* IO - Pointer in buffer */
958 unsigned char *bufend) /* I - End of buffer */
959{
960 int length; /* Length */
961
962
963 length = **buffer;
964 (*buffer) ++;
965
966 if (length & 128)
967 length = asn1_get_integer(buffer, bufend, length & 127);
968
969 return (length);
970}
971
972
973/*
974 * 'asn1_get_oid()' - Get an OID value.
975 */
976
977static int /* O - Last OID number */
978asn1_get_oid(
979 unsigned char **buffer, /* IO - Pointer in buffer */
980 unsigned char *bufend, /* I - End of buffer */
981 int length, /* I - Length of value */
982 int *oid, /* I - OID buffer */
983 int oidsize) /* I - Size of OID buffer */
984{
985 unsigned char *valend; /* End of value */
986 int *oidend; /* End of OID buffer */
987 int number; /* OID number */
988
989
990 valend = *buffer + length;
991 oidend = oid + oidsize - 1;
992
993 if (valend > bufend)
994 valend = bufend;
995
996 number = asn1_get_packed(buffer, bufend);
997
998 if (number < 80)
999 {
1000 *oid++ = number / 40;
1001 number = number % 40;
1002 *oid++ = number;
1003 }
1004 else
1005 {
1006 *oid++ = 2;
1007 number -= 80;
1008 *oid++ = number;
1009 }
1010
1011 while (*buffer < valend)
1012 {
1013 number = asn1_get_packed(buffer, bufend);
1014
1015 if (oid < oidend)
1016 *oid++ = number;
1017 }
1018
1019 *oid = 0;
1020
1021 return (number);
1022}
1023
1024
1025/*
1026 * 'asn1_get_packed()' - Get a packed integer value.
1027 */
1028
1029static int /* O - Value */
1030asn1_get_packed(
1031 unsigned char **buffer, /* IO - Pointer in buffer */
1032 unsigned char *bufend) /* I - End of buffer */
1033{
1034 int value; /* Value */
1035
1036
1037 value = 0;
1038
1039 while ((**buffer & 128) && *buffer < bufend)
1040 {
1041 value = (value << 7) | (**buffer & 127);
1042 (*buffer) ++;
1043 }
1044
1045 if (*buffer < bufend)
1046 {
1047 value = (value << 7) | **buffer;
1048 (*buffer) ++;
1049 }
1050
1051 return (value);
1052}
1053
1054
1055/*
1056 * 'asn1_get_string()' - Get a string value.
1057 */
1058
1059static char * /* O - String */
1060asn1_get_string(
1061 unsigned char **buffer, /* IO - Pointer in buffer */
1062 unsigned char *bufend, /* I - End of buffer */
1063 int length, /* I - Value length */
1064 char *string, /* I - String buffer */
1065 int strsize) /* I - String buffer size */
1066{
1067 if (length < strsize)
1068 {
1069 memcpy(string, *buffer, length);
1070 string[length] = '\0';
1071 }
1072 else
1073 {
1074 memcpy(string, buffer, strsize - 1);
1075 string[strsize - 1] = '\0';
1076 }
1077
1078 (*buffer) += length;
1079
1080 return (string);
1081}
1082
1083
1084/*
1085 * 'asn1_get_type()' - Get a value type.
1086 */
1087
1088static int /* O - Type */
1089asn1_get_type(unsigned char **buffer, /* IO - Pointer in buffer */
1090 unsigned char *bufend) /* I - End of buffer */
1091{
1092 int type; /* Type */
1093
1094
1095 type = **buffer;
1096 (*buffer) ++;
1097
1098 if ((type & 31) == 31)
1099 type = asn1_get_packed(buffer, bufend);
1100
1101 return (type);
1102}
1103
1104
1105/*
1106 * 'asn1_set_integer()' - Set an integer value.
1107 */
1108
1109static void
1110asn1_set_integer(unsigned char **buffer,/* IO - Pointer in buffer */
1111 int integer) /* I - Integer value */
1112{
1113 **buffer = ASN1_INTEGER;
1114 (*buffer) ++;
1115
1116 if (integer > 0x7fffff || integer < -0x800000)
1117 {
1118 **buffer = 4;
1119 (*buffer) ++;
1120 **buffer = integer >> 24;
1121 (*buffer) ++;
1122 **buffer = integer >> 16;
1123 (*buffer) ++;
1124 **buffer = integer >> 8;
1125 (*buffer) ++;
1126 **buffer = integer;
1127 (*buffer) ++;
1128 }
1129 else if (integer > 0x7fff || integer < -0x8000)
1130 {
1131 **buffer = 3;
1132 (*buffer) ++;
1133 **buffer = integer >> 16;
1134 (*buffer) ++;
1135 **buffer = integer >> 8;
1136 (*buffer) ++;
1137 **buffer = integer;
1138 (*buffer) ++;
1139 }
1140 else if (integer > 0x7f || integer < -0x80)
1141 {
1142 **buffer = 2;
1143 (*buffer) ++;
1144 **buffer = integer >> 8;
1145 (*buffer) ++;
1146 **buffer = integer;
1147 (*buffer) ++;
1148 }
1149 else
1150 {
1151 **buffer = 1;
1152 (*buffer) ++;
1153 **buffer = integer;
1154 (*buffer) ++;
1155 }
1156}
1157
1158
1159/*
1160 * 'asn1_set_length()' - Set a value length.
1161 */
1162
1163static void
1164asn1_set_length(unsigned char **buffer, /* IO - Pointer in buffer */
1165 int length) /* I - Length value */
1166{
1167 if (length > 255)
1168 {
1169 **buffer = 0x82; /* 2-byte length */
1170 (*buffer) ++;
1171 **buffer = length >> 8;
1172 (*buffer) ++;
1173 **buffer = length;
1174 (*buffer) ++;
1175 }
1176 else if (length > 127)
1177 {
1178 **buffer = 0x81; /* 1-byte length */
1179 (*buffer) ++;
1180 **buffer = length;
1181 (*buffer) ++;
1182 }
1183 else
1184 {
1185 **buffer = length; /* Length */
1186 (*buffer) ++;
1187 }
1188}
1189
1190
1191/*
1192 * 'asn1_set_oid()' - Set an OID value.
1193 */
1194
1195static void
1196asn1_set_oid(unsigned char **buffer, /* IO - Pointer in buffer */
1197 const int *oid) /* I - OID value */
1198{
1199 **buffer = ASN1_OID;
1200 (*buffer) ++;
1201
1202 asn1_set_length(buffer, asn1_size_oid(oid));
1203
1204 asn1_set_packed(buffer, oid[0] * 40 + oid[1]);
1205
1206 for (oid += 2; *oid; oid ++)
1207 asn1_set_packed(buffer, *oid);
1208}
1209
1210
1211/*
1212 * 'asn1_set_packed()' - Set a packed integer value.
1213 */
1214
1215static void
1216asn1_set_packed(unsigned char **buffer, /* IO - Pointer in buffer */
1217 int integer) /* I - Integer value */
1218{
1219 if (integer > 0xfffffff)
1220 {
411affcf 1221 **buffer = (integer >> 28) & 0x7f;
89d46774 1222 (*buffer) ++;
1223 }
1224
1225 if (integer > 0x1fffff)
1226 {
1227 **buffer = (integer >> 21) & 0x7f;
1228 (*buffer) ++;
1229 }
1230
1231 if (integer > 0x3fff)
1232 {
1233 **buffer = (integer >> 14) & 0x7f;
1234 (*buffer) ++;
1235 }
1236
1237 if (integer > 0x7f)
1238 {
1239 **buffer = (integer >> 7) & 0x7f;
1240 (*buffer) ++;
1241 }
1242
1243 **buffer = integer & 0x7f;
1244 (*buffer) ++;
1245}
1246
1247/*
1248 * 'asn1_size_integer()' - Figure out the number of bytes needed for an
1249 * integer value.
1250 */
1251
1252static int /* O - Size in bytes */
1253asn1_size_integer(int integer) /* I - Integer value */
1254{
1255 if (integer > 0x7fffff || integer < -0x800000)
1256 return (4);
1257 else if (integer > 0x7fff || integer < -0x8000)
1258 return (3);
1259 else if (integer > 0x7f || integer < -0x80)
1260 return (2);
1261 else
1262 return (1);
1263}
1264
1265
1266/*
1267 * 'asn1_size_length()' - Figure out the number of bytes needed for a
1268 * length value.
1269 */
1270
1271static int /* O - Size in bytes */
1272asn1_size_length(int length) /* I - Length value */
1273{
1274 if (length > 0xff)
1275 return (3);
1276 else if (length > 0x7f)
1277 return (2);
1278 else
1279 return (1);
1280}
1281
1282
1283/*
1284 * 'asn1_size_oid()' - Figure out the numebr of bytes needed for an
1285 * OID value.
1286 */
1287
1288static int /* O - Size in bytes */
1289asn1_size_oid(const int *oid) /* I - OID value */
1290{
1291 int length; /* Length of value */
1292
1293
1294 for (length = asn1_size_packed(oid[0] * 40 + oid[1]), oid += 2; *oid; oid ++)
1295 length += asn1_size_packed(*oid);
1296
1297 return (length);
1298}
1299
1300
1301/*
1302 * 'asn1_size_packed()' - Figure out the number of bytes needed for a
1303 * packed integer value.
1304 */
1305
1306static int /* O - Size in bytes */
1307asn1_size_packed(int integer) /* I - Integer value */
1308{
1309 if (integer > 0xfffffff)
1310 return (5);
1311 else if (integer > 0x1fffff)
1312 return (4);
1313 else if (integer > 0x3fff)
1314 return (3);
1315 else if (integer > 0x7f)
1316 return (2);
1317 else
1318 return (1);
1319}
1320
1321
1322/*
1323 * 'compare_cache()' - Compare two cache entries.
1324 */
1325
1326static int /* O - Result of comparison */
1327compare_cache(snmp_cache_t *a, /* I - First cache entry */
1328 snmp_cache_t *b) /* I - Second cache entry */
1329{
8ca02f3c 1330 return (strcasecmp(a->addrname, b->addrname));
89d46774 1331}
1332
1333
1334/*
1335 * 'debug_printf()' - Display some debugging information.
1336 */
1337
1338static void
1339debug_printf(const char *format, /* I - Printf-style format string */
1340 ...) /* I - Additional arguments as needed */
1341{
1342 va_list ap; /* Pointer to arguments */
1343
1344
1345 if (!DebugLevel)
1346 return;
1347
1348 va_start(ap, format);
1349 vfprintf(stderr, format, ap);
1350 va_end(ap);
1351}
1352
1353
1354/*
1355 * 'fix_make_model()' - Fix common problems in the make-and-model string.
1356 */
1357
1358static void
1359fix_make_model(
1360 char *make_model, /* I - New make-and-model string */
1361 const char *old_make_model, /* I - Old make-and-model string */
1362 int make_model_size) /* I - Size of new string buffer */
1363{
a74454a7 1364 char *mmptr; /* Pointer into make-and-model string */
89d46774 1365
1366
1367 /*
1368 * Fix some common problems with the make-and-model string so
1369 * that printer driver detection works better...
1370 */
1371
1372 if (!strncasecmp(old_make_model, "Hewlett-Packard", 15))
1373 {
1374 /*
1375 * Strip leading Hewlett-Packard and hp prefixes and replace
1376 * with a single HP manufacturer prefix...
1377 */
1378
a74454a7 1379 mmptr = (char *)old_make_model + 15;
89d46774 1380
1381 while (isspace(*mmptr & 255))
1382 mmptr ++;
1383
1384 if (!strncasecmp(mmptr, "hp", 2))
1385 {
1386 mmptr += 2;
1387
1388 while (isspace(*mmptr & 255))
1389 mmptr ++;
1390 }
1391
1392 make_model[0] = 'H';
1393 make_model[1] = 'P';
1394 make_model[2] = ' ';
1395 strlcpy(make_model + 3, mmptr, make_model_size - 3);
1396 }
1397 else if (!strncasecmp(old_make_model, "deskjet", 7))
1398 snprintf(make_model, make_model_size, "HP DeskJet%s", old_make_model + 7);
b86bc4cf 1399 else if (!strncasecmp(old_make_model, "officejet", 9))
1400 snprintf(make_model, make_model_size, "HP OfficeJet%s", old_make_model + 9);
89d46774 1401 else if (!strncasecmp(old_make_model, "stylus_pro_", 11))
1402 snprintf(make_model, make_model_size, "EPSON Stylus Pro %s",
1403 old_make_model + 11);
1404 else
1405 strlcpy(make_model, old_make_model, make_model_size);
1406
1407 if ((mmptr = strstr(make_model, ", Inc.,")) != NULL)
1408 {
1409 /*
1410 * Strip inc. from name, e.g. "Tektronix, Inc., Phaser 560"
1411 * becomes "Tektronix Phaser 560"...
1412 */
1413
a74454a7 1414 _cups_strcpy(mmptr, mmptr + 7);
1415 }
1416
d09495fa 1417 if ((mmptr = strstr(make_model, " Network")) != NULL)
1418 {
1419 /*
1420 * Drop unnecessary informational text, e.g. "Xerox DocuPrint N2025
1421 * Network LaserJet - 2.12" becomes "Xerox DocuPrint N2025"...
1422 */
1423
1424 *mmptr = '\0';
1425 }
1426
a74454a7 1427 if ((mmptr = strchr(make_model, ',')) != NULL)
1428 {
1429 /*
1430 * Drop anything after a trailing comma...
1431 */
1432
1433 *mmptr = '\0';
89d46774 1434 }
1435}
1436
1437
1438/*
1439 * 'free_array()' - Free an array of strings.
1440 */
1441
1442static void
1443free_array(cups_array_t *a) /* I - Array */
1444{
1445 char *s; /* Current string */
1446
1447
1448 for (s = (char *)cupsArrayFirst(a); s; s = (char *)cupsArrayNext(a))
1449 free(s);
1450
1451 cupsArrayDelete(a);
1452}
1453
1454
1455/*
1456 * 'free_cache()' - Free the array of cached devices.
1457 */
1458
1459static void
1460free_cache(void)
1461{
1462 snmp_cache_t *cache; /* Cached device */
1463
1464
1465 for (cache = (snmp_cache_t *)cupsArrayFirst(Devices);
1466 cache;
1467 cache = (snmp_cache_t *)cupsArrayNext(Devices))
1468 {
1469 free(cache->addrname);
1470
1471 if (cache->uri)
1472 free(cache->uri);
1473
1474 if (cache->id)
1475 free(cache->id);
1476
1477 if (cache->make_and_model)
1478 free(cache->make_and_model);
1479
1480 free(cache);
1481 }
1482
1483 cupsArrayDelete(Devices);
1484 Devices = NULL;
1485}
1486
1487
1488/*
1489 * 'get_interface_addresses()' - Get the broadcast address(es) associated
1490 * with an interface.
1491 */
1492
1493static http_addrlist_t * /* O - List of addresses */
1494get_interface_addresses(
1495 const char *ifname) /* I - Interface name */
1496{
1497 struct ifaddrs *addrs, /* Interface address list */
1498 *addr; /* Current interface address */
1499 http_addrlist_t *first, /* First address in list */
1500 *last, /* Last address in list */
1501 *current; /* Current address */
1502
1503
1504 if (getifaddrs(&addrs) < 0)
1505 return (NULL);
1506
1507 for (addr = addrs, first = NULL, last = NULL; addr; addr = addr->ifa_next)
1508 if ((addr->ifa_flags & IFF_BROADCAST) && addr->ifa_broadaddr &&
1509 addr->ifa_broadaddr->sa_family == AF_INET &&
1510 (!ifname || !strcmp(ifname, addr->ifa_name)))
1511 {
1512 current = calloc(1, sizeof(http_addrlist_t));
1513
1514 memcpy(&(current->addr), addr->ifa_broadaddr,
1515 sizeof(struct sockaddr_in));
1516
1517 if (!last)
1518 first = current;
1519 else
1520 last->next = current;
1521
1522 last = current;
1523 }
1524
1525 freeifaddrs(addrs);
1526
1527 return (first);
1528}
1529
1530
1531/*
1532 * 'hex_debug()' - Output hex debugging data...
1533 */
1534
1535static void
1536hex_debug(unsigned char *buffer, /* I - Buffer */
1537 size_t len) /* I - Number of bytes */
1538{
1539 int col; /* Current column */
1540
1541
1542 fputs("DEBUG: Hex dump of packet:\n", stderr);
1543
1544 for (col = 0; len > 0; col ++, buffer ++, len --)
1545 {
1546 if ((col & 15) == 0)
1547 fprintf(stderr, "DEBUG: %04X ", col);
1548
1549 fprintf(stderr, " %02X", *buffer);
1550
1551 if ((col & 15) == 15)
1552 putc('\n', stderr);
1553 }
1554
1555 if (col & 15)
1556 putc('\n', stderr);
1557}
1558
1559
1560/*
d09495fa 1561 * 'list_device()' - List a device we found...
89d46774 1562 */
1563
1564static void
d09495fa 1565list_device(snmp_cache_t *cache) /* I - Cached device */
89d46774 1566{
d09495fa 1567 if (cache->uri)
1568 printf("network %s \"%s\" \"%s %s\" \"%s\"\n",
1569 cache->uri,
1570 cache->make_and_model ? cache->make_and_model : "Unknown",
1571 cache->make_and_model ? cache->make_and_model : "Unknown",
1572 cache->addrname, cache->id ? cache->id : "");
89d46774 1573}
1574
1575
1576/*
1577 * 'open_snmp_socket()' - Open the SNMP broadcast socket.
1578 */
1579
1580static int /* O - SNMP socket file descriptor */
1581open_snmp_socket(void)
1582{
1583 int fd; /* SNMP socket file descriptor */
1584 int val; /* Socket option value */
1585
1586
1587 /*
1588 * Create the SNMP socket...
1589 */
1590
1591 if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1592 {
1593 fprintf(stderr, "ERROR: Unable to create SNMP socket - %s\n",
1594 strerror(errno));
1595
1596 return (-1);
1597 }
1598
1599 /*
1600 * Set the "broadcast" flag...
1601 */
1602
1603 val = 1;
1604
1605 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)))
1606 {
1607 fprintf(stderr, "ERROR: Unable to set broadcast mode - %s\n",
1608 strerror(errno));
1609
1610 close(fd);
1611
1612 return (-1);
1613 }
1614
1615 return (fd);
1616}
1617
1618
1619/*
1620 * 'password_cb()' - Handle authentication requests.
1621 *
1622 * All we do right now is return NULL, indicating that no authentication
1623 * is possible.
1624 */
1625
1626static const char * /* O - Password (NULL) */
1627password_cb(const char *prompt) /* I - Prompt message */
1628{
1629 (void)prompt; /* Anti-compiler-warning-code */
1630
1631 return (NULL);
1632}
1633
1634
1635/*
1636 * 'probe_device()' - Probe a device to discover whether it is a printer.
1637 *
1638 * TODO: Try using the Port Monitor MIB to discover the correct protocol
1639 * to use - first need a commercially-available printer that supports
1640 * it, though...
1641 */
1642
1643static void
1644probe_device(snmp_cache_t *device) /* I - Device */
1645{
b94498cf 1646 char uri[1024], /* Full device URI */
1647 *uriptr, /* Pointer into URI */
1648 *format; /* Format string for device */
1649 device_uri_t *device_uri; /* Current DeviceURI match */
89d46774 1650
1651
89d46774 1652 debug_printf("DEBUG: %.3f Probing %s...\n", run_time(), device->addrname);
1653
b94498cf 1654#ifdef __APPLE__
1655 /*
1656 * TODO: Try an mDNS query first, and then fallback on direct probes...
1657 */
d09495fa 1658
b94498cf 1659 if (!try_connect(&(device->address), device->addrname, 5353))
d09495fa 1660 {
b94498cf 1661 debug_printf("DEBUG: %s supports mDNS, not reporting!\n", device->addrname);
1662 return;
d09495fa 1663 }
b94498cf 1664#endif /* __APPLE__ */
d09495fa 1665
b94498cf 1666 /*
1667 * Lookup the device in the match table...
1668 */
89d46774 1669
b94498cf 1670 for (device_uri = (device_uri_t *)cupsArrayFirst(DeviceURIs);
1671 device_uri;
1672 device_uri = (device_uri_t *)cupsArrayNext(DeviceURIs))
1673 if (!regexec(&(device_uri->re), device->make_and_model, 0, NULL, 0))
89d46774 1674 {
d09495fa 1675 /*
b94498cf 1676 * Found a match, add the URIs...
89d46774 1677 */
1678
b94498cf 1679 for (format = (char *)cupsArrayFirst(device_uri->uris);
1680 format;
1681 format = (char *)cupsArrayNext(device_uri->uris))
89d46774 1682 {
b94498cf 1683 for (uriptr = uri; *format && uriptr < (uri + sizeof(uri) - 1);)
1684 if (*format == '%' && format[1] == 's')
89d46774 1685 {
b94498cf 1686 /*
1687 * Insert hostname/address...
1688 */
89d46774 1689
b94498cf 1690 strlcpy(uriptr, device->addrname, sizeof(uri) - (uriptr - uri));
1691 uriptr += strlen(uriptr);
1692 format += 2;
1693 }
1694 else
1695 *uriptr++ = *format++;
89d46774 1696
b94498cf 1697 *uriptr = '\0';
89d46774 1698
b94498cf 1699 update_cache(device, uri, NULL, NULL);
89d46774 1700 }
1701
89d46774 1702 return;
b94498cf 1703 }
89d46774 1704
1705 /*
b94498cf 1706 * Then try the standard ports...
89d46774 1707 */
1708
1709 if (!try_connect(&(device->address), device->addrname, 9100))
1710 {
1711 debug_printf("DEBUG: %s supports AppSocket!\n", device->addrname);
1712
1713 snprintf(uri, sizeof(uri), "socket://%s", device->addrname);
1714 update_cache(device, uri, NULL, NULL);
1715 }
1716 else if (!try_connect(&(device->address), device->addrname, 515))
1717 {
1718 debug_printf("DEBUG: %s supports LPD!\n", device->addrname);
1719
1720 snprintf(uri, sizeof(uri), "lpd://%s/", device->addrname);
1721 update_cache(device, uri, NULL, NULL);
1722 }
1723}
1724
1725
1726/*
1727 * 'read_snmp_conf()' - Read the snmp.conf file.
1728 */
1729
1730static void
1731read_snmp_conf(const char *address) /* I - Single address to probe */
1732{
1733 cups_file_t *fp; /* File pointer */
1734 char filename[1024], /* Filename */
1735 line[1024], /* Line from file */
1736 *value; /* Value on line */
1737 int linenum; /* Line number */
1738 const char *cups_serverroot; /* CUPS_SERVERROOT env var */
1739 const char *debug; /* CUPS_DEBUG_LEVEL env var */
d09495fa 1740 const char *runtime; /* CUPS_MAX_RUN_TIME env var */
89d46774 1741
1742
1743 /*
1744 * Initialize the global address and community lists...
1745 */
1746
1747 Addresses = cupsArrayNew(NULL, NULL);
1748 Communities = cupsArrayNew(NULL, NULL);
1749
1750 if (address)
1751 add_array(Addresses, address);
1752
1753 if ((debug = getenv("CUPS_DEBUG_LEVEL")) != NULL)
1754 DebugLevel = atoi(debug);
1755
d09495fa 1756 if ((runtime = getenv("CUPS_MAX_RUN_TIME")) != NULL)
1757 MaxRunTime = atoi(runtime);
1758
89d46774 1759 /*
1760 * Find the snmp.conf file...
1761 */
1762
1763 if ((cups_serverroot = getenv("CUPS_SERVERROOT")) == NULL)
1764 cups_serverroot = CUPS_SERVERROOT;
1765
1766 snprintf(filename, sizeof(filename), "%s/snmp.conf", cups_serverroot);
1767
1768 if ((fp = cupsFileOpen(filename, "r")) != NULL)
1769 {
1770 /*
1771 * Read the snmp.conf file...
1772 */
1773
1774 linenum = 0;
1775
1776 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
1777 {
1778 if (!value)
1779 fprintf(stderr, "ERROR: Missing value on line %d of %s!\n", linenum,
1780 filename);
1781 else if (!strcasecmp(line, "Address"))
1782 {
1783 if (!address)
1784 add_array(Addresses, value);
1785 }
1786 else if (!strcasecmp(line, "Community"))
1787 add_array(Communities, value);
1788 else if (!strcasecmp(line, "DebugLevel"))
1789 DebugLevel = atoi(value);
b94498cf 1790 else if (!strcasecmp(line, "DeviceURI"))
1791 {
1792 if (*value != '\"')
1793 fprintf(stderr,
1794 "ERROR: Missing double quote for regular expression on "
1795 "line %d of %s!\n", linenum, filename);
1796 else
1797 add_device_uri(value);
1798 }
89d46774 1799 else if (!strcasecmp(line, "HostNameLookups"))
1800 HostNameLookups = !strcasecmp(value, "on") ||
1801 !strcasecmp(value, "yes") ||
1802 !strcasecmp(value, "true") ||
1803 !strcasecmp(value, "double");
d09495fa 1804 else if (!strcasecmp(line, "MaxRunTime"))
1805 MaxRunTime = atoi(value);
89d46774 1806 else
1807 fprintf(stderr, "ERROR: Unknown directive %s on line %d of %s!\n",
1808 line, linenum, filename);
1809 }
1810
1811 cupsFileClose(fp);
1812 }
1813
1814 /*
1815 * Use defaults if parameters are undefined...
1816 */
1817
1818 if (cupsArrayCount(Addresses) == 0)
1819 {
bc44d920 1820 /*
1821 * If we have no addresses, exit immediately...
1822 */
1823
1824 fprintf(stderr,
1825 "DEBUG: No address specified and no Address line in %s...\n",
1826 filename);
1827 exit(0);
89d46774 1828 }
1829
1830 if (cupsArrayCount(Communities) == 0)
1831 {
1832 fputs("INFO: Using default SNMP Community public\n", stderr);
1833 add_array(Communities, "public");
1834 }
1835}
1836
1837
1838/*
1839 * 'read_snmp_response()' - Read and parse a SNMP response...
1840 */
1841
1842static void
1843read_snmp_response(int fd) /* I - SNMP socket file descriptor */
1844{
1845 unsigned char buffer[SNMP_MAX_PACKET];/* Data packet */
1846 int bytes; /* Number of bytes received */
1847 http_addr_t addr; /* Source address */
1848 socklen_t addrlen; /* Source address length */
1849 char addrname[256]; /* Source address name */
1850 snmp_packet_t packet; /* Decoded packet */
1851 snmp_cache_t key, /* Search key */
1852 *device; /* Matching device */
1853
1854
1855 /*
1856 * Read the response data...
1857 */
1858
1859 addrlen = sizeof(addr);
1860
1861 if ((bytes = recvfrom(fd, buffer, sizeof(buffer), 0, (void *)&addr,
1862 &addrlen)) < 0)
1863 {
1864 fprintf(stderr, "ERROR: Unable to read data from socket: %s\n",
1865 strerror(errno));
1866 return;
1867 }
1868
1869 if (HostNameLookups)
1870 httpAddrLookup(&addr, addrname, sizeof(addrname));
1871 else
1872 httpAddrString(&addr, addrname, sizeof(addrname));
1873
1874 debug_printf("DEBUG: %.3f Received %d bytes from %s...\n", run_time(),
1875 bytes, addrname);
1876
1877 /*
1878 * Look for the response status code in the SNMP message header...
1879 */
1880
1881 if (asn1_decode_snmp(buffer, bytes, &packet))
1882 {
c0e1af83 1883 fprintf(stderr, "ERROR: Bad SNMP packet from %s: %s\n",
1884 addrname, packet.error);
89d46774 1885
1886 asn1_debug(buffer, bytes, 0);
1887 hex_debug(buffer, bytes);
1888
1889 return;
1890 }
1891
1892 debug_printf("DEBUG: community=\"%s\"\n", packet.community);
1893 debug_printf("DEBUG: request-id=%d\n", packet.request_id);
1894 debug_printf("DEBUG: error-status=%d\n", packet.error_status);
1895
1896 if (DebugLevel > 1)
1897 asn1_debug(buffer, bytes, 0);
1898
1899 if (DebugLevel > 2)
1900 hex_debug(buffer, bytes);
1901
1902 if (packet.error_status)
1903 return;
1904
1905 /*
1906 * Find a matching device in the cache...
1907 */
1908
8ca02f3c 1909 key.addrname = addrname;
1910 device = (snmp_cache_t *)cupsArrayFind(Devices, &key);
89d46774 1911
1912 /*
1913 * Process the message...
1914 */
1915
1916 if (packet.request_id == DeviceTypeRequest)
1917 {
1918 /*
1919 * Got the device type response...
1920 */
1921
1922 if (device)
1923 {
1924 debug_printf("DEBUG: Discarding duplicate device type for \"%s\"...\n",
1925 addrname);
1926 return;
1927 }
1928
1929 /*
1930 * Add the device and request the device description...
1931 */
1932
1933 add_cache(&addr, addrname, NULL, NULL, NULL);
1934
1935 send_snmp_query(fd, &addr, SNMP_VERSION_1, packet.community,
1936 DeviceDescRequest, DeviceDescOID);
1937 }
1938 else if (packet.request_id == DeviceDescRequest &&
1939 packet.object_type == ASN1_OCTET_STRING)
1940 {
1941 /*
1942 * Update an existing cache entry...
1943 */
1944
1945 char make_model[256]; /* Make and model */
1946
1947
1948 if (!device)
1949 {
1950 debug_printf("DEBUG: Discarding device description for \"%s\"...\n",
1951 addrname);
1952 return;
1953 }
1954
1955 /*
1956 * Convert the description to a make and model string...
1957 */
1958
1959 if (strchr(packet.object_value.string, ':') &&
1960 strchr(packet.object_value.string, ';'))
1961 {
1962 /*
1963 * Description is the IEEE-1284 device ID...
1964 */
1965
ed486911 1966 backendGetMakeModel(packet.object_value.string, make_model,
1967 sizeof(make_model));
89d46774 1968 }
1969 else
1970 {
1971 /*
1972 * Description is plain text...
1973 */
1974
1975 fix_make_model(make_model, packet.object_value.string,
1976 sizeof(make_model));
1977 }
1978
1979 if (device->make_and_model)
1980 free(device->make_and_model);
1981
1982 device->make_and_model = strdup(make_model);
1983 }
1984}
1985
1986
1987/*
1988 * 'run_time()' - Return the total running time...
1989 */
1990
1991static double /* O - Number of seconds */
1992run_time(void)
1993{
1994 struct timeval curtime; /* Current time */
1995
1996
1997 gettimeofday(&curtime, NULL);
1998
1999 return (curtime.tv_sec - StartTime.tv_sec +
2000 0.000001 * (curtime.tv_usec - StartTime.tv_usec));
2001}
2002
2003
2004/*
2005 * 'scan_devices()' - Scan for devices using SNMP.
2006 */
2007
2008static void
2009scan_devices(int fd) /* I - SNMP socket */
2010{
2011 char *address, /* Current address */
2012 *community; /* Current community */
2013 fd_set input; /* Input set for select() */
2014 struct timeval timeout; /* Timeout for select() */
2015 time_t endtime; /* End time for scan */
2016 http_addrlist_t *addrs, /* List of addresses */
2017 *addr; /* Current address */
2018 snmp_cache_t *device; /* Current device */
2019
2020
2021 /*
2022 * Setup the request IDs...
2023 */
2024
2025 gettimeofday(&StartTime, NULL);
2026
2027 DeviceTypeRequest = StartTime.tv_sec;
2028 DeviceDescRequest = StartTime.tv_sec + 1;
2029
2030 /*
2031 * First send all of the broadcast queries...
2032 */
2033
2034 for (address = (char *)cupsArrayFirst(Addresses);
2035 address;
2036 address = (char *)cupsArrayNext(Addresses))
2037 {
2038 if (!strcmp(address, "@LOCAL"))
2039 addrs = get_interface_addresses(NULL);
2040 else if (!strncmp(address, "@IF(", 4))
2041 {
2042 char ifname[255]; /* Interface name */
2043
2044
2045 strlcpy(ifname, address + 4, sizeof(ifname));
2046 if (ifname[0])
2047 ifname[strlen(ifname) - 1] = '\0';
2048
2049 addrs = get_interface_addresses(ifname);
2050 }
2051 else
2052 addrs = httpAddrGetList(address, AF_INET, NULL);
2053
2054 if (!addrs)
2055 {
2056 fprintf(stderr, "ERROR: Unable to scan \"%s\"!\n", address);
2057 continue;
2058 }
2059
2060 for (community = (char *)cupsArrayFirst(Communities);
2061 community;
2062 community = (char *)cupsArrayNext(Communities))
2063 {
2064 debug_printf("DEBUG: Scanning for devices in \"%s\" via \"%s\"...\n",
2065 community, address);
2066
2067 for (addr = addrs; addr; addr = addr->next)
2068 send_snmp_query(fd, &(addr->addr), SNMP_VERSION_1, community,
2069 DeviceTypeRequest, DeviceTypeOID);
2070 }
2071
2072 httpAddrFreeList(addrs);
2073 }
2074
2075 /*
2076 * Then read any responses that come in over the next 3 seconds...
2077 */
2078
2079 endtime = time(NULL) + 3;
2080
2081 FD_ZERO(&input);
2082
2083 while (time(NULL) < endtime)
2084 {
2085 timeout.tv_sec = 1;
2086 timeout.tv_usec = 0;
2087
2088 FD_SET(fd, &input);
2089 if (select(fd + 1, &input, NULL, NULL, &timeout) < 0)
2090 {
2091 fprintf(stderr, "ERROR: %.3f select() for %d failed: %s\n", run_time(),
2092 fd, strerror(errno));
2093 break;
2094 }
2095
2096 if (FD_ISSET(fd, &input))
2097 read_snmp_response(fd);
2098 else
2099 break;
2100 }
2101
2102 /*
2103 * Finally, probe all of the printers we discovered to see how they are
2104 * connected...
2105 */
2106
2107 for (device = (snmp_cache_t *)cupsArrayFirst(Devices);
2108 device;
2109 device = (snmp_cache_t *)cupsArrayNext(Devices))
d09495fa 2110 if (MaxRunTime > 0 && run_time() >= MaxRunTime)
2111 break;
2112 else if (!device->uri)
89d46774 2113 probe_device(device);
2114
2115 debug_printf("DEBUG: %.3f Scan complete!\n", run_time());
2116}
2117
2118
2119/*
2120 * 'send_snmp_query()' - Send an SNMP query packet.
2121 */
2122
2123static void
2124send_snmp_query(
2125 int fd, /* I - SNMP socket */
2126 http_addr_t *addr, /* I - Address to send to */
2127 int version, /* I - SNMP version */
2128 const char *community, /* I - Community name */
2129 const unsigned request_id, /* I - Request ID */
2130 const int *oid) /* I - OID */
2131{
2132 int i; /* Looping var */
2133 snmp_packet_t packet; /* SNMP message packet */
2134 unsigned char buffer[SNMP_MAX_PACKET];/* SNMP message buffer */
2135 int bytes; /* Size of message */
2136 char addrname[32]; /* Address name */
2137
2138
2139 /*
2140 * Create the SNMP message...
2141 */
2142
2143 memset(&packet, 0, sizeof(packet));
2144
2145 packet.version = version;
2146 packet.request_type = ASN1_GET_REQUEST;
2147 packet.request_id = request_id;
2148 packet.object_type = ASN1_NULL_VALUE;
2149
2150 strlcpy(packet.community, community, sizeof(packet.community));
2151
2152 for (i = 0; oid[i]; i ++)
2153 packet.object_name[i] = oid[i];
2154
2155 bytes = asn1_encode_snmp(buffer, sizeof(buffer), &packet);
2156
2157 if (bytes < 0)
2158 {
c0e1af83 2159 fprintf(stderr, "ERROR: Unable to send SNMP query: %s\n",
2160 packet.error);
89d46774 2161 return;
2162 }
2163
2164 /*
2165 * Send the message...
2166 */
2167
2168 debug_printf("DEBUG: %.3f Sending %d bytes to %s...\n", run_time(),
2169 bytes, httpAddrString(addr, addrname, sizeof(addrname)));
2170 if (DebugLevel > 1)
2171 asn1_debug(buffer, bytes, 0);
2172 if (DebugLevel > 2)
2173 hex_debug(buffer, bytes);
2174
2175 addr->ipv4.sin_port = htons(SNMP_PORT);
2176
2177 if (sendto(fd, buffer, bytes, 0, (void *)addr, sizeof(addr->ipv4)) < bytes)
2178 fprintf(stderr, "ERROR: Unable to send %d bytes to %s: %s\n",
2179 bytes, addrname, strerror(errno));
2180}
2181
2182
2183/*
2184 * 'try_connect()' - Try connecting on a port...
2185 */
2186
2187static int /* O - 0 on success or -1 on error */
2188try_connect(http_addr_t *addr, /* I - Socket address */
2189 const char *addrname, /* I - Hostname or IP address */
2190 int port) /* I - Port number */
2191{
2192 int fd; /* Socket */
2193 int status; /* Connection status */
2194
2195
2196 debug_printf("DEBUG: %.3f Trying %s://%s:%d...\n", run_time(),
2197 port == 515 ? "lpd" : "socket", addrname, port);
2198
2199 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
2200 {
c0e1af83 2201 fprintf(stderr, "ERROR: Unable to create socket: %s\n",
2202 strerror(errno));
89d46774 2203 return (-1);
2204 }
2205
2206 addr->ipv4.sin_port = htons(port);
2207
89d46774 2208 alarm(1);
2209
2210 status = connect(fd, (void *)addr, httpAddrLength(addr));
2211
2212 close(fd);
2213 alarm(0);
2214
2215 return (status);
2216}
2217
2218
2219/*
2220 * 'update_cache()' - Update a cached device...
2221 */
2222
2223static void
2224update_cache(snmp_cache_t *device, /* I - Device */
2225 const char *uri, /* I - Device URI */
2226 const char *id, /* I - Device ID */
2227 const char *make_model) /* I - Device make and model */
2228{
2229 if (device->uri)
2230 free(device->uri);
2231
2232 device->uri = strdup(uri);
2233
2234 if (id)
2235 {
2236 if (device->id)
2237 free(device->id);
2238
2239 device->id = strdup(id);
2240 }
2241
2242 if (make_model)
2243 {
2244 if (device->make_and_model)
2245 free(device->make_and_model);
2246
2247 device->make_and_model = strdup(make_model);
2248 }
d09495fa 2249
2250 list_device(device);
89d46774 2251}
2252
2253
2254/*
bc44d920 2255 * End of "$Id: snmp.c 6649 2007-07-11 21:46:42Z mike $".
89d46774 2256 */