xref: /freebsd/usr.sbin/moused/moused.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
1 /**
2  ** Copyright (c) 1995 Michael Smith, All rights reserved.
3  **
4  ** Redistribution and use in source and binary forms, with or without
5  ** modification, are permitted provided that the following conditions
6  ** are met:
7  ** 1. Redistributions of source code must retain the above copyright
8  **    notice, this list of conditions and the following disclaimer as
9  **    the first lines of this file unmodified.
10  ** 2. Redistributions in binary form must reproduce the above copyright
11  **    notice, this list of conditions and the following disclaimer in the
12  **    documentation and/or other materials provided with the distribution.
13  ** 3. All advertising materials mentioning features or use of this software
14  **    must display the following acknowledgment:
15  **      This product includes software developed by Michael Smith.
16  ** 4. The name of the author may not be used to endorse or promote products
17  **    derived from this software without specific prior written permission.
18  **
19  **
20  ** THIS SOFTWARE IS PROVIDED BY Michael Smith ``AS IS'' AND ANY
21  ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  ** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Michael Smith BE LIABLE FOR
24  ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  ** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  ** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27  ** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28  ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29  ** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  ** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  **
32  **/
33 
34 /**
35  ** MOUSED.C
36  **
37  ** Mouse daemon : listens to a serial port, the bus mouse interface, or
38  ** the PS/2 mouse port for mouse data stream, interprets data and passes
39  ** ioctls off to the console driver.
40  **
41  ** The mouse interface functions are derived closely from the mouse
42  ** handler in the XFree86 X server.  Many thanks to the XFree86 people
43  ** for their great work!
44  **
45  **/
46 
47 #ifndef lint
48 static const char rcsid[] =
49 	"$Id: moused.c,v 1.18 1998/03/12 15:00:06 yokota Exp $";
50 #endif /* not lint */
51 
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <limits.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <stdarg.h>
59 #include <string.h>
60 #include <ctype.h>
61 #include <signal.h>
62 #include <setjmp.h>
63 #include <termios.h>
64 #include <syslog.h>
65 
66 #include <machine/console.h>
67 #include <machine/mouse.h>
68 
69 #include <sys/types.h>
70 #include <sys/time.h>
71 #include <sys/socket.h>
72 #include <sys/un.h>
73 #include <unistd.h>
74 
75 #define MAX_CLICKTHRESHOLD	2000	/* 2 seconds */
76 
77 #define TRUE		1
78 #define FALSE		0
79 
80 #define MOUSE_XAXIS	(-1)
81 #define MOUSE_YAXIS	(-2)
82 
83 #define	ChordMiddle	0x0001
84 #define Emulate3Button	0x0002
85 #define ClearDTR	0x0004
86 #define ClearRTS	0x0008
87 #define NoPnP		0x0010
88 
89 #define ID_NONE		0
90 #define ID_PORT		1
91 #define ID_IF		2
92 #define ID_TYPE 	4
93 #define ID_MODEL	8
94 #define ID_ALL		(ID_PORT | ID_IF | ID_TYPE | ID_MODEL)
95 
96 #define debug(fmt,args...) \
97 	if (debug&&nodaemon) warnx(fmt, ##args)
98 
99 #define logerr(e, fmt, args...) {				\
100 	if (background) {					\
101 	    syslog(LOG_DAEMON | LOG_ERR, fmt ": %m", ##args);	\
102 	    exit(e);						\
103 	} else							\
104 	    err(e, fmt, ##args);				\
105 }
106 
107 #define logerrx(e, fmt, args...) {				\
108 	if (background) {					\
109 	    syslog(LOG_DAEMON | LOG_ERR, fmt, ##args);		\
110 	    exit(e);						\
111 	} else							\
112 	    errx(e, fmt, ##args);				\
113 }
114 
115 #define logwarn(fmt, args...) {					\
116 	if (background)						\
117 	    syslog(LOG_DAEMON | LOG_WARNING, fmt ": %m", ##args); \
118 	else							\
119 	    warn(fmt, ##args);					\
120 }
121 
122 #define logwarnx(fmt, args...) {				\
123 	if (background)						\
124 	    syslog(LOG_DAEMON | LOG_WARNING, fmt, ##args);	\
125 	else							\
126 	    warnx(fmt, ##args);					\
127 }
128 
129 /* structures */
130 
131 /* symbol table entry */
132 typedef struct {
133     char *name;
134     int val;
135     int val2;
136 } symtab_t;
137 
138 /* serial PnP ID string */
139 typedef struct {
140     int revision;	/* PnP revision, 100 for 1.00 */
141     char *eisaid;	/* EISA ID including mfr ID and product ID */
142     char *serial;	/* serial No, optional */
143     char *class;	/* device class, optional */
144     char *compat;	/* list of compatible drivers, optional */
145     char *description;	/* product description, optional */
146     int neisaid;	/* length of the above fields... */
147     int nserial;
148     int nclass;
149     int ncompat;
150     int ndescription;
151 } pnpid_t;
152 
153 /* global variables */
154 
155 int	debug = 0;
156 int	nodaemon = FALSE;
157 int	background = FALSE;
158 int	identify = ID_NONE;
159 int	extioctl = FALSE;
160 char	*pidfile = "/var/run/moused.pid";
161 
162 /* local variables */
163 
164 /* interface (the table must be ordered by MOUSE_IF_XXX in mouse.h) */
165 static symtab_t rifs[] = {
166     { "serial",		MOUSE_IF_SERIAL },
167     { "bus",		MOUSE_IF_BUS },
168     { "inport",		MOUSE_IF_INPORT },
169     { "ps/2",		MOUSE_IF_PS2 },
170     { "sysmouse",	MOUSE_IF_SYSMOUSE },
171     { NULL,		MOUSE_IF_UNKNOWN },
172 };
173 
174 /* types (the table must be ordered by MOUSE_PROTO_XXX in mouse.h) */
175 static char *rnames[] = {
176     "microsoft",
177     "mousesystems",
178     "logitech",
179     "mmseries",
180     "mouseman",
181     "busmouse",
182     "inportmouse",
183     "ps/2",
184     "mmhitab",
185     "glidepoint",
186     "intellimouse",
187     "thinkingmouse",
188     "sysmouse",
189     "x10mouseremote",
190 #if notyet
191     "mariqua",
192 #endif
193     NULL
194 };
195 
196 /* models */
197 static symtab_t	rmodels[] = {
198     { "NetScroll",	MOUSE_MODEL_NETSCROLL },
199     { "NetMouse",	MOUSE_MODEL_NET },
200     { "GlidePoint",	MOUSE_MODEL_GLIDEPOINT },
201     { "ThinkingMouse",	MOUSE_MODEL_THINK },
202     { "IntelliMouse",	MOUSE_MODEL_INTELLI },
203     { "EasyScroll",	MOUSE_MODEL_EASYSCROLL },
204     { "MouseMan+",	MOUSE_MODEL_MOUSEMANPLUS },
205     { "generic",	MOUSE_MODEL_GENERIC },
206     { NULL, 		MOUSE_MODEL_UNKNOWN },
207 };
208 
209 /* PnP EISA/product IDs */
210 static symtab_t pnpprod[] = {
211     /* Kensignton ThinkingMouse */
212     { "KML0001",	MOUSE_PROTO_THINK,	MOUSE_MODEL_THINK },
213     /* MS IntelliMouse */
214     { "MSH0001",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
215     /* MS IntelliMouse TrackBall */
216     { "MSH0004",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
217     /* Genius PnP Mouse */
218     { "KYE0001",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
219     /* Genius NetMouse */
220     { "KYE0003",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_NET },
221     /* Genius EZScroll */
222     { "KYEEZ00",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
223     /* Logitech MouseMan (new 4 button model) */
224     { "LGI800C",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
225     /* Logitech MouseMan+ */
226     { "LGI8050",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
227     /* Logitech FirstMouse+ */
228     { "LGI8051",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
229     /* Logitech serial */
230     { "LGI8001",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
231 
232     /* MS bus */
233     { "PNP0F00",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
234     /* MS serial */
235     { "PNP0F01",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
236     /* MS InPort */
237     { "PNP0F02",	MOUSE_PROTO_INPORT,	MOUSE_MODEL_GENERIC },
238     /* MS PS/2 */
239     { "PNP0F03",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
240     /*
241      * EzScroll returns PNP0F04 in the compatible device field; but it
242      * doesn't look compatible... XXX
243      */
244     /* MouseSystems */
245     { "PNP0F04",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
246     /* MouseSystems */
247     { "PNP0F05",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
248 #if notyet
249     /* Genius Mouse */
250     { "PNP0F06",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
251     /* Genius Mouse */
252     { "PNP0F07",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
253 #endif
254     /* Logitech serial */
255     { "PNP0F08",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
256     /* MS BallPoint serial */
257     { "PNP0F09",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
258     /* MS PnP serial */
259     { "PNP0F0A",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
260     /* MS PnP BallPoint serial */
261     { "PNP0F0B",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
262     /* MS serial comatible */
263     { "PNP0F0C",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
264     /* MS InPort comatible */
265     { "PNP0F0D",	MOUSE_PROTO_INPORT,	MOUSE_MODEL_GENERIC },
266     /* MS PS/2 comatible */
267     { "PNP0F0E",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
268     /* MS BallPoint comatible */
269     { "PNP0F0F",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
270 #if notyet
271     /* TI QuickPort */
272     { "PNP0F10",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
273 #endif
274     /* MS bus comatible */
275     { "PNP0F11",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
276     /* Logitech PS/2 */
277     { "PNP0F12",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
278     /* PS/2 */
279     { "PNP0F13",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
280 #if notyet
281     /* MS Kids Mouse */
282     { "PNP0F14",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
283 #endif
284     /* Logitech bus */
285     { "PNP0F15",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
286 #if notyet
287     /* Logitech SWIFT */
288     { "PNP0F16",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
289 #endif
290     /* Logitech serial compat */
291     { "PNP0F17",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
292     /* Logitech bus compatible */
293     { "PNP0F18",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
294     /* Logitech PS/2 compatible */
295     { "PNP0F19",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
296 #if notyet
297     /* Logitech SWIFT compatible */
298     { "PNP0F1A",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
299     /* HP Omnibook */
300     { "PNP0F1B",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
301     /* Compaq LTE TrackBall PS/2 */
302     { "PNP0F1C",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
303     /* Compaq LTE TrackBall serial */
304     { "PNP0F1D",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
305     /* MS Kidts Trackball */
306     { "PNP0F1E",	MOUSE_PROTO_???,	MOUSE_MODEL_GENERIC },
307 #endif
308 
309     { NULL,		MOUSE_PROTO_UNKNOWN,	MOUSE_MODEL_GENERIC },
310 };
311 
312 /* the table must be ordered by MOUSE_PROTO_XXX in mouse.h */
313 static unsigned short rodentcflags[] =
314 {
315     (CS7	           | CREAD | CLOCAL | HUPCL ),	/* MicroSoft */
316     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL ),	/* MouseSystems */
317     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL ),	/* Logitech */
318     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL ),	/* MMSeries */
319     (CS7		   | CREAD | CLOCAL | HUPCL ),	/* MouseMan */
320     0,							/* Bus */
321     0,							/* InPort */
322     0,							/* PS/2 */
323     (CS8		   | CREAD | CLOCAL | HUPCL ),	/* MM HitTablet */
324     (CS7	           | CREAD | CLOCAL | HUPCL ),	/* GlidePoint */
325     (CS7                   | CREAD | CLOCAL | HUPCL ),	/* IntelliMouse */
326     (CS7                   | CREAD | CLOCAL | HUPCL ),	/* Thinking Mouse */
327     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL ),	/* sysmouse */
328     (CS7	           | CREAD | CLOCAL | HUPCL ),	/* X10 MouseRemote */
329 #if notyet
330     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL ),	/* Mariqua */
331 #endif
332 };
333 
334 static struct rodentparam {
335     int flags;
336     char *portname;		/* /dev/XXX */
337     int rtype;			/* MOUSE_PROTO_XXX */
338     int level;			/* operation level: 0 or greater */
339     int baudrate;
340     int rate;			/* report rate */
341     int resolution;		/* MOUSE_RES_XXX or a positive number */
342     int zmap;			/* MOUSE_{X|Y}AXIS or a button number */
343     int mfd;			/* mouse file descriptor */
344     int cfd;			/* /dev/consolectl file descriptor */
345     int mremsfd;		/* mouse remote server file descriptor */
346     int mremcfd;		/* mouse remote client file descriptor */
347     long clickthreshold;	/* double click speed in msec */
348     mousehw_t hw;		/* mouse device hardware information */
349     mousemode_t mode;		/* protocol information */
350 } rodent = {
351     flags : 0,
352     portname : NULL,
353     rtype : MOUSE_PROTO_UNKNOWN,
354     level : -1,
355     baudrate : 1200,
356     rate : 0,
357     resolution : MOUSE_RES_UNKNOWN,
358     zmap: 0,
359     mfd : -1,
360     cfd : -1,
361     mremsfd : -1,
362     mremcfd : -1,
363     clickthreshold : 500,	/* 0.5 sec */
364 };
365 
366 /* button status */
367 static struct {
368     int count;		/* 0: up, 1: single click, 2: double click,... */
369     struct timeval tv;	/* timestamp on the last `up' event */
370 } buttonstate[MOUSE_MAXBUTTON];
371 
372 static jmp_buf env;
373 
374 /* function prototypes */
375 
376 static void	moused(void);
377 static void	hup(int sig);
378 static void	cleanup(int sig);
379 static void	usage(void);
380 
381 static int	r_identify(void);
382 static char	*r_if(int type);
383 static char	*r_name(int type);
384 static char	*r_model(int model);
385 static void	r_init(void);
386 static int	r_protocol(u_char b, mousestatus_t *act);
387 static int	r_installmap(char *arg);
388 static void	r_map(mousestatus_t *act1, mousestatus_t *act2);
389 static void	r_click(mousestatus_t *act);
390 static void	setmousespeed(int old, int new, unsigned cflag);
391 
392 static int	pnpgets(char *buf);
393 static int	pnpparse(pnpid_t *id, char *buf, int len);
394 static symtab_t	*pnpproto(pnpid_t *id);
395 
396 static symtab_t	*gettoken(symtab_t *tab, char *s, int len);
397 static char	*gettokenname(symtab_t *tab, int val);
398 
399 static void	mremote_serversetup();
400 static void	mremote_clientchg(int add);
401 
402 void
403 main(int argc, char *argv[])
404 {
405     int c;
406     int	i;
407 
408     while((c = getopt(argc,argv,"3C:DF:I:PRS:cdfhi:l:m:p:r:st:z:")) != -1)
409 	switch(c) {
410 
411 	case '3':
412 	    rodent.flags |= Emulate3Button;
413 	    break;
414 
415 	case 'c':
416 	    rodent.flags |= ChordMiddle;
417 	    break;
418 
419 	case 'd':
420 	    ++debug;
421 	    break;
422 
423 	case 'f':
424 	    nodaemon = TRUE;
425 	    break;
426 
427 	case 'i':
428 	    if (strcmp(optarg, "all") == 0)
429 	        identify = ID_ALL;
430 	    else if (strcmp(optarg, "port") == 0)
431 	        identify = ID_PORT;
432 	    else if (strcmp(optarg, "if") == 0)
433 	        identify = ID_IF;
434 	    else if (strcmp(optarg, "type") == 0)
435 	        identify = ID_TYPE;
436 	    else if (strcmp(optarg, "model") == 0)
437 	        identify = ID_MODEL;
438 	    else {
439 	        warnx("invalid argument `%s'", optarg);
440 	        usage();
441 	    }
442 	    nodaemon = TRUE;
443 	    break;
444 
445 	case 'l':
446 	    rodent.level = atoi(optarg);
447 	    if ((rodent.level < 0) || (rodent.level > 4)) {
448 	        warnx("invalid argument `%s'", optarg);
449 	        usage();
450 	    }
451 	    break;
452 
453 	case 'm':
454 	    if (!r_installmap(optarg)) {
455 	        warnx("invalid argument `%s'", optarg);
456 	        usage();
457 	    }
458 	    break;
459 
460 	case 'p':
461 	    rodent.portname = optarg;
462 	    break;
463 
464 	case 'r':
465 	    if (strcmp(optarg, "high") == 0)
466 	        rodent.resolution = MOUSE_RES_HIGH;
467 	    else if (strcmp(optarg, "medium-high") == 0)
468 	        rodent.resolution = MOUSE_RES_HIGH;
469 	    else if (strcmp(optarg, "medium-low") == 0)
470 	        rodent.resolution = MOUSE_RES_MEDIUMLOW;
471 	    else if (strcmp(optarg, "low") == 0)
472 	        rodent.resolution = MOUSE_RES_LOW;
473 	    else if (strcmp(optarg, "default") == 0)
474 	        rodent.resolution = MOUSE_RES_DEFAULT;
475 	    else {
476 	        rodent.resolution = atoi(optarg);
477 	        if (rodent.resolution <= 0) {
478 	            warnx("invalid argument `%s'", optarg);
479 	            usage();
480 	        }
481 	    }
482 	    break;
483 
484 	case 's':
485 	    rodent.baudrate = 9600;
486 	    break;
487 
488 	case 'z':
489 	    if (strcmp(optarg, "x") == 0)
490 		rodent.zmap = MOUSE_XAXIS;
491 	    else if (strcmp(optarg, "y") == 0)
492 		rodent.zmap = MOUSE_YAXIS;
493             else {
494 		i = atoi(optarg);
495 		/*
496 		 * Use button i for negative Z axis movement and
497 		 * button (i + 1) for positive Z axis movement.
498 		 */
499 		if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
500 	            warnx("invalid argument `%s'", optarg);
501 	            usage();
502 		}
503 		rodent.zmap = 1 << (i - 1);
504 	    }
505 	    break;
506 
507 	case 'C':
508 	    rodent.clickthreshold = atoi(optarg);
509 	    if ((rodent.clickthreshold < 0) ||
510 	        (rodent.clickthreshold > MAX_CLICKTHRESHOLD)) {
511 	        warnx("invalid argument `%s'", optarg);
512 	        usage();
513 	    }
514 	    break;
515 
516 	case 'D':
517 	    rodent.flags |= ClearDTR;
518 	    break;
519 
520 	case 'F':
521 	    rodent.rate = atoi(optarg);
522 	    if (rodent.rate <= 0) {
523 	        warnx("invalid argument `%s'", optarg);
524 	        usage();
525 	    }
526 	    break;
527 
528 	case 'I':
529 	    pidfile = optarg;
530 	    break;
531 
532 	case 'P':
533 	    rodent.flags |= NoPnP;
534 	    break;
535 
536 	case 'R':
537 	    rodent.flags |= ClearRTS;
538 	    break;
539 
540 	case 'S':
541 	    rodent.baudrate = atoi(optarg);
542 	    if (rodent.baudrate <= 0) {
543 	        warnx("invalid argument `%s'", optarg);
544 	        usage();
545 	    }
546 	    debug("rodent baudrate %d", rodent.baudrate);
547 	    break;
548 
549 	case 't':
550 	    if (strcmp(optarg, "auto") == 0) {
551 		rodent.rtype = MOUSE_PROTO_UNKNOWN;
552 		rodent.flags &= ~NoPnP;
553 		rodent.level = -1;
554 		break;
555 	    }
556 	    for (i = 0; rnames[i]; i++)
557 		if (strcmp(optarg, rnames[i]) == 0) {
558 		    rodent.rtype = i;
559 		    rodent.flags |= NoPnP;
560 		    rodent.level = (i == MOUSE_PROTO_SYSMOUSE) ? 1 : 0;
561 		    break;
562 		}
563 	    if (rnames[i])
564 		break;
565 	    warnx("no such mouse type `%s'", optarg);
566 	    usage();
567 
568 	case 'h':
569 	case '?':
570 	default:
571 	    usage();
572 	}
573 
574     /* the default port name */
575     switch(rodent.rtype) {
576 
577     case MOUSE_PROTO_INPORT:
578         /* INPORT and BUS are the same... */
579 	rodent.rtype = MOUSE_PROTO_BUS;
580 	/* FALL THROUGH */
581     case MOUSE_PROTO_BUS:
582 	if (!rodent.portname)
583 	    rodent.portname = "/dev/mse0";
584 	break;
585 
586     case MOUSE_PROTO_PS2:
587 	if (!rodent.portname)
588 	    rodent.portname = "/dev/psm0";
589 	break;
590 
591     default:
592 	if (rodent.portname)
593 	    break;
594 	warnx("no port name specified");
595 	usage();
596     }
597 
598     for (;;) {
599 	if (setjmp(env) == 0) {
600 	    signal(SIGHUP, hup);
601 	    signal(SIGINT , cleanup);
602 	    signal(SIGQUIT, cleanup);
603 	    signal(SIGTERM, cleanup);
604             if ((rodent.mfd = open(rodent.portname, O_RDWR | O_NONBLOCK, 0))
605 		== -1)
606 	        logerr(1, "unable to open %s", rodent.portname);
607             if (r_identify() == MOUSE_PROTO_UNKNOWN) {
608 	        logwarnx("cannot determine mouse type on %s", rodent.portname);
609 	        close(rodent.mfd);
610 	        rodent.mfd = -1;
611             }
612 
613 	    /* print some information */
614             if (identify != ID_NONE) {
615 		if (identify == ID_ALL)
616                     printf("%s %s %s %s\n",
617 		        rodent.portname, r_if(rodent.hw.iftype),
618 		        r_name(rodent.rtype), r_model(rodent.hw.model));
619 		else if (identify & ID_PORT)
620 		    printf("%s\n", rodent.portname);
621 		else if (identify & ID_IF)
622 		    printf("%s\n", r_if(rodent.hw.iftype));
623 		else if (identify & ID_TYPE)
624 		    printf("%s\n", r_name(rodent.rtype));
625 		else if (identify & ID_MODEL)
626 		    printf("%s\n", r_model(rodent.hw.model));
627 		exit(0);
628 	    } else {
629                 debug("port: %s  interface: %s  type: %s  model: %s",
630 		    rodent.portname, r_if(rodent.hw.iftype),
631 		    r_name(rodent.rtype), r_model(rodent.hw.model));
632 	    }
633 
634 	    if (rodent.mfd == -1) {
635 	        /*
636 	         * We cannot continue because of error.  Exit if the
637 		 * program has not become a daemon.  Otherwise, block
638 		 * until the the user corrects the problem and issues SIGHUP.
639 	         */
640 	        if (!background)
641 		    exit(1);
642 	        sigpause(0);
643 	    }
644 
645             r_init();			/* call init function */
646 	    moused();
647 	}
648 
649 	if (rodent.mfd != -1)
650 	    close(rodent.mfd);
651 	if (rodent.cfd != -1)
652 	    close(rodent.cfd);
653 	rodent.mfd = rodent.cfd = -1;
654     }
655     /* NOT REACHED */
656 
657     exit(0);
658 }
659 
660 static void
661 moused(void)
662 {
663     struct mouse_info mouse;
664     mousestatus_t action;		/* original mouse action */
665     mousestatus_t action2;		/* mapped action */
666     fd_set fds;
667     u_char b;
668     FILE *fp;
669 
670     if ((rodent.cfd = open("/dev/consolectl", O_RDWR, 0)) == -1)
671 	logerr(1, "cannot open /dev/consolectl", 0);
672 
673     if (!nodaemon && !background)
674 	if (daemon(0, 0)) {
675 	    logerr(1, "failed to become a daemon", 0);
676 	} else {
677 	    background = TRUE;
678 	    fp = fopen(pidfile, "w");
679 	    if (fp != NULL) {
680 		fprintf(fp, "%d\n", getpid());
681 		fclose(fp);
682 	    }
683 	}
684 
685     /* clear mouse data */
686     bzero(&action, sizeof(action));
687     bzero(&action2, sizeof(action2));
688     bzero(&buttonstate, sizeof(buttonstate));
689     bzero(&mouse, sizeof(mouse));
690 
691     /* choose which ioctl command to use */
692     mouse.operation = MOUSE_MOTION_EVENT;
693     extioctl = (ioctl(rodent.cfd, CONS_MOUSECTL, &mouse) == 0);
694 
695     /* process mouse data */
696     for (;;) {
697 
698 	FD_ZERO(&fds);
699 	FD_SET(rodent.mfd, &fds);
700 	if (rodent.mremsfd >= 0)  FD_SET(rodent.mremsfd, &fds);
701 	if (rodent.mremcfd >= 0)  FD_SET(rodent.mremcfd, &fds);
702 
703 	if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
704 	    logwarn("failed to read from mouse", 0);
705 
706 	/*  MouseRemote client connect/disconnect  */
707 	if ((rodent.mremsfd >= 0) && FD_ISSET(rodent.mremsfd, &fds)) {
708 	    mremote_clientchg(TRUE);
709 	    continue;
710 	}
711 
712 	if ((rodent.mremcfd >= 0) && FD_ISSET(rodent.mremcfd, &fds)) {
713 	    mremote_clientchg(FALSE);
714 	    continue;
715 	}
716 
717 	/*  mouse event  */
718 	read(rodent.mfd, &b, 1);
719 	if (r_protocol(b, &action)) {	/* handler detected action */
720 	    r_map(&action, &action2);
721 	    debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
722 		action2.button, action2.dx, action2.dy, action2.dz);
723 
724 	    if (extioctl) {
725 	        r_click(&action2);
726 	        if (action2.flags & MOUSE_POSCHANGED) {
727     		    mouse.operation = MOUSE_MOTION_EVENT;
728 	            mouse.u.data.buttons = action2.button;
729 	            mouse.u.data.x = action2.dx;
730 	            mouse.u.data.y = action2.dy;
731 	            mouse.u.data.z = action2.dz;
732 		    if (debug < 2)
733 	                ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
734 	        }
735 	    } else {
736 	        mouse.operation = MOUSE_ACTION;
737 	        mouse.u.data.buttons = action2.button;
738 	        mouse.u.data.x = action2.dx;
739 	        mouse.u.data.y = action2.dy;
740 	        mouse.u.data.z = action2.dz;
741 		if (debug < 2)
742 	            ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
743 	    }
744 
745             /*
746 	     * If the Z axis movement is mapped to a imaginary physical
747 	     * button, we need to cook up a corresponding button `up' event
748 	     * after sending a button `down' event.
749 	     */
750             if ((rodent.zmap > 0) && (action.dz != 0)) {
751 		action.obutton = action.button;
752 		action.dx = action.dy = action.dz = 0;
753 	        r_map(&action, &action2);
754 	        debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
755 		    action2.button, action2.dx, action2.dy, action2.dz);
756 
757 	        if (extioctl) {
758 	            r_click(&action2);
759 	        } else {
760 	            mouse.operation = MOUSE_ACTION;
761 	            mouse.u.data.buttons = action2.button;
762 		    mouse.u.data.x = mouse.u.data.y = mouse.u.data.z = 0;
763 		    if (debug < 2)
764 	                ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
765 	        }
766 	    }
767 	}
768     }
769     /* NOT REACHED */
770 }
771 
772 static void
773 hup(int sig)
774 {
775     longjmp(env, 1);
776 }
777 
778 static void
779 cleanup(int sig)
780 {
781     if (rodent.rtype == MOUSE_PROTO_X10MOUSEREM)
782 	unlink(_PATH_MOUSEREMOTE);
783     exit(0);
784 }
785 
786 /**
787  ** usage
788  **
789  ** Complain, and free the CPU for more worthy tasks
790  **/
791 static void
792 usage(void)
793 {
794     fprintf(stderr, "%s\n%s\n%s\n",
795         "usage: moused [-3DRcdfs] [-I file] [-F rate] [-r resolution] [-S baudrate] [-C threshold]",
796         "              [-m N=M] [-z N] [-t <mousetype>] -p <port>",
797 	"       moused [-d] -i -p <port>");
798     exit(1);
799 }
800 
801 /**
802  ** Mouse interface code, courtesy of XFree86 3.1.2.
803  **
804  ** Note: Various bits have been trimmed, and in my shortsighted enthusiasm
805  ** to clean, reformat and rationalise naming, it's quite possible that
806  ** some things in here have been broken.
807  **
808  ** I hope not 8)
809  **
810  ** The following code is derived from a module marked :
811  **/
812 
813 /* $XConsortium: xf86_Mouse.c,v 1.2 94/10/12 20:33:21 kaleb Exp $ */
814 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.2 1995/01/28
815  17:03:40 dawes Exp $ */
816 /*
817  *
818  * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
819  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
820  *
821  * Permission to use, copy, modify, distribute, and sell this software and its
822  * documentation for any purpose is hereby granted without fee, provided that
823  * the above copyright notice appear in all copies and that both that
824  * copyright notice and this permission notice appear in supporting
825  * documentation, and that the names of Thomas Roell and David Dawes not be
826  * used in advertising or publicity pertaining to distribution of the
827  * software without specific, written prior permission.  Thomas Roell
828  * and David Dawes makes no representations about the suitability of this
829  * software for any purpose.  It is provided "as is" without express or
830  * implied warranty.
831  *
832  * THOMAS ROELL AND DAVID DAWES DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
833  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
834  * FITNESS, IN NO EVENT SHALL THOMAS ROELL OR DAVID DAWES BE LIABLE FOR ANY
835  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
836  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
837  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
838  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
839  *
840  */
841 
842 /**
843  ** GlidePoint support from XFree86 3.2.
844  ** Derived from the module:
845  **/
846 
847 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.19 1996/10/16 14:40:51 dawes Exp $ */
848 /* $XConsortium: xf86_Mouse.c /main/10 1996/01/30 15:16:12 kaleb $ */
849 
850 /* the following table must be ordered by MOUSE_PROTO_XXX in mouse.h */
851 static unsigned char proto[][7] = {
852     /*  hd_mask hd_id   dp_mask dp_id   bytes b4_mask b4_id */
853     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* MicroSoft */
854     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* MouseSystems */
855     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* Logitech */
856     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MMSeries */
857     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* MouseMan */
858     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* Bus */
859     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* InPort */
860     {	0xc0,	0x00,	0x00,	0x00,	3,    0x00,  0xff }, /* PS/2 mouse */
861     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MM HitTablet */
862     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* GlidePoint */
863     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x3f,  0x00 }, /* IntelliMouse */
864     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* ThinkingMouse */
865     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* sysmouse */
866     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* X10 MouseRem */
867 #if notyet
868     {	0xf8,	0x80,	0x00,	0x00,	5,   ~0x2f,  0x10 }, /* Mariqua */
869 #endif
870 };
871 static unsigned char cur_proto[7];
872 
873 static int
874 r_identify(void)
875 {
876     char pnpbuf[256];	/* PnP identifier string may be up to 256 bytes long */
877     pnpid_t pnpid;
878     symtab_t *t;
879     int level;
880     int len;
881 
882     /* set the driver operation level, if applicable */
883     if (rodent.level < 0)
884 	rodent.level = 1;
885     ioctl(rodent.mfd, MOUSE_SETLEVEL, &rodent.level);
886     rodent.level = (ioctl(rodent.mfd, MOUSE_GETLEVEL, &level) == 0) ? level : 0;
887 
888     /*
889      * Interrogate the driver and get some intelligence on the device...
890      * The following ioctl functions are not always supported by device
891      * drivers.  When the driver doesn't support them, we just trust the
892      * user to supply valid information.
893      */
894     rodent.hw.iftype = MOUSE_IF_UNKNOWN;
895     rodent.hw.model = MOUSE_MODEL_GENERIC;
896     ioctl(rodent.mfd, MOUSE_GETHWINFO, &rodent.hw);
897 
898     if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
899         bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
900     rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
901     rodent.mode.rate = -1;
902     rodent.mode.resolution = MOUSE_RES_UNKNOWN;
903     rodent.mode.accelfactor = 0;
904     rodent.mode.level = 0;
905     if (ioctl(rodent.mfd, MOUSE_GETMODE, &rodent.mode) == 0) {
906         if ((rodent.mode.protocol == MOUSE_PROTO_UNKNOWN)
907 	    || (rodent.mode.protocol >= sizeof(proto)/sizeof(proto[0]))) {
908 	    logwarnx("unknown mouse protocol (%d)", rodent.mode.protocol);
909 	    return MOUSE_PROTO_UNKNOWN;
910         } else {
911 	    /* INPORT and BUS are the same... */
912 	    if (rodent.mode.protocol == MOUSE_PROTO_INPORT)
913 	        rodent.mode.protocol = MOUSE_PROTO_BUS;
914 	    if (rodent.mode.protocol != rodent.rtype) {
915 		/* Hmm, the driver doesn't agree with the user... */
916                 if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
917 	            logwarnx("mouse type mismatch (%s != %s), %s is assumed",
918 		        r_name(rodent.mode.protocol), r_name(rodent.rtype),
919 		        r_name(rodent.mode.protocol));
920 	        rodent.rtype = rodent.mode.protocol;
921                 bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
922 	    }
923         }
924         cur_proto[4] = rodent.mode.packetsize;
925         cur_proto[0] = rodent.mode.syncmask[0];	/* header byte bit mask */
926         cur_proto[1] = rodent.mode.syncmask[1];	/* header bit pattern */
927     }
928 
929     /* maybe this is an PnP mouse... */
930     if (rodent.mode.protocol == MOUSE_PROTO_UNKNOWN) {
931 
932         if (rodent.flags & NoPnP)
933             return rodent.rtype;
934 	if (((len = pnpgets(pnpbuf)) <= 0) || !pnpparse(&pnpid, pnpbuf, len))
935             return rodent.rtype;
936 
937         debug("PnP serial mouse: '%*.*s' '%*.*s' '%*.*s'",
938 	    pnpid.neisaid, pnpid.neisaid, pnpid.eisaid,
939 	    pnpid.ncompat, pnpid.ncompat, pnpid.compat,
940 	    pnpid.ndescription, pnpid.ndescription, pnpid.description);
941 
942 	/* we have a valid PnP serial device ID */
943         rodent.hw.iftype = MOUSE_IF_SERIAL;
944 	t = pnpproto(&pnpid);
945 	if (t != NULL) {
946             rodent.mode.protocol = t->val;
947             rodent.hw.model = t->val2;
948 	} else {
949             rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
950 	}
951 	if (rodent.mode.protocol == MOUSE_PROTO_INPORT)
952 	    rodent.mode.protocol = MOUSE_PROTO_BUS;
953 
954         /* make final adjustment */
955 	if (rodent.mode.protocol != MOUSE_PROTO_UNKNOWN) {
956 	    if (rodent.mode.protocol != rodent.rtype) {
957 		/* Hmm, the device doesn't agree with the user... */
958                 if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
959 	            logwarnx("mouse type mismatch (%s != %s), %s is assumed",
960 		        r_name(rodent.mode.protocol), r_name(rodent.rtype),
961 		        r_name(rodent.mode.protocol));
962 	        rodent.rtype = rodent.mode.protocol;
963                 bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
964 	    }
965 	}
966     }
967 
968     debug("proto params: %02x %02x %02x %02x %d %02x %02x",
969 	cur_proto[0], cur_proto[1], cur_proto[2], cur_proto[3],
970 	cur_proto[4], cur_proto[5], cur_proto[6]);
971 
972     return rodent.rtype;
973 }
974 
975 static char *
976 r_if(int iftype)
977 {
978     char *s;
979 
980     s = gettokenname(rifs, iftype);
981     return (s == NULL) ? "unknown" : s;
982 }
983 
984 static char *
985 r_name(int type)
986 {
987     return ((type == MOUSE_PROTO_UNKNOWN)
988 	|| (type > sizeof(rnames)/sizeof(rnames[0]) - 1))
989 	? "unknown" : rnames[type];
990 }
991 
992 static char *
993 r_model(int model)
994 {
995     char *s;
996 
997     s = gettokenname(rmodels, model);
998     return (s == NULL) ? "unknown" : s;
999 }
1000 
1001 static void
1002 r_init(void)
1003 {
1004     fd_set fds;
1005     char *s;
1006     char c;
1007     int i;
1008 
1009     /**
1010      ** This comment is a little out of context here, but it contains
1011      ** some useful information...
1012      ********************************************************************
1013      **
1014      ** The following lines take care of the Logitech MouseMan protocols.
1015      **
1016      ** NOTE: There are different versions of both MouseMan and TrackMan!
1017      **       Hence I add another protocol P_LOGIMAN, which the user can
1018      **       specify as MouseMan in his XF86Config file. This entry was
1019      **       formerly handled as a special case of P_MS. However, people
1020      **       who don't have the middle button problem, can still specify
1021      **       Microsoft and use P_MS.
1022      **
1023      ** By default, these mice should use a 3 byte Microsoft protocol
1024      ** plus a 4th byte for the middle button. However, the mouse might
1025      ** have switched to a different protocol before we use it, so I send
1026      ** the proper sequence just in case.
1027      **
1028      ** NOTE: - all commands to (at least the European) MouseMan have to
1029      **         be sent at 1200 Baud.
1030      **       - each command starts with a '*'.
1031      **       - whenever the MouseMan receives a '*', it will switch back
1032      **	 to 1200 Baud. Hence I have to select the desired protocol
1033      **	 first, then select the baud rate.
1034      **
1035      ** The protocols supported by the (European) MouseMan are:
1036      **   -  5 byte packed binary protocol, as with the Mouse Systems
1037      **      mouse. Selected by sequence "*U".
1038      **   -  2 button 3 byte MicroSoft compatible protocol. Selected
1039      **      by sequence "*V".
1040      **   -  3 button 3+1 byte MicroSoft compatible protocol (default).
1041      **      Selected by sequence "*X".
1042      **
1043      ** The following baud rates are supported:
1044      **   -  1200 Baud (default). Selected by sequence "*n".
1045      **   -  9600 Baud. Selected by sequence "*q".
1046      **
1047      ** Selecting a sample rate is no longer supported with the MouseMan!
1048      ** Some additional lines in xf86Config.c take care of ill configured
1049      ** baud rates and sample rates. (The user will get an error.)
1050      */
1051 
1052     switch (rodent.rtype) {
1053 
1054     case MOUSE_PROTO_LOGI:
1055 	/*
1056 	 * The baud rate selection command must be sent at the current
1057 	 * baud rate; try all likely settings
1058 	 */
1059 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1060 	setmousespeed(4800, rodent.baudrate, rodentcflags[rodent.rtype]);
1061 	setmousespeed(2400, rodent.baudrate, rodentcflags[rodent.rtype]);
1062 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1063 	/* select MM series data format */
1064 	write(rodent.mfd, "S", 1);
1065 	setmousespeed(rodent.baudrate, rodent.baudrate,
1066 		      rodentcflags[MOUSE_PROTO_MM]);
1067 	/* select report rate/frequency */
1068 	if      (rodent.rate <= 0)   write(rodent.mfd, "O", 1);
1069 	else if (rodent.rate <= 15)  write(rodent.mfd, "J", 1);
1070 	else if (rodent.rate <= 27)  write(rodent.mfd, "K", 1);
1071 	else if (rodent.rate <= 42)  write(rodent.mfd, "L", 1);
1072 	else if (rodent.rate <= 60)  write(rodent.mfd, "R", 1);
1073 	else if (rodent.rate <= 85)  write(rodent.mfd, "M", 1);
1074 	else if (rodent.rate <= 125) write(rodent.mfd, "Q", 1);
1075 	else			     write(rodent.mfd, "N", 1);
1076 	break;
1077 
1078     case MOUSE_PROTO_LOGIMOUSEMAN:
1079 	/* The command must always be sent at 1200 baud */
1080 	setmousespeed(1200, 1200, rodentcflags[rodent.rtype]);
1081 	write(rodent.mfd, "*X", 2);
1082 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1083 	break;
1084 
1085     case MOUSE_PROTO_HITTAB:
1086 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1087 
1088 	/*
1089 	 * Initialize Hitachi PUMA Plus - Model 1212E to desired settings.
1090 	 * The tablet must be configured to be in MM mode, NO parity,
1091 	 * Binary Format.  xf86Info.sampleRate controls the sensativity
1092 	 * of the tablet.  We only use this tablet for it's 4-button puck
1093 	 * so we don't run in "Absolute Mode"
1094 	 */
1095 	write(rodent.mfd, "z8", 2);	/* Set Parity = "NONE" */
1096 	usleep(50000);
1097 	write(rodent.mfd, "zb", 2);	/* Set Format = "Binary" */
1098 	usleep(50000);
1099 	write(rodent.mfd, "@", 1);	/* Set Report Mode = "Stream" */
1100 	usleep(50000);
1101 	write(rodent.mfd, "R", 1);	/* Set Output Rate = "45 rps" */
1102 	usleep(50000);
1103 	write(rodent.mfd, "I\x20", 2);	/* Set Incrememtal Mode "20" */
1104 	usleep(50000);
1105 	write(rodent.mfd, "E", 1);	/* Set Data Type = "Relative */
1106 	usleep(50000);
1107 
1108 	/* Resolution is in 'lines per inch' on the Hitachi tablet */
1109 	if      (rodent.resolution == MOUSE_RES_LOW) 		c = 'g';
1110 	else if (rodent.resolution == MOUSE_RES_MEDIUMLOW)	c = 'e';
1111 	else if (rodent.resolution == MOUSE_RES_MEDIUMHIGH)	c = 'h';
1112 	else if (rodent.resolution == MOUSE_RES_HIGH)		c = 'd';
1113 	else if (rodent.resolution <=   40) 			c = 'g';
1114 	else if (rodent.resolution <=  100) 			c = 'd';
1115 	else if (rodent.resolution <=  200) 			c = 'e';
1116 	else if (rodent.resolution <=  500) 			c = 'h';
1117 	else if (rodent.resolution <= 1000) 			c = 'j';
1118 	else                                			c = 'd';
1119 	write(rodent.mfd, &c, 1);
1120 	usleep(50000);
1121 
1122 	write(rodent.mfd, "\021", 1);	/* Resume DATA output */
1123 	break;
1124 
1125     case MOUSE_PROTO_THINK:
1126 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1127 	/* the PnP ID string may be sent again, discard it */
1128 	usleep(200000);
1129 	i = FREAD;
1130 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1131 	/* send the command to initialize the beast */
1132 	for (s = "E5E5"; *s; ++s) {
1133 	    write(rodent.mfd, s, 1);
1134 	    FD_ZERO(&fds);
1135 	    FD_SET(rodent.mfd, &fds);
1136 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1137 		break;
1138 	    read(rodent.mfd, &c, 1);
1139 	    debug("%c", c);
1140 	    if (c != *s)
1141 	        break;
1142 	}
1143 	break;
1144 
1145     case MOUSE_PROTO_MSC:
1146 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1147 	if (rodent.flags & ClearDTR) {
1148 	   i = TIOCM_DTR;
1149 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1150         }
1151         if (rodent.flags & ClearRTS) {
1152 	   i = TIOCM_RTS;
1153 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1154         }
1155 	break;
1156 
1157     case MOUSE_PROTO_SYSMOUSE:
1158 	if (rodent.hw.iftype == MOUSE_IF_SYSMOUSE)
1159 	    setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1160 	/* fall through */
1161 
1162     case MOUSE_PROTO_BUS:
1163     case MOUSE_PROTO_INPORT:
1164     case MOUSE_PROTO_PS2:
1165 	if (rodent.rate >= 0)
1166 	    rodent.mode.rate = rodent.rate;
1167 	if (rodent.resolution != MOUSE_RES_UNKNOWN)
1168 	    rodent.mode.resolution = rodent.resolution;
1169 	ioctl(rodent.mfd, MOUSE_SETMODE, &rodent.mode);
1170 	break;
1171 
1172     case MOUSE_PROTO_X10MOUSEREM:
1173 	mremote_serversetup();
1174 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1175 	break;
1176 
1177 
1178     default:
1179 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1180 	break;
1181     }
1182 }
1183 
1184 static int
1185 r_protocol(u_char rBuf, mousestatus_t *act)
1186 {
1187     /* MOUSE_MSS_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1188     static int butmapmss[4] = {	/* Microsoft, MouseMan, GlidePoint,
1189 				   IntelliMouse, Thinking Mouse */
1190 	0,
1191 	MOUSE_BUTTON3DOWN,
1192 	MOUSE_BUTTON1DOWN,
1193 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1194     };
1195     static int butmapmss2[4] = { /* Microsoft, MouseMan, GlidePoint,
1196 				    Thinking Mouse */
1197 	0,
1198 	MOUSE_BUTTON4DOWN,
1199 	MOUSE_BUTTON2DOWN,
1200 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1201     };
1202     /* MOUSE_INTELLI_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1203     static int butmapintelli[4] = { /* IntelliMouse, NetMouse, Mie Mouse,
1204 				       MouseMan+ */
1205 	0,
1206 	MOUSE_BUTTON2DOWN,
1207 	MOUSE_BUTTON4DOWN,
1208 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1209     };
1210     /* MOUSE_MSC_BUTTON?UP -> MOUSE_BUTTON?DOWN */
1211     static int butmapmsc[8] = {	/* MouseSystems, MMSeries, Logitech,
1212 				   Bus, sysmouse */
1213 	0,
1214 	MOUSE_BUTTON3DOWN,
1215 	MOUSE_BUTTON2DOWN,
1216 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1217 	MOUSE_BUTTON1DOWN,
1218 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1219 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1220 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1221     };
1222     /* MOUSE_PS2_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1223     static int butmapps2[8] = {	/* PS/2 */
1224 	0,
1225 	MOUSE_BUTTON1DOWN,
1226 	MOUSE_BUTTON3DOWN,
1227 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1228 	MOUSE_BUTTON2DOWN,
1229 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1230 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1231 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1232     };
1233     /* for Hitachi tablet */
1234     static int butmaphit[8] = {	/* MM HitTablet */
1235 	0,
1236 	MOUSE_BUTTON3DOWN,
1237 	MOUSE_BUTTON2DOWN,
1238 	MOUSE_BUTTON1DOWN,
1239 	MOUSE_BUTTON4DOWN,
1240 	MOUSE_BUTTON5DOWN,
1241 	MOUSE_BUTTON6DOWN,
1242 	MOUSE_BUTTON7DOWN,
1243     };
1244     static int           pBufP = 0;
1245     static unsigned char pBuf[8];
1246 
1247     debug("received char 0x%x",(int)rBuf);
1248 
1249     /*
1250      * Hack for resyncing: We check here for a package that is:
1251      *  a) illegal (detected by wrong data-package header)
1252      *  b) invalid (0x80 == -128 and that might be wrong for MouseSystems)
1253      *  c) bad header-package
1254      *
1255      * NOTE: b) is a voilation of the MouseSystems-Protocol, since values of
1256      *       -128 are allowed, but since they are very seldom we can easily
1257      *       use them as package-header with no button pressed.
1258      * NOTE/2: On a PS/2 mouse any byte is valid as a data byte. Furthermore,
1259      *         0x80 is not valid as a header byte. For a PS/2 mouse we skip
1260      *         checking data bytes.
1261      *         For resyncing a PS/2 mouse we require the two most significant
1262      *         bits in the header byte to be 0. These are the overflow bits,
1263      *         and in case of an overflow we actually lose sync. Overflows
1264      *         are very rare, however, and we quickly gain sync again after
1265      *         an overflow condition. This is the best we can do. (Actually,
1266      *         we could use bit 0x08 in the header byte for resyncing, since
1267      *         that bit is supposed to be always on, but nobody told
1268      *         Microsoft...)
1269      */
1270 
1271     if (pBufP != 0 && rodent.rtype != MOUSE_PROTO_PS2 &&
1272 	((rBuf & cur_proto[2]) != cur_proto[3] || rBuf == 0x80))
1273     {
1274 	pBufP = 0;		/* skip package */
1275     }
1276 
1277     if (pBufP == 0 && (rBuf & cur_proto[0]) != cur_proto[1])
1278 	return 0;
1279 
1280     /* is there an extra data byte? */
1281     if (pBufP >= cur_proto[4] && (rBuf & cur_proto[0]) != cur_proto[1])
1282     {
1283 	/*
1284 	 * Hack for Logitech MouseMan Mouse - Middle button
1285 	 *
1286 	 * Unfortunately this mouse has variable length packets: the standard
1287 	 * Microsoft 3 byte packet plus an optional 4th byte whenever the
1288 	 * middle button status changes.
1289 	 *
1290 	 * We have already processed the standard packet with the movement
1291 	 * and button info.  Now post an event message with the old status
1292 	 * of the left and right buttons and the updated middle button.
1293 	 */
1294 
1295 	/*
1296 	 * Even worse, different MouseMen and TrackMen differ in the 4th
1297 	 * byte: some will send 0x00/0x20, others 0x01/0x21, or even
1298 	 * 0x02/0x22, so I have to strip off the lower bits.
1299          *
1300          * [JCH-96/01/21]
1301          * HACK for ALPS "fourth button". (It's bit 0x10 of the "fourth byte"
1302          * and it is activated by tapping the glidepad with the finger! 8^)
1303          * We map it to bit bit3, and the reverse map in xf86Events just has
1304          * to be extended so that it is identified as Button 4. The lower
1305          * half of the reverse-map may remain unchanged.
1306 	 */
1307 
1308         /*
1309 	 * [KY-97/08/03]
1310 	 * Receive the fourth byte only when preceeding three bytes have
1311 	 * been detected (pBufP >= cur_proto[4]).  In the previous
1312 	 * versions, the test was pBufP == 0; thus, we may have mistakingly
1313 	 * received a byte even if we didn't see anything preceeding
1314 	 * the byte.
1315 	 */
1316 
1317 	if ((rBuf & cur_proto[5]) != cur_proto[6]) {
1318             pBufP = 0;
1319 	    return 0;
1320 	}
1321 
1322 	switch (rodent.rtype) {
1323 #if notyet
1324 	case MOUSE_PROTO_MARIQUA:
1325 	    /*
1326 	     * This mouse has 16! buttons in addition to the standard
1327 	     * three of them.  They return 0x10 though 0x1f in the
1328 	     * so-called `ten key' mode and 0x30 though 0x3f in the
1329 	     * `function key' mode.  As there are only 31 bits for
1330 	     * button state (including the standard three), we ignore
1331 	     * the bit 0x20 and don't distinguish the two modes.
1332 	     */
1333 	    act->dx = act->dy = act->dz = 0;
1334 	    act->obutton = act->button;
1335 	    rBuf &= 0x1f;
1336 	    act->button = (1 << (rBuf - 13))
1337                 | (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1338 	    /*
1339 	     * FIXME: this is a button "down" event. There needs to be
1340 	     * a corresponding button "up" event... XXX
1341 	     */
1342 	    break;
1343 #endif /* notyet */
1344 
1345 	/*
1346 	 * IntelliMouse, NetMouse (including NetMouse Pro) and Mie Mouse
1347 	 * always send the fourth byte, whereas the fourth byte is
1348 	 * optional for GlidePoint and ThinkingMouse. The fourth byte
1349 	 * is also optional for MouseMan+ and FirstMouse+ in their
1350 	 * native mode. It is always sent if they are in the IntelliMouse
1351 	 * compatible mode.
1352 	 */
1353 	case MOUSE_PROTO_INTELLI:	/* IntelliMouse, NetMouse, Mie Mouse,
1354 					   MouseMan+ */
1355 	    act->dx = act->dy = 0;
1356 	    act->dz = (rBuf & 0x08) ? (rBuf & 0x0f) - 16 : (rBuf & 0x0f);
1357 	    act->obutton = act->button;
1358 	    act->button = butmapintelli[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
1359 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1360 	    break;
1361 
1362 	default:
1363 	    act->dx = act->dy = act->dz = 0;
1364 	    act->obutton = act->button;
1365 	    act->button = butmapmss2[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
1366 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1367 	    break;
1368 	}
1369 
1370 	act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
1371 	    | (act->obutton ^ act->button);
1372         pBufP = 0;
1373 	return act->flags;
1374     }
1375 
1376     if (pBufP >= cur_proto[4])
1377 	pBufP = 0;
1378     pBuf[pBufP++] = rBuf;
1379     if (pBufP != cur_proto[4])
1380 	return 0;
1381 
1382     /*
1383      * assembly full package
1384      */
1385 
1386     debug("assembled full packet (len %d) %x,%x,%x,%x,%x,%x,%x,%x",
1387 	cur_proto[4],
1388 	pBuf[0], pBuf[1], pBuf[2], pBuf[3],
1389 	pBuf[4], pBuf[5], pBuf[6], pBuf[7]);
1390 
1391     act->dz = 0;
1392     act->obutton = act->button;
1393     switch (rodent.rtype)
1394     {
1395     case MOUSE_PROTO_MS:		/* Microsoft */
1396     case MOUSE_PROTO_LOGIMOUSEMAN:	/* MouseMan/TrackMan */
1397     case MOUSE_PROTO_X10MOUSEREM:	/* X10 MouseRemote */
1398 	act->button = act->obutton & MOUSE_BUTTON4DOWN;
1399 	if (rodent.flags & ChordMiddle)
1400 	    act->button |= ((pBuf[0] & MOUSE_MSS_BUTTONS) == MOUSE_MSS_BUTTONS)
1401 		? MOUSE_BUTTON2DOWN
1402 		: butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1403 	else
1404 	    act->button |= (act->obutton & MOUSE_BUTTON2DOWN)
1405 		| butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1406 
1407 	/* Send X10 btn events to remote client (ensure -128-+127 range) */
1408 	if ((rodent.rtype == MOUSE_PROTO_X10MOUSEREM) &&
1409 	    ((pBuf[0] & 0xFC) == 0x44) && (pBuf[2] == 0x3F)) {
1410 	    if (rodent.mremcfd >= 0) {
1411 		unsigned char key = (signed char)(((pBuf[0] & 0x03) << 6) |
1412 						  (pBuf[1] & 0x3F));
1413 		write( rodent.mremcfd, &key, 1 );
1414 	    }
1415 	    return 0;
1416 	}
1417 
1418 	act->dx = (char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
1419 	act->dy = (char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
1420 	break;
1421 
1422     case MOUSE_PROTO_GLIDEPOINT:	/* GlidePoint */
1423     case MOUSE_PROTO_THINK:		/* ThinkingMouse */
1424     case MOUSE_PROTO_INTELLI:		/* IntelliMouse, NetMouse, Mie Mouse,
1425 					   MouseMan+ */
1426 	act->button = (act->obutton & (MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN))
1427             | butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1428 	act->dx = (char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
1429 	act->dy = (char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
1430 	break;
1431 
1432     case MOUSE_PROTO_MSC:		/* MouseSystems Corp */
1433 #if notyet
1434     case MOUSE_PROTO_MARIQUA:		/* Mariqua */
1435 #endif
1436 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
1437 	act->dx =    (char)(pBuf[1]) + (char)(pBuf[3]);
1438 	act->dy = - ((char)(pBuf[2]) + (char)(pBuf[4]));
1439 	break;
1440 
1441     case MOUSE_PROTO_HITTAB:		/* MM HitTablet */
1442 	act->button = butmaphit[pBuf[0] & 0x07];
1443 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
1444 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
1445 	break;
1446 
1447     case MOUSE_PROTO_MM:		/* MM Series */
1448     case MOUSE_PROTO_LOGI:		/* Logitech Mice */
1449 	act->button = butmapmsc[pBuf[0] & MOUSE_MSC_BUTTONS];
1450 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
1451 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
1452 	break;
1453 
1454     case MOUSE_PROTO_BUS:		/* Bus */
1455     case MOUSE_PROTO_INPORT:		/* InPort */
1456 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
1457 	act->dx =   (char)pBuf[1];
1458 	act->dy = - (char)pBuf[2];
1459 	break;
1460 
1461     case MOUSE_PROTO_PS2:		/* PS/2 */
1462 	act->button = butmapps2[pBuf[0] & MOUSE_PS2_BUTTONS];
1463 	act->dx = (pBuf[0] & MOUSE_PS2_XNEG) ?    pBuf[1] - 256  :  pBuf[1];
1464 	act->dy = (pBuf[0] & MOUSE_PS2_YNEG) ?  -(pBuf[2] - 256) : -pBuf[2];
1465 	/*
1466 	 * Moused usually operates the psm driver at the operation level 1
1467 	 * which sends mouse data in MOUSE_PROTO_SYSMOUSE protocol.
1468 	 * The following code takes effect only when the user explicitly
1469 	 * requets the level 2 at which wheel movement and additional button
1470 	 * actions are encoded in model-dependent formats. At the level 0
1471 	 * the following code is no-op because the psm driver says the model
1472 	 * is MOUSE_MODEL_GENERIC.
1473 	 */
1474 	switch (rodent.hw.model) {
1475 	case MOUSE_MODEL_INTELLI:
1476 	case MOUSE_MODEL_NET:
1477 	    /* wheel data is in the fourth byte */
1478 	    act->dz = (char)pBuf[3];
1479 	    break;
1480 	case MOUSE_MODEL_MOUSEMANPLUS:
1481 	    if ((pBuf[0] & ~MOUSE_PS2_BUTTONS) == 0xc8) {
1482 		/* the extended data packet encodes button and wheel events */
1483 		act->dx = act->dy = 0;
1484 		act->dz = (pBuf[1] & MOUSE_PS2PLUS_ZNEG)
1485 		    ? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
1486 		act->button |= ((pBuf[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
1487 		    ? MOUSE_BUTTON4DOWN : 0);
1488 	    } else {
1489 		/* preserve button states */
1490 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
1491 	    }
1492 	    break;
1493 	case MOUSE_MODEL_GLIDEPOINT:
1494 	    /* `tapping' action */
1495 	    act->button |= ((pBuf[0] & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1496 	    break;
1497 	case MOUSE_MODEL_NETSCROLL:
1498 	    /* three addtional bytes encode button and wheel events */
1499 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON3DOWN)
1500 		? MOUSE_BUTTON4DOWN : 0;
1501 	    act->dz = (pBuf[3] & MOUSE_PS2_XNEG) ? pBuf[4] - 256 : pBuf[4];
1502 	    break;
1503 	case MOUSE_MODEL_THINK:
1504 	    /* the fourth button state in the first byte */
1505 	    act->button |= (pBuf[0] & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
1506 	    break;
1507 	case MOUSE_MODEL_GENERIC:
1508 	default:
1509 	    break;
1510 	}
1511 	break;
1512 
1513     case MOUSE_PROTO_SYSMOUSE:		/* sysmouse */
1514 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_SYS_STDBUTTONS];
1515 	act->dx =    (char)(pBuf[1]) + (char)(pBuf[3]);
1516 	act->dy = - ((char)(pBuf[2]) + (char)(pBuf[4]));
1517 	if (rodent.level == 1) {
1518 	    act->dz = ((char)(pBuf[5] << 1) + (char)(pBuf[6] << 1))/2;
1519 	    act->button |= ((~pBuf[7] & MOUSE_SYS_EXTBUTTONS) << 3);
1520 	}
1521 	break;
1522 
1523     default:
1524 	return 0;
1525     }
1526     /*
1527      * We don't reset pBufP here yet, as there may be an additional data
1528      * byte in some protocols. See above.
1529      */
1530 
1531     /* has something changed? */
1532     act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
1533 	| (act->obutton ^ act->button);
1534 
1535     if (rodent.flags & Emulate3Button) {
1536 	if (((act->flags & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN))
1537 	        == (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN))
1538 	    && ((act->button & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN))
1539 	        == (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN))) {
1540 	    act->button &= ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN);
1541 	    act->button |= MOUSE_BUTTON2DOWN;
1542 	} else if ((act->obutton & MOUSE_BUTTON2DOWN)
1543 	    && ((act->button & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN))
1544 	        != (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN))) {
1545 	    act->button &= ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN
1546 			       | MOUSE_BUTTON3DOWN);
1547 	}
1548 	act->flags &= MOUSE_POSCHANGED;
1549 	act->flags |= act->obutton ^ act->button;
1550     }
1551 
1552     return act->flags;
1553 }
1554 
1555 /* phisical to logical button mapping */
1556 static int p2l[MOUSE_MAXBUTTON] = {
1557     MOUSE_BUTTON1DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON4DOWN,
1558     MOUSE_BUTTON5DOWN, MOUSE_BUTTON6DOWN, MOUSE_BUTTON7DOWN, MOUSE_BUTTON8DOWN,
1559     0x00000100,        0x00000200,        0x00000400,        0x00000800,
1560     0x00001000,        0x00002000,        0x00004000,        0x00008000,
1561     0x00010000,        0x00020000,        0x00040000,        0x00080000,
1562     0x00100000,        0x00200000,        0x00400000,        0x00800000,
1563     0x01000000,        0x02000000,        0x04000000,        0x08000000,
1564     0x10000000,        0x20000000,        0x40000000,
1565 };
1566 
1567 static char *
1568 skipspace(char *s)
1569 {
1570     while(isspace(*s))
1571 	++s;
1572     return s;
1573 }
1574 
1575 static int
1576 r_installmap(char *arg)
1577 {
1578     int pbutton;
1579     int lbutton;
1580     char *s;
1581 
1582     while (*arg) {
1583 	arg = skipspace(arg);
1584 	s = arg;
1585 	while (isdigit(*arg))
1586 	    ++arg;
1587 	arg = skipspace(arg);
1588 	if ((arg <= s) || (*arg != '='))
1589 	    return FALSE;
1590 	lbutton = atoi(s);
1591 
1592 	arg = skipspace(++arg);
1593 	s = arg;
1594 	while (isdigit(*arg))
1595 	    ++arg;
1596 	if ((arg <= s) || (!isspace(*arg) && (*arg != '\0')))
1597 	    return FALSE;
1598 	pbutton = atoi(s);
1599 
1600 	if ((lbutton <= 0) || (lbutton > MOUSE_MAXBUTTON))
1601 	    return FALSE;
1602 	if ((pbutton <= 0) || (pbutton > MOUSE_MAXBUTTON))
1603 	    return FALSE;
1604 	p2l[pbutton - 1] = 1 << (lbutton - 1);
1605     }
1606 
1607     return TRUE;
1608 }
1609 
1610 static void
1611 r_map(mousestatus_t *act1, mousestatus_t *act2)
1612 {
1613     register int pb;
1614     register int pbuttons;
1615     int lbuttons;
1616 
1617     pbuttons = act1->button;
1618     lbuttons = 0;
1619 
1620     act2->obutton = act2->button;
1621     act2->dx = act1->dx;
1622     act2->dy = act1->dy;
1623     act2->dz = act1->dz;
1624 
1625     switch (rodent.zmap) {
1626     case 0:	/* do nothing */
1627 	break;
1628     case MOUSE_XAXIS:
1629 	if (act1->dz != 0) {
1630 	    act2->dx = act1->dz;
1631 	    act2->dz = 0;
1632 	}
1633 	break;
1634     case MOUSE_YAXIS:
1635 	if (act1->dz != 0) {
1636 	    act2->dy = act1->dz;
1637 	    act2->dz = 0;
1638 	}
1639 	break;
1640     default:	/* buttons */
1641 	pbuttons &= ~(rodent.zmap | (rodent.zmap << 1));
1642 	if (act1->dz < 0)
1643 	    pbuttons |= rodent.zmap;
1644 	else if (act1->dz > 0)
1645 	    pbuttons |= (rodent.zmap << 1);
1646 	act2->dz = 0;
1647 	break;
1648     }
1649 
1650     for (pb = 0; (pb < MOUSE_MAXBUTTON) && (pbuttons != 0); ++pb) {
1651 	lbuttons |= (pbuttons & 1) ? p2l[pb] : 0;
1652 	pbuttons >>= 1;
1653     }
1654     act2->button = lbuttons;
1655 
1656     act2->flags = ((act2->dx || act2->dy || act2->dz) ? MOUSE_POSCHANGED : 0)
1657 	| (act2->obutton ^ act2->button);
1658 }
1659 
1660 static void
1661 r_click(mousestatus_t *act)
1662 {
1663     struct mouse_info mouse;
1664     struct timeval tv;
1665     struct timeval tv1;
1666     struct timeval tv2;
1667     struct timezone tz;
1668     int button;
1669     int mask;
1670     int i;
1671 
1672     mask = act->flags & MOUSE_BUTTONS;
1673     if (mask == 0)
1674 	return;
1675 
1676     gettimeofday(&tv1, &tz);
1677     tv2.tv_sec = rodent.clickthreshold/1000;
1678     tv2.tv_usec = (rodent.clickthreshold%1000)*1000;
1679     timersub(&tv1, &tv2, &tv);
1680     debug("tv:  %ld %ld", tv.tv_sec, tv.tv_usec);
1681     button = MOUSE_BUTTON1DOWN;
1682     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
1683         if (mask & 1) {
1684             if (act->button & button) {
1685                 /* the button is down */
1686     		debug("  :  %ld %ld",
1687 		    buttonstate[i].tv.tv_sec, buttonstate[i].tv.tv_usec);
1688 		if (timercmp(&tv, &buttonstate[i].tv, >)) {
1689                     buttonstate[i].tv.tv_sec = 0;
1690                     buttonstate[i].tv.tv_usec = 0;
1691                     buttonstate[i].count = 1;
1692                 } else {
1693                     ++buttonstate[i].count;
1694                 }
1695 	        mouse.u.event.value = buttonstate[i].count;
1696             } else {
1697                 /* the button is up */
1698                 buttonstate[i].tv = tv1;
1699 	        mouse.u.event.value = 0;
1700             }
1701 	    mouse.operation = MOUSE_BUTTON_EVENT;
1702 	    mouse.u.event.id = button;
1703 	    if (debug < 2)
1704 	        ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1705 	    debug("button %d  count %d", i + 1, mouse.u.event.value);
1706         }
1707 	button <<= 1;
1708 	mask >>= 1;
1709     }
1710 }
1711 
1712 /* $XConsortium: posix_tty.c,v 1.3 95/01/05 20:42:55 kaleb Exp $ */
1713 /* $XFree86: xc/programs/Xserver/hw/xfree86/os-support/shared/posix_tty.c,v 3.4 1995/01/28 17:05:03 dawes Exp $ */
1714 /*
1715  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
1716  *
1717  * Permission to use, copy, modify, distribute, and sell this software and its
1718  * documentation for any purpose is hereby granted without fee, provided that
1719  * the above copyright notice appear in all copies and that both that
1720  * copyright notice and this permission notice appear in supporting
1721  * documentation, and that the name of David Dawes
1722  * not be used in advertising or publicity pertaining to distribution of
1723  * the software without specific, written prior permission.
1724  * David Dawes makes no representations about the suitability of this
1725  * software for any purpose.  It is provided "as is" without express or
1726  * implied warranty.
1727  *
1728  * DAVID DAWES DISCLAIMS ALL WARRANTIES WITH REGARD TO
1729  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
1730  * FITNESS, IN NO EVENT SHALL DAVID DAWES BE LIABLE FOR
1731  * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
1732  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
1733  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1734  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1735  *
1736  */
1737 
1738 
1739 static void
1740 setmousespeed(int old, int new, unsigned cflag)
1741 {
1742 	struct termios tty;
1743 	char *c;
1744 
1745 	if (tcgetattr(rodent.mfd, &tty) < 0)
1746 	{
1747 		logwarn("unable to get status of mouse fd", 0);
1748 		return;
1749 	}
1750 
1751 	tty.c_iflag = IGNBRK | IGNPAR;
1752 	tty.c_oflag = 0;
1753 	tty.c_lflag = 0;
1754 	tty.c_cflag = (tcflag_t)cflag;
1755 	tty.c_cc[VTIME] = 0;
1756 	tty.c_cc[VMIN] = 1;
1757 
1758 	switch (old)
1759 	{
1760 	case 9600:
1761 		cfsetispeed(&tty, B9600);
1762 		cfsetospeed(&tty, B9600);
1763 		break;
1764 	case 4800:
1765 		cfsetispeed(&tty, B4800);
1766 		cfsetospeed(&tty, B4800);
1767 		break;
1768 	case 2400:
1769 		cfsetispeed(&tty, B2400);
1770 		cfsetospeed(&tty, B2400);
1771 		break;
1772 	case 1200:
1773 	default:
1774 		cfsetispeed(&tty, B1200);
1775 		cfsetospeed(&tty, B1200);
1776 	}
1777 
1778 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
1779 	{
1780 		logwarn("unable to set status of mouse fd", 0);
1781 		return;
1782 	}
1783 
1784 	switch (new)
1785 	{
1786 	case 9600:
1787 		c = "*q";
1788 		cfsetispeed(&tty, B9600);
1789 		cfsetospeed(&tty, B9600);
1790 		break;
1791 	case 4800:
1792 		c = "*p";
1793 		cfsetispeed(&tty, B4800);
1794 		cfsetospeed(&tty, B4800);
1795 		break;
1796 	case 2400:
1797 		c = "*o";
1798 		cfsetispeed(&tty, B2400);
1799 		cfsetospeed(&tty, B2400);
1800 		break;
1801 	case 1200:
1802 	default:
1803 		c = "*n";
1804 		cfsetispeed(&tty, B1200);
1805 		cfsetospeed(&tty, B1200);
1806 	}
1807 
1808 	if (rodent.rtype == MOUSE_PROTO_LOGIMOUSEMAN
1809 	    || rodent.rtype == MOUSE_PROTO_LOGI)
1810 	{
1811 		if (write(rodent.mfd, c, 2) != 2)
1812 		{
1813 			logwarn("unable to write to mouse fd", 0);
1814 			return;
1815 		}
1816 	}
1817 	usleep(100000);
1818 
1819 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
1820 		logwarn("unable to set status of mouse fd", 0);
1821 }
1822 
1823 /*
1824  * PnP COM device support
1825  *
1826  * It's a simplistic implementation, but it works :-)
1827  * KY, 31/7/97.
1828  */
1829 
1830 /*
1831  * Try to elicit a PnP ID as described in
1832  * Microsoft, Hayes: "Plug and Play External COM Device Specification,
1833  * rev 1.00", 1995.
1834  *
1835  * The routine does not fully implement the COM Enumerator as par Section
1836  * 2.1 of the document.  In particular, we don't have idle state in which
1837  * the driver software monitors the com port for dynamic connection or
1838  * removal of a device at the port, because `moused' simply quits if no
1839  * device is found.
1840  *
1841  * In addition, as PnP COM device enumeration procedure slightly has
1842  * changed since its first publication, devices which follow earlier
1843  * revisions of the above spec. may fail to respond if the rev 1.0
1844  * procedure is used. XXX
1845  */
1846 static int
1847 pnpgets(char *buf)
1848 {
1849     struct timeval timeout;
1850     fd_set fds;
1851     int i;
1852     char c;
1853 
1854 #if 0
1855     /*
1856      * This is the procedure described in rev 1.0 of PnP COM device spec.
1857      * Unfortunately, some devices which comform to earlier revisions of
1858      * the spec gets confused and do not return the ID string...
1859      */
1860 
1861     /* port initialization (2.1.2) */
1862     ioctl(rodent.mfd, TIOCMGET, &i);
1863     i |= TIOCM_DTR;		/* DTR = 1 */
1864     i &= ~TIOCM_RTS;		/* RTS = 0 */
1865     ioctl(rodent.mfd, TIOCMSET, &i);
1866     usleep(200000);
1867     if ((ioctl(rodent.mfd, TIOCMGET, &i) == -1) || ((i & TIOCM_DSR) == 0))
1868 	goto disconnect_idle;
1869 
1870     /* port setup, 1st phase (2.1.3) */
1871     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
1872     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
1873     ioctl(rodent.mfd, TIOCMBIC, &i);
1874     usleep(200000);
1875     i = TIOCM_DTR;		/* DTR = 1, RTS = 0 */
1876     ioctl(rodent.mfd, TIOCMBIS, &i);
1877     usleep(200000);
1878 
1879     /* wait for response, 1st phase (2.1.4) */
1880     i = FREAD;
1881     ioctl(rodent.mfd, TIOCFLUSH, &i);
1882     i = TIOCM_RTS;		/* DTR = 1, RTS = 1 */
1883     ioctl(rodent.mfd, TIOCMBIS, &i);
1884 
1885     /* try to read something */
1886     FD_ZERO(&fds);
1887     FD_SET(rodent.mfd, &fds);
1888     timeout.tv_sec = 0;
1889     timeout.tv_usec = 200000;
1890     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0) {
1891 
1892 	/* port setup, 2nd phase (2.1.5) */
1893         i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
1894         ioctl(rodent.mfd, TIOCMBIC, &i);
1895         usleep(200000);
1896 
1897 	/* wait for respose, 2nd phase (2.1.6) */
1898         i = FREAD;
1899         ioctl(rodent.mfd, TIOCFLUSH, &i);
1900         i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
1901         ioctl(rodent.mfd, TIOCMBIS, &i);
1902 
1903         /* try to read something */
1904         FD_ZERO(&fds);
1905         FD_SET(rodent.mfd, &fds);
1906         timeout.tv_sec = 0;
1907         timeout.tv_usec = 200000;
1908         if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
1909 	    goto connect_idle;
1910     }
1911 #else
1912     /*
1913      * This is a simplified procedure; it simply toggles RTS.
1914      */
1915 
1916     ioctl(rodent.mfd, TIOCMGET, &i);
1917     i |= TIOCM_DTR;		/* DTR = 1 */
1918     i &= ~TIOCM_RTS;		/* RTS = 0 */
1919     ioctl(rodent.mfd, TIOCMSET, &i);
1920     usleep(200000);
1921 
1922     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
1923 
1924     /* wait for respose */
1925     i = FREAD;
1926     ioctl(rodent.mfd, TIOCFLUSH, &i);
1927     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
1928     ioctl(rodent.mfd, TIOCMBIS, &i);
1929 
1930     /* try to read something */
1931     FD_ZERO(&fds);
1932     FD_SET(rodent.mfd, &fds);
1933     timeout.tv_sec = 0;
1934     timeout.tv_usec = 200000;
1935     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
1936         goto connect_idle;
1937 #endif
1938 
1939     /* collect PnP COM device ID (2.1.7) */
1940     i = 0;
1941     usleep(200000);	/* the mouse must send `Begin ID' within 200msec */
1942     while (read(rodent.mfd, &c, 1) == 1) {
1943 	/* we may see "M", or "M3..." before `Begin ID' */
1944         if ((c == 0x08) || (c == 0x28)) {	/* Begin ID */
1945 	    buf[i++] = c;
1946 	    break;
1947         }
1948         debug("%c %02x", c, c);
1949     }
1950     if (i <= 0) {
1951 	/* we haven't seen `Begin ID' in time... */
1952 	goto connect_idle;
1953     }
1954 
1955     ++c;			/* make it `End ID' */
1956     for (;;) {
1957         FD_ZERO(&fds);
1958         FD_SET(rodent.mfd, &fds);
1959         timeout.tv_sec = 0;
1960         timeout.tv_usec = 200000;
1961         if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
1962 	    break;
1963 
1964 	read(rodent.mfd, &buf[i], 1);
1965         if (buf[i++] == c)	/* End ID */
1966 	    break;
1967 	if (i >= 256)
1968 	    break;
1969     }
1970     /* string may not be human readable... */
1971     debug("'%-*.*s'", i, i, buf);
1972     if (buf[i - 1] != c)
1973 	goto connect_idle;
1974     return i;
1975 
1976     /*
1977      * According to PnP spec, we should set DTR = 1 and RTS = 0 while
1978      * in idle state.  But, `moused' shall set DTR = RTS = 1 and proceed,
1979      * assuming there is something at the port even if it didn't
1980      * respond to the PnP enumeration procedure.
1981      */
1982 disconnect_idle:
1983     i = TIOCM_DTR | TIOCM_RTS;		/* DTR = 1, RTS = 1 */
1984     ioctl(rodent.mfd, TIOCMBIS, &i);
1985 connect_idle:
1986     return 0;
1987 }
1988 
1989 static int
1990 pnpparse(pnpid_t *id, char *buf, int len)
1991 {
1992     char s[3];
1993     int offset;
1994     int sum = 0;
1995     int i, j;
1996 
1997     id->revision = 0;
1998     id->eisaid = NULL;
1999     id->serial = NULL;
2000     id->class = NULL;
2001     id->compat = NULL;
2002     id->description = NULL;
2003     id->neisaid = 0;
2004     id->nserial = 0;
2005     id->nclass = 0;
2006     id->ncompat = 0;
2007     id->ndescription = 0;
2008 
2009     offset = 0x28 - buf[0];
2010 
2011     /* calculate checksum */
2012     for (i = 0; i < len - 3; ++i) {
2013 	sum += buf[i];
2014 	buf[i] += offset;
2015     }
2016     sum += buf[len - 1];
2017     for (; i < len; ++i)
2018 	buf[i] += offset;
2019     debug("PnP ID string: '%*.*s'", len, len, buf);
2020 
2021     /* revision */
2022     buf[1] -= offset;
2023     buf[2] -= offset;
2024     id->revision = ((buf[1] & 0x3f) << 6) | (buf[2] & 0x3f);
2025     debug("PnP rev %d.%02d", id->revision / 100, id->revision % 100);
2026 
2027     /* EISA vender and product ID */
2028     id->eisaid = &buf[3];
2029     id->neisaid = 7;
2030 
2031     /* option strings */
2032     i = 10;
2033     if (buf[i] == '\\') {
2034         /* device serial # */
2035         for (j = ++i; i < len; ++i) {
2036             if (buf[i] == '\\')
2037 		break;
2038         }
2039 	if (i >= len)
2040 	    i -= 3;
2041 	if (i - j == 8) {
2042             id->serial = &buf[j];
2043             id->nserial = 8;
2044 	}
2045     }
2046     if (buf[i] == '\\') {
2047         /* PnP class */
2048         for (j = ++i; i < len; ++i) {
2049             if (buf[i] == '\\')
2050 		break;
2051         }
2052 	if (i >= len)
2053 	    i -= 3;
2054 	if (i > j + 1) {
2055             id->class = &buf[j];
2056             id->nclass = i - j;
2057         }
2058     }
2059     if (buf[i] == '\\') {
2060 	/* compatible driver */
2061         for (j = ++i; i < len; ++i) {
2062             if (buf[i] == '\\')
2063 		break;
2064         }
2065 	/*
2066 	 * PnP COM spec prior to v0.96 allowed '*' in this field,
2067 	 * it's not allowed now; just igore it.
2068 	 */
2069 	if (buf[j] == '*')
2070 	    ++j;
2071 	if (i >= len)
2072 	    i -= 3;
2073 	if (i > j + 1) {
2074             id->compat = &buf[j];
2075             id->ncompat = i - j;
2076         }
2077     }
2078     if (buf[i] == '\\') {
2079 	/* product description */
2080         for (j = ++i; i < len; ++i) {
2081             if (buf[i] == ';')
2082 		break;
2083         }
2084 	if (i >= len)
2085 	    i -= 3;
2086 	if (i > j + 1) {
2087             id->description = &buf[j];
2088             id->ndescription = i - j;
2089         }
2090     }
2091 
2092     /* checksum exists if there are any optional fields */
2093     if ((id->nserial > 0) || (id->nclass > 0)
2094 	|| (id->ncompat > 0) || (id->ndescription > 0)) {
2095         debug("PnP checksum: 0x%X", sum);
2096         sprintf(s, "%02X", sum & 0x0ff);
2097         if (strncmp(s, &buf[len - 3], 2) != 0) {
2098 #if 0
2099             /*
2100 	     * I found some mice do not comply with the PnP COM device
2101 	     * spec regarding checksum... XXX
2102 	     */
2103             logwarnx("PnP checksum error", 0);
2104 	    return FALSE;
2105 #endif
2106         }
2107     }
2108 
2109     return TRUE;
2110 }
2111 
2112 static symtab_t *
2113 pnpproto(pnpid_t *id)
2114 {
2115     symtab_t *t;
2116     int i, j;
2117 
2118     if (id->nclass > 0)
2119 	if (strncmp(id->class, "MOUSE", id->nclass) != 0)
2120 	    /* this is not a mouse! */
2121 	    return NULL;
2122 
2123     if (id->neisaid > 0) {
2124         t = gettoken(pnpprod, id->eisaid, id->neisaid);
2125 	if (t->val != MOUSE_PROTO_UNKNOWN)
2126             return t;
2127     }
2128 
2129     /*
2130      * The 'Compatible drivers' field may contain more than one
2131      * ID separated by ','.
2132      */
2133     if (id->ncompat <= 0)
2134 	return NULL;
2135     for (i = 0; i < id->ncompat; ++i) {
2136         for (j = i; id->compat[i] != ','; ++i)
2137             if (i >= id->ncompat)
2138 		break;
2139         if (i > j) {
2140             t = gettoken(pnpprod, id->compat + j, i - j);
2141 	    if (t->val != MOUSE_PROTO_UNKNOWN)
2142                 return t;
2143 	}
2144     }
2145 
2146     return NULL;
2147 }
2148 
2149 /* name/val mapping */
2150 
2151 static symtab_t *
2152 gettoken(symtab_t *tab, char *s, int len)
2153 {
2154     int i;
2155 
2156     for (i = 0; tab[i].name != NULL; ++i) {
2157 	if (strncmp(tab[i].name, s, len) == 0)
2158 	    break;
2159     }
2160     return &tab[i];
2161 }
2162 
2163 static char *
2164 gettokenname(symtab_t *tab, int val)
2165 {
2166     int i;
2167 
2168     for (i = 0; tab[i].name != NULL; ++i) {
2169 	if (tab[i].val == val)
2170 	    return tab[i].name;
2171     }
2172     return NULL;
2173 }
2174 
2175 static void
2176 mremote_serversetup()
2177 {
2178     struct sockaddr_un ad;
2179 
2180     /* Open a UNIX domain stream socket to listen for mouse remote clients */
2181     unlink(_PATH_MOUSEREMOTE);
2182 
2183     if ( (rodent.mremsfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
2184 	logerrx(1, "unable to create unix domain socket %s",_PATH_MOUSEREMOTE);
2185 
2186     umask(0111);
2187 
2188     bzero(&ad, sizeof(ad));
2189     ad.sun_family = AF_UNIX;
2190     strcpy(ad.sun_path, _PATH_MOUSEREMOTE);
2191 #ifndef SUN_LEN
2192 #define SUN_LEN(unp) ( ((char *)(unp)->sun_path - (char *)(unp)) + \
2193                        strlen((unp)->path) )
2194 #endif
2195     if (bind(rodent.mremsfd, (struct sockaddr *) &ad, SUN_LEN(&ad)) < 0)
2196 	logerrx(1, "unable to bind unix domain socket %s", _PATH_MOUSEREMOTE);
2197 
2198     listen(rodent.mremsfd, 1);
2199 }
2200 
2201 static void
2202 mremote_clientchg(int add)
2203 {
2204     struct sockaddr_un ad;
2205     int ad_len, fd;
2206 
2207     if (rodent.rtype != MOUSE_PROTO_X10MOUSEREM)
2208 	return;
2209 
2210     if ( add ) {
2211 	/*  Accept client connection, if we don't already have one  */
2212 	ad_len = sizeof(ad);
2213 	fd = accept(rodent.mremsfd, (struct sockaddr *) &ad, &ad_len);
2214 	if (fd < 0)
2215 	    logwarnx("failed accept on mouse remote socket");
2216 
2217 	if ( rodent.mremcfd < 0 ) {
2218 	    rodent.mremcfd = fd;
2219 	    debug("remote client connect...accepted");
2220 	}
2221 	else {
2222 	    close(fd);
2223 	    debug("another remote client connect...disconnected");
2224 	}
2225     }
2226     else {
2227 	/* Client disconnected */
2228 	debug("remote client disconnected");
2229 	close( rodent.mremcfd );
2230 	rodent.mremcfd = -1;
2231     }
2232 }
2233 
2234 
2235