xref: /freebsd/usr.sbin/moused/moused.c (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 /**
2  ** SPDX-License-Identifier: BSD-4-Clause
3  **
4  ** Copyright (c) 1995 Michael Smith, All rights reserved.
5  **
6  ** Redistribution and use in source and binary forms, with or without
7  ** modification, are permitted provided that the following conditions
8  ** are met:
9  ** 1. Redistributions of source code must retain the above copyright
10  **    notice, this list of conditions and the following disclaimer as
11  **    the first lines of this file unmodified.
12  ** 2. Redistributions in binary form must reproduce the above copyright
13  **    notice, this list of conditions and the following disclaimer in the
14  **    documentation and/or other materials provided with the distribution.
15  ** 3. All advertising materials mentioning features or use of this software
16  **    must display the following acknowledgment:
17  **      This product includes software developed by Michael Smith.
18  ** 4. The name of the author may not be used to endorse or promote products
19  **    derived from this software without specific prior written permission.
20  **
21  **
22  ** THIS SOFTWARE IS PROVIDED BY Michael Smith ``AS IS'' AND ANY
23  ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  ** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Michael Smith BE LIABLE FOR
26  ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  ** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  ** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29  ** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31  ** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
32  ** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  **
34  **/
35 
36 /**
37  ** MOUSED.C
38  **
39  ** Mouse daemon : listens to a serial port, the bus mouse interface, or
40  ** the PS/2 mouse port for mouse data stream, interprets data and passes
41  ** ioctls off to the console driver.
42  **
43  ** The mouse interface functions are derived closely from the mouse
44  ** handler in the XFree86 X server.  Many thanks to the XFree86 people
45  ** for their great work!
46  **
47  **/
48 
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
51 
52 #include <sys/param.h>
53 #include <sys/consio.h>
54 #include <sys/mouse.h>
55 #include <sys/socket.h>
56 #include <sys/stat.h>
57 #include <sys/time.h>
58 #include <sys/un.h>
59 
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <libutil.h>
65 #include <limits.h>
66 #include <setjmp.h>
67 #include <signal.h>
68 #include <stdarg.h>
69 #include <stdint.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <syslog.h>
74 #include <termios.h>
75 #include <unistd.h>
76 #include <math.h>
77 
78 #define MAX_CLICKTHRESHOLD	2000	/* 2 seconds */
79 #define MAX_BUTTON2TIMEOUT	2000	/* 2 seconds */
80 #define DFLT_CLICKTHRESHOLD	 500	/* 0.5 second */
81 #define DFLT_BUTTON2TIMEOUT	 100	/* 0.1 second */
82 #define DFLT_SCROLLTHRESHOLD	   3	/* 3 pixels */
83 #define DFLT_SCROLLSPEED	   2	/* 2 pixels */
84 
85 /* Abort 3-button emulation delay after this many movement events. */
86 #define BUTTON2_MAXMOVE	3
87 
88 #define TRUE		1
89 #define FALSE		0
90 
91 #define MOUSE_XAXIS	(-1)
92 #define MOUSE_YAXIS	(-2)
93 
94 /* Logitech PS2++ protocol */
95 #define MOUSE_PS2PLUS_CHECKBITS(b)	\
96 			((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
97 #define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
98 			(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
99 
100 #define	ChordMiddle	0x0001
101 #define Emulate3Button	0x0002
102 #define ClearDTR	0x0004
103 #define ClearRTS	0x0008
104 #define NoPnP		0x0010
105 #define VirtualScroll	0x0020
106 #define HVirtualScroll	0x0040
107 #define ExponentialAcc	0x0080
108 
109 #define ID_NONE		0
110 #define ID_PORT		1
111 #define ID_IF		2
112 #define ID_TYPE		4
113 #define ID_MODEL	8
114 #define ID_ALL		(ID_PORT | ID_IF | ID_TYPE | ID_MODEL)
115 
116 /* Operations on timespecs */
117 #define	tsclr(tvp)	((tvp)->tv_sec = (tvp)->tv_nsec = 0)
118 #define	tscmp(tvp, uvp, cmp)						\
119 	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
120 	    ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :			\
121 	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
122 #define	tssub(tvp, uvp, vvp)						\
123 	do {								\
124 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
125 		(vvp)->tv_nsec = (tvp)->tv_nsec - (uvp)->tv_nsec;	\
126 		if ((vvp)->tv_nsec < 0) {				\
127 			(vvp)->tv_sec--;				\
128 			(vvp)->tv_nsec += 1000000000;			\
129 		}							\
130 	} while (0)
131 
132 #define debug(...) do {						\
133 	if (debug && nodaemon)					\
134 		warnx(__VA_ARGS__);				\
135 } while (0)
136 
137 #define logerr(e, ...) do {					\
138 	log_or_warn(LOG_DAEMON | LOG_ERR, errno, __VA_ARGS__);	\
139 	exit(e);						\
140 } while (0)
141 
142 #define logerrx(e, ...) do {					\
143 	log_or_warn(LOG_DAEMON | LOG_ERR, 0, __VA_ARGS__);	\
144 	exit(e);						\
145 } while (0)
146 
147 #define logwarn(...)						\
148 	log_or_warn(LOG_DAEMON | LOG_WARNING, errno, __VA_ARGS__)
149 
150 #define logwarnx(...)						\
151 	log_or_warn(LOG_DAEMON | LOG_WARNING, 0, __VA_ARGS__)
152 
153 /* structures */
154 
155 /* symbol table entry */
156 typedef struct {
157     const char *name;
158     int val;
159     int val2;
160 } symtab_t;
161 
162 /* serial PnP ID string */
163 typedef struct {
164     int revision;	/* PnP revision, 100 for 1.00 */
165     const char *eisaid;	/* EISA ID including mfr ID and product ID */
166     char *serial;	/* serial No, optional */
167     const char *class;	/* device class, optional */
168     char *compat;	/* list of compatible drivers, optional */
169     char *description;	/* product description, optional */
170     int neisaid;	/* length of the above fields... */
171     int nserial;
172     int nclass;
173     int ncompat;
174     int ndescription;
175 } pnpid_t;
176 
177 /* global variables */
178 
179 static int	debug = 0;
180 static int	nodaemon = FALSE;
181 static int	background = FALSE;
182 static int	paused = FALSE;
183 static int	identify = ID_NONE;
184 static int	extioctl = FALSE;
185 static const char *pidfile = "/var/run/moused.pid";
186 static struct pidfh *pfh;
187 
188 #define SCROLL_NOTSCROLLING	0
189 #define SCROLL_PREPARE		1
190 #define SCROLL_SCROLLING	2
191 
192 static int	scroll_state;
193 static int	scroll_movement;
194 static int	hscroll_movement;
195 
196 /* local variables */
197 
198 /* interface (the table must be ordered by MOUSE_IF_XXX in mouse.h) */
199 static symtab_t rifs[] = {
200     { "serial",		MOUSE_IF_SERIAL,	0 },
201     { "ps/2",		MOUSE_IF_PS2,		0 },
202     { "sysmouse",	MOUSE_IF_SYSMOUSE,	0 },
203     { "usb",		MOUSE_IF_USB,		0 },
204     { NULL,		MOUSE_IF_UNKNOWN,	0 },
205 };
206 
207 /* types (the table must be ordered by MOUSE_PROTO_XXX in mouse.h) */
208 static const char *rnames[] = {
209     "microsoft",
210     "mousesystems",
211     "logitech",
212     "mmseries",
213     "mouseman",
214     "wasbusmouse",
215     "wasinportmouse",
216     "ps/2",
217     "mmhitab",
218     "glidepoint",
219     "intellimouse",
220     "thinkingmouse",
221     "sysmouse",
222     "x10mouseremote",
223     "kidspad",
224     "versapad",
225     "jogdial",
226 #if notyet
227     "mariqua",
228 #endif
229     "gtco_digipad",
230     NULL
231 };
232 
233 /* models */
234 static symtab_t	rmodels[] = {
235     { "NetScroll",		MOUSE_MODEL_NETSCROLL,		0 },
236     { "NetMouse/NetScroll Optical", MOUSE_MODEL_NET,		0 },
237     { "GlidePoint",		MOUSE_MODEL_GLIDEPOINT,		0 },
238     { "ThinkingMouse",		MOUSE_MODEL_THINK,		0 },
239     { "IntelliMouse",		MOUSE_MODEL_INTELLI,		0 },
240     { "EasyScroll/SmartScroll",	MOUSE_MODEL_EASYSCROLL,		0 },
241     { "MouseMan+",		MOUSE_MODEL_MOUSEMANPLUS,	0 },
242     { "Kidspad",		MOUSE_MODEL_KIDSPAD,		0 },
243     { "VersaPad",		MOUSE_MODEL_VERSAPAD,		0 },
244     { "IntelliMouse Explorer",	MOUSE_MODEL_EXPLORER,		0 },
245     { "4D Mouse",		MOUSE_MODEL_4D,			0 },
246     { "4D+ Mouse",		MOUSE_MODEL_4DPLUS,		0 },
247     { "Synaptics Touchpad",	MOUSE_MODEL_SYNAPTICS,		0 },
248     { "TrackPoint",		MOUSE_MODEL_TRACKPOINT,		0 },
249     { "Elantech Touchpad",	MOUSE_MODEL_ELANTECH,		0 },
250     { "generic",		MOUSE_MODEL_GENERIC,		0 },
251     { NULL,			MOUSE_MODEL_UNKNOWN,		0 },
252 };
253 
254 /* PnP EISA/product IDs */
255 static symtab_t pnpprod[] = {
256     /* Kensignton ThinkingMouse */
257     { "KML0001",	MOUSE_PROTO_THINK,	MOUSE_MODEL_THINK },
258     /* MS IntelliMouse */
259     { "MSH0001",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
260     /* MS IntelliMouse TrackBall */
261     { "MSH0004",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
262     /* Tremon Wheel Mouse MUSD */
263     { "HTK0001",        MOUSE_PROTO_INTELLI,    MOUSE_MODEL_INTELLI },
264     /* Genius PnP Mouse */
265     { "KYE0001",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
266     /* MouseSystems SmartScroll Mouse (OEM from Genius?) */
267     { "KYE0002",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
268     /* Genius NetMouse */
269     { "KYE0003",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_NET },
270     /* Genius Kidspad, Easypad and other tablets */
271     { "KYE0005",	MOUSE_PROTO_KIDSPAD,	MOUSE_MODEL_KIDSPAD },
272     /* Genius EZScroll */
273     { "KYEEZ00",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
274     /* Logitech Cordless MouseMan Wheel */
275     { "LGI8033",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
276     /* Logitech MouseMan (new 4 button model) */
277     { "LGI800C",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
278     /* Logitech MouseMan+ */
279     { "LGI8050",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
280     /* Logitech FirstMouse+ */
281     { "LGI8051",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
282     /* Logitech serial */
283     { "LGI8001",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
284     /* A4 Tech 4D/4D+ Mouse */
285     { "A4W0005",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_4D },
286     /* 8D Scroll Mouse */
287     { "PEC9802",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
288     /* Mitsumi Wireless Scroll Mouse */
289     { "MTM6401",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
290 
291     /* MS serial */
292     { "PNP0F01",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
293     /* MS PS/2 */
294     { "PNP0F03",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
295     /*
296      * EzScroll returns PNP0F04 in the compatible device field; but it
297      * doesn't look compatible... XXX
298      */
299     /* MouseSystems */
300     { "PNP0F04",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
301     /* MouseSystems */
302     { "PNP0F05",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
303 #if notyet
304     /* Genius Mouse */
305     { "PNP0F06",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
306     /* Genius Mouse */
307     { "PNP0F07",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
308 #endif
309     /* Logitech serial */
310     { "PNP0F08",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
311     /* MS BallPoint serial */
312     { "PNP0F09",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
313     /* MS PnP serial */
314     { "PNP0F0A",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
315     /* MS PnP BallPoint serial */
316     { "PNP0F0B",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
317     /* MS serial comatible */
318     { "PNP0F0C",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
319     /* MS PS/2 comatible */
320     { "PNP0F0E",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
321     /* MS BallPoint comatible */
322     { "PNP0F0F",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
323 #if notyet
324     /* TI QuickPort */
325     { "PNP0F10",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
326 #endif
327     /* Logitech PS/2 */
328     { "PNP0F12",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
329     /* PS/2 */
330     { "PNP0F13",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
331 #if notyet
332     /* MS Kids Mouse */
333     { "PNP0F14",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
334 #endif
335 #if notyet
336     /* Logitech SWIFT */
337     { "PNP0F16",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
338 #endif
339     /* Logitech serial compat */
340     { "PNP0F17",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
341     /* Logitech PS/2 compatible */
342     { "PNP0F19",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
343 #if notyet
344     /* Logitech SWIFT compatible */
345     { "PNP0F1A",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
346     /* HP Omnibook */
347     { "PNP0F1B",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
348     /* Compaq LTE TrackBall PS/2 */
349     { "PNP0F1C",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
350     /* Compaq LTE TrackBall serial */
351     { "PNP0F1D",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
352     /* MS Kidts Trackball */
353     { "PNP0F1E",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
354 #endif
355     /* Interlink VersaPad */
356     { "LNK0001",	MOUSE_PROTO_VERSAPAD,	MOUSE_MODEL_VERSAPAD },
357 
358     { NULL,		MOUSE_PROTO_UNKNOWN,	MOUSE_MODEL_GENERIC },
359 };
360 
361 /* the table must be ordered by MOUSE_PROTO_XXX in mouse.h */
362 static unsigned short rodentcflags[] =
363 {
364     (CS7	           | CREAD | CLOCAL | HUPCL),	/* MicroSoft */
365     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* MouseSystems */
366     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* Logitech */
367     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL),	/* MMSeries */
368     (CS7		   | CREAD | CLOCAL | HUPCL),	/* MouseMan */
369     0,							/* Bus */
370     0,							/* InPort */
371     0,							/* PS/2 */
372     (CS8		   | CREAD | CLOCAL | HUPCL),	/* MM HitTablet */
373     (CS7	           | CREAD | CLOCAL | HUPCL),	/* GlidePoint */
374     (CS7                   | CREAD | CLOCAL | HUPCL),	/* IntelliMouse */
375     (CS7                   | CREAD | CLOCAL | HUPCL),	/* Thinking Mouse */
376     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* sysmouse */
377     (CS7	           | CREAD | CLOCAL | HUPCL),	/* X10 MouseRemote */
378     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL),	/* kidspad etc. */
379     (CS8		   | CREAD | CLOCAL | HUPCL),	/* VersaPad */
380     0,							/* JogDial */
381 #if notyet
382     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* Mariqua */
383 #endif
384     (CS8		   | CREAD |	      HUPCL ),	/* GTCO Digi-Pad */
385 };
386 
387 static struct rodentparam {
388     int flags;
389     const char *portname;	/* /dev/XXX */
390     int rtype;			/* MOUSE_PROTO_XXX */
391     int level;			/* operation level: 0 or greater */
392     int baudrate;
393     int rate;			/* report rate */
394     int resolution;		/* MOUSE_RES_XXX or a positive number */
395     int zmap[4];		/* MOUSE_{X|Y}AXIS or a button number */
396     int wmode;			/* wheel mode button number */
397     int mfd;			/* mouse file descriptor */
398     int cfd;			/* /dev/consolectl file descriptor */
399     int mremsfd;		/* mouse remote server file descriptor */
400     int mremcfd;		/* mouse remote client file descriptor */
401     int is_removable;		/* set if device is removable, like USB */
402     long clickthreshold;	/* double click speed in msec */
403     long button2timeout;	/* 3 button emulation timeout */
404     mousehw_t hw;		/* mouse device hardware information */
405     mousemode_t mode;		/* protocol information */
406     float accelx;		/* Acceleration in the X axis */
407     float accely;		/* Acceleration in the Y axis */
408     float expoaccel;		/* Exponential acceleration */
409     float expoffset;		/* Movement offset for exponential accel. */
410     float remainx;		/* Remainder on X and Y axis, respectively... */
411     float remainy;		/*    ... to compensate for rounding errors. */
412     int scrollthreshold;	/* Movement distance before virtual scrolling */
413     int scrollspeed;		/* Movement distance to rate of scrolling */
414 } rodent = {
415     .flags = 0,
416     .portname = NULL,
417     .rtype = MOUSE_PROTO_UNKNOWN,
418     .level = -1,
419     .baudrate = 1200,
420     .rate = 0,
421     .resolution = MOUSE_RES_UNKNOWN,
422     .zmap = { 0, 0, 0, 0 },
423     .wmode = 0,
424     .mfd = -1,
425     .cfd = -1,
426     .mremsfd = -1,
427     .mremcfd = -1,
428     .is_removable = 0,
429     .clickthreshold = DFLT_CLICKTHRESHOLD,
430     .button2timeout = DFLT_BUTTON2TIMEOUT,
431     .accelx = 1.0,
432     .accely = 1.0,
433     .expoaccel = 1.0,
434     .expoffset = 1.0,
435     .remainx = 0.0,
436     .remainy = 0.0,
437     .scrollthreshold = DFLT_SCROLLTHRESHOLD,
438     .scrollspeed = DFLT_SCROLLSPEED,
439 };
440 
441 /* button status */
442 struct button_state {
443     int count;		/* 0: up, 1: single click, 2: double click,... */
444     struct timespec ts;	/* timestamp on the last button event */
445 };
446 static struct button_state	bstate[MOUSE_MAXBUTTON];	/* button state */
447 static struct button_state	*mstate[MOUSE_MAXBUTTON];/* mapped button st.*/
448 static struct button_state	zstate[4];		 /* Z/W axis state */
449 
450 /* state machine for 3 button emulation */
451 
452 #define S0	0	/* start */
453 #define S1	1	/* button 1 delayed down */
454 #define S2	2	/* button 3 delayed down */
455 #define S3	3	/* both buttons down -> button 2 down */
456 #define S4	4	/* button 1 delayed up */
457 #define S5	5	/* button 1 down */
458 #define S6	6	/* button 3 down */
459 #define S7	7	/* both buttons down */
460 #define S8	8	/* button 3 delayed up */
461 #define S9	9	/* button 1 or 3 up after S3 */
462 
463 #define A(b1, b3)	(((b1) ? 2 : 0) | ((b3) ? 1 : 0))
464 #define A_TIMEOUT	4
465 #define S_DELAYED(st)	(states[st].s[A_TIMEOUT] != (st))
466 
467 static struct {
468     int s[A_TIMEOUT + 1];
469     int buttons;
470     int mask;
471     int timeout;
472 } states[10] = {
473     /* S0 */
474     { { S0, S2, S1, S3, S0 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), FALSE },
475     /* S1 */
476     { { S4, S2, S1, S3, S5 }, 0, ~MOUSE_BUTTON1DOWN, FALSE },
477     /* S2 */
478     { { S8, S2, S1, S3, S6 }, 0, ~MOUSE_BUTTON3DOWN, FALSE },
479     /* S3 */
480     { { S0, S9, S9, S3, S3 }, MOUSE_BUTTON2DOWN, ~0, FALSE },
481     /* S4 */
482     { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON1DOWN, ~0, TRUE },
483     /* S5 */
484     { { S0, S2, S5, S7, S5 }, MOUSE_BUTTON1DOWN, ~0, FALSE },
485     /* S6 */
486     { { S0, S6, S1, S7, S6 }, MOUSE_BUTTON3DOWN, ~0, FALSE },
487     /* S7 */
488     { { S0, S6, S5, S7, S7 }, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, ~0, FALSE },
489     /* S8 */
490     { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON3DOWN, ~0, TRUE },
491     /* S9 */
492     { { S0, S9, S9, S3, S9 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), FALSE },
493 };
494 static int		mouse_button_state;
495 static struct timespec	mouse_button_state_ts;
496 static int		mouse_move_delayed;
497 
498 static jmp_buf env;
499 
500 struct drift_xy {
501     int x;
502     int y;
503 };
504 static int		drift_distance = 4;	/* max steps X+Y */
505 static int		drift_time = 500;	/* in 0.5 sec */
506 static struct timespec	drift_time_ts;
507 static struct timespec	drift_2time_ts;		/* 2*drift_time */
508 static int		drift_after = 4000;	/* 4 sec */
509 static struct timespec	drift_after_ts;
510 static int		drift_terminate = FALSE;
511 static struct timespec	drift_current_ts;
512 static struct timespec	drift_tmp;
513 static struct timespec	drift_last_activity = {0, 0};
514 static struct timespec	drift_since = {0, 0};
515 static struct drift_xy	drift_last = {0, 0};	/* steps in last drift_time */
516 static struct drift_xy  drift_previous = {0, 0};	/* steps in prev. drift_time */
517 
518 /* function prototypes */
519 
520 static void	linacc(int, int, int*, int*);
521 static void	expoacc(int, int, int*, int*);
522 static void	moused(void);
523 static void	hup(int sig);
524 static void	cleanup(int sig);
525 static void	pause_mouse(int sig);
526 static void	usage(void);
527 static void	log_or_warn(int log_pri, int errnum, const char *fmt, ...)
528 		    __printflike(3, 4);
529 
530 static int	r_identify(void);
531 static const char *r_if(int type);
532 static const char *r_name(int type);
533 static const char *r_model(int model);
534 static void	r_init(void);
535 static int	r_protocol(u_char b, mousestatus_t *act);
536 static int	r_statetrans(mousestatus_t *a1, mousestatus_t *a2, int trans);
537 static int	r_installmap(char *arg);
538 static void	r_map(mousestatus_t *act1, mousestatus_t *act2);
539 static void	r_timestamp(mousestatus_t *act);
540 static int	r_timeout(void);
541 static void	r_click(mousestatus_t *act);
542 static void	setmousespeed(int old, int new, unsigned cflag);
543 
544 static int	pnpwakeup1(void);
545 static int	pnpwakeup2(void);
546 static int	pnpgets(char *buf);
547 static int	pnpparse(pnpid_t *id, char *buf, int len);
548 static symtab_t	*pnpproto(pnpid_t *id);
549 
550 static symtab_t	*gettoken(symtab_t *tab, const char *s, int len);
551 static const char *gettokenname(symtab_t *tab, int val);
552 
553 static void	mremote_serversetup(void);
554 static void	mremote_clientchg(int add);
555 
556 static int	kidspad(u_char rxc, mousestatus_t *act);
557 static int	gtco_digipad(u_char, mousestatus_t *);
558 
559 int
560 main(int argc, char *argv[])
561 {
562     int c;
563     int	i;
564     int	j;
565 
566     for (i = 0; i < MOUSE_MAXBUTTON; ++i)
567 	mstate[i] = &bstate[i];
568 
569     while ((c = getopt(argc, argv, "3A:C:DE:F:HI:L:PRS:T:VU:a:cdfhi:l:m:p:r:st:w:z:")) != -1)
570 	switch(c) {
571 
572 	case '3':
573 	    rodent.flags |= Emulate3Button;
574 	    break;
575 
576 	case 'E':
577 	    rodent.button2timeout = atoi(optarg);
578 	    if ((rodent.button2timeout < 0) ||
579 		(rodent.button2timeout > MAX_BUTTON2TIMEOUT)) {
580 		warnx("invalid argument `%s'", optarg);
581 		usage();
582 	    }
583 	    break;
584 
585 	case 'a':
586 	    i = sscanf(optarg, "%f,%f", &rodent.accelx, &rodent.accely);
587 	    if (i == 0) {
588 		warnx("invalid linear acceleration argument '%s'", optarg);
589 		usage();
590 	    }
591 
592 	    if (i == 1)
593 		rodent.accely = rodent.accelx;
594 
595 	    break;
596 
597 	case 'A':
598 	    rodent.flags |= ExponentialAcc;
599 	    i = sscanf(optarg, "%f,%f", &rodent.expoaccel, &rodent.expoffset);
600 	    if (i == 0) {
601 		warnx("invalid exponential acceleration argument '%s'", optarg);
602 		usage();
603 	    }
604 
605 	    if (i == 1)
606 		rodent.expoffset = 1.0;
607 
608 	    break;
609 
610 	case 'c':
611 	    rodent.flags |= ChordMiddle;
612 	    break;
613 
614 	case 'd':
615 	    ++debug;
616 	    break;
617 
618 	case 'f':
619 	    nodaemon = TRUE;
620 	    break;
621 
622 	case 'i':
623 	    if (strcmp(optarg, "all") == 0)
624 		identify = ID_ALL;
625 	    else if (strcmp(optarg, "port") == 0)
626 		identify = ID_PORT;
627 	    else if (strcmp(optarg, "if") == 0)
628 		identify = ID_IF;
629 	    else if (strcmp(optarg, "type") == 0)
630 		identify = ID_TYPE;
631 	    else if (strcmp(optarg, "model") == 0)
632 		identify = ID_MODEL;
633 	    else {
634 		warnx("invalid argument `%s'", optarg);
635 		usage();
636 	    }
637 	    nodaemon = TRUE;
638 	    break;
639 
640 	case 'l':
641 	    rodent.level = atoi(optarg);
642 	    if ((rodent.level < 0) || (rodent.level > 4)) {
643 		warnx("invalid argument `%s'", optarg);
644 		usage();
645 	    }
646 	    break;
647 
648 	case 'm':
649 	    if (!r_installmap(optarg)) {
650 		warnx("invalid argument `%s'", optarg);
651 		usage();
652 	    }
653 	    break;
654 
655 	case 'p':
656 	    rodent.portname = optarg;
657 	    break;
658 
659 	case 'r':
660 	    if (strcmp(optarg, "high") == 0)
661 		rodent.resolution = MOUSE_RES_HIGH;
662 	    else if (strcmp(optarg, "medium-high") == 0)
663 		rodent.resolution = MOUSE_RES_HIGH;
664 	    else if (strcmp(optarg, "medium-low") == 0)
665 		rodent.resolution = MOUSE_RES_MEDIUMLOW;
666 	    else if (strcmp(optarg, "low") == 0)
667 		rodent.resolution = MOUSE_RES_LOW;
668 	    else if (strcmp(optarg, "default") == 0)
669 		rodent.resolution = MOUSE_RES_DEFAULT;
670 	    else {
671 		rodent.resolution = atoi(optarg);
672 		if (rodent.resolution <= 0) {
673 		    warnx("invalid argument `%s'", optarg);
674 		    usage();
675 		}
676 	    }
677 	    break;
678 
679 	case 's':
680 	    rodent.baudrate = 9600;
681 	    break;
682 
683 	case 'w':
684 	    i = atoi(optarg);
685 	    if ((i <= 0) || (i > MOUSE_MAXBUTTON)) {
686 		warnx("invalid argument `%s'", optarg);
687 		usage();
688 	    }
689 	    rodent.wmode = 1 << (i - 1);
690 	    break;
691 
692 	case 'z':
693 	    if (strcmp(optarg, "x") == 0)
694 		rodent.zmap[0] = MOUSE_XAXIS;
695 	    else if (strcmp(optarg, "y") == 0)
696 		rodent.zmap[0] = MOUSE_YAXIS;
697 	    else {
698 		i = atoi(optarg);
699 		/*
700 		 * Use button i for negative Z axis movement and
701 		 * button (i + 1) for positive Z axis movement.
702 		 */
703 		if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
704 		    warnx("invalid argument `%s'", optarg);
705 		    usage();
706 		}
707 		rodent.zmap[0] = i;
708 		rodent.zmap[1] = i + 1;
709 		debug("optind: %d, optarg: '%s'", optind, optarg);
710 		for (j = 1; j < 4; ++j) {
711 		    if ((optind >= argc) || !isdigit(*argv[optind]))
712 			break;
713 		    i = atoi(argv[optind]);
714 		    if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
715 			warnx("invalid argument `%s'", argv[optind]);
716 			usage();
717 		    }
718 		    rodent.zmap[j] = i;
719 		    ++optind;
720 		}
721 		if ((rodent.zmap[2] != 0) && (rodent.zmap[3] == 0))
722 		    rodent.zmap[3] = rodent.zmap[2] + 1;
723 	    }
724 	    break;
725 
726 	case 'C':
727 	    rodent.clickthreshold = atoi(optarg);
728 	    if ((rodent.clickthreshold < 0) ||
729 		(rodent.clickthreshold > MAX_CLICKTHRESHOLD)) {
730 		warnx("invalid argument `%s'", optarg);
731 		usage();
732 	    }
733 	    break;
734 
735 	case 'D':
736 	    rodent.flags |= ClearDTR;
737 	    break;
738 
739 	case 'F':
740 	    rodent.rate = atoi(optarg);
741 	    if (rodent.rate <= 0) {
742 		warnx("invalid argument `%s'", optarg);
743 		usage();
744 	    }
745 	    break;
746 
747 	case 'H':
748 	    rodent.flags |= HVirtualScroll;
749 	    break;
750 
751 	case 'I':
752 	    pidfile = optarg;
753 	    break;
754 
755 	case 'L':
756 	    rodent.scrollspeed = atoi(optarg);
757 	    if (rodent.scrollspeed < 0) {
758 		warnx("invalid argument `%s'", optarg);
759 		usage();
760 	    }
761 	    break;
762 
763 	case 'P':
764 	    rodent.flags |= NoPnP;
765 	    break;
766 
767 	case 'R':
768 	    rodent.flags |= ClearRTS;
769 	    break;
770 
771 	case 'S':
772 	    rodent.baudrate = atoi(optarg);
773 	    if (rodent.baudrate <= 0) {
774 		warnx("invalid argument `%s'", optarg);
775 		usage();
776 	    }
777 	    debug("rodent baudrate %d", rodent.baudrate);
778 	    break;
779 
780 	case 'T':
781 	    drift_terminate = TRUE;
782 	    sscanf(optarg, "%d,%d,%d", &drift_distance, &drift_time,
783 		&drift_after);
784 	    if (drift_distance <= 0 || drift_time <= 0 || drift_after <= 0) {
785 		warnx("invalid argument `%s'", optarg);
786 		usage();
787 	    }
788 	    debug("terminate drift: distance %d, time %d, after %d",
789 		drift_distance, drift_time, drift_after);
790 	    drift_time_ts.tv_sec = drift_time / 1000;
791 	    drift_time_ts.tv_nsec = (drift_time % 1000) * 1000000;
792  	    drift_2time_ts.tv_sec = (drift_time *= 2) / 1000;
793 	    drift_2time_ts.tv_nsec = (drift_time % 1000) * 1000000;
794 	    drift_after_ts.tv_sec = drift_after / 1000;
795 	    drift_after_ts.tv_nsec = (drift_after % 1000) * 1000000;
796 	    break;
797 
798 	case 't':
799 	    if (strcmp(optarg, "auto") == 0) {
800 		rodent.rtype = MOUSE_PROTO_UNKNOWN;
801 		rodent.flags &= ~NoPnP;
802 		rodent.level = -1;
803 		break;
804 	    }
805 	    for (i = 0; rnames[i] != NULL; i++)
806 		if (strcmp(optarg, rnames[i]) == 0) {
807 		    rodent.rtype = i;
808 		    rodent.flags |= NoPnP;
809 		    rodent.level = (i == MOUSE_PROTO_SYSMOUSE) ? 1 : 0;
810 		    break;
811 		}
812 	    if (rnames[i] == NULL) {
813 		warnx("no such mouse type `%s'", optarg);
814 		usage();
815 	    }
816 	    break;
817 
818 	case 'V':
819 	    rodent.flags |= VirtualScroll;
820 	    break;
821 	case 'U':
822 	    rodent.scrollthreshold = atoi(optarg);
823 	    if (rodent.scrollthreshold < 0) {
824 		warnx("invalid argument `%s'", optarg);
825 		usage();
826 	    }
827 	    break;
828 
829 	case 'h':
830 	case '?':
831 	default:
832 	    usage();
833 	}
834 
835     /* fix Z axis mapping */
836     for (i = 0; i < 4; ++i) {
837 	if (rodent.zmap[i] > 0) {
838 	    for (j = 0; j < MOUSE_MAXBUTTON; ++j) {
839 		if (mstate[j] == &bstate[rodent.zmap[i] - 1])
840 		    mstate[j] = &zstate[i];
841 	    }
842 	    rodent.zmap[i] = 1 << (rodent.zmap[i] - 1);
843 	}
844     }
845 
846     /* the default port name */
847     switch(rodent.rtype) {
848 
849     case MOUSE_PROTO_PS2:
850 	if (!rodent.portname)
851 	    rodent.portname = "/dev/psm0";
852 	break;
853 
854     default:
855 	if (rodent.portname)
856 	    break;
857 	warnx("no port name specified");
858 	usage();
859     }
860 
861     if (strncmp(rodent.portname, "/dev/ums", 8) == 0)
862 	rodent.is_removable = 1;
863 
864     for (;;) {
865 	if (setjmp(env) == 0) {
866 	    signal(SIGHUP, hup);
867 	    signal(SIGINT , cleanup);
868 	    signal(SIGQUIT, cleanup);
869 	    signal(SIGTERM, cleanup);
870 	    signal(SIGUSR1, pause_mouse);
871 
872 	    rodent.mfd = open(rodent.portname, O_RDWR | O_NONBLOCK);
873 	    if (rodent.mfd == -1)
874 		logerr(1, "unable to open %s", rodent.portname);
875 	    if (r_identify() == MOUSE_PROTO_UNKNOWN) {
876 		logwarnx("cannot determine mouse type on %s", rodent.portname);
877 		close(rodent.mfd);
878 		rodent.mfd = -1;
879 	    }
880 
881 	    /* print some information */
882 	    if (identify != ID_NONE) {
883 		if (identify == ID_ALL)
884 		    printf("%s %s %s %s\n",
885 			rodent.portname, r_if(rodent.hw.iftype),
886 			r_name(rodent.rtype), r_model(rodent.hw.model));
887 		else if (identify & ID_PORT)
888 		    printf("%s\n", rodent.portname);
889 		else if (identify & ID_IF)
890 		    printf("%s\n", r_if(rodent.hw.iftype));
891 		else if (identify & ID_TYPE)
892 		    printf("%s\n", r_name(rodent.rtype));
893 		else if (identify & ID_MODEL)
894 		    printf("%s\n", r_model(rodent.hw.model));
895 		exit(0);
896 	    } else {
897 		debug("port: %s  interface: %s  type: %s  model: %s",
898 		    rodent.portname, r_if(rodent.hw.iftype),
899 		    r_name(rodent.rtype), r_model(rodent.hw.model));
900 	    }
901 
902 	    if (rodent.mfd == -1) {
903 		/*
904 		 * We cannot continue because of error.  Exit if the
905 		 * program has not become a daemon.  Otherwise, block
906 		 * until the user corrects the problem and issues SIGHUP.
907 		 */
908 		if (!background)
909 		    exit(1);
910 		sigpause(0);
911 	    }
912 
913 	    r_init();			/* call init function */
914 	    moused();
915 	}
916 
917 	if (rodent.mfd != -1)
918 	    close(rodent.mfd);
919 	if (rodent.cfd != -1)
920 	    close(rodent.cfd);
921 	rodent.mfd = rodent.cfd = -1;
922 	if (rodent.is_removable)
923 		exit(0);
924     }
925     /* NOT REACHED */
926 
927     exit(0);
928 }
929 
930 /*
931  * Function to calculate linear acceleration.
932  *
933  * If there are any rounding errors, the remainder
934  * is stored in the remainx and remainy variables
935  * and taken into account upon the next movement.
936  */
937 
938 static void
939 linacc(int dx, int dy, int *movex, int *movey)
940 {
941     float fdx, fdy;
942 
943     if (dx == 0 && dy == 0) {
944 	*movex = *movey = 0;
945 	return;
946     }
947     fdx = dx * rodent.accelx + rodent.remainx;
948     fdy = dy * rodent.accely + rodent.remainy;
949     *movex = lround(fdx);
950     *movey = lround(fdy);
951     rodent.remainx = fdx - *movex;
952     rodent.remainy = fdy - *movey;
953 }
954 
955 /*
956  * Function to calculate exponential acceleration.
957  * (Also includes linear acceleration if enabled.)
958  *
959  * In order to give a smoother behaviour, we record the four
960  * most recent non-zero movements and use their average value
961  * to calculate the acceleration.
962  */
963 
964 static void
965 expoacc(int dx, int dy, int *movex, int *movey)
966 {
967     static float lastlength[3] = {0.0, 0.0, 0.0};
968     float fdx, fdy, length, lbase, accel;
969 
970     if (dx == 0 && dy == 0) {
971 	*movex = *movey = 0;
972 	return;
973     }
974     fdx = dx * rodent.accelx;
975     fdy = dy * rodent.accely;
976     length = sqrtf((fdx * fdx) + (fdy * fdy));		/* Pythagoras */
977     length = (length + lastlength[0] + lastlength[1] + lastlength[2]) / 4;
978     lbase = length / rodent.expoffset;
979     accel = powf(lbase, rodent.expoaccel) / lbase;
980     fdx = fdx * accel + rodent.remainx;
981     fdy = fdy * accel + rodent.remainy;
982     *movex = lroundf(fdx);
983     *movey = lroundf(fdy);
984     rodent.remainx = fdx - *movex;
985     rodent.remainy = fdy - *movey;
986     lastlength[2] = lastlength[1];
987     lastlength[1] = lastlength[0];
988     lastlength[0] = length;	/* Insert new average, not original length! */
989 }
990 
991 static void
992 moused(void)
993 {
994     struct mouse_info mouse;
995     mousestatus_t action0;		/* original mouse action */
996     mousestatus_t action;		/* interim buffer */
997     mousestatus_t action2;		/* mapped action */
998     struct timeval timeout;
999     fd_set fds;
1000     u_char b;
1001     pid_t mpid;
1002     int flags;
1003     int c;
1004     int i;
1005 
1006     if ((rodent.cfd = open("/dev/consolectl", O_RDWR, 0)) == -1)
1007 	logerr(1, "cannot open /dev/consolectl");
1008 
1009     if (!nodaemon && !background) {
1010 	pfh = pidfile_open(pidfile, 0600, &mpid);
1011 	if (pfh == NULL) {
1012 	    if (errno == EEXIST)
1013 		logerrx(1, "moused already running, pid: %d", mpid);
1014 	    logwarn("cannot open pid file");
1015 	}
1016 	if (daemon(0, 0)) {
1017 	    int saved_errno = errno;
1018 	    pidfile_remove(pfh);
1019 	    errno = saved_errno;
1020 	    logerr(1, "failed to become a daemon");
1021 	} else {
1022 	    background = TRUE;
1023 	    pidfile_write(pfh);
1024 	}
1025     }
1026 
1027     /* clear mouse data */
1028     bzero(&action0, sizeof(action0));
1029     bzero(&action, sizeof(action));
1030     bzero(&action2, sizeof(action2));
1031     bzero(&mouse, sizeof(mouse));
1032     mouse_button_state = S0;
1033     clock_gettime(CLOCK_MONOTONIC_FAST, &mouse_button_state_ts);
1034     mouse_move_delayed = 0;
1035     for (i = 0; i < MOUSE_MAXBUTTON; ++i) {
1036 	bstate[i].count = 0;
1037 	bstate[i].ts = mouse_button_state_ts;
1038     }
1039     for (i = 0; i < (int)(sizeof(zstate) / sizeof(zstate[0])); ++i) {
1040 	zstate[i].count = 0;
1041 	zstate[i].ts = mouse_button_state_ts;
1042     }
1043 
1044     /* choose which ioctl command to use */
1045     mouse.operation = MOUSE_MOTION_EVENT;
1046     extioctl = (ioctl(rodent.cfd, CONS_MOUSECTL, &mouse) == 0);
1047 
1048     /* process mouse data */
1049     timeout.tv_sec = 0;
1050     timeout.tv_usec = 20000;		/* 20 msec */
1051     for (;;) {
1052 
1053 	FD_ZERO(&fds);
1054 	FD_SET(rodent.mfd, &fds);
1055 	if (rodent.mremsfd >= 0)
1056 	    FD_SET(rodent.mremsfd, &fds);
1057 	if (rodent.mremcfd >= 0)
1058 	    FD_SET(rodent.mremcfd, &fds);
1059 
1060 	c = select(FD_SETSIZE, &fds, NULL, NULL,
1061 		   ((rodent.flags & Emulate3Button) &&
1062 		    S_DELAYED(mouse_button_state)) ? &timeout : NULL);
1063 	if (c < 0) {                    /* error */
1064 	    logwarn("failed to read from mouse");
1065 	    continue;
1066 	} else if (c == 0) {            /* timeout */
1067 	    /* assert(rodent.flags & Emulate3Button) */
1068 	    action0.button = action0.obutton;
1069 	    action0.dx = action0.dy = action0.dz = 0;
1070 	    action0.flags = flags = 0;
1071 	    if (r_timeout() && r_statetrans(&action0, &action, A_TIMEOUT)) {
1072 		if (debug > 2)
1073 		    debug("flags:%08x buttons:%08x obuttons:%08x",
1074 			  action.flags, action.button, action.obutton);
1075 	    } else {
1076 		action0.obutton = action0.button;
1077 		continue;
1078 	    }
1079 	} else {
1080 	    /*  MouseRemote client connect/disconnect  */
1081 	    if ((rodent.mremsfd >= 0) && FD_ISSET(rodent.mremsfd, &fds)) {
1082 		mremote_clientchg(TRUE);
1083 		continue;
1084 	    }
1085 	    if ((rodent.mremcfd >= 0) && FD_ISSET(rodent.mremcfd, &fds)) {
1086 		mremote_clientchg(FALSE);
1087 		continue;
1088 	    }
1089 	    /* mouse movement */
1090 	    if (read(rodent.mfd, &b, 1) == -1) {
1091 		if (errno == EWOULDBLOCK)
1092 		    continue;
1093 		else
1094 		    return;
1095 	    }
1096 	    if ((flags = r_protocol(b, &action0)) == 0)
1097 		continue;
1098 
1099 	    if ((rodent.flags & VirtualScroll) || (rodent.flags & HVirtualScroll)) {
1100 		/* Allow middle button drags to scroll up and down */
1101 		if (action0.button == MOUSE_BUTTON2DOWN) {
1102 		    if (scroll_state == SCROLL_NOTSCROLLING) {
1103 			scroll_state = SCROLL_PREPARE;
1104 			scroll_movement = hscroll_movement = 0;
1105 			debug("PREPARING TO SCROLL");
1106 		    }
1107 		    debug("[BUTTON2] flags:%08x buttons:%08x obuttons:%08x",
1108 			  action.flags, action.button, action.obutton);
1109 		} else {
1110 		    debug("[NOTBUTTON2] flags:%08x buttons:%08x obuttons:%08x",
1111 			  action.flags, action.button, action.obutton);
1112 
1113 		    /* This isn't a middle button down... move along... */
1114 		    if (scroll_state == SCROLL_SCROLLING) {
1115 			/*
1116 			 * We were scrolling, someone let go of button 2.
1117 			 * Now turn autoscroll off.
1118 			 */
1119 			scroll_state = SCROLL_NOTSCROLLING;
1120 			debug("DONE WITH SCROLLING / %d", scroll_state);
1121 		    } else if (scroll_state == SCROLL_PREPARE) {
1122 			mousestatus_t newaction = action0;
1123 
1124 			/* We were preparing to scroll, but we never moved... */
1125 			r_timestamp(&action0);
1126 			r_statetrans(&action0, &newaction,
1127 				     A(newaction.button & MOUSE_BUTTON1DOWN,
1128 				       action0.button & MOUSE_BUTTON3DOWN));
1129 
1130 			/* Send middle down */
1131 			newaction.button = MOUSE_BUTTON2DOWN;
1132 			r_click(&newaction);
1133 
1134 			/* Send middle up */
1135 			r_timestamp(&newaction);
1136 			newaction.obutton = newaction.button;
1137 			newaction.button = action0.button;
1138 			r_click(&newaction);
1139 		    }
1140 		}
1141 	    }
1142 
1143 	    r_timestamp(&action0);
1144 	    r_statetrans(&action0, &action,
1145 			 A(action0.button & MOUSE_BUTTON1DOWN,
1146 			   action0.button & MOUSE_BUTTON3DOWN));
1147 	    debug("flags:%08x buttons:%08x obuttons:%08x", action.flags,
1148 		  action.button, action.obutton);
1149 	}
1150 	action0.obutton = action0.button;
1151 	flags &= MOUSE_POSCHANGED;
1152 	flags |= action.obutton ^ action.button;
1153 	action.flags = flags;
1154 
1155 	if (flags) {			/* handler detected action */
1156 	    r_map(&action, &action2);
1157 	    debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
1158 		action2.button, action2.dx, action2.dy, action2.dz);
1159 
1160 	    if ((rodent.flags & VirtualScroll) || (rodent.flags & HVirtualScroll)) {
1161 		/*
1162 		 * If *only* the middle button is pressed AND we are moving
1163 		 * the stick/trackpoint/nipple, scroll!
1164 		 */
1165 		if (scroll_state == SCROLL_PREPARE) {
1166 			/* Middle button down, waiting for movement threshold */
1167 			if (action2.dy || action2.dx) {
1168 				if (rodent.flags & VirtualScroll) {
1169 					scroll_movement += action2.dy;
1170 					if (scroll_movement < -rodent.scrollthreshold) {
1171 						scroll_state = SCROLL_SCROLLING;
1172 					} else if (scroll_movement > rodent.scrollthreshold) {
1173 						scroll_state = SCROLL_SCROLLING;
1174 					}
1175 				}
1176 				if (rodent.flags & HVirtualScroll) {
1177 					hscroll_movement += action2.dx;
1178 					if (hscroll_movement < -rodent.scrollthreshold) {
1179 						scroll_state = SCROLL_SCROLLING;
1180 					} else if (hscroll_movement > rodent.scrollthreshold) {
1181 						scroll_state = SCROLL_SCROLLING;
1182 					}
1183 				}
1184 				if (scroll_state == SCROLL_SCROLLING) scroll_movement = hscroll_movement = 0;
1185 			}
1186 		} else if (scroll_state == SCROLL_SCROLLING) {
1187 			 if (rodent.flags & VirtualScroll) {
1188 				 scroll_movement += action2.dy;
1189 				 debug("SCROLL: %d", scroll_movement);
1190 			    if (scroll_movement < -rodent.scrollspeed) {
1191 				/* Scroll down */
1192 				action2.dz = -1;
1193 				scroll_movement = 0;
1194 			    }
1195 			    else if (scroll_movement > rodent.scrollspeed) {
1196 				/* Scroll up */
1197 				action2.dz = 1;
1198 				scroll_movement = 0;
1199 			    }
1200 			 }
1201 			 if (rodent.flags & HVirtualScroll) {
1202 				 hscroll_movement += action2.dx;
1203 				 debug("HORIZONTAL SCROLL: %d", hscroll_movement);
1204 
1205 				 if (hscroll_movement < -rodent.scrollspeed) {
1206 					 action2.dz = -2;
1207 					 hscroll_movement = 0;
1208 				 }
1209 				 else if (hscroll_movement > rodent.scrollspeed) {
1210 					 action2.dz = 2;
1211 					 hscroll_movement = 0;
1212 				 }
1213 			 }
1214 
1215 		    /* Don't move while scrolling */
1216 		    action2.dx = action2.dy = 0;
1217 		}
1218 	    }
1219 
1220 	    if (drift_terminate) {
1221 		if ((flags & MOUSE_POSCHANGED) == 0 || action.dz || action2.dz)
1222 		    drift_last_activity = drift_current_ts;
1223 		else {
1224 		    /* X or/and Y movement only - possibly drift */
1225 		    tssub(&drift_current_ts, &drift_last_activity, &drift_tmp);
1226 		    if (tscmp(&drift_tmp, &drift_after_ts, >)) {
1227 			tssub(&drift_current_ts, &drift_since, &drift_tmp);
1228 			if (tscmp(&drift_tmp, &drift_time_ts, <)) {
1229 			    drift_last.x += action2.dx;
1230 			    drift_last.y += action2.dy;
1231 			} else {
1232 			    /* discard old accumulated steps (drift) */
1233 			    if (tscmp(&drift_tmp, &drift_2time_ts, >))
1234 				drift_previous.x = drift_previous.y = 0;
1235 			    else
1236 				drift_previous = drift_last;
1237 			    drift_last.x = action2.dx;
1238 			    drift_last.y = action2.dy;
1239 			    drift_since = drift_current_ts;
1240 			}
1241 			if (abs(drift_last.x) + abs(drift_last.y)
1242 			  > drift_distance) {
1243 			    /* real movement, pass all accumulated steps */
1244 			    action2.dx = drift_previous.x + drift_last.x;
1245 			    action2.dy = drift_previous.y + drift_last.y;
1246 			    /* and reset accumulators */
1247 			    tsclr(&drift_since);
1248 			    drift_last.x = drift_last.y = 0;
1249 			    /* drift_previous will be cleared at next movement*/
1250 			    drift_last_activity = drift_current_ts;
1251 			} else {
1252 			    continue;   /* don't pass current movement to
1253 					 * console driver */
1254 			}
1255 		    }
1256 		}
1257 	    }
1258 
1259 	    if (extioctl) {
1260 		/* Defer clicks until we aren't VirtualScroll'ing. */
1261 		if (scroll_state == SCROLL_NOTSCROLLING)
1262 		    r_click(&action2);
1263 
1264 		if (action2.flags & MOUSE_POSCHANGED) {
1265 		    mouse.operation = MOUSE_MOTION_EVENT;
1266 		    mouse.u.data.buttons = action2.button;
1267 		    if (rodent.flags & ExponentialAcc) {
1268 			expoacc(action2.dx, action2.dy,
1269 			    &mouse.u.data.x, &mouse.u.data.y);
1270 		    }
1271 		    else {
1272 			linacc(action2.dx, action2.dy,
1273 			    &mouse.u.data.x, &mouse.u.data.y);
1274 		    }
1275 		    mouse.u.data.z = action2.dz;
1276 		    if (debug < 2)
1277 			if (!paused)
1278 				ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1279 		}
1280 	    } else {
1281 		mouse.operation = MOUSE_ACTION;
1282 		mouse.u.data.buttons = action2.button;
1283 		if (rodent.flags & ExponentialAcc) {
1284 		    expoacc(action2.dx, action2.dy,
1285 			&mouse.u.data.x, &mouse.u.data.y);
1286 		}
1287 		else {
1288 		    linacc(action2.dx, action2.dy,
1289 			&mouse.u.data.x, &mouse.u.data.y);
1290 		}
1291 		mouse.u.data.z = action2.dz;
1292 		if (debug < 2)
1293 		    if (!paused)
1294 			ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1295 	    }
1296 
1297 	    /*
1298 	     * If the Z axis movement is mapped to an imaginary physical
1299 	     * button, we need to cook up a corresponding button `up' event
1300 	     * after sending a button `down' event.
1301 	     */
1302 	    if ((rodent.zmap[0] > 0) && (action.dz != 0)) {
1303 		action.obutton = action.button;
1304 		action.dx = action.dy = action.dz = 0;
1305 		r_map(&action, &action2);
1306 		debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
1307 		    action2.button, action2.dx, action2.dy, action2.dz);
1308 
1309 		if (extioctl) {
1310 		    r_click(&action2);
1311 		} else {
1312 		    mouse.operation = MOUSE_ACTION;
1313 		    mouse.u.data.buttons = action2.button;
1314 		    mouse.u.data.x = mouse.u.data.y = mouse.u.data.z = 0;
1315 		    if (debug < 2)
1316 			if (!paused)
1317 			    ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1318 		}
1319 	    }
1320 	}
1321     }
1322     /* NOT REACHED */
1323 }
1324 
1325 static void
1326 hup(__unused int sig)
1327 {
1328     longjmp(env, 1);
1329 }
1330 
1331 static void
1332 cleanup(__unused int sig)
1333 {
1334     if (rodent.rtype == MOUSE_PROTO_X10MOUSEREM)
1335 	unlink(_PATH_MOUSEREMOTE);
1336     exit(0);
1337 }
1338 
1339 static void
1340 pause_mouse(__unused int sig)
1341 {
1342     paused = !paused;
1343 }
1344 
1345 /**
1346  ** usage
1347  **
1348  ** Complain, and free the CPU for more worthy tasks
1349  **/
1350 static void
1351 usage(void)
1352 {
1353     fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
1354 	"usage: moused [-DRcdfs] [-I file] [-F rate] [-r resolution] [-S baudrate]",
1355 	"              [-VH [-U threshold]] [-a X[,Y]] [-C threshold] [-m N=M] [-w N]",
1356 	"              [-z N] [-t <mousetype>] [-l level] [-3 [-E timeout]]",
1357 	"              [-T distance[,time[,after]]] -p <port>",
1358 	"       moused [-d] -i <port|if|type|model|all> -p <port>");
1359     exit(1);
1360 }
1361 
1362 /*
1363  * Output an error message to syslog or stderr as appropriate. If
1364  * `errnum' is non-zero, append its string form to the message.
1365  */
1366 static void
1367 log_or_warn(int log_pri, int errnum, const char *fmt, ...)
1368 {
1369 	va_list ap;
1370 	char buf[256];
1371 
1372 	va_start(ap, fmt);
1373 	vsnprintf(buf, sizeof(buf), fmt, ap);
1374 	va_end(ap);
1375 	if (errnum) {
1376 		strlcat(buf, ": ", sizeof(buf));
1377 		strlcat(buf, strerror(errnum), sizeof(buf));
1378 	}
1379 
1380 	if (background)
1381 		syslog(log_pri, "%s", buf);
1382 	else
1383 		warnx("%s", buf);
1384 }
1385 
1386 /**
1387  ** Mouse interface code, courtesy of XFree86 3.1.2.
1388  **
1389  ** Note: Various bits have been trimmed, and in my shortsighted enthusiasm
1390  ** to clean, reformat and rationalise naming, it's quite possible that
1391  ** some things in here have been broken.
1392  **
1393  ** I hope not 8)
1394  **
1395  ** The following code is derived from a module marked :
1396  **/
1397 
1398 /* $XConsortium: xf86_Mouse.c,v 1.2 94/10/12 20:33:21 kaleb Exp $ */
1399 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.2 1995/01/28
1400  17:03:40 dawes Exp $ */
1401 /*
1402  *
1403  * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
1404  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
1405  *
1406  * Permission to use, copy, modify, distribute, and sell this software and its
1407  * documentation for any purpose is hereby granted without fee, provided that
1408  * the above copyright notice appear in all copies and that both that
1409  * copyright notice and this permission notice appear in supporting
1410  * documentation, and that the names of Thomas Roell and David Dawes not be
1411  * used in advertising or publicity pertaining to distribution of the
1412  * software without specific, written prior permission.  Thomas Roell
1413  * and David Dawes makes no representations about the suitability of this
1414  * software for any purpose.  It is provided "as is" without express or
1415  * implied warranty.
1416  *
1417  * THOMAS ROELL AND DAVID DAWES DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
1418  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
1419  * FITNESS, IN NO EVENT SHALL THOMAS ROELL OR DAVID DAWES BE LIABLE FOR ANY
1420  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
1421  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
1422  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1423  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1424  *
1425  */
1426 
1427 /**
1428  ** GlidePoint support from XFree86 3.2.
1429  ** Derived from the module:
1430  **/
1431 
1432 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.19 1996/10/16 14:40:51 dawes Exp $ */
1433 /* $XConsortium: xf86_Mouse.c /main/10 1996/01/30 15:16:12 kaleb $ */
1434 
1435 /* the following table must be ordered by MOUSE_PROTO_XXX in mouse.h */
1436 static unsigned char proto[][7] = {
1437     /*  hd_mask hd_id   dp_mask dp_id   bytes b4_mask b4_id */
1438     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* MicroSoft */
1439     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* MouseSystems */
1440     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* Logitech */
1441     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MMSeries */
1442     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* MouseMan */
1443     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* Bus */
1444     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* InPort */
1445     {	0xc0,	0x00,	0x00,	0x00,	3,    0x00,  0xff }, /* PS/2 mouse */
1446     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MM HitTablet */
1447     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* GlidePoint */
1448     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x3f,  0x00 }, /* IntelliMouse */
1449     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* ThinkingMouse */
1450     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* sysmouse */
1451     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* X10 MouseRem */
1452     {	0x80,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* KIDSPAD */
1453     {	0xc3,	0xc0,	0x00,	0x00,	6,    0x00,  0xff }, /* VersaPad */
1454     {	0x00,	0x00,	0x00,	0x00,	1,    0x00,  0xff }, /* JogDial */
1455 #if notyet
1456     {	0xf8,	0x80,	0x00,	0x00,	5,   ~0x2f,  0x10 }, /* Mariqua */
1457 #endif
1458 };
1459 static unsigned char cur_proto[7];
1460 
1461 static int
1462 r_identify(void)
1463 {
1464     char pnpbuf[256];	/* PnP identifier string may be up to 256 bytes long */
1465     pnpid_t pnpid;
1466     symtab_t *t;
1467     int level;
1468     int len;
1469 
1470     /* set the driver operation level, if applicable */
1471     if (rodent.level < 0)
1472 	rodent.level = 1;
1473     ioctl(rodent.mfd, MOUSE_SETLEVEL, &rodent.level);
1474     rodent.level = (ioctl(rodent.mfd, MOUSE_GETLEVEL, &level) == 0) ? level : 0;
1475 
1476     /*
1477      * Interrogate the driver and get some intelligence on the device...
1478      * The following ioctl functions are not always supported by device
1479      * drivers.  When the driver doesn't support them, we just trust the
1480      * user to supply valid information.
1481      */
1482     rodent.hw.iftype = MOUSE_IF_UNKNOWN;
1483     rodent.hw.model = MOUSE_MODEL_GENERIC;
1484     ioctl(rodent.mfd, MOUSE_GETHWINFO, &rodent.hw);
1485 
1486     if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1487 	bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1488     rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
1489     rodent.mode.rate = -1;
1490     rodent.mode.resolution = MOUSE_RES_UNKNOWN;
1491     rodent.mode.accelfactor = 0;
1492     rodent.mode.level = 0;
1493     if (ioctl(rodent.mfd, MOUSE_GETMODE, &rodent.mode) == 0) {
1494 	if (rodent.mode.protocol == MOUSE_PROTO_UNKNOWN ||
1495 	    rodent.mode.protocol >= (int)(sizeof(proto) / sizeof(proto[0]))) {
1496 	    logwarnx("unknown mouse protocol (%d)", rodent.mode.protocol);
1497 	    return (MOUSE_PROTO_UNKNOWN);
1498 	} else {
1499 	    if (rodent.mode.protocol != rodent.rtype) {
1500 		/* Hmm, the driver doesn't agree with the user... */
1501 		if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1502 		    logwarnx("mouse type mismatch (%s != %s), %s is assumed",
1503 			r_name(rodent.mode.protocol), r_name(rodent.rtype),
1504 			r_name(rodent.mode.protocol));
1505 		rodent.rtype = rodent.mode.protocol;
1506 		bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1507 	    }
1508 	}
1509 	cur_proto[4] = rodent.mode.packetsize;
1510 	cur_proto[0] = rodent.mode.syncmask[0];	/* header byte bit mask */
1511 	cur_proto[1] = rodent.mode.syncmask[1];	/* header bit pattern */
1512     }
1513 
1514     /* maybe this is a PnP mouse... */
1515     if (rodent.mode.protocol == MOUSE_PROTO_UNKNOWN) {
1516 
1517 	if (rodent.flags & NoPnP)
1518 	    return (rodent.rtype);
1519 	if (((len = pnpgets(pnpbuf)) <= 0) || !pnpparse(&pnpid, pnpbuf, len))
1520 	    return (rodent.rtype);
1521 
1522 	debug("PnP serial mouse: '%*.*s' '%*.*s' '%*.*s'",
1523 	    pnpid.neisaid, pnpid.neisaid, pnpid.eisaid,
1524 	    pnpid.ncompat, pnpid.ncompat, pnpid.compat,
1525 	    pnpid.ndescription, pnpid.ndescription, pnpid.description);
1526 
1527 	/* we have a valid PnP serial device ID */
1528 	rodent.hw.iftype = MOUSE_IF_SERIAL;
1529 	t = pnpproto(&pnpid);
1530 	if (t != NULL) {
1531 	    rodent.mode.protocol = t->val;
1532 	    rodent.hw.model = t->val2;
1533 	} else {
1534 	    rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
1535 	}
1536 
1537 	/* make final adjustment */
1538 	if (rodent.mode.protocol != MOUSE_PROTO_UNKNOWN) {
1539 	    if (rodent.mode.protocol != rodent.rtype) {
1540 		/* Hmm, the device doesn't agree with the user... */
1541 		if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1542 		    logwarnx("mouse type mismatch (%s != %s), %s is assumed",
1543 			r_name(rodent.mode.protocol), r_name(rodent.rtype),
1544 			r_name(rodent.mode.protocol));
1545 		rodent.rtype = rodent.mode.protocol;
1546 		bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1547 	    }
1548 	}
1549     }
1550 
1551     debug("proto params: %02x %02x %02x %02x %d %02x %02x",
1552 	cur_proto[0], cur_proto[1], cur_proto[2], cur_proto[3],
1553 	cur_proto[4], cur_proto[5], cur_proto[6]);
1554 
1555     return (rodent.rtype);
1556 }
1557 
1558 static const char *
1559 r_if(int iftype)
1560 {
1561 
1562     return (gettokenname(rifs, iftype));
1563 }
1564 
1565 static const char *
1566 r_name(int type)
1567 {
1568     const char *unknown = "unknown";
1569 
1570     return (type == MOUSE_PROTO_UNKNOWN ||
1571 	type >= (int)(sizeof(rnames) / sizeof(rnames[0])) ?
1572 	unknown : rnames[type]);
1573 }
1574 
1575 static const char *
1576 r_model(int model)
1577 {
1578 
1579     return (gettokenname(rmodels, model));
1580 }
1581 
1582 static void
1583 r_init(void)
1584 {
1585     unsigned char buf[16];	/* scrach buffer */
1586     fd_set fds;
1587     const char *s;
1588     char c;
1589     int i;
1590 
1591     /**
1592      ** This comment is a little out of context here, but it contains
1593      ** some useful information...
1594      ********************************************************************
1595      **
1596      ** The following lines take care of the Logitech MouseMan protocols.
1597      **
1598      ** NOTE: There are different versions of both MouseMan and TrackMan!
1599      **       Hence I add another protocol P_LOGIMAN, which the user can
1600      **       specify as MouseMan in his XF86Config file. This entry was
1601      **       formerly handled as a special case of P_MS. However, people
1602      **       who don't have the middle button problem, can still specify
1603      **       Microsoft and use P_MS.
1604      **
1605      ** By default, these mice should use a 3 byte Microsoft protocol
1606      ** plus a 4th byte for the middle button. However, the mouse might
1607      ** have switched to a different protocol before we use it, so I send
1608      ** the proper sequence just in case.
1609      **
1610      ** NOTE: - all commands to (at least the European) MouseMan have to
1611      **         be sent at 1200 Baud.
1612      **       - each command starts with a '*'.
1613      **       - whenever the MouseMan receives a '*', it will switch back
1614      **	 to 1200 Baud. Hence I have to select the desired protocol
1615      **	 first, then select the baud rate.
1616      **
1617      ** The protocols supported by the (European) MouseMan are:
1618      **   -  5 byte packed binary protocol, as with the Mouse Systems
1619      **      mouse. Selected by sequence "*U".
1620      **   -  2 button 3 byte MicroSoft compatible protocol. Selected
1621      **      by sequence "*V".
1622      **   -  3 button 3+1 byte MicroSoft compatible protocol (default).
1623      **      Selected by sequence "*X".
1624      **
1625      ** The following baud rates are supported:
1626      **   -  1200 Baud (default). Selected by sequence "*n".
1627      **   -  9600 Baud. Selected by sequence "*q".
1628      **
1629      ** Selecting a sample rate is no longer supported with the MouseMan!
1630      ** Some additional lines in xf86Config.c take care of ill configured
1631      ** baud rates and sample rates. (The user will get an error.)
1632      */
1633 
1634     switch (rodent.rtype) {
1635 
1636     case MOUSE_PROTO_LOGI:
1637 	/*
1638 	 * The baud rate selection command must be sent at the current
1639 	 * baud rate; try all likely settings
1640 	 */
1641 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1642 	setmousespeed(4800, rodent.baudrate, rodentcflags[rodent.rtype]);
1643 	setmousespeed(2400, rodent.baudrate, rodentcflags[rodent.rtype]);
1644 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1645 	/* select MM series data format */
1646 	write(rodent.mfd, "S", 1);
1647 	setmousespeed(rodent.baudrate, rodent.baudrate,
1648 		      rodentcflags[MOUSE_PROTO_MM]);
1649 	/* select report rate/frequency */
1650 	if      (rodent.rate <= 0)   write(rodent.mfd, "O", 1);
1651 	else if (rodent.rate <= 15)  write(rodent.mfd, "J", 1);
1652 	else if (rodent.rate <= 27)  write(rodent.mfd, "K", 1);
1653 	else if (rodent.rate <= 42)  write(rodent.mfd, "L", 1);
1654 	else if (rodent.rate <= 60)  write(rodent.mfd, "R", 1);
1655 	else if (rodent.rate <= 85)  write(rodent.mfd, "M", 1);
1656 	else if (rodent.rate <= 125) write(rodent.mfd, "Q", 1);
1657 	else			     write(rodent.mfd, "N", 1);
1658 	break;
1659 
1660     case MOUSE_PROTO_LOGIMOUSEMAN:
1661 	/* The command must always be sent at 1200 baud */
1662 	setmousespeed(1200, 1200, rodentcflags[rodent.rtype]);
1663 	write(rodent.mfd, "*X", 2);
1664 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1665 	break;
1666 
1667     case MOUSE_PROTO_HITTAB:
1668 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1669 
1670 	/*
1671 	 * Initialize Hitachi PUMA Plus - Model 1212E to desired settings.
1672 	 * The tablet must be configured to be in MM mode, NO parity,
1673 	 * Binary Format.  xf86Info.sampleRate controls the sensativity
1674 	 * of the tablet.  We only use this tablet for it's 4-button puck
1675 	 * so we don't run in "Absolute Mode"
1676 	 */
1677 	write(rodent.mfd, "z8", 2);	/* Set Parity = "NONE" */
1678 	usleep(50000);
1679 	write(rodent.mfd, "zb", 2);	/* Set Format = "Binary" */
1680 	usleep(50000);
1681 	write(rodent.mfd, "@", 1);	/* Set Report Mode = "Stream" */
1682 	usleep(50000);
1683 	write(rodent.mfd, "R", 1);	/* Set Output Rate = "45 rps" */
1684 	usleep(50000);
1685 	write(rodent.mfd, "I\x20", 2);	/* Set Incrememtal Mode "20" */
1686 	usleep(50000);
1687 	write(rodent.mfd, "E", 1);	/* Set Data Type = "Relative */
1688 	usleep(50000);
1689 
1690 	/* Resolution is in 'lines per inch' on the Hitachi tablet */
1691 	if      (rodent.resolution == MOUSE_RES_LOW)		c = 'g';
1692 	else if (rodent.resolution == MOUSE_RES_MEDIUMLOW)	c = 'e';
1693 	else if (rodent.resolution == MOUSE_RES_MEDIUMHIGH)	c = 'h';
1694 	else if (rodent.resolution == MOUSE_RES_HIGH)		c = 'd';
1695 	else if (rodent.resolution <=   40)			c = 'g';
1696 	else if (rodent.resolution <=  100)			c = 'd';
1697 	else if (rodent.resolution <=  200)			c = 'e';
1698 	else if (rodent.resolution <=  500)			c = 'h';
1699 	else if (rodent.resolution <= 1000)			c = 'j';
1700 	else			c = 'd';
1701 	write(rodent.mfd, &c, 1);
1702 	usleep(50000);
1703 
1704 	write(rodent.mfd, "\021", 1);	/* Resume DATA output */
1705 	break;
1706 
1707     case MOUSE_PROTO_THINK:
1708 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1709 	/* the PnP ID string may be sent again, discard it */
1710 	usleep(200000);
1711 	i = FREAD;
1712 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1713 	/* send the command to initialize the beast */
1714 	for (s = "E5E5"; *s; ++s) {
1715 	    write(rodent.mfd, s, 1);
1716 	    FD_ZERO(&fds);
1717 	    FD_SET(rodent.mfd, &fds);
1718 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1719 		break;
1720 	    read(rodent.mfd, &c, 1);
1721 	    debug("%c", c);
1722 	    if (c != *s)
1723 		break;
1724 	}
1725 	break;
1726 
1727     case MOUSE_PROTO_JOGDIAL:
1728 	break;
1729     case MOUSE_PROTO_MSC:
1730 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1731 	if (rodent.flags & ClearDTR) {
1732 	   i = TIOCM_DTR;
1733 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1734 	}
1735 	if (rodent.flags & ClearRTS) {
1736 	   i = TIOCM_RTS;
1737 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1738 	}
1739 	break;
1740 
1741     case MOUSE_PROTO_SYSMOUSE:
1742 	if (rodent.hw.iftype == MOUSE_IF_SYSMOUSE)
1743 	    setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1744 	/* FALLTHROUGH */
1745 
1746     case MOUSE_PROTO_PS2:
1747 	if (rodent.rate >= 0)
1748 	    rodent.mode.rate = rodent.rate;
1749 	if (rodent.resolution != MOUSE_RES_UNKNOWN)
1750 	    rodent.mode.resolution = rodent.resolution;
1751 	ioctl(rodent.mfd, MOUSE_SETMODE, &rodent.mode);
1752 	break;
1753 
1754     case MOUSE_PROTO_X10MOUSEREM:
1755 	mremote_serversetup();
1756 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1757 	break;
1758 
1759 
1760     case MOUSE_PROTO_VERSAPAD:
1761 	tcsendbreak(rodent.mfd, 0);	/* send break for 400 msec */
1762 	i = FREAD;
1763 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1764 	for (i = 0; i < 7; ++i) {
1765 	    FD_ZERO(&fds);
1766 	    FD_SET(rodent.mfd, &fds);
1767 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1768 		break;
1769 	    read(rodent.mfd, &c, 1);
1770 	    buf[i] = c;
1771 	}
1772 	debug("%s\n", buf);
1773 	if ((buf[0] != 'V') || (buf[1] != 'P')|| (buf[7] != '\r'))
1774 	    break;
1775 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1776 	tcsendbreak(rodent.mfd, 0);	/* send break for 400 msec again */
1777 	for (i = 0; i < 7; ++i) {
1778 	    FD_ZERO(&fds);
1779 	    FD_SET(rodent.mfd, &fds);
1780 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1781 		break;
1782 	    read(rodent.mfd, &c, 1);
1783 	    debug("%c", c);
1784 	    if (c != buf[i])
1785 		break;
1786 	}
1787 	i = FREAD;
1788 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1789 	break;
1790 
1791     default:
1792 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1793 	break;
1794     }
1795 }
1796 
1797 static int
1798 r_protocol(u_char rBuf, mousestatus_t *act)
1799 {
1800     /* MOUSE_MSS_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1801     static int butmapmss[4] = {	/* Microsoft, MouseMan, GlidePoint,
1802 				   IntelliMouse, Thinking Mouse */
1803 	0,
1804 	MOUSE_BUTTON3DOWN,
1805 	MOUSE_BUTTON1DOWN,
1806 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1807     };
1808     static int butmapmss2[4] = { /* Microsoft, MouseMan, GlidePoint,
1809 				    Thinking Mouse */
1810 	0,
1811 	MOUSE_BUTTON4DOWN,
1812 	MOUSE_BUTTON2DOWN,
1813 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1814     };
1815     /* MOUSE_INTELLI_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1816     static int butmapintelli[4] = { /* IntelliMouse, NetMouse, Mie Mouse,
1817 				       MouseMan+ */
1818 	0,
1819 	MOUSE_BUTTON2DOWN,
1820 	MOUSE_BUTTON4DOWN,
1821 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1822     };
1823     /* MOUSE_MSC_BUTTON?UP -> MOUSE_BUTTON?DOWN */
1824     static int butmapmsc[8] = {	/* MouseSystems, MMSeries, Logitech,
1825 				   Bus, sysmouse */
1826 	0,
1827 	MOUSE_BUTTON3DOWN,
1828 	MOUSE_BUTTON2DOWN,
1829 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1830 	MOUSE_BUTTON1DOWN,
1831 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1832 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1833 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1834     };
1835     /* MOUSE_PS2_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1836     static int butmapps2[8] = {	/* PS/2 */
1837 	0,
1838 	MOUSE_BUTTON1DOWN,
1839 	MOUSE_BUTTON3DOWN,
1840 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1841 	MOUSE_BUTTON2DOWN,
1842 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1843 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1844 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1845     };
1846     /* for Hitachi tablet */
1847     static int butmaphit[8] = {	/* MM HitTablet */
1848 	0,
1849 	MOUSE_BUTTON3DOWN,
1850 	MOUSE_BUTTON2DOWN,
1851 	MOUSE_BUTTON1DOWN,
1852 	MOUSE_BUTTON4DOWN,
1853 	MOUSE_BUTTON5DOWN,
1854 	MOUSE_BUTTON6DOWN,
1855 	MOUSE_BUTTON7DOWN,
1856     };
1857     /* for serial VersaPad */
1858     static int butmapversa[8] = { /* VersaPad */
1859 	0,
1860 	0,
1861 	MOUSE_BUTTON3DOWN,
1862 	MOUSE_BUTTON3DOWN,
1863 	MOUSE_BUTTON1DOWN,
1864 	MOUSE_BUTTON1DOWN,
1865 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1866 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1867     };
1868     /* for PS/2 VersaPad */
1869     static int butmapversaps2[8] = { /* VersaPad */
1870 	0,
1871 	MOUSE_BUTTON3DOWN,
1872 	0,
1873 	MOUSE_BUTTON3DOWN,
1874 	MOUSE_BUTTON1DOWN,
1875 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1876 	MOUSE_BUTTON1DOWN,
1877 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1878     };
1879     static int           pBufP = 0;
1880     static unsigned char pBuf[8];
1881     static int		 prev_x, prev_y;
1882     static int		 on = FALSE;
1883     int			 x, y;
1884 
1885     debug("received char 0x%x",(int)rBuf);
1886     if (rodent.rtype == MOUSE_PROTO_KIDSPAD)
1887 	return (kidspad(rBuf, act));
1888     if (rodent.rtype == MOUSE_PROTO_GTCO_DIGIPAD)
1889 	return (gtco_digipad(rBuf, act));
1890 
1891     /*
1892      * Hack for resyncing: We check here for a package that is:
1893      *  a) illegal (detected by wrong data-package header)
1894      *  b) invalid (0x80 == -128 and that might be wrong for MouseSystems)
1895      *  c) bad header-package
1896      *
1897      * NOTE: b) is a voilation of the MouseSystems-Protocol, since values of
1898      *       -128 are allowed, but since they are very seldom we can easily
1899      *       use them as package-header with no button pressed.
1900      * NOTE/2: On a PS/2 mouse any byte is valid as a data byte. Furthermore,
1901      *         0x80 is not valid as a header byte. For a PS/2 mouse we skip
1902      *         checking data bytes.
1903      *         For resyncing a PS/2 mouse we require the two most significant
1904      *         bits in the header byte to be 0. These are the overflow bits,
1905      *         and in case of an overflow we actually lose sync. Overflows
1906      *         are very rare, however, and we quickly gain sync again after
1907      *         an overflow condition. This is the best we can do. (Actually,
1908      *         we could use bit 0x08 in the header byte for resyncing, since
1909      *         that bit is supposed to be always on, but nobody told
1910      *         Microsoft...)
1911      */
1912 
1913     if (pBufP != 0 && rodent.rtype != MOUSE_PROTO_PS2 &&
1914 	((rBuf & cur_proto[2]) != cur_proto[3] || rBuf == 0x80))
1915     {
1916 	pBufP = 0;		/* skip package */
1917     }
1918 
1919     if (pBufP == 0 && (rBuf & cur_proto[0]) != cur_proto[1])
1920 	return (0);
1921 
1922     /* is there an extra data byte? */
1923     if (pBufP >= cur_proto[4] && (rBuf & cur_proto[0]) != cur_proto[1])
1924     {
1925 	/*
1926 	 * Hack for Logitech MouseMan Mouse - Middle button
1927 	 *
1928 	 * Unfortunately this mouse has variable length packets: the standard
1929 	 * Microsoft 3 byte packet plus an optional 4th byte whenever the
1930 	 * middle button status changes.
1931 	 *
1932 	 * We have already processed the standard packet with the movement
1933 	 * and button info.  Now post an event message with the old status
1934 	 * of the left and right buttons and the updated middle button.
1935 	 */
1936 
1937 	/*
1938 	 * Even worse, different MouseMen and TrackMen differ in the 4th
1939 	 * byte: some will send 0x00/0x20, others 0x01/0x21, or even
1940 	 * 0x02/0x22, so I have to strip off the lower bits.
1941 	 *
1942 	 * [JCH-96/01/21]
1943 	 * HACK for ALPS "fourth button". (It's bit 0x10 of the "fourth byte"
1944 	 * and it is activated by tapping the glidepad with the finger! 8^)
1945 	 * We map it to bit bit3, and the reverse map in xf86Events just has
1946 	 * to be extended so that it is identified as Button 4. The lower
1947 	 * half of the reverse-map may remain unchanged.
1948 	 */
1949 
1950 	/*
1951 	 * [KY-97/08/03]
1952 	 * Receive the fourth byte only when preceding three bytes have
1953 	 * been detected (pBufP >= cur_proto[4]).  In the previous
1954 	 * versions, the test was pBufP == 0; thus, we may have mistakingly
1955 	 * received a byte even if we didn't see anything preceding
1956 	 * the byte.
1957 	 */
1958 
1959 	if ((rBuf & cur_proto[5]) != cur_proto[6]) {
1960 	    pBufP = 0;
1961 	    return (0);
1962 	}
1963 
1964 	switch (rodent.rtype) {
1965 #if notyet
1966 	case MOUSE_PROTO_MARIQUA:
1967 	    /*
1968 	     * This mouse has 16! buttons in addition to the standard
1969 	     * three of them.  They return 0x10 though 0x1f in the
1970 	     * so-called `ten key' mode and 0x30 though 0x3f in the
1971 	     * `function key' mode.  As there are only 31 bits for
1972 	     * button state (including the standard three), we ignore
1973 	     * the bit 0x20 and don't distinguish the two modes.
1974 	     */
1975 	    act->dx = act->dy = act->dz = 0;
1976 	    act->obutton = act->button;
1977 	    rBuf &= 0x1f;
1978 	    act->button = (1 << (rBuf - 13))
1979 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1980 	    /*
1981 	     * FIXME: this is a button "down" event. There needs to be
1982 	     * a corresponding button "up" event... XXX
1983 	     */
1984 	    break;
1985 #endif /* notyet */
1986 	case MOUSE_PROTO_JOGDIAL:
1987 	    break;
1988 
1989 	/*
1990 	 * IntelliMouse, NetMouse (including NetMouse Pro) and Mie Mouse
1991 	 * always send the fourth byte, whereas the fourth byte is
1992 	 * optional for GlidePoint and ThinkingMouse. The fourth byte
1993 	 * is also optional for MouseMan+ and FirstMouse+ in their
1994 	 * native mode. It is always sent if they are in the IntelliMouse
1995 	 * compatible mode.
1996 	 */
1997 	case MOUSE_PROTO_INTELLI:	/* IntelliMouse, NetMouse, Mie Mouse,
1998 					   MouseMan+ */
1999 	    act->dx = act->dy = 0;
2000 	    act->dz = (rBuf & 0x08) ? (rBuf & 0x0f) - 16 : (rBuf & 0x0f);
2001 	    if ((act->dz >= 7) || (act->dz <= -7))
2002 		act->dz = 0;
2003 	    act->obutton = act->button;
2004 	    act->button = butmapintelli[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
2005 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
2006 	    break;
2007 
2008 	default:
2009 	    act->dx = act->dy = act->dz = 0;
2010 	    act->obutton = act->button;
2011 	    act->button = butmapmss2[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
2012 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
2013 	    break;
2014 	}
2015 
2016 	act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2017 	    | (act->obutton ^ act->button);
2018 	pBufP = 0;
2019 	return (act->flags);
2020     }
2021 
2022     if (pBufP >= cur_proto[4])
2023 	pBufP = 0;
2024     pBuf[pBufP++] = rBuf;
2025     if (pBufP != cur_proto[4])
2026 	return (0);
2027 
2028     /*
2029      * assembly full package
2030      */
2031 
2032     debug("assembled full packet (len %d) %x,%x,%x,%x,%x,%x,%x,%x",
2033 	cur_proto[4],
2034 	pBuf[0], pBuf[1], pBuf[2], pBuf[3],
2035 	pBuf[4], pBuf[5], pBuf[6], pBuf[7]);
2036 
2037     act->dz = 0;
2038     act->obutton = act->button;
2039     switch (rodent.rtype)
2040     {
2041     case MOUSE_PROTO_MS:		/* Microsoft */
2042     case MOUSE_PROTO_LOGIMOUSEMAN:	/* MouseMan/TrackMan */
2043     case MOUSE_PROTO_X10MOUSEREM:	/* X10 MouseRemote */
2044 	act->button = act->obutton & MOUSE_BUTTON4DOWN;
2045 	if (rodent.flags & ChordMiddle)
2046 	    act->button |= ((pBuf[0] & MOUSE_MSS_BUTTONS) == MOUSE_MSS_BUTTONS)
2047 		? MOUSE_BUTTON2DOWN
2048 		: butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
2049 	else
2050 	    act->button |= (act->obutton & MOUSE_BUTTON2DOWN)
2051 		| butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
2052 
2053 	/* Send X10 btn events to remote client (ensure -128-+127 range) */
2054 	if ((rodent.rtype == MOUSE_PROTO_X10MOUSEREM) &&
2055 	    ((pBuf[0] & 0xFC) == 0x44) && (pBuf[2] == 0x3F)) {
2056 	    if (rodent.mremcfd >= 0) {
2057 		unsigned char key = (signed char)(((pBuf[0] & 0x03) << 6) |
2058 						  (pBuf[1] & 0x3F));
2059 		write(rodent.mremcfd, &key, 1);
2060 	    }
2061 	    return (0);
2062 	}
2063 
2064 	act->dx = (signed char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
2065 	act->dy = (signed char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
2066 	break;
2067 
2068     case MOUSE_PROTO_GLIDEPOINT:	/* GlidePoint */
2069     case MOUSE_PROTO_THINK:		/* ThinkingMouse */
2070     case MOUSE_PROTO_INTELLI:		/* IntelliMouse, NetMouse, Mie Mouse,
2071 					   MouseMan+ */
2072 	act->button = (act->obutton & (MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN))
2073 	    | butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
2074 	act->dx = (signed char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
2075 	act->dy = (signed char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
2076 	break;
2077 
2078     case MOUSE_PROTO_MSC:		/* MouseSystems Corp */
2079 #if notyet
2080     case MOUSE_PROTO_MARIQUA:		/* Mariqua */
2081 #endif
2082 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
2083 	act->dx =    (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
2084 	act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
2085 	break;
2086 
2087     case MOUSE_PROTO_JOGDIAL:		/* JogDial */
2088 	    if (rBuf == 0x6c)
2089 	      act->dz = -1;
2090 	    if (rBuf == 0x72)
2091 	      act->dz = 1;
2092 	    if (rBuf == 0x64)
2093 	      act->button = MOUSE_BUTTON1DOWN;
2094 	    if (rBuf == 0x75)
2095 	      act->button = 0;
2096 	break;
2097 
2098     case MOUSE_PROTO_HITTAB:		/* MM HitTablet */
2099 	act->button = butmaphit[pBuf[0] & 0x07];
2100 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
2101 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
2102 	break;
2103 
2104     case MOUSE_PROTO_MM:		/* MM Series */
2105     case MOUSE_PROTO_LOGI:		/* Logitech Mice */
2106 	act->button = butmapmsc[pBuf[0] & MOUSE_MSC_BUTTONS];
2107 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
2108 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
2109 	break;
2110 
2111     case MOUSE_PROTO_VERSAPAD:		/* VersaPad */
2112 	act->button = butmapversa[(pBuf[0] & MOUSE_VERSA_BUTTONS) >> 3];
2113 	act->button |= (pBuf[0] & MOUSE_VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2114 	act->dx = act->dy = 0;
2115 	if (!(pBuf[0] & MOUSE_VERSA_IN_USE)) {
2116 	    on = FALSE;
2117 	    break;
2118 	}
2119 	x = (pBuf[2] << 6) | pBuf[1];
2120 	if (x & 0x800)
2121 	    x -= 0x1000;
2122 	y = (pBuf[4] << 6) | pBuf[3];
2123 	if (y & 0x800)
2124 	    y -= 0x1000;
2125 	if (on) {
2126 	    act->dx = prev_x - x;
2127 	    act->dy = prev_y - y;
2128 	} else {
2129 	    on = TRUE;
2130 	}
2131 	prev_x = x;
2132 	prev_y = y;
2133 	break;
2134 
2135     case MOUSE_PROTO_PS2:		/* PS/2 */
2136 	act->button = butmapps2[pBuf[0] & MOUSE_PS2_BUTTONS];
2137 	act->dx = (pBuf[0] & MOUSE_PS2_XNEG) ?    pBuf[1] - 256  :  pBuf[1];
2138 	act->dy = (pBuf[0] & MOUSE_PS2_YNEG) ?  -(pBuf[2] - 256) : -pBuf[2];
2139 	/*
2140 	 * Moused usually operates the psm driver at the operation level 1
2141 	 * which sends mouse data in MOUSE_PROTO_SYSMOUSE protocol.
2142 	 * The following code takes effect only when the user explicitly
2143 	 * requets the level 2 at which wheel movement and additional button
2144 	 * actions are encoded in model-dependent formats. At the level 0
2145 	 * the following code is no-op because the psm driver says the model
2146 	 * is MOUSE_MODEL_GENERIC.
2147 	 */
2148 	switch (rodent.hw.model) {
2149 	case MOUSE_MODEL_EXPLORER:
2150 	    /* wheel and additional button data is in the fourth byte */
2151 	    act->dz = (pBuf[3] & MOUSE_EXPLORER_ZNEG)
2152 		? (pBuf[3] & 0x0f) - 16 : (pBuf[3] & 0x0f);
2153 	    act->button |= (pBuf[3] & MOUSE_EXPLORER_BUTTON4DOWN)
2154 		? MOUSE_BUTTON4DOWN : 0;
2155 	    act->button |= (pBuf[3] & MOUSE_EXPLORER_BUTTON5DOWN)
2156 		? MOUSE_BUTTON5DOWN : 0;
2157 	    break;
2158 	case MOUSE_MODEL_INTELLI:
2159 	case MOUSE_MODEL_NET:
2160 	    /* wheel data is in the fourth byte */
2161 	    act->dz = (signed char)pBuf[3];
2162 	    if ((act->dz >= 7) || (act->dz <= -7))
2163 		act->dz = 0;
2164 	    /* some compatible mice may have additional buttons */
2165 	    act->button |= (pBuf[0] & MOUSE_PS2INTELLI_BUTTON4DOWN)
2166 		? MOUSE_BUTTON4DOWN : 0;
2167 	    act->button |= (pBuf[0] & MOUSE_PS2INTELLI_BUTTON5DOWN)
2168 		? MOUSE_BUTTON5DOWN : 0;
2169 	    break;
2170 	case MOUSE_MODEL_MOUSEMANPLUS:
2171 	    if (((pBuf[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
2172 		    && (abs(act->dx) > 191)
2173 		    && MOUSE_PS2PLUS_CHECKBITS(pBuf)) {
2174 		/* the extended data packet encodes button and wheel events */
2175 		switch (MOUSE_PS2PLUS_PACKET_TYPE(pBuf)) {
2176 		case 1:
2177 		    /* wheel data packet */
2178 		    act->dx = act->dy = 0;
2179 		    if (pBuf[2] & 0x80) {
2180 			/* horizontal roller count - ignore it XXX*/
2181 		    } else {
2182 			/* vertical roller count */
2183 			act->dz = (pBuf[2] & MOUSE_PS2PLUS_ZNEG)
2184 			    ? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
2185 		    }
2186 		    act->button |= (pBuf[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2187 			? MOUSE_BUTTON4DOWN : 0;
2188 		    act->button |= (pBuf[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2189 			? MOUSE_BUTTON5DOWN : 0;
2190 		    break;
2191 		case 2:
2192 		    /* this packet type is reserved by Logitech */
2193 		    /*
2194 		     * IBM ScrollPoint Mouse uses this packet type to
2195 		     * encode both vertical and horizontal scroll movement.
2196 		     */
2197 		    act->dx = act->dy = 0;
2198 		    /* horizontal roller count */
2199 		    if (pBuf[2] & 0x0f)
2200 			act->dz = (pBuf[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2201 		    /* vertical roller count */
2202 		    if (pBuf[2] & 0xf0)
2203 			act->dz = (pBuf[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2204 #if 0
2205 		    /* vertical roller count */
2206 		    act->dz = (pBuf[2] & MOUSE_SPOINT_ZNEG)
2207 			? ((pBuf[2] >> 4) & 0x0f) - 16
2208 			: ((pBuf[2] >> 4) & 0x0f);
2209 		    /* horizontal roller count */
2210 		    act->dw = (pBuf[2] & MOUSE_SPOINT_WNEG)
2211 			? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
2212 #endif
2213 		    break;
2214 		case 0:
2215 		    /* device type packet - shouldn't happen */
2216 		    /* FALLTHROUGH */
2217 		default:
2218 		    act->dx = act->dy = 0;
2219 		    act->button = act->obutton;
2220 		    debug("unknown PS2++ packet type %d: 0x%02x 0x%02x 0x%02x\n",
2221 			  MOUSE_PS2PLUS_PACKET_TYPE(pBuf),
2222 			  pBuf[0], pBuf[1], pBuf[2]);
2223 		    break;
2224 		}
2225 	    } else {
2226 		/* preserve button states */
2227 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
2228 	    }
2229 	    break;
2230 	case MOUSE_MODEL_GLIDEPOINT:
2231 	    /* `tapping' action */
2232 	    act->button |= ((pBuf[0] & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2233 	    break;
2234 	case MOUSE_MODEL_NETSCROLL:
2235 	    /* three additional bytes encode buttons and wheel events */
2236 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON3DOWN)
2237 		? MOUSE_BUTTON4DOWN : 0;
2238 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON1DOWN)
2239 		? MOUSE_BUTTON5DOWN : 0;
2240 	    act->dz = (pBuf[3] & MOUSE_PS2_XNEG) ? pBuf[4] - 256 : pBuf[4];
2241 	    break;
2242 	case MOUSE_MODEL_THINK:
2243 	    /* the fourth button state in the first byte */
2244 	    act->button |= (pBuf[0] & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2245 	    break;
2246 	case MOUSE_MODEL_VERSAPAD:
2247 	    act->button = butmapversaps2[pBuf[0] & MOUSE_PS2VERSA_BUTTONS];
2248 	    act->button |=
2249 		(pBuf[0] & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2250 	    act->dx = act->dy = 0;
2251 	    if (!(pBuf[0] & MOUSE_PS2VERSA_IN_USE)) {
2252 		on = FALSE;
2253 		break;
2254 	    }
2255 	    x = ((pBuf[4] << 8) & 0xf00) | pBuf[1];
2256 	    if (x & 0x800)
2257 		x -= 0x1000;
2258 	    y = ((pBuf[4] << 4) & 0xf00) | pBuf[2];
2259 	    if (y & 0x800)
2260 		y -= 0x1000;
2261 	    if (on) {
2262 		act->dx = prev_x - x;
2263 		act->dy = prev_y - y;
2264 	    } else {
2265 		on = TRUE;
2266 	    }
2267 	    prev_x = x;
2268 	    prev_y = y;
2269 	    break;
2270 	case MOUSE_MODEL_4D:
2271 	    act->dx = (pBuf[1] & 0x80) ?    pBuf[1] - 256  :  pBuf[1];
2272 	    act->dy = (pBuf[2] & 0x80) ?  -(pBuf[2] - 256) : -pBuf[2];
2273 	    switch (pBuf[0] & MOUSE_4D_WHEELBITS) {
2274 	    case 0x10:
2275 		act->dz = 1;
2276 		break;
2277 	    case 0x30:
2278 		act->dz = -1;
2279 		break;
2280 	    case 0x40:	/* 2nd wheel rolling right XXX */
2281 		act->dz = 2;
2282 		break;
2283 	    case 0xc0:	/* 2nd wheel rolling left XXX */
2284 		act->dz = -2;
2285 		break;
2286 	    }
2287 	    break;
2288 	case MOUSE_MODEL_4DPLUS:
2289 	    if ((act->dx < 16 - 256) && (act->dy > 256 - 16)) {
2290 		act->dx = act->dy = 0;
2291 		if (pBuf[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2292 		    act->button |= MOUSE_BUTTON4DOWN;
2293 		act->dz = (pBuf[2] & MOUSE_4DPLUS_ZNEG)
2294 			      ? ((pBuf[2] & 0x07) - 8) : (pBuf[2] & 0x07);
2295 	    } else {
2296 		/* preserve previous button states */
2297 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
2298 	    }
2299 	    break;
2300 	case MOUSE_MODEL_GENERIC:
2301 	default:
2302 	    break;
2303 	}
2304 	break;
2305 
2306     case MOUSE_PROTO_SYSMOUSE:		/* sysmouse */
2307 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_SYS_STDBUTTONS];
2308 	act->dx =    (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
2309 	act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
2310 	if (rodent.level == 1) {
2311 	    act->dz = ((signed char)(pBuf[5] << 1) + (signed char)(pBuf[6] << 1)) >> 1;
2312 	    act->button |= ((~pBuf[7] & MOUSE_SYS_EXTBUTTONS) << 3);
2313 	}
2314 	break;
2315 
2316     default:
2317 	return (0);
2318     }
2319     /*
2320      * We don't reset pBufP here yet, as there may be an additional data
2321      * byte in some protocols. See above.
2322      */
2323 
2324     /* has something changed? */
2325     act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2326 	| (act->obutton ^ act->button);
2327 
2328     return (act->flags);
2329 }
2330 
2331 static int
2332 r_statetrans(mousestatus_t *a1, mousestatus_t *a2, int trans)
2333 {
2334     int changed;
2335     int flags;
2336 
2337     a2->dx = a1->dx;
2338     a2->dy = a1->dy;
2339     a2->dz = a1->dz;
2340     a2->obutton = a2->button;
2341     a2->button = a1->button;
2342     a2->flags = a1->flags;
2343     changed = FALSE;
2344 
2345     if (rodent.flags & Emulate3Button) {
2346 	if (debug > 2)
2347 	    debug("state:%d, trans:%d -> state:%d",
2348 		  mouse_button_state, trans,
2349 		  states[mouse_button_state].s[trans]);
2350 	/*
2351 	 * Avoid re-ordering button and movement events. While a button
2352 	 * event is deferred, throw away up to BUTTON2_MAXMOVE movement
2353 	 * events to allow for mouse jitter. If more movement events
2354 	 * occur, then complete the deferred button events immediately.
2355 	 */
2356 	if ((a2->dx != 0 || a2->dy != 0) &&
2357 	    S_DELAYED(states[mouse_button_state].s[trans])) {
2358 		if (++mouse_move_delayed > BUTTON2_MAXMOVE) {
2359 			mouse_move_delayed = 0;
2360 			mouse_button_state =
2361 			    states[mouse_button_state].s[A_TIMEOUT];
2362 			changed = TRUE;
2363 		} else
2364 			a2->dx = a2->dy = 0;
2365 	} else
2366 		mouse_move_delayed = 0;
2367 	if (mouse_button_state != states[mouse_button_state].s[trans])
2368 		changed = TRUE;
2369 	if (changed)
2370 		clock_gettime(CLOCK_MONOTONIC_FAST, &mouse_button_state_ts);
2371 	mouse_button_state = states[mouse_button_state].s[trans];
2372 	a2->button &=
2373 	    ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN);
2374 	a2->button &= states[mouse_button_state].mask;
2375 	a2->button |= states[mouse_button_state].buttons;
2376 	flags = a2->flags & MOUSE_POSCHANGED;
2377 	flags |= a2->obutton ^ a2->button;
2378 	if (flags & MOUSE_BUTTON2DOWN) {
2379 	    a2->flags = flags & MOUSE_BUTTON2DOWN;
2380 	    r_timestamp(a2);
2381 	}
2382 	a2->flags = flags;
2383     }
2384     return (changed);
2385 }
2386 
2387 /* phisical to logical button mapping */
2388 static int p2l[MOUSE_MAXBUTTON] = {
2389     MOUSE_BUTTON1DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON4DOWN,
2390     MOUSE_BUTTON5DOWN, MOUSE_BUTTON6DOWN, MOUSE_BUTTON7DOWN, MOUSE_BUTTON8DOWN,
2391     0x00000100,        0x00000200,        0x00000400,        0x00000800,
2392     0x00001000,        0x00002000,        0x00004000,        0x00008000,
2393     0x00010000,        0x00020000,        0x00040000,        0x00080000,
2394     0x00100000,        0x00200000,        0x00400000,        0x00800000,
2395     0x01000000,        0x02000000,        0x04000000,        0x08000000,
2396     0x10000000,        0x20000000,        0x40000000,
2397 };
2398 
2399 static char *
2400 skipspace(char *s)
2401 {
2402     while(isspace(*s))
2403 	++s;
2404     return (s);
2405 }
2406 
2407 static int
2408 r_installmap(char *arg)
2409 {
2410     int pbutton;
2411     int lbutton;
2412     char *s;
2413 
2414     while (*arg) {
2415 	arg = skipspace(arg);
2416 	s = arg;
2417 	while (isdigit(*arg))
2418 	    ++arg;
2419 	arg = skipspace(arg);
2420 	if ((arg <= s) || (*arg != '='))
2421 	    return (FALSE);
2422 	lbutton = atoi(s);
2423 
2424 	arg = skipspace(++arg);
2425 	s = arg;
2426 	while (isdigit(*arg))
2427 	    ++arg;
2428 	if ((arg <= s) || (!isspace(*arg) && (*arg != '\0')))
2429 	    return (FALSE);
2430 	pbutton = atoi(s);
2431 
2432 	if ((lbutton <= 0) || (lbutton > MOUSE_MAXBUTTON))
2433 	    return (FALSE);
2434 	if ((pbutton <= 0) || (pbutton > MOUSE_MAXBUTTON))
2435 	    return (FALSE);
2436 	p2l[pbutton - 1] = 1 << (lbutton - 1);
2437 	mstate[lbutton - 1] = &bstate[pbutton - 1];
2438     }
2439 
2440     return (TRUE);
2441 }
2442 
2443 static void
2444 r_map(mousestatus_t *act1, mousestatus_t *act2)
2445 {
2446     register int pb;
2447     register int pbuttons;
2448     int lbuttons;
2449 
2450     pbuttons = act1->button;
2451     lbuttons = 0;
2452 
2453     act2->obutton = act2->button;
2454     if (pbuttons & rodent.wmode) {
2455 	pbuttons &= ~rodent.wmode;
2456 	act1->dz = act1->dy;
2457 	act1->dx = 0;
2458 	act1->dy = 0;
2459     }
2460     act2->dx = act1->dx;
2461     act2->dy = act1->dy;
2462     act2->dz = act1->dz;
2463 
2464     switch (rodent.zmap[0]) {
2465     case 0:	/* do nothing */
2466 	break;
2467     case MOUSE_XAXIS:
2468 	if (act1->dz != 0) {
2469 	    act2->dx = act1->dz;
2470 	    act2->dz = 0;
2471 	}
2472 	break;
2473     case MOUSE_YAXIS:
2474 	if (act1->dz != 0) {
2475 	    act2->dy = act1->dz;
2476 	    act2->dz = 0;
2477 	}
2478 	break;
2479     default:	/* buttons */
2480 	pbuttons &= ~(rodent.zmap[0] | rodent.zmap[1]
2481 		    | rodent.zmap[2] | rodent.zmap[3]);
2482 	if ((act1->dz < -1) && rodent.zmap[2]) {
2483 	    pbuttons |= rodent.zmap[2];
2484 	    zstate[2].count = 1;
2485 	} else if (act1->dz < 0) {
2486 	    pbuttons |= rodent.zmap[0];
2487 	    zstate[0].count = 1;
2488 	} else if ((act1->dz > 1) && rodent.zmap[3]) {
2489 	    pbuttons |= rodent.zmap[3];
2490 	    zstate[3].count = 1;
2491 	} else if (act1->dz > 0) {
2492 	    pbuttons |= rodent.zmap[1];
2493 	    zstate[1].count = 1;
2494 	}
2495 	act2->dz = 0;
2496 	break;
2497     }
2498 
2499     for (pb = 0; (pb < MOUSE_MAXBUTTON) && (pbuttons != 0); ++pb) {
2500 	lbuttons |= (pbuttons & 1) ? p2l[pb] : 0;
2501 	pbuttons >>= 1;
2502     }
2503     act2->button = lbuttons;
2504 
2505     act2->flags = ((act2->dx || act2->dy || act2->dz) ? MOUSE_POSCHANGED : 0)
2506 	| (act2->obutton ^ act2->button);
2507 }
2508 
2509 static void
2510 r_timestamp(mousestatus_t *act)
2511 {
2512     struct timespec ts;
2513     struct timespec ts1;
2514     struct timespec ts2;
2515     struct timespec ts3;
2516     int button;
2517     int mask;
2518     int i;
2519 
2520     mask = act->flags & MOUSE_BUTTONS;
2521 #if 0
2522     if (mask == 0)
2523 	return;
2524 #endif
2525 
2526     clock_gettime(CLOCK_MONOTONIC_FAST, &ts1);
2527     drift_current_ts = ts1;
2528 
2529     /* double click threshold */
2530     ts2.tv_sec = rodent.clickthreshold / 1000;
2531     ts2.tv_nsec = (rodent.clickthreshold % 1000) * 1000000;
2532     tssub(&ts1, &ts2, &ts);
2533     debug("ts:  %jd %ld", (intmax_t)ts.tv_sec, ts.tv_nsec);
2534 
2535     /* 3 button emulation timeout */
2536     ts2.tv_sec = rodent.button2timeout / 1000;
2537     ts2.tv_nsec = (rodent.button2timeout % 1000) * 1000000;
2538     tssub(&ts1, &ts2, &ts3);
2539 
2540     button = MOUSE_BUTTON1DOWN;
2541     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2542 	if (mask & 1) {
2543 	    if (act->button & button) {
2544 		/* the button is down */
2545 		debug("  :  %jd %ld",
2546 		    (intmax_t)bstate[i].ts.tv_sec, bstate[i].ts.tv_nsec);
2547 		if (tscmp(&ts, &bstate[i].ts, >)) {
2548 		    bstate[i].count = 1;
2549 		} else {
2550 		    ++bstate[i].count;
2551 		}
2552 		bstate[i].ts = ts1;
2553 	    } else {
2554 		/* the button is up */
2555 		bstate[i].ts = ts1;
2556 	    }
2557 	} else {
2558 	    if (act->button & button) {
2559 		/* the button has been down */
2560 		if (tscmp(&ts3, &bstate[i].ts, >)) {
2561 		    bstate[i].count = 1;
2562 		    bstate[i].ts = ts1;
2563 		    act->flags |= button;
2564 		    debug("button %d timeout", i + 1);
2565 		}
2566 	    } else {
2567 		/* the button has been up */
2568 	    }
2569 	}
2570 	button <<= 1;
2571 	mask >>= 1;
2572     }
2573 }
2574 
2575 static int
2576 r_timeout(void)
2577 {
2578     struct timespec ts;
2579     struct timespec ts1;
2580     struct timespec ts2;
2581 
2582     if (states[mouse_button_state].timeout)
2583 	return (TRUE);
2584     clock_gettime(CLOCK_MONOTONIC_FAST, &ts1);
2585     ts2.tv_sec = rodent.button2timeout / 1000;
2586     ts2.tv_nsec = (rodent.button2timeout % 1000) * 1000000;
2587     tssub(&ts1, &ts2, &ts);
2588     return (tscmp(&ts, &mouse_button_state_ts, >));
2589 }
2590 
2591 static void
2592 r_click(mousestatus_t *act)
2593 {
2594     struct mouse_info mouse;
2595     int button;
2596     int mask;
2597     int i;
2598 
2599     mask = act->flags & MOUSE_BUTTONS;
2600     if (mask == 0)
2601 	return;
2602 
2603     button = MOUSE_BUTTON1DOWN;
2604     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2605 	if (mask & 1) {
2606 	    debug("mstate[%d]->count:%d", i, mstate[i]->count);
2607 	    if (act->button & button) {
2608 		/* the button is down */
2609 		mouse.u.event.value = mstate[i]->count;
2610 	    } else {
2611 		/* the button is up */
2612 		mouse.u.event.value = 0;
2613 	    }
2614 	    mouse.operation = MOUSE_BUTTON_EVENT;
2615 	    mouse.u.event.id = button;
2616 	    if (debug < 2)
2617 		if (!paused)
2618 		    ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
2619 	    debug("button %d  count %d", i + 1, mouse.u.event.value);
2620 	}
2621 	button <<= 1;
2622 	mask >>= 1;
2623     }
2624 }
2625 
2626 /* $XConsortium: posix_tty.c,v 1.3 95/01/05 20:42:55 kaleb Exp $ */
2627 /* $XFree86: xc/programs/Xserver/hw/xfree86/os-support/shared/posix_tty.c,v 3.4 1995/01/28 17:05:03 dawes Exp $ */
2628 /*
2629  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
2630  *
2631  * Permission to use, copy, modify, distribute, and sell this software and its
2632  * documentation for any purpose is hereby granted without fee, provided that
2633  * the above copyright notice appear in all copies and that both that
2634  * copyright notice and this permission notice appear in supporting
2635  * documentation, and that the name of David Dawes
2636  * not be used in advertising or publicity pertaining to distribution of
2637  * the software without specific, written prior permission.
2638  * David Dawes makes no representations about the suitability of this
2639  * software for any purpose.  It is provided "as is" without express or
2640  * implied warranty.
2641  *
2642  * DAVID DAWES DISCLAIMS ALL WARRANTIES WITH REGARD TO
2643  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
2644  * FITNESS, IN NO EVENT SHALL DAVID DAWES BE LIABLE FOR
2645  * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
2646  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
2647  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
2648  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2649  *
2650  */
2651 
2652 
2653 static void
2654 setmousespeed(int old, int new, unsigned cflag)
2655 {
2656 	struct termios tty;
2657 	const char *c;
2658 
2659 	if (tcgetattr(rodent.mfd, &tty) < 0)
2660 	{
2661 		logwarn("unable to get status of mouse fd");
2662 		return;
2663 	}
2664 
2665 	tty.c_iflag = IGNBRK | IGNPAR;
2666 	tty.c_oflag = 0;
2667 	tty.c_lflag = 0;
2668 	tty.c_cflag = (tcflag_t)cflag;
2669 	tty.c_cc[VTIME] = 0;
2670 	tty.c_cc[VMIN] = 1;
2671 
2672 	switch (old)
2673 	{
2674 	case 9600:
2675 		cfsetispeed(&tty, B9600);
2676 		cfsetospeed(&tty, B9600);
2677 		break;
2678 	case 4800:
2679 		cfsetispeed(&tty, B4800);
2680 		cfsetospeed(&tty, B4800);
2681 		break;
2682 	case 2400:
2683 		cfsetispeed(&tty, B2400);
2684 		cfsetospeed(&tty, B2400);
2685 		break;
2686 	case 1200:
2687 	default:
2688 		cfsetispeed(&tty, B1200);
2689 		cfsetospeed(&tty, B1200);
2690 	}
2691 
2692 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2693 	{
2694 		logwarn("unable to set status of mouse fd");
2695 		return;
2696 	}
2697 
2698 	switch (new)
2699 	{
2700 	case 9600:
2701 		c = "*q";
2702 		cfsetispeed(&tty, B9600);
2703 		cfsetospeed(&tty, B9600);
2704 		break;
2705 	case 4800:
2706 		c = "*p";
2707 		cfsetispeed(&tty, B4800);
2708 		cfsetospeed(&tty, B4800);
2709 		break;
2710 	case 2400:
2711 		c = "*o";
2712 		cfsetispeed(&tty, B2400);
2713 		cfsetospeed(&tty, B2400);
2714 		break;
2715 	case 1200:
2716 	default:
2717 		c = "*n";
2718 		cfsetispeed(&tty, B1200);
2719 		cfsetospeed(&tty, B1200);
2720 	}
2721 
2722 	if (rodent.rtype == MOUSE_PROTO_LOGIMOUSEMAN
2723 	    || rodent.rtype == MOUSE_PROTO_LOGI)
2724 	{
2725 		if (write(rodent.mfd, c, 2) != 2)
2726 		{
2727 			logwarn("unable to write to mouse fd");
2728 			return;
2729 		}
2730 	}
2731 	usleep(100000);
2732 
2733 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2734 		logwarn("unable to set status of mouse fd");
2735 }
2736 
2737 /*
2738  * PnP COM device support
2739  *
2740  * It's a simplistic implementation, but it works :-)
2741  * KY, 31/7/97.
2742  */
2743 
2744 /*
2745  * Try to elicit a PnP ID as described in
2746  * Microsoft, Hayes: "Plug and Play External COM Device Specification,
2747  * rev 1.00", 1995.
2748  *
2749  * The routine does not fully implement the COM Enumerator as par Section
2750  * 2.1 of the document.  In particular, we don't have idle state in which
2751  * the driver software monitors the com port for dynamic connection or
2752  * removal of a device at the port, because `moused' simply quits if no
2753  * device is found.
2754  *
2755  * In addition, as PnP COM device enumeration procedure slightly has
2756  * changed since its first publication, devices which follow earlier
2757  * revisions of the above spec. may fail to respond if the rev 1.0
2758  * procedure is used. XXX
2759  */
2760 static int
2761 pnpwakeup1(void)
2762 {
2763     struct timeval timeout;
2764     fd_set fds;
2765     int i;
2766 
2767     /*
2768      * This is the procedure described in rev 1.0 of PnP COM device spec.
2769      * Unfortunately, some devices which comform to earlier revisions of
2770      * the spec gets confused and do not return the ID string...
2771      */
2772     debug("PnP COM device rev 1.0 probe...");
2773 
2774     /* port initialization (2.1.2) */
2775     ioctl(rodent.mfd, TIOCMGET, &i);
2776     i |= TIOCM_DTR;		/* DTR = 1 */
2777     i &= ~TIOCM_RTS;		/* RTS = 0 */
2778     ioctl(rodent.mfd, TIOCMSET, &i);
2779     usleep(240000);
2780 
2781     /*
2782      * The PnP COM device spec. dictates that the mouse must set DSR
2783      * in response to DTR (by hardware or by software) and that if DSR is
2784      * not asserted, the host computer should think that there is no device
2785      * at this serial port.  But some mice just don't do that...
2786      */
2787     ioctl(rodent.mfd, TIOCMGET, &i);
2788     debug("modem status 0%o", i);
2789     if ((i & TIOCM_DSR) == 0)
2790 	return (FALSE);
2791 
2792     /* port setup, 1st phase (2.1.3) */
2793     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2794     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2795     ioctl(rodent.mfd, TIOCMBIC, &i);
2796     usleep(240000);
2797     i = TIOCM_DTR;		/* DTR = 1, RTS = 0 */
2798     ioctl(rodent.mfd, TIOCMBIS, &i);
2799     usleep(240000);
2800 
2801     /* wait for response, 1st phase (2.1.4) */
2802     i = FREAD;
2803     ioctl(rodent.mfd, TIOCFLUSH, &i);
2804     i = TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2805     ioctl(rodent.mfd, TIOCMBIS, &i);
2806 
2807     /* try to read something */
2808     FD_ZERO(&fds);
2809     FD_SET(rodent.mfd, &fds);
2810     timeout.tv_sec = 0;
2811     timeout.tv_usec = 240000;
2812     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2813 	debug("pnpwakeup1(): valid response in first phase.");
2814 	return (TRUE);
2815     }
2816 
2817     /* port setup, 2nd phase (2.1.5) */
2818     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2819     ioctl(rodent.mfd, TIOCMBIC, &i);
2820     usleep(240000);
2821 
2822     /* wait for respose, 2nd phase (2.1.6) */
2823     i = FREAD;
2824     ioctl(rodent.mfd, TIOCFLUSH, &i);
2825     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2826     ioctl(rodent.mfd, TIOCMBIS, &i);
2827 
2828     /* try to read something */
2829     FD_ZERO(&fds);
2830     FD_SET(rodent.mfd, &fds);
2831     timeout.tv_sec = 0;
2832     timeout.tv_usec = 240000;
2833     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2834 	debug("pnpwakeup1(): valid response in second phase.");
2835 	return (TRUE);
2836     }
2837 
2838     return (FALSE);
2839 }
2840 
2841 static int
2842 pnpwakeup2(void)
2843 {
2844     struct timeval timeout;
2845     fd_set fds;
2846     int i;
2847 
2848     /*
2849      * This is a simplified procedure; it simply toggles RTS.
2850      */
2851     debug("alternate probe...");
2852 
2853     ioctl(rodent.mfd, TIOCMGET, &i);
2854     i |= TIOCM_DTR;		/* DTR = 1 */
2855     i &= ~TIOCM_RTS;		/* RTS = 0 */
2856     ioctl(rodent.mfd, TIOCMSET, &i);
2857     usleep(240000);
2858 
2859     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2860 
2861     /* wait for respose */
2862     i = FREAD;
2863     ioctl(rodent.mfd, TIOCFLUSH, &i);
2864     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2865     ioctl(rodent.mfd, TIOCMBIS, &i);
2866 
2867     /* try to read something */
2868     FD_ZERO(&fds);
2869     FD_SET(rodent.mfd, &fds);
2870     timeout.tv_sec = 0;
2871     timeout.tv_usec = 240000;
2872     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2873 	debug("pnpwakeup2(): valid response.");
2874 	return (TRUE);
2875     }
2876 
2877     return (FALSE);
2878 }
2879 
2880 static int
2881 pnpgets(char *buf)
2882 {
2883     struct timeval timeout;
2884     fd_set fds;
2885     int begin;
2886     int i;
2887     char c;
2888 
2889     if (!pnpwakeup1() && !pnpwakeup2()) {
2890 	/*
2891 	 * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2892 	 * in idle state.  But, `moused' shall set DTR = RTS = 1 and proceed,
2893 	 * assuming there is something at the port even if it didn't
2894 	 * respond to the PnP enumeration procedure.
2895 	 */
2896 	i = TIOCM_DTR | TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2897 	ioctl(rodent.mfd, TIOCMBIS, &i);
2898 	return (0);
2899     }
2900 
2901     /* collect PnP COM device ID (2.1.7) */
2902     begin = -1;
2903     i = 0;
2904     usleep(240000);	/* the mouse must send `Begin ID' within 200msec */
2905     while (read(rodent.mfd, &c, 1) == 1) {
2906 	/* we may see "M", or "M3..." before `Begin ID' */
2907 	buf[i++] = c;
2908 	if ((c == 0x08) || (c == 0x28)) {	/* Begin ID */
2909 	    debug("begin-id %02x", c);
2910 	    begin = i - 1;
2911 	    break;
2912 	}
2913 	debug("%c %02x", c, c);
2914 	if (i >= 256)
2915 	    break;
2916     }
2917     if (begin < 0) {
2918 	/* we haven't seen `Begin ID' in time... */
2919 	goto connect_idle;
2920     }
2921 
2922     ++c;			/* make it `End ID' */
2923     for (;;) {
2924 	FD_ZERO(&fds);
2925 	FD_SET(rodent.mfd, &fds);
2926 	timeout.tv_sec = 0;
2927 	timeout.tv_usec = 240000;
2928 	if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
2929 	    break;
2930 
2931 	read(rodent.mfd, &buf[i], 1);
2932 	if (buf[i++] == c)	/* End ID */
2933 	    break;
2934 	if (i >= 256)
2935 	    break;
2936     }
2937     if (begin > 0) {
2938 	i -= begin;
2939 	bcopy(&buf[begin], &buf[0], i);
2940     }
2941     /* string may not be human readable... */
2942     debug("len:%d, '%-*.*s'", i, i, i, buf);
2943 
2944     if (buf[i - 1] == c)
2945 	return (i);		/* a valid PnP string */
2946 
2947     /*
2948      * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2949      * in idle state.  But, `moused' shall leave the modem control lines
2950      * as they are. See above.
2951      */
2952 connect_idle:
2953 
2954     /* we may still have something in the buffer */
2955     return (MAX(i, 0));
2956 }
2957 
2958 static int
2959 pnpparse(pnpid_t *id, char *buf, int len)
2960 {
2961     char s[3];
2962     int offset;
2963     int sum = 0;
2964     int i, j;
2965 
2966     id->revision = 0;
2967     id->eisaid = NULL;
2968     id->serial = NULL;
2969     id->class = NULL;
2970     id->compat = NULL;
2971     id->description = NULL;
2972     id->neisaid = 0;
2973     id->nserial = 0;
2974     id->nclass = 0;
2975     id->ncompat = 0;
2976     id->ndescription = 0;
2977 
2978     if ((buf[0] != 0x28) && (buf[0] != 0x08)) {
2979 	/* non-PnP mice */
2980 	switch(buf[0]) {
2981 	default:
2982 	    return (FALSE);
2983 	case 'M': /* Microsoft */
2984 	    id->eisaid = "PNP0F01";
2985 	    break;
2986 	case 'H': /* MouseSystems */
2987 	    id->eisaid = "PNP0F04";
2988 	    break;
2989 	}
2990 	id->neisaid = strlen(id->eisaid);
2991 	id->class = "MOUSE";
2992 	id->nclass = strlen(id->class);
2993 	debug("non-PnP mouse '%c'", buf[0]);
2994 	return (TRUE);
2995     }
2996 
2997     /* PnP mice */
2998     offset = 0x28 - buf[0];
2999 
3000     /* calculate checksum */
3001     for (i = 0; i < len - 3; ++i) {
3002 	sum += buf[i];
3003 	buf[i] += offset;
3004     }
3005     sum += buf[len - 1];
3006     for (; i < len; ++i)
3007 	buf[i] += offset;
3008     debug("PnP ID string: '%*.*s'", len, len, buf);
3009 
3010     /* revision */
3011     buf[1] -= offset;
3012     buf[2] -= offset;
3013     id->revision = ((buf[1] & 0x3f) << 6) | (buf[2] & 0x3f);
3014     debug("PnP rev %d.%02d", id->revision / 100, id->revision % 100);
3015 
3016     /* EISA vender and product ID */
3017     id->eisaid = &buf[3];
3018     id->neisaid = 7;
3019 
3020     /* option strings */
3021     i = 10;
3022     if (buf[i] == '\\') {
3023 	/* device serial # */
3024 	for (j = ++i; i < len; ++i) {
3025 	    if (buf[i] == '\\')
3026 		break;
3027 	}
3028 	if (i >= len)
3029 	    i -= 3;
3030 	if (i - j == 8) {
3031 	    id->serial = &buf[j];
3032 	    id->nserial = 8;
3033 	}
3034     }
3035     if (buf[i] == '\\') {
3036 	/* PnP class */
3037 	for (j = ++i; i < len; ++i) {
3038 	    if (buf[i] == '\\')
3039 		break;
3040 	}
3041 	if (i >= len)
3042 	    i -= 3;
3043 	if (i > j + 1) {
3044 	    id->class = &buf[j];
3045 	    id->nclass = i - j;
3046 	}
3047     }
3048     if (buf[i] == '\\') {
3049 	/* compatible driver */
3050 	for (j = ++i; i < len; ++i) {
3051 	    if (buf[i] == '\\')
3052 		break;
3053 	}
3054 	/*
3055 	 * PnP COM spec prior to v0.96 allowed '*' in this field,
3056 	 * it's not allowed now; just igore it.
3057 	 */
3058 	if (buf[j] == '*')
3059 	    ++j;
3060 	if (i >= len)
3061 	    i -= 3;
3062 	if (i > j + 1) {
3063 	    id->compat = &buf[j];
3064 	    id->ncompat = i - j;
3065 	}
3066     }
3067     if (buf[i] == '\\') {
3068 	/* product description */
3069 	for (j = ++i; i < len; ++i) {
3070 	    if (buf[i] == ';')
3071 		break;
3072 	}
3073 	if (i >= len)
3074 	    i -= 3;
3075 	if (i > j + 1) {
3076 	    id->description = &buf[j];
3077 	    id->ndescription = i - j;
3078 	}
3079     }
3080 
3081     /* checksum exists if there are any optional fields */
3082     if ((id->nserial > 0) || (id->nclass > 0)
3083 	|| (id->ncompat > 0) || (id->ndescription > 0)) {
3084 	debug("PnP checksum: 0x%X", sum);
3085 	sprintf(s, "%02X", sum & 0x0ff);
3086 	if (strncmp(s, &buf[len - 3], 2) != 0) {
3087 #if 0
3088 	    /*
3089 	     * I found some mice do not comply with the PnP COM device
3090 	     * spec regarding checksum... XXX
3091 	     */
3092 	    logwarnx("PnP checksum error", 0);
3093 	    return (FALSE);
3094 #endif
3095 	}
3096     }
3097 
3098     return (TRUE);
3099 }
3100 
3101 static symtab_t *
3102 pnpproto(pnpid_t *id)
3103 {
3104     symtab_t *t;
3105     int i, j;
3106 
3107     if (id->nclass > 0)
3108 	if (strncmp(id->class, "MOUSE", id->nclass) != 0 &&
3109 	    strncmp(id->class, "TABLET", id->nclass) != 0)
3110 	    /* this is not a mouse! */
3111 	    return (NULL);
3112 
3113     if (id->neisaid > 0) {
3114 	t = gettoken(pnpprod, id->eisaid, id->neisaid);
3115 	if (t->val != MOUSE_PROTO_UNKNOWN)
3116 	    return (t);
3117     }
3118 
3119     /*
3120      * The 'Compatible drivers' field may contain more than one
3121      * ID separated by ','.
3122      */
3123     if (id->ncompat <= 0)
3124 	return (NULL);
3125     for (i = 0; i < id->ncompat; ++i) {
3126 	for (j = i; id->compat[i] != ','; ++i)
3127 	    if (i >= id->ncompat)
3128 		break;
3129 	if (i > j) {
3130 	    t = gettoken(pnpprod, id->compat + j, i - j);
3131 	    if (t->val != MOUSE_PROTO_UNKNOWN)
3132 		return (t);
3133 	}
3134     }
3135 
3136     return (NULL);
3137 }
3138 
3139 /* name/val mapping */
3140 
3141 static symtab_t *
3142 gettoken(symtab_t *tab, const char *s, int len)
3143 {
3144     int i;
3145 
3146     for (i = 0; tab[i].name != NULL; ++i) {
3147 	if (strncmp(tab[i].name, s, len) == 0)
3148 	    break;
3149     }
3150     return (&tab[i]);
3151 }
3152 
3153 static const char *
3154 gettokenname(symtab_t *tab, int val)
3155 {
3156     static const char unknown[] = "unknown";
3157     int i;
3158 
3159     for (i = 0; tab[i].name != NULL; ++i) {
3160 	if (tab[i].val == val)
3161 	    return (tab[i].name);
3162     }
3163     return (unknown);
3164 }
3165 
3166 
3167 /*
3168  * code to read from the Genius Kidspad tablet.
3169 
3170 The tablet responds to the COM PnP protocol 1.0 with EISA-ID KYE0005,
3171 and to pre-pnp probes (RTS toggle) with 'T' (tablet ?)
3172 9600, 8 bit, parity odd.
3173 
3174 The tablet puts out 5 bytes. b0 (mask 0xb8, value 0xb8) contains
3175 the proximity, tip and button info:
3176    (byte0 & 0x1)	true = tip pressed
3177    (byte0 & 0x2)	true = button pressed
3178    (byte0 & 0x40)	false = pen in proximity of tablet.
3179 
3180 The next 4 bytes are used for coordinates xl, xh, yl, yh (7 bits valid).
3181 
3182 Only absolute coordinates are returned, so we use the following approach:
3183 we store the last coordinates sent when the pen went out of the tablet,
3184 
3185 
3186  *
3187  */
3188 
3189 typedef enum {
3190     S_IDLE, S_PROXY, S_FIRST, S_DOWN, S_UP
3191 } k_status;
3192 
3193 static int
3194 kidspad(u_char rxc, mousestatus_t *act)
3195 {
3196     static int buf[5];
3197     static int buflen = 0, b_prev = 0 , x_prev = -1, y_prev = -1;
3198     static k_status status = S_IDLE;
3199     static struct timespec now;
3200 
3201     int x, y;
3202 
3203     if (buflen > 0 && (rxc & 0x80)) {
3204 	fprintf(stderr, "invalid code %d 0x%x\n", buflen, rxc);
3205 	buflen = 0;
3206     }
3207     if (buflen == 0 && (rxc & 0xb8) != 0xb8) {
3208 	fprintf(stderr, "invalid code 0 0x%x\n", rxc);
3209 	return (0);	/* invalid code, no action */
3210     }
3211     buf[buflen++] = rxc;
3212     if (buflen < 5)
3213 	return (0);
3214 
3215     buflen = 0;	/* for next time... */
3216 
3217     x = buf[1]+128*(buf[2] - 7);
3218     if (x < 0) x = 0;
3219     y = 28*128 - (buf[3] + 128* (buf[4] - 7));
3220     if (y < 0) y = 0;
3221 
3222     x /= 8;
3223     y /= 8;
3224 
3225     act->flags = 0;
3226     act->obutton = act->button;
3227     act->dx = act->dy = act->dz = 0;
3228     clock_gettime(CLOCK_MONOTONIC_FAST, &now);
3229     if (buf[0] & 0x40) /* pen went out of reach */
3230 	status = S_IDLE;
3231     else if (status == S_IDLE) { /* pen is newly near the tablet */
3232 	act->flags |= MOUSE_POSCHANGED;	/* force update */
3233 	status = S_PROXY;
3234 	x_prev = x;
3235 	y_prev = y;
3236     }
3237     act->dx = x - x_prev;
3238     act->dy = y - y_prev;
3239     if (act->dx || act->dy)
3240 	act->flags |= MOUSE_POSCHANGED;
3241     x_prev = x;
3242     y_prev = y;
3243     if (b_prev != 0 && b_prev != buf[0]) { /* possibly record button change */
3244 	act->button = 0;
3245 	if (buf[0] & 0x01) /* tip pressed */
3246 	    act->button |= MOUSE_BUTTON1DOWN;
3247 	if (buf[0] & 0x02) /* button pressed */
3248 	    act->button |= MOUSE_BUTTON2DOWN;
3249 	act->flags |= MOUSE_BUTTONSCHANGED;
3250     }
3251     b_prev = buf[0];
3252     return (act->flags);
3253 }
3254 
3255 static int
3256 gtco_digipad (u_char rxc, mousestatus_t *act)
3257 {
3258 	static u_char buf[5];
3259  	static int buflen = 0, b_prev = 0 , x_prev = -1, y_prev = -1;
3260 	static k_status status = S_IDLE;
3261 	int x, y;
3262 
3263 #define	GTCO_HEADER	0x80
3264 #define	GTCO_PROXIMITY	0x40
3265 #define	GTCO_START	(GTCO_HEADER|GTCO_PROXIMITY)
3266 #define	GTCO_BUTTONMASK	0x3c
3267 
3268 
3269 	if (buflen > 0 && ((rxc & GTCO_HEADER) != GTCO_HEADER)) {
3270 		fprintf(stderr, "invalid code %d 0x%x\n", buflen, rxc);
3271 		buflen = 0;
3272 	}
3273 	if (buflen == 0 && (rxc & GTCO_START) != GTCO_START) {
3274 		fprintf(stderr, "invalid code 0 0x%x\n", rxc);
3275 		return (0);	/* invalid code, no action */
3276 	}
3277 
3278 	buf[buflen++] = rxc;
3279 	if (buflen < 5)
3280 		return (0);
3281 
3282 	buflen = 0;	/* for next time... */
3283 
3284 	x = ((buf[2] & ~GTCO_START) << 6 | (buf[1] & ~GTCO_START));
3285 	y = 4768 - ((buf[4] & ~GTCO_START) << 6 | (buf[3] & ~GTCO_START));
3286 
3287 	x /= 2.5;
3288 	y /= 2.5;
3289 
3290 	act->flags = 0;
3291 	act->obutton = act->button;
3292 	act->dx = act->dy = act->dz = 0;
3293 
3294 	if ((buf[0] & 0x40) == 0) /* pen went out of reach */
3295 		status = S_IDLE;
3296 	else if (status == S_IDLE) { /* pen is newly near the tablet */
3297 		act->flags |= MOUSE_POSCHANGED;	/* force update */
3298 		status = S_PROXY;
3299 		x_prev = x;
3300 		y_prev = y;
3301 	}
3302 
3303 	act->dx = x - x_prev;
3304 	act->dy = y - y_prev;
3305 	if (act->dx || act->dy)
3306 		act->flags |= MOUSE_POSCHANGED;
3307 	x_prev = x;
3308 	y_prev = y;
3309 
3310 	/* possibly record button change */
3311 	if (b_prev != 0 && b_prev != buf[0]) {
3312 		act->button = 0;
3313 		if (buf[0] & 0x04) {
3314 			/* tip pressed/yellow */
3315 			act->button |= MOUSE_BUTTON1DOWN;
3316 		}
3317 		if (buf[0] & 0x08) {
3318 			/* grey/white */
3319 			act->button |= MOUSE_BUTTON2DOWN;
3320 		}
3321 		if (buf[0] & 0x10) {
3322 			/* black/green */
3323 			act->button |= MOUSE_BUTTON3DOWN;
3324 		}
3325 		if (buf[0] & 0x20) {
3326 			/* tip+grey/blue */
3327 			act->button |= MOUSE_BUTTON4DOWN;
3328 		}
3329 		act->flags |= MOUSE_BUTTONSCHANGED;
3330 	}
3331 	b_prev = buf[0];
3332 	return (act->flags);
3333 }
3334 
3335 static void
3336 mremote_serversetup(void)
3337 {
3338     struct sockaddr_un ad;
3339 
3340     /* Open a UNIX domain stream socket to listen for mouse remote clients */
3341     unlink(_PATH_MOUSEREMOTE);
3342 
3343     if ((rodent.mremsfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
3344 	logerrx(1, "unable to create unix domain socket %s",_PATH_MOUSEREMOTE);
3345 
3346     umask(0111);
3347 
3348     bzero(&ad, sizeof(ad));
3349     ad.sun_family = AF_UNIX;
3350     strcpy(ad.sun_path, _PATH_MOUSEREMOTE);
3351 #ifndef SUN_LEN
3352 #define SUN_LEN(unp) (((char *)(unp)->sun_path - (char *)(unp)) + \
3353 		       strlen((unp)->path))
3354 #endif
3355     if (bind(rodent.mremsfd, (struct sockaddr *) &ad, SUN_LEN(&ad)) < 0)
3356 	logerrx(1, "unable to bind unix domain socket %s", _PATH_MOUSEREMOTE);
3357 
3358     listen(rodent.mremsfd, 1);
3359 }
3360 
3361 static void
3362 mremote_clientchg(int add)
3363 {
3364     struct sockaddr_un ad;
3365     socklen_t ad_len;
3366     int fd;
3367 
3368     if (rodent.rtype != MOUSE_PROTO_X10MOUSEREM)
3369 	return;
3370 
3371     if (add) {
3372 	/*  Accept client connection, if we don't already have one  */
3373 	ad_len = sizeof(ad);
3374 	fd = accept(rodent.mremsfd, (struct sockaddr *) &ad, &ad_len);
3375 	if (fd < 0)
3376 	    logwarnx("failed accept on mouse remote socket");
3377 
3378 	if (rodent.mremcfd < 0) {
3379 	    rodent.mremcfd = fd;
3380 	    debug("remote client connect...accepted");
3381 	}
3382 	else {
3383 	    close(fd);
3384 	    debug("another remote client connect...disconnected");
3385 	}
3386     }
3387     else {
3388 	/* Client disconnected */
3389 	debug("remote client disconnected");
3390 	close(rodent.mremcfd);
3391 	rodent.mremcfd = -1;
3392     }
3393 }
3394