summaryrefslogtreecommitdiff
path: root/src/pv/cursor.c
blob: 0c6fc5b7109a339bad7cbb7ec8e6968650c6a2e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*
 * Cursor positioning functions.
 *
 * If IPC is available, then a shared memory segment is used to co-ordinate
 * cursor positioning across multiple instances of `pv'. The shared memory
 * segment contains an integer which is the original "y" co-ordinate of the
 * first `pv' process.
 *
 * However, some OSes (FreeBSD and MacOS X so far) don't allow locking of a
 * terminal, so we try to use a lockfile if terminal locking doesn't work,
 * and finally abort if even that is unavailable.
 *
 * Copyright 2012 Andrew Wood, distributed under the Artistic License 2.0.
 */

#include "options.h"
#include "pv.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_IPC
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
# ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
# endif
# ifdef HAVE_LIBGEN_H
# include <libgen.h>
# endif
#endif				/* HAVE_IPC */


#ifdef HAVE_IPC
static int pv_crs__shmid = -1;		 /* ID of our shared memory segment */
static int pv_crs__pvcount = 1;		 /* number of `pv' processes in total */
static int pv_crs__pvmax = 0;		 /* highest number of `pv's seen */
static int *pv_crs__y_top = 0;		 /* pointer to Y coord of topmost `pv' */
static int pv_crs__y_lastread = 0;	 /* last value of __y_top seen */
static int pv_crs__y_offset = 0;	 /* our Y offset from this top position */
static int pv_crs__needreinit = 0;	 /* set if we need to reinit cursor pos */
static int pv_crs__noipc = 0;		 /* set if we can't use IPC */
#endif				/* HAVE_IPC */
static int pv_crs__uselockfile = 0;	 /* set if we used a lockfile */
static int pv_crs__lock_fd = -1;	 /* fd of lockfile, -1 if none open */
static int pv_crs__y_start = 0;		 /* our initial Y coordinate */


/*
 * Lock the terminal on the given file descriptor by creating and locking a
 * per-euid, per-tty, lockfile in ${TMPDIR:-${TMP:-/tmp}}.
 */
static void pv_crs__lock_lockfile(int fd)
{
#ifdef O_EXLOCK
	char *ttydev;
	char *tmpdir;
#ifndef MAXPATHLEN
#define MAXPATHLEN 4096
#endif
	char lockfile[MAXPATHLEN + 1];	 /* RATS: ignore */

	pv_crs__uselockfile = 1;

	ttydev = ttyname(fd);		    /* RATS: ignore */
	if (!ttydev) {
#ifdef HAVE_IPC
		pv_crs__noipc = 1;
#endif
		return;
	}

	tmpdir = (char *) getenv("TMPDIR"); /* RATS: ignore */
	if (!tmpdir)
		tmpdir = (char *) getenv("TMP");	/* RATS: ignore */
	if (!tmpdir)
		tmpdir = "/tmp";

#ifdef HAVE_SNPRINTF
	snprintf(lockfile, MAXPATHLEN, "%s/pv-%s-%i.lock",
		 tmpdir, basename(ttydev), geteuid());
#else
	sprintf(lockfile,		    /* RATS: ignore */
		"%.*s/pv-%8s-%i.lock",
		MAXPATHLEN - 64, tmpdir, basename(ttydev), geteuid());
#endif

	pv_crs__lock_fd =
	    open(lockfile, O_RDWR | O_EXLOCK | O_CREAT | O_NOFOLLOW, 0600);
#ifdef HAVE_IPC
	if (pv_crs__lock_fd < 0)
		pv_crs__noipc = 1;
#endif

#else				/* !O_EXLOCK */

	pv_crs__uselockfile = 1;
#ifdef HAVE_IPC
	pv_crs__noipc = 1;
#endif

#endif				/* O_EXLOCK */
}


/*
 * Lock the terminal on the given file descriptor, falling back to using a
 * lockfile if the terminal itself cannot be locked.
 */
static void pv_crs__lock(int fd)
{
	struct flock lock;

	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 1;
	while (fcntl(fd, F_SETLKW, &lock) < 0) {
		if (errno != EINTR) {
			pv_crs__lock_lockfile(fd);
			return;
		}
	}
}


/*
 * Unlock the terminal on the given file descriptor.  If pv_crs__lock used
 * lockfile locking, unlock the lockfile.
 */
static void pv_crs__unlock(int fd)
{
	struct flock lock;

	if (pv_crs__uselockfile) {
		if (pv_crs__lock_fd >= 0)
			close(pv_crs__lock_fd);
		pv_crs__lock_fd = -1;
	} else {
		lock.l_type = F_UNLCK;
		lock.l_whence = SEEK_SET;
		lock.l_start = 0;
		lock.l_len = 1;
		fcntl(fd, F_SETLK, &lock);
	}
}


#ifdef HAVE_IPC
/*
 * Get the current number of processes attached to our shared memory
 * segment, i.e. find out how many `pv' processes in total are running in
 * cursor mode (including us), and store it in pv_crs__pvcount. If this is
 * larger than pv_crs__pvmax, update pv_crs__pvmax.
 */
static void pv_crs__ipccount(void)
{
	struct shmid_ds buf;

	buf.shm_nattch = 0;

	shmctl(pv_crs__shmid, IPC_STAT, &buf);
	pv_crs__pvcount = buf.shm_nattch;

	if (pv_crs__pvcount > pv_crs__pvmax)
		pv_crs__pvmax = pv_crs__pvcount;
}
#endif				/* HAVE_IPC */


/*
 * Get the current cursor Y co-ordinate by sending the ECMA-48 CPR code to
 * the terminal connected to the given file descriptor.
 */
static int pv_crs__get_ypos(int terminalfd)
{
	struct termios tty;
	struct termios old_tty;
	char cpr[32];			 /* RATS: ignore (checked) */
	int ypos;

	tcgetattr(terminalfd, &tty);
	tcgetattr(terminalfd, &old_tty);
	tty.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(terminalfd, TCSANOW | TCSAFLUSH, &tty);
	write(terminalfd, "\033[6n", 4);
	memset(cpr, 0, sizeof(cpr));
	read(terminalfd, cpr, 6);	    /* RATS: ignore (OK) */
	ypos = pv_getnum_i(cpr + 2);
	tcsetattr(terminalfd, TCSANOW | TCSAFLUSH, &old_tty);

	return ypos;
}


#ifdef HAVE_IPC
/*
 * Initialise the IPC data, returning nonzero on error.
 *
 * To do this, we attach to the shared memory segment (creating it if it
 * does not exist). If we are the only process attached to it, then we
 * initialise it with the current cursor position.
 *
 * There is a race condition here: another process could attach before we've
 * had a chance to check, such that no process ends up getting an "attach
 * count" of one, and so no initialisation occurs. So, we lock the terminal
 * with pv_crs__lock() while we are attaching and checking.
 */
static int pv_crs__ipcinit(opts_t opts, char *ttyfile, int terminalfd)
{
	key_t key;

	/*
	 * Base the key for the shared memory segment on our current tty, so
	 * we don't end up interfering in any way with instances of `pv'
	 * running on another terminal.
	 */
	key = ftok(ttyfile, 'p');
	if (key == -1) {
		fprintf(stderr, "%s: %s: %s\n",
			opts->program_name,
			_("failed to open terminal"), strerror(errno));
		return 1;
	}

	pv_crs__lock(terminalfd);
	if (pv_crs__noipc) {
		fprintf(stderr, "%s: %s: %s\n",
			opts->program_name,
			_("failed to lock terminal"), strerror(errno));
		return 1;
	}

	pv_crs__shmid = shmget(key, sizeof(int), 0600 | IPC_CREAT);
	if (pv_crs__shmid < 0) {
		fprintf(stderr, "%s: %s: %s\n",
			opts->program_name,
			_("failed to open terminal"), strerror(errno));
		pv_crs__unlock(terminalfd);
		return 1;
	}

	pv_crs__y_top = shmat(pv_crs__shmid, 0, 0);

	pv_crs__ipccount();

	/*
	 * If nobody else is attached to the shared memory segment, we're
	 * the first, so we need to initialise the shared memory with our
	 * current Y cursor co-ordinate.
	 */
	if (pv_crs__pvcount < 2) {
		pv_crs__y_start = pv_crs__get_ypos(terminalfd);
		*pv_crs__y_top = pv_crs__y_start;
		pv_crs__y_lastread = pv_crs__y_start;
	}

	pv_crs__y_offset = pv_crs__pvcount - 1;
	if (pv_crs__y_offset < 0)
		pv_crs__y_offset = 0;

	/*
	 * If anyone else had attached to the shared memory segment, we need
	 * to read the top Y co-ordinate from it.
	 */
	if (pv_crs__pvcount > 1) {
		pv_crs__y_start = *pv_crs__y_top;
		pv_crs__y_lastread = pv_crs__y_start;
	}

	pv_crs__unlock(terminalfd);

	return 0;
}
#endif				/* HAVE_IPC */


/*
 * Initialise the terminal for cursor positioning.
 */
void pv_crs_init(opts_t opts)
{
	char *ttyfile;
	int fd;

	if (!opts->cursor)
		return;

	ttyfile = ttyname(STDERR_FILENO);   /* RATS: ignore (unimportant) */
	if (!ttyfile) {
		opts->cursor = 0;
		return;
	}

	fd = open(ttyfile, O_RDWR);	    /* RATS: ignore (no race) */
	if (fd < 0) {
		fprintf(stderr, "%s: %s: %s\n",
			opts->program_name,
			_("failed to open terminal"), strerror(errno));
		opts->cursor = 0;
		return;
	}
#ifdef HAVE_IPC
	if (pv_crs__ipcinit(opts, ttyfile, fd)) {
		opts->cursor = 0;
		close(fd);
		return;
	}

	/*
	 * If we are not using IPC, then we need to get the current Y
	 * co-ordinate. If we are using IPC, then the pv_crs__ipcinit()
	 * function takes care of this in a more multi-process-friendly way.
	 */
	if (pv_crs__noipc) {
#else				/* ! HAVE_IPC */
	if (1) {
#endif				/* HAVE_IPC */
		/*
		 * Get current cursor position + 1.
		 */
		pv_crs__lock(fd);
		pv_crs__y_start = pv_crs__get_ypos(fd);
		pv_crs__unlock(fd);

		if (pv_crs__y_start < 1)
			opts->cursor = 0;
	}

	close(fd);
}


#ifdef HAVE_IPC
/*
 * Set the "we need to reinitialise cursor positioning" flag.
 */
void pv_crs_needreinit(void)
{
	pv_crs__needreinit += 2;
	if (pv_crs__needreinit > 3)
		pv_crs__needreinit = 3;
}
#endif


#ifdef HAVE_IPC
/*
 * Reinitialise the cursor positioning code (called if we are backgrounded
 * then foregrounded again).
 */
void pv_crs_reinit(void)
{
	pv_crs__lock(STDERR_FILENO);

	pv_crs__needreinit--;
	if (pv_crs__y_offset < 1)
		pv_crs__needreinit = 0;

	if (pv_crs__needreinit > 0) {
		pv_crs__unlock(STDERR_FILENO);
		return;
	}

	pv_crs__y_start = pv_crs__get_ypos(STDERR_FILENO);

	if (pv_crs__y_offset < 1)
		*pv_crs__y_top = pv_crs__y_start;
	pv_crs__y_lastread = pv_crs__y_start;

	pv_crs__unlock(STDERR_FILENO);
}
#endif


/*
 * Output a single-line update, moving the cursor to the correct position to
 * do so.
 */
void pv_crs_update(opts_t opts, char *str)
{
	char pos[32];			 /* RATS: ignore (checked OK) */
	int y;

#ifdef HAVE_IPC
	if (!pv_crs__noipc) {
		if (pv_crs__needreinit)
			pv_crs_reinit();

		pv_crs__ipccount();
		if (pv_crs__y_lastread != *pv_crs__y_top) {
			pv_crs__y_start = *pv_crs__y_top;
			pv_crs__y_lastread = pv_crs__y_start;
		}

		if (pv_crs__needreinit > 0)
			return;
	}
#endif				/* HAVE_IPC */

	y = pv_crs__y_start;

#ifdef HAVE_IPC
	/*
	 * If the screen has scrolled, or is about to scroll, due to
	 * multiple `pv' instances taking us near the bottom of the screen,
	 * scroll the screen (only if we're the first `pv'), and then move
	 * our initial Y co-ordinate up.
	 */
	if (((pv_crs__y_start + pv_crs__pvmax) > opts->height)
	    && (!pv_crs__noipc)
	    ) {
		int offs;

		offs = ((pv_crs__y_start + pv_crs__pvmax) - opts->height);

		pv_crs__y_start -= offs;
		if (pv_crs__y_start < 1)
			pv_crs__y_start = 1;

		/*
		 * Scroll the screen if we're the first `pv'.
		 */
		if (pv_crs__y_offset == 0) {
			pv_crs__lock(STDERR_FILENO);

			sprintf(pos, "\033[%d;1H", opts->height);
			write(STDERR_FILENO, pos, strlen(pos));
			for (; offs > 0; offs--) {
				write(STDERR_FILENO, "\n", 1);
			}

			pv_crs__unlock(STDERR_FILENO);
		}
	}

	if (!pv_crs__noipc)
		y = pv_crs__y_start + pv_crs__y_offset;
#endif				/* HAVE_IPC */

	/*
	 * Keep the Y co-ordinate within sensible bounds, so we can never
	 * overflow the "pos" buffer.
	 */
	if ((y < 1) || (y > 999999))
		y = 1;
	sprintf(pos, "\033[%d;1H", y);

	pv_crs__lock(STDERR_FILENO);

	write(STDERR_FILENO, pos, strlen(pos));	/* RATS: ignore */
	write(STDERR_FILENO, str, strlen(str));	/* RATS: ignore */

	pv_crs__unlock(STDERR_FILENO);
}


/*
 * Reposition the cursor to a final position.
 */
void pv_crs_fini(opts_t opts)
{
	char pos[32];			 /* RATS: ignore (checked OK) */
	int y;

	y = pv_crs__y_start;

#ifdef HAVE_IPC
	if ((pv_crs__pvmax > 0) && (!pv_crs__noipc))
		y += pv_crs__pvmax - 1;
#endif				/* HAVE_IPC */

	if (y > opts->height)
		y = opts->height;

	/*
	 * Absolute bounds check.
	 */
	if ((y < 1) || (y > 999999))
		y = 1;

	sprintf(pos, "\033[%d;1H\n", y);    /* RATS: ignore */

	pv_crs__lock(STDERR_FILENO);

	write(STDERR_FILENO, pos, strlen(pos));	/* RATS: ignore */

#ifdef HAVE_IPC
	pv_crs__ipccount();
	shmdt((void *) pv_crs__y_top);

	/*
	 * If we are the last instance detaching from the shared memory,
	 * delete it so it's not left lying around.
	 */
	if (pv_crs__pvcount < 2)
		shmctl(pv_crs__shmid, IPC_RMID, 0);

#endif				/* HAVE_IPC */

	pv_crs__unlock(STDERR_FILENO);
}

/* EOF */