forked from kfish/xsel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xsel.c
2229 lines (1910 loc) · 61.1 KB
/
xsel.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* xsel -- manipulate the X selection
* Copyright (C) 2001 Conrad Parker <[email protected]>
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation. No representations are made about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/time.h>
#include <setjmp.h>
#include <signal.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include "xsel.h"
/* The name we were invoked as (argv[0]) */
static char * progname;
/* Verbosity level for debugging */
static int debug_level = DEBUG_LEVEL;
/* Our X Display and Window */
static Display * display;
static Window window;
/* Maxmimum request size supported by this X server */
static long max_req;
/* Our timestamp for all operations */
static Time timestamp;
static Atom timestamp_atom; /* The TIMESTAMP atom */
static Atom multiple_atom; /* The MULTIPLE atom */
static Atom targets_atom; /* The TARGETS atom */
static Atom delete_atom; /* The DELETE atom */
static Atom incr_atom; /* The INCR atom */
static Atom null_atom; /* The NULL atom */
static Atom text_atom; /* The TEXT atom */
static Atom utf8_atom; /* The UTF8 atom */
static Atom compound_text_atom; /* The COMPOUND_TEXT atom */
/* Number of selection targets served by this.
* (MULTIPLE, INCR, TARGETS, TIMESTAMP, DELETE, TEXT, UTF8_STRING and STRING)
* NB. We do not currently serve COMPOUND_TEXT; we can retrieve it but do not
* perform charset conversion.
*/
#define MAX_NUM_TARGETS 9
static int NUM_TARGETS;
static Atom supported_targets[MAX_NUM_TARGETS];
/* do_zeroflush: Use only last zero-separated part of input.
* All previous parts are discarded */
static Bool do_zeroflush = False;
/* do_follow: Follow mode for output */
static Bool do_follow = False;
/* nodaemon: Disable daemon mode if True. */
static Bool no_daemon = False;
/* logfile: name of file to log error messages to when detached */
static char logfile[MAXFNAME];
/* fstat() on stdin and stdout */
static struct stat in_statbuf, out_statbuf;
static int total_input = 0;
static int current_alloc = 0;
static long timeout = 0;
static struct itimerval timer;
static int saved_argc;
static char ** saved_argv;
/*
* usage ()
*
* print usage information.
*/
static void
usage (void)
{
printf ("Usage: xsel [options]\n");
printf ("Manipulate the X selection.\n\n");
printf ("By default the current selection is output and not modified if both\n");
printf ("standard input and standard output are terminals (ttys). Otherwise,\n");
printf ("the current selection is output if standard output is not a terminal\n");
printf ("(tty), and the selection is set from standard input if standard input\n");
printf ("is not a terminal (tty). If any input or output options are given then\n");
printf ("the program behaves only in the requested mode.\n\n");
printf ("If both input and output is required then the previous selection is\n");
printf ("output before being replaced by the contents of standard input.\n\n");
printf ("Input options\n");
printf (" -a, --append Append standard input to the selection\n");
printf (" -f, --follow Append to selection as standard input grows\n");
printf (" -z, --zeroflush Overwrites selection when zero ('\\0') is received\n");
printf (" -i, --input Read standard input into the selection\n\n");
printf ("Output options\n");
printf (" -o, --output Write the selection to standard output\n\n");
printf ("Action options\n");
printf (" -c, --clear Clear the selection\n");
printf (" -d, --delete Request that the selection be cleared and that\n");
printf (" the application owning it delete its contents\n\n");
printf ("Selection options\n");
printf (" -p, --primary Operate on the PRIMARY selection (default)\n");
printf (" -s, --secondary Operate on the SECONDARY selection\n");
printf (" -b, --clipboard Operate on the CLIPBOARD selection\n\n");
printf (" -k, --keep Do not modify the selections, but make the PRIMARY\n");
printf (" and SECONDARY selections persist even after the\n");
printf (" programs they were selected in exit.\n");
printf (" -x, --exchange Exchange the PRIMARY and SECONDARY selections\n\n");
printf ("X options\n");
printf (" --display displayname\n");
printf (" Specify the connection to the X server\n");
printf (" -t ms, --selectionTimeout ms\n");
printf (" Specify the timeout in milliseconds within which the\n");
printf (" selection must be retrieved. A value of 0 (zero)\n");
printf (" specifies no timeout (default)\n\n");
printf ("Miscellaneous options\n");
printf (" -l, --logfile Specify file to log errors to when detached.\n");
printf (" -n, --nodetach Do not detach from the controlling terminal. Without\n");
printf (" this option, xsel will fork to become a background\n");
printf (" process in input, exchange and keep modes.\n\n");
printf (" -h, --help Display this help and exit\n");
printf (" -v, --verbose Print informative messages\n");
printf (" --version Output version information and exit\n\n");
printf ("Please report bugs to <[email protected]>.\n");
}
/*
* exit_err (fmt)
*
* Print a formatted error message and errno information to stderr,
* then exit with return code 1.
*/
static void
exit_err (const char * fmt, ...)
{
va_list ap;
int errno_save;
char buf[MAXLINE];
int n;
errno_save = errno;
va_start (ap, fmt);
snprintf (buf, MAXLINE, "%s: ", progname);
n = strlen (buf);
vsnprintf (buf+n, MAXLINE-n, fmt, ap);
n = strlen (buf);
snprintf (buf+n, MAXLINE-n, ": %s\n", strerror (errno_save));
fflush (stdout); /* in case stdout and stderr are the same */
fputs (buf, stderr);
fflush (NULL);
va_end (ap);
exit (1);
}
/*
* print_err (fmt)
*
* Print a formatted error message to stderr.
*/
static void
print_err (const char * fmt, ...)
{
va_list ap;
int errno_save;
char buf[MAXLINE];
int n;
errno_save = errno;
va_start (ap, fmt);
snprintf (buf, MAXLINE, "%s: ", progname);
n = strlen (buf);
vsnprintf (buf+n, MAXLINE-n, fmt, ap);
n = strlen (buf);
fflush (stdout); /* in case stdout and stderr are the same */
fputs (buf, stderr);
fputc ('\n', stderr);
fflush (NULL);
va_end (ap);
}
/*
* print_debug (level, fmt)
*
* Print a formatted debugging message of level 'level' to stderr
*/
#define print_debug(x,y...) {if (x <= debug_level) print_err (y);}
/*
* get_atom_name (atom)
*
* Returns a string with a printable name for the Atom 'atom'.
*/
static char *
get_atom_name (Atom atom)
{
char * ret;
static char atom_name[MAXLINE+1];
if (atom == None) return "None";
if (atom == XA_STRING) return "STRING";
if (atom == XA_PRIMARY) return "PRIMARY";
if (atom == XA_SECONDARY) return "SECONDARY";
if (atom == timestamp_atom) return "TIMESTAMP";
if (atom == multiple_atom) return "MULTIPLE";
if (atom == targets_atom) return "TARGETS";
if (atom == delete_atom) return "DELETE";
if (atom == incr_atom) return "INCR";
if (atom == null_atom) return "NULL";
if (atom == text_atom) return "TEXT";
if (atom == utf8_atom) return "UTF8_STRING";
ret = XGetAtomName (display, atom);
strncpy (atom_name, ret, sizeof (atom_name));
if (atom_name[MAXLINE] != '\0')
{
atom_name[MAXLINE-3] = '.';
atom_name[MAXLINE-2] = '.';
atom_name[MAXLINE-1] = '.';
atom_name[MAXLINE] = '\0';
}
XFree (ret);
return atom_name;
}
/*
* debug_property (level, requestor, property, target, length)
*
* Print debugging information (at level 'level') about a property received.
*/
static void
debug_property (int level, Window requestor, Atom property, Atom target,
unsigned long length)
{
print_debug (level, "Got window property: requestor 0x%x, property 0x%x, target 0x%x %s, length %ld bytes", requestor, property, target, get_atom_name (target), length);
}
/*
* xs_malloc (size)
*
* Malloc wrapper. Always returns a successful allocation. Exits if the
* allocation didn't succeed.
*/
static void *
xs_malloc (size_t size)
{
void * ret;
if (size == 0) size = 1;
if ((ret = malloc (size)) == NULL) {
exit_err ("malloc error");
}
return ret;
}
/*
* xs_strdup (s)
*
* strdup wrapper for unsigned char *
*/
#define xs_strdup(s) ((unsigned char *) _xs_strdup ((const char *)s))
static char * _xs_strdup (const char * s)
{
char * ret;
if (s == NULL) return NULL;
if ((ret = strdup(s)) == NULL) {
exit_err ("strdup error");
}
return ret;
}
/*
* xs_strlen (s)
*
* strlen wrapper for unsigned char *
*/
#define xs_strlen(s) (strlen ((const char *) s))
/*
* xs_strncpy (s)
*
* strncpy wrapper for unsigned char *
*/
#define xs_strncpy(dest,s,n) (_xs_strncpy ((char *)dest, (const char *)s, n))
static char *
_xs_strncpy (char * dest, const char * src, size_t n)
{
if (n > 0) {
strncpy (dest, src, n);
dest[n-1] = '\0';
}
return dest;
}
/*
* get_homedir ()
*
* Get the user's home directory.
*/
static char *
get_homedir (void)
{
uid_t uid;
char * username, * homedir;
struct passwd * pw;
if ((homedir = getenv ("HOME")) != NULL) {
return homedir;
}
/* else ... go hunting for it */
uid = getuid ();
username = getenv ("LOGNAME");
if (!username) username = getenv ("USER");
if (username) {
pw = getpwnam (username);
if (pw && pw->pw_uid == uid) goto gotpw;
}
pw = getpwuid (uid);
gotpw:
if (!pw) {
exit_err ("error retrieving passwd entry");
}
homedir = _xs_strdup (pw->pw_dir);
return homedir;
}
/*
* become_daemon ()
*
* Perform the required procedure to become a daemon process, as
* outlined in the Unix programming FAQ:
* http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC16
* and open a logfile.
*/
static void
become_daemon (void)
{
pid_t pid;
int null_r_fd, null_w_fd, log_fd;
char * homedir;
if (no_daemon) return;
homedir = get_homedir ();
/* Check that we can open a logfile before continuing */
/* If the user has specified a --logfile, use that ... */
if (logfile[0] == '\0') {
/* ... otherwise use the default logfile */
snprintf (logfile, MAXFNAME, "%s/.xsel.log", homedir);
}
/* Make sure to create the logfile with sane permissions */
log_fd = open (logfile, O_WRONLY|O_APPEND|O_CREAT, 0600);
if (log_fd == -1) {
exit_err ("error opening logfile %s for writing", logfile);
}
print_debug (D_INFO, "opened logfile %s", logfile);
if ((pid = fork()) == -1) {
exit_err ("error forking");
} else if (pid > 0) {
_exit (0);
}
if (setsid () == -1) {
exit_err ("setsid error");
}
if ((pid = fork()) == -1) {
exit_err ("error forking");
} else if (pid > 0) {
_exit (0);
}
umask (0);
if (chdir (homedir) == -1) {
print_debug (D_WARN, "Could not chdir to %s\n", homedir);
if (chdir ("/") == -1) {
exit_err ("Error chdir to /");
}
}
/* dup2 /dev/null on stdin unless following input */
if (!do_follow) {
null_r_fd = open ("/dev/null", O_RDONLY);
if (null_r_fd == -1) {
exit_err ("error opening /dev/null for reading");
}
if (dup2 (null_r_fd, 0) == -1) {
exit_err ("error duplicating /dev/null on stdin");
}
}
/* dup2 /dev/null on stdout */
null_w_fd = open ("/dev/null", O_WRONLY|O_APPEND);
if (null_w_fd == -1) {
exit_err ("error opening /dev/null for writing");
}
if (dup2 (null_w_fd, 1) == -1) {
exit_err ("error duplicating /dev/null on stdout");
}
/* dup2 logfile on stderr */
if (dup2 (log_fd, 2) == -1) {
exit_err ("error duplicating logfile %s on stderr", logfile);
}
}
/*
* get_timestamp ()
*
* Get the current X server time.
*
* This is done by doing a zero-length append to a random property of the
* window, and checking the time on the subsequent PropertyNotify event.
*
* PRECONDITION: the window must have PropertyChangeMask set.
*/
static Time
get_timestamp (void)
{
XEvent event;
XChangeProperty (display, window, XA_WM_NAME, XA_STRING, 8,
PropModeAppend, NULL, 0);
while (1) {
XNextEvent (display, &event);
if (event.type == PropertyNotify)
return event.xproperty.time;
}
}
/*
* SELECTION RETRIEVAL
* ===================
*
* The following functions implement retrieval of an X selection,
* optionally within a user-specified timeout.
*
*
* Selection timeout handling.
* ---------------------------
*
* The selection retrieval can time out if no response is received within
* a user-specified time limit. In order to ensure we time the entire
* selection retrieval, we use an interval timer and catch SIGVTALRM.
* [Calling select() on the XConnectionNumber would only provide a timeout
* to the first XEvent.]
*/
/* The jmp_buf to longjmp out of the signal handler */
static sigjmp_buf env_alrm;
/*
* alarm_handler (sig)
*
* Signal handler for catching SIGVTALRM.
*/
static void
alarm_handler (int sig)
{
siglongjmp (env_alrm, 1);
}
/*
* get_append_property ()
*
* Get a window property and append its data to a buffer at a given offset
* pointed to by *offset. 'offset' is modified by this routine to point to
* the end of the data.
*
* Returns True if more data is available for receipt.
*
* If an error is encountered, the buffer is free'd.
*/
static Bool
get_append_property (XSelectionEvent * xsl, unsigned char ** buffer,
unsigned long * offset, unsigned long * alloc)
{
unsigned char * ptr;
Atom target;
int format;
unsigned long bytesafter, length;
unsigned char * value;
XGetWindowProperty (xsl->display, xsl->requestor, xsl->property,
0L, 1000000, True, (Atom)AnyPropertyType,
&target, &format, &length, &bytesafter, &value);
debug_property (D_TRACE, xsl->requestor, xsl->property, target, length);
if (target != XA_STRING && target != utf8_atom) {
print_debug (D_OBSC, "target %s not XA_STRING nor UTF8_STRING in get_append_property()",
get_atom_name (target));
free (*buffer);
*buffer = NULL;
return False;
} else if (length == 0) {
/* A length of 0 indicates the end of the transfer */
print_debug (D_TRACE, "Got zero length property; end of INCR transfer");
return False;
} else if (format == 8) {
if (*offset + length > *alloc) {
*alloc = *offset + length;
if ((*buffer = realloc (*buffer, *alloc)) == NULL) {
exit_err ("realloc error");
}
}
ptr = *buffer + *offset;
xs_strncpy (ptr, value, length);
*offset += length;
print_debug (D_TRACE, "Appended %d bytes to buffer\n", length);
} else {
print_debug (D_WARN, "Retrieved non-8-bit data\n");
}
return True;
}
/*
* wait_incr_selection (selection)
*
* Retrieve a property of target type INCR. Perform incremental retrieval
* and return the resulting data.
*/
static unsigned char *
wait_incr_selection (Atom selection, XSelectionEvent * xsl, int init_alloc)
{
XEvent event;
unsigned char * incr_base = NULL, * incr_ptr = NULL;
unsigned long incr_alloc = 0, incr_xfer = 0;
Bool wait_prop = True;
print_debug (D_TRACE, "Initialising incremental retrieval of at least %d bytes\n", init_alloc);
/* Take an interest in the requestor */
XSelectInput (xsl->display, xsl->requestor, PropertyChangeMask);
incr_alloc = init_alloc;
incr_base = xs_malloc (incr_alloc);
incr_ptr = incr_base;
print_debug (D_TRACE, "Deleting property that informed of INCR transfer");
XDeleteProperty (xsl->display, xsl->requestor, xsl->property);
print_debug (D_TRACE, "Waiting on PropertyNotify events");
while (wait_prop) {
XNextEvent (xsl->display, &event);
switch (event.type) {
case PropertyNotify:
if (event.xproperty.state != PropertyNewValue) break;
wait_prop = get_append_property (xsl, &incr_base, &incr_xfer,
&incr_alloc);
break;
default:
break;
}
}
/* when zero length found, finish up & delete last */
XDeleteProperty (xsl->display, xsl->requestor, xsl->property);
print_debug (D_TRACE, "Finished INCR retrieval");
return incr_base;
}
/*
* wait_selection (selection, request_target)
*
* Block until we receive a SelectionNotify event, and return its
* contents; or NULL in the case of a deletion or error. This assumes we
* have already called XConvertSelection, requesting a string (explicitly
* XA_STRING) or deletion (delete_atom).
*/
static unsigned char *
wait_selection (Atom selection, Atom request_target)
{
XEvent event;
Atom target;
int format;
unsigned long bytesafter, length;
unsigned char * value, * retval = NULL;
Bool keep_waiting = True;
while (keep_waiting) {
XNextEvent (display, &event);
switch (event.type) {
case SelectionNotify:
if (event.xselection.selection != selection) break;
if (event.xselection.property == None) {
print_debug (D_WARN, "Conversion refused");
value = NULL;
keep_waiting = False;
} else if (event.xselection.property == null_atom &&
request_target == delete_atom) {
} else {
XGetWindowProperty (event.xselection.display,
event.xselection.requestor,
event.xselection.property, 0L, 1000000,
False, (Atom)AnyPropertyType, &target,
&format, &length, &bytesafter, &value);
debug_property (D_TRACE, event.xselection.requestor,
event.xselection.property, target, length);
if (request_target == delete_atom && value == NULL) {
keep_waiting = False;
} else if (target == incr_atom) {
/* Handle INCR transfers */
retval = wait_incr_selection (selection, &event.xselection,
*(int *)value);
keep_waiting = False;
} else if (target != utf8_atom && target != XA_STRING &&
target != compound_text_atom &&
request_target != delete_atom) {
/* Report non-TEXT atoms */
print_debug (D_WARN, "Selection (type %s) is not a string.",
get_atom_name (target));
free (retval);
retval = NULL;
keep_waiting = False;
} else {
retval = xs_strdup (value);
XFree (value);
keep_waiting = False;
}
XDeleteProperty (event.xselection.display,
event.xselection.requestor,
event.xselection.property);
}
break;
default:
break;
}
}
/* Now that we've received the SelectionNotify event, clear any
* remaining timeout. */
if (timeout > 0) {
setitimer (ITIMER_VIRTUAL, (struct itimerval *)0, (struct itimerval *)0);
}
return retval;
}
/*
* get_selection (selection, request_target)
*
* Retrieves the specified selection and returns its value.
*
* If a non-zero timeout is specified then set a virtual interval
* timer. Return NULL and print an error message if the timeout
* expires before the selection has been retrieved.
*/
static unsigned char *
get_selection (Atom selection, Atom request_target)
{
Atom prop;
unsigned char * retval;
prop = XInternAtom (display, "XSEL_DATA", False);
XConvertSelection (display, selection, request_target, prop, window,
timestamp);
XSync (display, False);
if (timeout > 0) {
if (signal (SIGVTALRM, alarm_handler) == SIG_ERR) {
exit_err ("error setting timeout handler");
}
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = timeout;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = timeout;
if (sigsetjmp (env_alrm, 0) == 0) {
setitimer (ITIMER_VIRTUAL, &timer, (struct itimerval *)0);
retval = wait_selection (selection, request_target);
} else {
print_debug (D_WARN, "selection timed out");
retval = NULL;
}
} else {
retval = wait_selection (selection, request_target);
}
return retval;
}
/*
* get_selection_text (Atom selection)
*
* Retrieve a text selection. First attempt to retrieve it as UTF_STRING,
* and if that fails attempt to retrieve it as a plain XA_STRING.
*
* NB. Before implementing this, an attempt was made to query TARGETS and
* request UTF8_STRING only if listed there, as described in:
* http://www.pps.jussieu.fr/~jch/software/UTF8_STRING/UTF8_STRING.text
* However, that did not seem to work reliably when tested against various
* applications (eg. Mozilla Firefox). This method is of course more
* reliable.
*/
static unsigned char *
get_selection_text (Atom selection)
{
unsigned char * retval;
if ((retval = get_selection (selection, utf8_atom)) == NULL)
retval = get_selection (selection, XA_STRING);
return retval;
}
/*
* SELECTION SETTING
* =================
*
* The following functions allow a given selection to be set, appended to
* or cleared, or to exchange the primary and secondary selections.
*/
/*
* copy_sel (s)
*
* Copy a string into a new selection buffer, and intitialise
* current_alloc and total_input to exactly its length.
*/
static unsigned char *
copy_sel (unsigned char * s)
{
unsigned char * new_sel = NULL;
new_sel = xs_strdup (s);
current_alloc = total_input = xs_strlen (s);
return new_sel;
}
/*
* read_input (read_buffer, do_select)
*
* Read input from stdin into the specified read_buffer.
*
* read_buffer must have been dynamically allocated before calling this
* function, or be NULL. Input is read until end-of-file is reached, and
* read_buffer will be reallocated to accomodate the entire contents of
* the input. read_buffer, which may have been reallocated, is returned
* upon completion.
*
* If 'do_select' is True, this function will first check if any data
* is available for reading, and return immediately if not.
*/
static unsigned char *
read_input (unsigned char * read_buffer, Bool do_select)
{
int insize = in_statbuf.st_blksize;
unsigned char * new_buffer = NULL;
int d, fatal = 0, nfd;
ssize_t n;
fd_set fds;
struct timeval select_timeout;
do {
if (do_select) {
try_read:
/* Check if data is available for reading -- if not, return immediately */
FD_ZERO (&fds);
FD_SET (0, &fds);
select_timeout.tv_sec = (time_t)0;
select_timeout.tv_usec = (time_t)0;
nfd = select (1, &fds, NULL, NULL, &select_timeout);
if (nfd == -1) {
if (errno == EINTR) goto try_read;
else exit_err ("select error");
} else if (nfd == 0) {
print_debug (D_TRACE, "No data available for reading");
break;
}
}
/* check if buffer is full */
if (current_alloc == total_input) {
if ((d = (current_alloc % insize)) != 0) current_alloc += (insize-d);
current_alloc *= 2;
new_buffer = realloc (read_buffer, current_alloc);
if (new_buffer == NULL) {
exit_err ("realloc error");
}
read_buffer = new_buffer;
}
/* read the remaining data, up to the optimal block length */
n = read (0, &read_buffer[total_input],
MIN(current_alloc - total_input, insize));
if (n == -1) {
switch (errno) {
case EAGAIN:
case EINTR:
break;
default:
perror ("read error");
fatal = 1;
break;
}
}
total_input += n;
} while (n != 0 && !fatal);
read_buffer[total_input] = '\0';
if(do_zeroflush && total_input > 0) {
int i;
for(i=total_input-1; i>=0; i--) {
if(read_buffer[i] == '\0') {
print_debug (D_TRACE, "Flushing input at %d", i);
memmove(&read_buffer[0], &read_buffer[i+1], total_input - i);
total_input = total_input - i - 1;
read_buffer[total_input] = '\0';
break;
}
}
}
print_debug (D_TRACE, "Accumulated %d bytes input", total_input);
return read_buffer;
}
/*
* initialise_read (read_buffer)
*
* Initialises the read_buffer and the state variable current_alloc.
* read_buffer is reallocated to accomodate either the entire input
* if stdin is a regular file, or at least one block of input otherwise.
* If the supplied read_buffer is NULL, a new buffer will be allocated.
*/
static unsigned char *
initialise_read (unsigned char * read_buffer)
{
int insize = in_statbuf.st_blksize;
unsigned char * new_buffer = NULL;
if (S_ISREG (in_statbuf.st_mode)) {
current_alloc += in_statbuf.st_size;
} else {
current_alloc += insize;
}
if ((new_buffer = realloc (read_buffer, current_alloc)) == NULL) {
exit_err ("realloc error");
}
read_buffer = new_buffer;
return read_buffer;
}
/* Forward declaration of refuse_all_incr () */
static void
refuse_all_incr (void);
/*
* handle_x_errors ()
*
* XError handler.
*/
static int
handle_x_errors (Display * display, XErrorEvent * eev)
{
char err_buf[MAXLINE];
/* Make sure to send a refusal to all waiting INCR requests
* and delete the corresponding properties. */
if (eev->error_code == BadAlloc) refuse_all_incr ();
XGetErrorText (display, eev->error_code, err_buf, MAXLINE);
exit_err (err_buf);
return 0;
}
/*
* clear_selection (selection)
*
* Clears the specified X selection 'selection'. This requests that no
* process should own 'selection'; thus the X server will respond to
* SelectionRequests with an empty property and we don't need to leave
* a daemon hanging around to service this selection.
*/
static void
clear_selection (Atom selection)
{
XSetSelectionOwner (display, selection, None, timestamp);
/* Call XSync to ensure this operation completes before program
* termination, especially if this is all we are doing. */
XSync (display, False);
}
/*
* own_selection (selection)
*
* Requests ownership of the X selection. Returns True if ownership was
* granted, and False otherwise.
*/
static Bool
own_selection (Atom selection)
{
Window owner;
XSetSelectionOwner (display, selection, window, timestamp);
/* XGetSelectionOwner does a round trip to the X server, so there is
* no need to call XSync here. */
owner = XGetSelectionOwner (display, selection);
if (owner != window) {
return False;
} else {
XSetErrorHandler (handle_x_errors);
return True;
}
}
static IncrTrack * incrtrack_list = NULL;
/*
* add_incrtrack (it)
*
* Add 'it' to the head of incrtrack_list.
*/
static void
add_incrtrack (IncrTrack * it)
{
if (incrtrack_list) {
incrtrack_list->prev = it;
}