File: hal.c

package info (click to toggle)
hal-cups-utils 0.6.16-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 468 kB
  • ctags: 39
  • sloc: sh: 985; python: 401; ansic: 365; makefile: 17
file content (560 lines) | stat: -rw-r--r-- 13,047 bytes parent folder | download
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/*
 *
 *   HAL backend for the Common UNIX Printing System (CUPS).
 *
 *   Copyright 1997-2003 by Easy Software Products, all rights reserved.
 *   Copyright (C) 2004 Novell, Inc.
 *   Copyright (C) 2007, 2008 Red Hat, Inc.
 *
 *   These coded instructions, statements, and computer programs are the
 *   property of Easy Software Products and are protected by Federal
 *   copyright law.  Distribution and use rights are outlined in the file
 *   "LICENSE" which should have been included with this file.  If this
 *   file is missing or damaged please contact Easy Software Products
 *   at:
 *
 *       Attn: CUPS Licensing Information
 *       Easy Software Products
 *       44141 Airport View Drive, Suite 204
 *       Hollywood, Maryland 20636-3111 USA
 *
 *       Voice: (301) 373-9603
 *       EMail: cups-info@cups.org
 *         WWW: http://www.cups.org
 *
 *   This file is subject to the Apple OS-Developed Software exception.
 *
 * Contents:
 *
 *   main()         - Send a file to the specified HAL device.
 *   list_devices() - List all HAL printer devices.
 */

/*
 * Include necessary headers.
 */

#include <cups/backend.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#ifdef __linux
#include <sys/ioctl.h>
#include <linux/lp.h>
#endif /* __linux */

#include <libhal.h>

/*
 * 'hal_init()' - Initializes a HAL context
 */
LibHalContext *
hal_init(void)
{
	LibHalContext *hal_ctx;
	DBusError error;
	DBusConnection *dbus_conn;

	hal_ctx = libhal_ctx_new ();

	if (hal_ctx == NULL) {
		fprintf (stderr, "ERROR: Unable to access HAL daemon\n");
		return NULL;
	}

	dbus_error_init (&error);
	dbus_conn = dbus_bus_get (DBUS_BUS_SYSTEM, &error);

	if (dbus_error_is_set (&error)) {
		fprintf (stderr, "ERROR: Could not connect to system bus: %s\n", error.message);
		dbus_error_free (&error);
		libhal_ctx_free (hal_ctx);
		return NULL;
	}

	libhal_ctx_set_dbus_connection (hal_ctx, dbus_conn);

	if (!libhal_ctx_init (hal_ctx, &error)) {
		fprintf (stderr, "ERROR: Could initialize HAL daemon: %s\n", error.message);
		dbus_error_free (&error);
		libhal_ctx_free (hal_ctx);
		return NULL;
	}

	return hal_ctx;
}

/*
 * 'list_devices()' - List all HAL printer devices.
 */

void
list_devices(void)
{
	LibHalContext *hal_ctx;
	char **printer_list;
	int num_printers, i;
	DBusError error;

	hal_ctx = hal_init ();

	if (hal_ctx == NULL)
		return;

	printer_list = libhal_find_device_by_capability (hal_ctx, "printer",
			 			         &num_printers, NULL);
	if (printer_list == NULL || num_printers == 0)
		printf("direct hal \"Unknown\" \"Hal printing backend\"\n"); 

	for (i = 0; i < num_printers; i++) {
		const char *vendor, *product, *description,
			*commandset, *serial;
		char make_model[1024];
		char deviceid[4000], *dp;
		size_t dlen;

		/* We only want printers that have device nodes */
		if (!libhal_device_property_exists (hal_ctx, printer_list[i],
						    "printer.device", NULL))
			continue;

		vendor = libhal_device_get_property_string (hal_ctx,
							    printer_list[i],
							    "printer.vendor",
							    NULL);

		product = libhal_device_get_property_string (hal_ctx,
							     printer_list[i],
							     "printer.product",
							     NULL);

		description = libhal_device_get_property_string (hal_ctx,
							         printer_list[i],
							         "printer.description",
								 NULL);

		commandset = libhal_device_get_property_string (hal_ctx,
								printer_list[i],
								"printer.commandset",
								NULL);

		serial = libhal_device_get_property_string (hal_ctx,
							    printer_list[i],
							    "printer.serial",
							    NULL);

		/* Try our hardest to get a good name */
		if (product != NULL) {
			if (vendor != NULL) {
				snprintf (make_model, sizeof (make_model),
					  "%s %s", vendor, product);
			} else {
				strncpy (make_model, product,
					 sizeof (make_model));
			}
		} else if (description != NULL) {
			strncpy (make_model, description, sizeof (make_model));
		} else if (vendor != NULL) {
			snprintf (make_model, sizeof (make_model),
				  "%s printer", vendor);
		} else {
			strncpy (make_model, "Unknown", sizeof (make_model));
		}

		/* Reconstruct the Device ID. */
		deviceid[0] = '\0';
		dp = deviceid;
		dlen = sizeof (deviceid) - 1;
		if (vendor != NULL) {
			int l = snprintf (dp, dlen, "MFG:%s;", vendor);
			dlen -= l;
			dp += l;
		}
		if (product != NULL) {
			int l = snprintf (dp, dlen, "MDL:%s;", product);
			dlen -= l;
			dp += l;
		}
		if (commandset != NULL) {
			int l = snprintf (dp, dlen, "CMD:%s;", commandset);
			dlen -= l;
			dp += l;
		}
		snprintf (dp, dlen, "CLS:PRINTER;");
		dlen -= 12;
		dp += 12;
		if (serial != NULL) {
			int l = snprintf (dp, dlen, "SN:%s;", serial);
			dlen -= l;
			dp += l;
		}
		/* Replace double-quotes with single quotes. */
		dp = deviceid;
		while (*dp != '\0') {
			if (*dp == '"')
				*dp = '\'';
			dp++;
		}

		printf ("direct hal://%s \"%s\" \"%s\" \"%s\"\n",
			printer_list[i], make_model, make_model,
			deviceid);
	}

	dbus_error_init (&error);
	libhal_ctx_shutdown (hal_ctx, &error);
	if (dbus_error_is_set (&error))
		dbus_error_free (&error);

	libhal_ctx_free (hal_ctx);
}

/*
 * 'get_device_file()' - Get a device file from a HAL device UDI
 */
const char *
get_device_file (const char *uri)
{
	LibHalContext *hal_ctx;
	char *udi, *options;
	const char *device_file;

	hal_ctx = hal_init ();

	if (hal_ctx == NULL)
		return NULL;

	if (strncmp (uri, "hal://", 6) != 0)
		return NULL;

	udi = strdup (uri + 6);
	if ((options = strchr (udi, '?')) != NULL)
	  *options++ = '\0';

	device_file = libhal_device_get_property_string (hal_ctx, udi,
						         "printer.device",
							 NULL);

	free (udi);
	return device_file;
}

/*
 * 'main()' - Send a file to the specified HAL printer device.
 *
 * Usage:
 *
 *    printer-uri job-id user title copies options [file]
 */

int			/* O - Exit status */
main(int  argc,		/* I - Number of command-line arguments (6 or 7) */
     char *argv[])	/* I - Command-line arguments */
{
  int		fp;		/* Print file */
  int		copies;		/* Number of copies to print */
  const char    *device_file;   /* Device file to open */
  int		fd;		/* Device file descriptor */
  int		wbytes;		/* Number of bytes written */
  size_t	nbytes,		/* Number of bytes read */
		tbytes;		/* Total number of bytes written */
  char		buffer[8192],	/* Output buffer */
		*bufptr;	/* Pointer into buffer */
  struct termios opts;		/* Parallel port options */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction action;	/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
#if defined(__linux) && defined(LP_POUTPA)
  unsigned char	status;		/* Port status (off-line, out-of-paper, etc.) */
#endif /* __linux */
  int		offline = -1,
		paperout = -1;
  

 /*
  * Make sure status messages are not buffered...
  */

  setbuf(stderr, NULL);

 /*
  * Ignore SIGPIPE signals...
  */

#ifdef HAVE_SIGSET
  sigset(SIGPIPE, SIG_IGN);
#elif defined(HAVE_SIGACTION)
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &action, NULL);
#else
  signal(SIGPIPE, SIG_IGN);
#endif /* HAVE_SIGSET */

 /*
  * Check command-line...
  */

  if (argc == 1)
  {
    list_devices();
    return (CUPS_BACKEND_OK);
  }
  else if (argc < 6 || argc > 7)
  {
    fputs("Usage: URI job-id user title copies options [file]\n", stderr);
    return (CUPS_BACKEND_FAILED);
  }

 /*
  * If we have 7 arguments, print the file named on the command-line.
  * Otherwise, send stdin instead...
  */

  if (argc == 6)
  {
    fp     = 0;
    copies = 1;
  }
  else
  {
   /*
    * Try to open the print file...
    */

    if ((fp = open(argv[6], O_RDONLY)) < 0)
    {
      perror("ERROR: unable to open print file");
      return (CUPS_BACKEND_FAILED);
    }

    copies = atoi(argv[4]);
  }

 /*
  * Open the port device...
  */

  fputs ("STATE: +connecting-to-device\n", stderr);
  do
  {
    device_file = get_device_file (cupsBackendDeviceURI (argv));

    if (device_file == NULL)
    {
        fputs("INFO: Printer not connected; will retry in 30 seconds...\n",
	      stderr);
	sleep(30);
	fd = -1;
	continue;
    }

    if ((fd = open (device_file, O_RDWR | O_EXCL)) == -1)
    {
      if (getenv("CLASS") != NULL)
      {
	/*
        * If the CLASS environment variable is set, the job was submitted
	* to a class and not to a specific queue.  In this case, we want
	* to abort immediately so that the job can be requeued on the next
	* available printer in the class.
	*/

	fputs ("INFO: Unable to contact printer, queuing on next printer "
	       "in class...\n", stderr);
	sleep (5); /* avoid job requeuing too rapidly */
	return (CUPS_BACKEND_FAILED);
      }

      if (errno == EBUSY)
      {
        fputs("INFO: Device busy; will retry in 30 seconds...\n", stderr);
	sleep(30);
      }
      else if (errno == ENXIO || errno == EIO || errno == ENOENT)
      {
        fputs("INFO: Printer not connected; will retry in 30 seconds...\n", stderr);
	sleep(30);
      }
      else
      {
	fprintf(stderr, "ERROR: Unable to open device \"%s\": %s\n",
	        argv[0], strerror(errno));
	return (CUPS_BACKEND_FAILED);
      }
    }
  }
  while (fd < 0);

  fputs ("STATE: -connecting-to-device\n", stderr);

 /*
  * Set any options provided...
  */

  tcgetattr(fd, &opts);

  opts.c_lflag &= ~(ICANON | ECHO | ISIG);	/* Raw mode */

  /**** No options supported yet ****/

  tcsetattr(fd, TCSANOW, &opts);

#ifdef __linux
  {
    /* Tell the driver to return from write() with errno==ENOSPC on
     * paper-out */
    unsigned int t = 1;
    ioctl (fd, LPABORT, &t);
  }
#endif /* __linux */

 /*
  * Now that we are "connected" to the port, ignore SIGTERM so that we
  * can finish out any page data the driver sends (e.g. to eject the
  * current page...  Only ignore SIGTERM if we are printing data from
  * stdin (otherwise you can't cancel raw jobs...)
  */

  if (argc < 7)
  {
#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
    sigset(SIGTERM, SIG_IGN);
#elif defined(HAVE_SIGACTION)
    memset(&action, 0, sizeof(action));

    sigemptyset(&action.sa_mask);
    action.sa_handler = SIG_IGN;
    sigaction(SIGTERM, &action, NULL);
#else
    signal(SIGTERM, SIG_IGN);
#endif /* HAVE_SIGSET */
  }

#if defined(__linux) && defined(LP_POUTPA)
 /*
  * Show the printer status before we send the file; normally, we'd
  * do this while we write data to the printer, however at least some
  * Linux kernels have buggy USB drivers which don't like to be
  * queried while sending data to the printer...
  *
  * Also, we're using the 8255 constants instead of the ones that are
  * supposed to be used, as it appears that the USB driver also doesn't
  * follow standards...
  */

  if (ioctl(fd, LPGETSTATUS, &status) == 0)
  {
    fprintf(stderr, "DEBUG: LPGETSTATUS returned a port status of %02X...\n", status);

    if (status & LP_POUTPA)
      fputs("WARNING: Media tray empty!\n", stderr);
    else if (!(status & LP_PERRORP))
      fputs("WARNING: Printer fault!\n", stderr);
    else if (!(status & LP_PSELECD))
      fputs("WARNING: Printer off-line.\n", stderr);
  }
#endif /* __linux && LP_POUTPA */

 /*
  * Finally, send the print file...
  */

  while (copies > 0)
  {
    copies --;

    if (fp != 0)
    {
      fputs("PAGE: 1 1\n", stderr);
      lseek(fp, 0, SEEK_SET);
    }

    tbytes = 0;
    while ((nbytes = read(fp, buffer, sizeof(buffer))) > 0)
    {
     /*
      * Write the print data to the printer...
      */

      tbytes += nbytes;
      bufptr = buffer;

      while (nbytes > 0)
      {

	if ((wbytes = write(fd, bufptr, nbytes)) < 0)
	{
	  if (errno == ENOSPC)
	  {
	    if (paperout != 1)
	    {
	      fputs ("STATE: +media-empty-error\n", stderr);
	      fputs ("ERROR: Out of paper!\n", stderr);
	      paperout = 1;
	    }
	  }
	  else if (errno == ENXIO)
	  {
	    if (offline != 1)
	    {
	      fputs ("STATE: +offline-error\n", stderr);
	      fputs ("INFO: Printer is currently off-line.\n", stderr);
	      offline = 1;
	    }
	  }
	  else if (errno != EAGAIN && errno != EINTR && errno != ENOTTY)
	  {
	    perror ("ERROR: Unable to write print data");
	    wbytes = -1;
	    break;
	  }
	}
	else
	{
	  if (paperout)
	  {
	    fputs ("STATE: -media-empty-error\n", stderr);
	    paperout = 0;
	  }

	  if (offline)
	  {
	    fputs ("STATE: -offline-error\n", stderr);
	    fputs ("INFO: Printer is now on-line.\n", stderr);
	    offline = 0;
	  }
	}

	nbytes -= wbytes;
	bufptr += wbytes;
      }

      if (wbytes < 0)
        break;

      if (argc > 6)
	fprintf(stderr, "INFO: Sending print file, %lu bytes...\n",
	        (unsigned long)tbytes);
    }
  }

 /*
  * Close the socket connection and input file and return...
  */

  close(fd);
  if (fp != 0)
    close(fp);

  return (wbytes < 0 ? CUPS_BACKEND_FAILED : CUPS_BACKEND_OK);
}
						      
/*
 * End of "$Id: hal.c,v 1.8 2007/06/07 16:49:54 twaugh Exp $".
 */