File: cups-polld.c

package info (click to toggle)
cups 1.4.4-7%2Bsqueeze10
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 25,548 kB
  • ctags: 9,583
  • sloc: ansic: 138,214; sh: 37,926; cpp: 25,469; makefile: 3,285; perl: 190; python: 127; php: 28
file content (475 lines) | stat: -rw-r--r-- 11,903 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
 * "$Id: cups-polld.c 7198 2008-01-08 00:12:17Z mike $"
 *
 *   Polling daemon for the Common UNIX Printing System (CUPS).
 *
 *   Copyright 2007 by Apple Inc.
 *   Copyright 1997-2006 by Easy Software Products, all rights reserved.
 *
 *   These coded instructions, statements, and computer programs are the
 *   property of Apple Inc. and are protected by Federal copyright
 *   law.  Distribution and use rights are outlined in the file "LICENSE.txt"
 *   which should have been included with this file.  If this file is
 *   file is missing or damaged, see the license at "http://www.cups.org/".
 *
 * Contents:
 *
 *   main()           - Open sockets and poll until we are killed...
 *   dequote()        - Remote quotes from a string.
 *   poll_server()    - Poll the server for the given set of printers or
 *                      classes.
 *   sighup_handler() - Handle 'hangup' signals to restart polling.
 */

/*
 * Include necessary headers...
 */

#include <cups/http-private.h>
#include <cups/cups.h>
#include <stdlib.h>
#include <errno.h>
#include <cups/language.h>
#include <cups/string.h>
#include <signal.h>


/*
 * Local globals...
 */

static int	restart_polling = 1;


/*
 * Local functions...
 */

static char	*dequote(char *d, const char *s, int dlen);
static int	poll_server(http_t *http, int sock, int port, int interval,
			    const char *prefix);
static void	sighup_handler(int sig);


/*
 * 'main()' - Open sockets and poll until we are killed...
 */

int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
  http_t	*http;			/* HTTP connection */
  int		interval;		/* Polling interval */
  int		sock;			/* Browser sock */
  int		port;			/* Browser port */
  int		val;			/* Socket option value */
  int		seconds,		/* Seconds left from poll */
		remain;			/* Total remaining time to sleep */
  char		prefix[1024];		/* Prefix for log messages */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction action;		/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */


 /*
  * Catch hangup signals for when the network changes...
  */

#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
  sigset(SIGHUP, sighup_handler);
#elif defined(HAVE_SIGACTION)
  memset(&action, 0, sizeof(action));

  sigemptyset(&action.sa_mask);
  sigaddset(&action.sa_mask, SIGHUP);
  action.sa_handler = sighup_handler;
  sigaction(SIGHUP, &action, NULL);
#else
  signal(SIGHUP, sighup_handler);
#endif /* HAVE_SIGSET */

 /*
  * Don't buffer log messages...
  */

  setbuf(stderr, NULL);

 /*
  * The command-line must contain the following:
  *
  *    cups-polld server server-port interval port
  */

  if (argc != 5)
  {
    fputs("Usage: cups-polld server server-port interval port\n", stderr);
    return (1);
  }

  interval = atoi(argv[3]);
  port     = atoi(argv[4]);

  if (interval < 2)
    interval = 2;

  snprintf(prefix, sizeof(prefix), "[cups-polld %s:%d]", argv[1], atoi(argv[2]));

 /*
  * Open a broadcast socket...
  */

  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  {
    fprintf(stderr, "ERROR: %s Unable to open broadcast socket: %s\n", prefix,
            strerror(errno));
    return (1);
  }

 /*
  * Set the "broadcast" flag...
  */

  val = 1;
  if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)))
  {
    fprintf(stderr, "ERROR: %s Unable to put socket in broadcast mode: %s\n",
            prefix, strerror(errno));

    close(sock);
    return (1);
  }

 /*
  * Loop forever, asking for available printers and classes...
  */

  for (http = NULL; !ferror(stderr);)
  {
   /*
    * Open a connection to the server...
    */

    if (restart_polling || !http)
    {
      restart_polling = 0;
      httpClose(http);

      if ((http = httpConnectEncrypt(argv[1], atoi(argv[2]),
                                     cupsEncryption())) == NULL)
      {
	fprintf(stderr, "ERROR: %s Unable to connect to %s on port %s: %s\n",
        	prefix, argv[1], argv[2],
		h_errno ? hstrerror(h_errno) : strerror(errno));
      }
    }

   /*
    * Get the printers and classes...
    */

    remain = interval;

    if (http && (seconds = poll_server(http, sock, port, interval, prefix)) > 0)
      remain -= seconds;

   /*
    * Sleep for any remaining time...
    */

    if (remain > 0 && !restart_polling)
      sleep(remain);
  }

  return (1);
}


/*
 * 'dequote()' - Remote quotes from a string.
 */

static char *				/* O - Dequoted string */
dequote(char       *d,			/* I - Destination string */
        const char *s,			/* I - Source string */
	int        dlen)		/* I - Destination length */
{
  char	*dptr;				/* Pointer into destination */


  if (s)
  {
    for (dptr = d, dlen --; *s && dlen > 0; s ++)
      if (*s != '\"')
      {
	*dptr++ = *s;
	dlen --;
      }

    *dptr = '\0';
  }
  else
    *d = '\0';

  return (d);
}


/*
 * 'poll_server()' - Poll the server for the given set of printers or classes.
 */

static int				/* O - Number of seconds or -1 on error */
poll_server(http_t      *http,		/* I - HTTP connection */
	    int         sock,		/* I - Broadcast sock */
	    int         port,		/* I - Broadcast port */
	    int         interval,	/* I - Polling interval */
	    const char	*prefix)	/* I - Prefix for log messages */
{
  int			seconds;	/* Number of seconds */
  int			count,		/* Current number of printers/classes */
			max_count;	/* Maximum printers/classes per second */
  ipp_t			*request,	/* Request data */
			*response;	/* Response data */
  ipp_attribute_t	*attr;		/* Current attribute */
  const char		*uri;		/* printer-uri */
  char			info[1024],	/* printer-info */
			job_sheets[1024],/* job-sheets-default */
			location[1024],	/* printer-location */
			make_model[1024];
					/* printer-make-and-model */
  cups_ptype_t		type;		/* printer-type */
  ipp_pstate_t		state;		/* printer-state */
  int			accepting;	/* printer-is-accepting-jobs */
  struct sockaddr_in	addr;		/* Broadcast address */
  char			packet[1540];	/* Data packet */
  static const char * const attrs[] =	/* Requested attributes */
			{
			  "job-sheets-default",
			  "printer-info",
			  "printer-is-accepting-jobs",
			  "printer-location",
			  "printer-make-and-model",
			  "printer-name",
			  "printer-state",
			  "printer-type",
			  "printer-uri-supported"
			};


 /*
  * Broadcast to 127.0.0.1 (localhost)
  */

  memset(&addr, 0, sizeof(addr));
  addr.sin_addr.s_addr = htonl(0x7f000001);
  addr.sin_family      = AF_INET;
  addr.sin_port        = htons(port);

 /*
  * Build a CUPS_GET_PRINTERS request and pass along a list of the
  * attributes we are interested in along with the types of printers
  * (and classes) we want.
  */

  request = ippNewRequest(CUPS_GET_PRINTERS);

  ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
               "requested-attributes", sizeof(attrs) / sizeof(attrs[0]),
	       NULL, attrs);

  ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM,
                "printer-type", 0);
  ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM,
                "printer-type-mask",
		CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
		CUPS_PRINTER_NOT_SHARED);

 /*
  * Do the request and get back a response...
  */

  seconds  = time(NULL);
  response = cupsDoRequest(http, request, "/");

  if (cupsLastError() > IPP_OK_CONFLICT)
  {
    fprintf(stderr, "ERROR: %s CUPS-Get-Printers failed: %s\n", prefix,
            cupsLastErrorString());
    ippDelete(response);
    return (-1);
  }

  if (response)
  {
   /*
    * Figure out how many printers/classes we have...
    */

    for (attr = ippFindAttribute(response, "printer-name", IPP_TAG_NAME),
             max_count = 0;
	 attr != NULL;
	 attr = ippFindNextAttribute(response, "printer-name", IPP_TAG_NAME),
	     max_count ++);

    fprintf(stderr, "DEBUG: %s Found %d printers.\n", prefix, max_count);

    count     = 0;
    max_count = max_count / interval + 1;

   /*
    * Loop through the printers or classes returned in the list...
    */

    for (attr = response->attrs; attr; attr = attr->next)
    {
     /*
      * Skip leading attributes until we hit a printer...
      */

      while (attr && attr->group_tag != IPP_TAG_PRINTER)
        attr = attr->next;

      if (!attr)
        break;

     /*
      * Pull the needed attributes from this printer...
      */

      uri           = NULL;
      info[0]       = '\0';
      job_sheets[0] = '\0';
      location[0]   = '\0';
      make_model[0] = '\0';
      type          = CUPS_PRINTER_REMOTE;
      accepting     = 1;
      state         = IPP_PRINTER_IDLE;

      while (attr != NULL && attr->group_tag == IPP_TAG_PRINTER)
      {
        if (!strcmp(attr->name, "job-sheets-default") &&
	    (attr->value_tag == IPP_TAG_NAME ||
	     attr->value_tag == IPP_TAG_KEYWORD))
	{
	  if (attr->num_values == 1)
	    snprintf(job_sheets, sizeof(job_sheets), " job-sheets=%s",
	             attr->values[0].string.text);
          else
	    snprintf(job_sheets, sizeof(job_sheets), " job-sheets=%s,%s",
	             attr->values[0].string.text,
	             attr->values[1].string.text);
	}
        else if (!strcmp(attr->name, "printer-uri-supported") &&
	         attr->value_tag == IPP_TAG_URI)
	  uri = attr->values[0].string.text;
        else if (!strcmp(attr->name, "printer-info") &&
		 attr->value_tag == IPP_TAG_TEXT)
	  dequote(info, attr->values[0].string.text, sizeof(info));
        else if (!strcmp(attr->name, "printer-is-accepting-jobs") &&
	         attr->value_tag == IPP_TAG_BOOLEAN)
	  accepting = attr->values[0].boolean;
        else if (!strcmp(attr->name, "printer-location") &&
	         attr->value_tag == IPP_TAG_TEXT)
	  dequote(location, attr->values[0].string.text, sizeof(location));
        else if (!strcmp(attr->name, "printer-make-and-model") &&
	         attr->value_tag == IPP_TAG_TEXT)
	  dequote(make_model, attr->values[0].string.text, sizeof(location));
        else if (!strcmp(attr->name, "printer-state") &&
	         attr->value_tag == IPP_TAG_ENUM)
	  state = (ipp_pstate_t)attr->values[0].integer;
        else if (!strcmp(attr->name, "printer-type") &&
	         attr->value_tag == IPP_TAG_ENUM)
	  type = (cups_ptype_t)attr->values[0].integer;

        attr = attr->next;
      }

     /*
      * See if we have everything needed...
      */

      if (uri == NULL)
      {
        if (attr == NULL)
	  break;
	else
          continue;
      }

     /*
      * Send the printer information...
      */

      type |= CUPS_PRINTER_REMOTE;

      if (!accepting)
	type |= CUPS_PRINTER_REJECTING;

      snprintf(packet, sizeof(packet),
               "%x %x %s \"%s\" \"%s\" \"%s\" lease-duration=%d%s\n",
               type, state, uri, location, info, make_model, interval * 2,
	       job_sheets);

      fprintf(stderr, "DEBUG2: %s Sending %s", prefix, packet);

      if (sendto(sock, packet, strlen(packet), 0,
	         (struct sockaddr *)&addr, sizeof(addr)) <= 0)
      {
	ippDelete(response);
	perror("cups-polld");
	return (-1);
      }

     /*
      * Throttle the local broadcasts as needed so that we don't
      * overwhelm the local server...
      */

      count ++;
      if (count >= max_count)
      {
       /*
	* Sleep for a second...
	*/

	count = 0;

	sleep(1);
      }

      if (!attr || restart_polling)
        break;
    }

    ippDelete(response);
  }

 /*
  * Return the number of seconds we used...
  */

  return (time(NULL) - seconds);
}


/*
 * 'sighup_handler()' - Handle 'hangup' signals to restart polling.
 */

static void
sighup_handler(int sig)			/* I - Signal number */
{
  (void)sig;

  restart_polling = 1;

#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
  signal(SIGHUP, sighup_handler);
#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
}


/*
 * End of "$Id: cups-polld.c 7198 2008-01-08 00:12:17Z mike $".
 */