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