/
connections.c
5557 lines (5044 loc) · 153 KB
/
connections.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
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 2000-10 The R Development Core Team.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* http://www.r-project.org/Licenses/
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <Defn.h>
#include <Fileio.h>
#include <Rconnections.h>
#include <R_ext/Complex.h>
#include <R_ext/R-ftp-http.h>
#include <R_ext/RS.h> /* R_chk_calloc and Free */
#include <R_ext/Riconv.h>
#undef ERROR /* for compilation on Windows */
int attribute_hidden R_OutputCon; /* used in printutils.c */
static void con_destroy(int i);
#include <errno.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
/* Solaris and AIX define open as open64 under some circumstances */
# undef open
/* AIX defines truncate as truncate64 under some circumstances */
# undef truncate
#endif
/* This should work on Win64, as long is 4 bytes but long long is 8 bytes. */
#if defined __GNUC__ && __GNUC__ >= 2
__extension__ typedef long long int _lli_t;
#else
typedef long long int _lli_t;
#endif
/* Win32 does have popen, but it does not work in GUI applications,
so test that later */
#ifdef Win32
# include <R_ext/RStartup.h>
extern UImode CharacterMode;
#endif
#define NCONNECTIONS 128 /* snow needs one per slave node */
#define NSINKS 21
static Rconnection Connections[NCONNECTIONS];
static SEXP OutTextData;
static int R_SinkNumber;
static int SinkCons[NSINKS], SinkConsClose[NSINKS], R_SinkSplit[NSINKS];
/* We need a unique id for a connection to ensure that the finalizer
does not try to close it after it is already closed. And that id
will be passed as a pointer, so it seemed easiest to use void *.
*/
static void * current_id = NULL;
#include <zlib.h>
typedef struct gzconn {
Rconnection con;
int cp; /* compression level */
z_stream s;
int z_err, z_eof;
uLong crc;
Byte *inbuf, *outbuf;
int nsaved;
char saved[2];
Rboolean allow;
} *Rgzconn;
/* ------------- admin functions (see also at end) ----------------- */
static int NextConnection(void)
{
int i;
for(i = 3; i < NCONNECTIONS; i++)
if(!Connections[i]) break;
if(i >= NCONNECTIONS) {
R_gc(); /* Try to reclaim unused ones */
for(i = 3; i < NCONNECTIONS; i++)
if(!Connections[i]) break;
if(i >= NCONNECTIONS)
error(_("all connections are in use"));
}
return i;
}
static int ConnIndex(Rconnection con)
{
int i;
for(i = 0; i < NCONNECTIONS; i++)
if(Connections[i] == con) break;
if(i >= NCONNECTIONS)
error(_("connection not found"));
return i;
}
/* internal, not the same as R function getConnection */
attribute_hidden
Rconnection getConnection(int n)
{
Rconnection con = NULL;
if(n < 0 || n >= NCONNECTIONS || n == NA_INTEGER ||
!(con = Connections[n]))
error(_("invalid connection"));
return con;
}
attribute_hidden
int getActiveSink(int n)
{
if (n >= R_SinkNumber || n < 0)
return 0;
if (R_SinkSplit[R_SinkNumber - n])
return SinkCons[R_SinkNumber - n - 1];
else
return 0;
}
static void conFinalizer(SEXP ptr)
{
int i, ncon;
void *cptr = R_ExternalPtrAddr(ptr);
if(!cptr) return;
for(i = 3; i < NCONNECTIONS; i++)
if(Connections[i] && Connections[i]->id == cptr) {
ncon = i;
break;
}
if(i >= NCONNECTIONS) return;
/* printf("closing unused connection %d (%s)\n", ncon,
getConnection(ncon)->description); */
warning(_("closing unused connection %d (%s)\n"), ncon,
getConnection(ncon)->description);
con_destroy(ncon);
R_ClearExternalPtr(ptr); /* not really needed */
}
/* for use in REvprintf */
attribute_hidden
Rconnection getConnection_no_err(int n)
{
Rconnection con = NULL;
if(n < 0 || n >= NCONNECTIONS || n == NA_INTEGER ||
!(con = Connections[n]))
return NULL;
return con;
}
static void set_iconv_error(Rconnection con, char* from, char* to)
{
char buf[100];
snprintf(buf, 100, _("unsupported conversion from '%s' to '%s'"), from, to);
con_destroy(ConnIndex(con));
error(buf);
}
void set_iconv(Rconnection con)
{
void *tmp;
/* need to test if this is text, open for reading to writing or both,
and set inconv and/or outconv */
if(!con->text || !strlen(con->encname) ||
strcmp(con->encname, "native.enc") == 0) {
con->UTF8out = FALSE;
return;
}
if(con->canread) {
size_t onb = 50;
char *ob = con->oconvbuff;
/* UTF8out is set in readLines() and scan()
Was Windows-only until 2.12.0, but we now require iconv.
*/
Rboolean useUTF8 = !utf8locale && con->UTF8out;
tmp = Riconv_open(useUTF8 ? "UTF-8" : "", con->encname);
if(tmp != (void *)-1) con->inconv = tmp;
else set_iconv_error(con, con->encname, useUTF8 ? "UTF-8" : "");
con->EOF_signalled = FALSE;
/* initialize state, and prepare any initial bytes */
Riconv(tmp, NULL, NULL, &ob, &onb);
con->navail = 50-onb; con->inavail = 0;
/* libiconv can handle BOM marks on Windows Unicode files, but
glibc's iconv cannot. Aargh ... */
if(streql(con->encname, "UCS-2LE") ||
streql(con->encname, "UTF-16LE")) con->inavail = -2;
}
if(con->canwrite) {
size_t onb = 25;
char *ob = con->init_out;
tmp = Riconv_open(con->encname, "");
if(tmp != (void *)-1) con->outconv = tmp;
else set_iconv_error(con, con->encname, "");
/* initialize state, and prepare any initial bytes */
Riconv(tmp, NULL, NULL, &ob, &onb);
ob[25-onb] = '\0';
}
}
/* ------------------- null connection functions --------------------- */
static Rboolean null_open(Rconnection con)
{
error(_("%s not enabled for this connection"), "open");
return FALSE; /* -Wall */
}
static void null_close(Rconnection con)
{
con->isopen = FALSE;
}
static void null_destroy(Rconnection con)
{
if(con->private) free(con->private);
}
static int null_vfprintf(Rconnection con, const char *format, va_list ap)
{
error(_("%s not enabled for this connection"), "printing");
return 0; /* -Wall */
}
/* va_copy is C99, but a draft standard had __va_copy. Glibc has
__va_copy declared uncondiitonally */
#if defined(HAVE_VASPRINTF) && !HAVE_DECL_VASPRINTF
int vasprintf(char **strp, const char *fmt, va_list ap);
#endif
#if !HAVE_VA_COPY && HAVE___VA_COPY
# define va_copy __va_copy
# undef HAVE_VA_COPY
# define HAVE_VA_COPY 1
#endif
#ifdef HAVE_VA_COPY
# define BUFSIZE 10000
#else
# define BUFSIZE 100000
#endif
int dummy_vfprintf(Rconnection con, const char *format, va_list ap)
{
char buf[BUFSIZE], *b = buf;
int res;
#ifdef HAVE_VA_COPY
const void *vmax = vmaxget();
int usedRalloc = FALSE, usedVasprintf = FALSE;
va_list aq;
va_copy(aq, ap);
res = vsnprintf(buf, BUFSIZE, format, aq);
va_end(aq);
#ifdef HAVE_VASPRINTF
if(res >= BUFSIZE || res < 0) {
res = vasprintf(&b, format, ap);
if (res < 0) {
b = buf;
buf[BUFSIZE-1] = '\0';
warning(_("printing of extremely long output is truncated"));
} else usedVasprintf = TRUE;
}
#else
if(res >= BUFSIZE) { /* res is the desired output length */
usedRalloc = TRUE;
/* apparently some implementations count short,
<http://unixpapa.com/incnote/stdio.html>
so add some margin here */
b = R_alloc(res + 101, sizeof(char));
vsnprintf(b, res+100, format, ap);
} else if(res < 0) { /* just a failure indication */
usedRalloc = TRUE;
b = R_alloc(10*BUFSIZE, sizeof(char));
res = vsnprintf(b, 10*BUFSIZE, format, ap);
if (res < 0) {
b[10*BUFSIZE - 1] = '\0';
warning(_("printing of extremely long output is truncated"));
res = 10*BUFSIZE;
}
}
#endif /* HAVE_VASPRINTF */
#else /* no VA_COPY */
res = vsnprintf(buf, BUFSIZE, format, ap);
if(res >= BUFSIZE || res < 0) {
/* res is the desired output length or just a failure indication */
buf[BUFSIZE - 1] = '\0';
warning(_("printing of extremely long output is truncated"));
res = BUFSIZE;
}
#endif /* HAVE_VA_COPY */
if(con->outconv) { /* translate the buffer */
char outbuf[BUFSIZE+1], *ob;
const char *ib = b;
size_t inb = res, onb, ires;
Rboolean again = FALSE;
int ninit = strlen(con->init_out);
do {
onb = BUFSIZE; /* leave space for nul */
ob = outbuf;
if(ninit) {
strcpy(ob, con->init_out);
ob += ninit; onb -= ninit; ninit = 0;
}
ires = Riconv(con->outconv, &ib, &inb, &ob, &onb);
if(ires == (size_t)(-1) && errno == E2BIG) again = TRUE;
if(ires == (size_t)(-1) && errno != E2BIG)
/* is this safe? */
warning(_("invalid char string in output conversion"));
*ob = '\0';
con->write(outbuf, 1, strlen(outbuf), con);
} while(again && inb > 0); /* it seems some iconv signal -1 on
zero-length input */
} else
con->write(b, 1, res, con);
#ifdef HAVE_VA_COPY
if(usedRalloc) vmaxset(vmax);
if(usedVasprintf) free(b);
#endif
return res;
}
int dummy_fgetc(Rconnection con)
{
int c;
Rboolean checkBOM = FALSE;
if(con->inconv) {
if(con->navail <= 0) {
unsigned int i, inew = 0;
char *p, *ob;
const char *ib;
size_t inb, onb, res;
if(con->EOF_signalled) return R_EOF;
if(con->inavail == -2) {
con->inavail = 0;
checkBOM = TRUE;
}
p = con->iconvbuff + con->inavail;
for(i = con->inavail; i < 25; i++) {
c = con->fgetc_internal(con);
if(c == R_EOF){ con->EOF_signalled = TRUE; break; }
*p++ = c;
con->inavail++;
inew++;
}
if(inew == 0) return R_EOF;
if(checkBOM && con->inavail >= 2 &&
((int)con->iconvbuff[0] & 0xff) == 255 &&
((int)con->iconvbuff[1] & 0xff) == 254) {
con->inavail -= 2;
memmove(con->iconvbuff, con->iconvbuff+2, con->inavail);
}
ib = con->iconvbuff; inb = con->inavail;
ob = con->oconvbuff; onb = 50;
res = Riconv(con->inconv, &ib, &inb, &ob, &onb);
con->inavail = inb;
if(res == (size_t)-1) { /* an error condition */
if(errno == EINVAL || errno == E2BIG) {
/* incomplete input char or no space in output buffer */
memmove(con->iconvbuff, ib, inb);
} else {/* EILSEQ invalid input */
warning(_("invalid input found on input connection '%s'"),
con->description);
con->inavail = 0;
con->EOF_signalled = TRUE;
}
}
con->next = con->oconvbuff;
con->navail = 50 - onb;
}
con->navail--;
return *con->next++;
} else
return con->fgetc_internal(con);
}
static int null_fgetc(Rconnection con)
{
error(_("%s not enabled for this connection"), "'getc'");
return 0; /* -Wall */
}
static double null_seek(Rconnection con, double where, int origin, int rw)
{
error(_("%s not enabled for this connection"), "'seek'");
return 0.; /* -Wall */
}
static void null_truncate(Rconnection con)
{
error(_("%s not enabled for this connection"), "truncation");
}
static int null_fflush(Rconnection con)
{
return 0;
}
static size_t null_read(void *ptr, size_t size, size_t nitems,
Rconnection con)
{
error(_("%s not enabled for this connection"), "'read'");
return 0; /* -Wall */
}
static size_t null_write(const void *ptr, size_t size, size_t nitems,
Rconnection con)
{
error(_("%s not enabled for this connection"), "'write'");
return 0; /* -Wall */
}
void init_con(Rconnection new, const char *description, int enc,
const char * const mode)
{
strcpy(new->description, description);
new->enc = enc;
strncpy(new->mode, mode, 4); new->mode[4] = '\0';
new->isopen = new->incomplete = new->blocking = new->isGzcon = FALSE;
new->canread = new->canwrite = TRUE; /* in principle */
new->canseek = FALSE;
new->text = TRUE;
new->open = &null_open;
new->close = &null_close;
new->destroy = &null_destroy;
new->vfprintf = &null_vfprintf;
new->fgetc = new->fgetc_internal = &null_fgetc;
new->seek = &null_seek;
new->truncate = &null_truncate;
new->fflush = &null_fflush;
new->read = &null_read;
new->write = &null_write;
new->nPushBack = 0;
new->save = new->save2 = -1000;
new->private = NULL;
new->inconv = new->outconv = NULL;
new->UTF8out = FALSE;
/* increment id, avoid NULL */
current_id = (void *)((size_t) current_id+1);
if(!current_id) current_id = (void *) 1;
new->id = current_id;
new->ex_ptr = NULL;
}
/* ------------------- file connections --------------------- */
#if defined(HAVE_OFF_T) && defined(HAVE_FSEEKO)
#define f_seek fseeko
#define f_tell ftello
#else
#ifdef Win32
#define f_seek fseeko64
#define f_tell ftello64
#else
#define f_seek fseek
#define f_tell ftell
#endif
#endif
#ifdef Win32
size_t Rf_utf8towcs(wchar_t *wc, const char *s, size_t n);
#endif
typedef struct fileconn {
FILE *fp;
#if defined(HAVE_OFF_T) && defined(HAVE_FSEEKO)
off_t rpos, wpos;
#else
#ifdef Win32
off64_t rpos, wpos;
#else
long rpos, wpos;
#endif
#endif
Rboolean last_was_write;
Rboolean raw;
#ifdef Win32
Rboolean anon_file;
char name[PATH_MAX+1];
#endif
} *Rfileconn;
static Rboolean file_open(Rconnection con)
{
const char *name;
FILE *fp = NULL;
Rfileconn this = con->private;
Rboolean temp = FALSE;
#ifdef HAVE_FCNTL
int fd, flags;
#endif
int mlen = strlen(con->mode);
if(strlen(con->description) == 0) {
temp = TRUE;
name = R_tmpnam("Rf", R_TempDir);
} else name = R_ExpandFileName(con->description);
errno = 0; /* some systems require this */
if(strcmp(name, "stdin")) {
#ifdef Win32
if(con->enc == CE_UTF8) {
int n = strlen(name);
wchar_t wname[2 * (n+1)], wmode[10];
R_CheckStack();
Rf_utf8towcs(wname, name, n+1);
mbstowcs(wmode, con->mode, 10);
fp = _wfopen(wname, wmode);
} else
#endif
fp = R_fopen(name, con->mode);
} else { /* use file("stdin") to refer to the file and not the console */
#ifdef HAVE_FDOPEN
fp = fdopen(0, con->mode);
#else
warning(_("cannot open file '%s': %s"), name,
"fdopen is not supported on this platform");
#endif
}
if(!fp) {
warning(_("cannot open file '%s': %s"), name, strerror(errno));
return FALSE;
}
if(temp) {
/* This will fail on Windows, so arrange to remove in
* file_close. An alternative strategy would be to manipulate
* the underlying file handle to add FILE_SHARE_DELETE (so the
* unlink is valid) or FILE_FLAG_DELETE_ON_CLOSE. E.g. create
* via CreateFile, get an fd by _open_osfhandle and a file
* stream by fdopen. See
* e.g. http://www.codeproject.com/KB/files/handles.aspx
*/
unlink(name);
#ifdef Win32
strncpy(this->name, name, PATH_MAX);
#endif
free((char *) name); /* only free if allocated by R_tmpnam */
}
#ifdef Win32
this->anon_file = temp;
#endif
this->fp = fp;
con->isopen = TRUE;
con->canwrite = (con->mode[0] == 'w' || con->mode[0] == 'a');
con->canread = !con->canwrite;
if(mlen >= 2 && con->mode[1] == '+')
con->canread = con->canwrite = TRUE;
this->last_was_write = !con->canread;
this->rpos = 0;
if(con->canwrite) this->wpos = f_tell(fp);
if(mlen >= 2 && con->mode[mlen-1] == 'b') con->text = FALSE;
else con->text = TRUE;
con->save = -1000;
set_iconv(con);
#ifdef HAVE_FCNTL
if(!con->blocking) {
fd = fileno(fp);
flags = fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
}
#endif
return TRUE;
}
static void file_close(Rconnection con)
{
Rfileconn this = con->private;
if(con->isopen && strcmp(con->description, "stdin")) fclose(this->fp);
con->isopen = FALSE;
#ifdef Win32
if(this->anon_file) unlink(this->name);
#endif
}
static int file_vfprintf(Rconnection con, const char *format, va_list ap)
{
Rfileconn this = con->private;
if(!this->last_was_write) {
this->rpos = f_tell(this->fp);
this->last_was_write = TRUE;
f_seek(this->fp, this->wpos, SEEK_SET);
}
if(con->outconv) return dummy_vfprintf(con, format, ap);
else return vfprintf(this->fp, format, ap);
}
static int file_fgetc_internal(Rconnection con)
{
Rfileconn this = con->private;
FILE *fp = this->fp;
int c;
if(this->last_was_write) {
this->wpos = f_tell(this->fp);
this->last_was_write = FALSE;
f_seek(this->fp, this->rpos, SEEK_SET);
}
c =fgetc(fp);
return feof(fp) ? R_EOF : c;
}
static double file_seek(Rconnection con, double where, int origin, int rw)
{
Rfileconn this = con->private;
FILE *fp = this->fp;
#if defined(HAVE_OFF_T) && defined(HAVE_FSEEKO)
off_t pos;
#else
#ifdef Win32
off64_t pos;
#else
long pos;
#endif
#endif
int whence = SEEK_SET;
/* make sure both positions are set */
pos = f_tell(fp);
if(this->last_was_write) this->wpos = pos; else this->rpos = pos;
if(rw == 1) {
if(!con->canread) error(_("connection is not open for reading"));
pos = this->rpos;
this->last_was_write = FALSE;
}
if(rw == 2) {
if(!con->canwrite) error(_("connection is not open for writing"));
pos = this->wpos;
this->last_was_write = TRUE;
}
if(ISNA(where)) return pos;
switch(origin) {
case 2: whence = SEEK_CUR; break;
case 3: whence = SEEK_END;
#ifdef Win32
/* work around a bug in MinGW runtime 3.8 fseeko64, PR#7896 */
if(con->canwrite) fflush(fp);
#endif
break;
default: whence = SEEK_SET;
}
f_seek(fp, where, whence);
if(this->last_was_write) this->wpos = f_tell(this->fp);
else this->rpos = f_tell(this->fp);
return pos;
}
static void file_truncate(Rconnection con)
{
Rfileconn this = con->private;
#ifdef HAVE_FTRUNCATE
FILE *fp = this->fp;
int fd = fileno(fp);
#ifdef HAVE_OFF_T
off_t size = lseek(fd, 0, SEEK_CUR);
#else
#ifdef Win32
__int64 size = lseek64(fd, 0, SEEK_CUR);
#else
int size = lseek(fd, 0, SEEK_CUR);
#endif
#endif
#endif
if(!con->isopen || !con->canwrite)
error(_("can only truncate connections open for writing"));
if(!this->last_was_write) this->rpos = f_tell(this->fp);
#ifdef HAVE_FTRUNCATE
if(ftruncate(fd, size))
error(_("file truncation failed"));
#else
error(_("file truncation unavailable on this platform"));
#endif
this->last_was_write = TRUE;
this->wpos = f_tell(this->fp);
}
static int file_fflush(Rconnection con)
{
FILE *fp = ((Rfileconn)(con->private))->fp;
return fflush(fp);
}
static size_t file_read(void *ptr, size_t size, size_t nitems,
Rconnection con)
{
Rfileconn this = con->private;
FILE *fp = this->fp;
if(this->last_was_write) {
this->wpos = f_tell(this->fp);
this->last_was_write = FALSE;
f_seek(this->fp, this->rpos, SEEK_SET);
}
return fread(ptr, size, nitems, fp);
}
static size_t file_write(const void *ptr, size_t size, size_t nitems,
Rconnection con)
{
Rfileconn this = con->private;
FILE *fp = this->fp;
if(!this->last_was_write) {
this->rpos = f_tell(this->fp);
this->last_was_write = TRUE;
f_seek(this->fp, this->wpos, SEEK_SET);
}
return fwrite(ptr, size, nitems, fp);
}
static Rconnection newfile(const char *description, int enc, const char *mode,
int raw)
{
Rconnection new;
new = (Rconnection) malloc(sizeof(struct Rconn));
if(!new) error(_("allocation of file connection failed"));
new->class = (char *) malloc(strlen("file") + 1);
if(!new->class) {
free(new);
error(_("allocation of file connection failed"));
}
strcpy(new->class, "file");
new->description = (char *) malloc(strlen(description) + 1);
if(!new->description) {
free(new->class); free(new);
error(_("allocation of file connection failed"));
}
init_con(new, description, enc, mode);
new->open = &file_open;
new->close = &file_close;
new->vfprintf = &file_vfprintf;
new->fgetc_internal = &file_fgetc_internal;
new->fgetc = &dummy_fgetc;
new->seek = &file_seek;
new->truncate = &file_truncate;
new->fflush = &file_fflush;
new->read = &file_read;
new->write = &file_write;
new->canseek = (raw == 0);
new->private = (void *) malloc(sizeof(struct fileconn));
if(!new->private) {
free(new->description); free(new->class); free(new);
error(_("allocation of file connection failed"));
}
((Rfileconn)(new->private))->raw = raw;
return new;
}
/* file() is now implemented as an op of do_url */
/* ------------------- fifo connections --------------------- */
#if defined(HAVE_MKFIFO) && defined(HAVE_FCNTL_H)
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
# include <errno.h>
typedef struct fifoconn {
int fd;
} *Rfifoconn;
static Rboolean fifo_open(Rconnection con)
{
const char *name;
Rfifoconn this = con->private;
int fd, flags, res;
int mlen = strlen(con->mode);
struct stat sb;
Rboolean temp = FALSE;
if(strlen(con->description) == 0) {
temp = TRUE;
name = R_tmpnam("Rf", R_TempDir);
} else name = R_ExpandFileName(con->description);
con->canwrite = (con->mode[0] == 'w' || con->mode[0] == 'a');
con->canread = !con->canwrite;
if(mlen >= 2 && con->mode[1] == '+') con->canread = TRUE;
/* if we are to write, create the fifo if needed */
if(con->canwrite) {
res = stat(name, &sb);
if(res) { /* error, does not exist? */
errno = 0;
res = mkfifo(name, 00644);
if(res) {
warning(_("cannot create fifo '%s', reason '%s'"), name,
strerror(errno));
}
if(res) return FALSE;
} else {
if(!(sb.st_mode & S_IFIFO)) {
warning(_("'%s' exists but is not a fifo"), name);
return FALSE;
}
}
}
if(con->canread && con->canwrite) flags = O_RDWR;
else if(con->canread) flags = O_RDONLY;
else flags = O_WRONLY;
if(!con->blocking) flags |= O_NONBLOCK;
if(con->mode[0] == 'a') flags |= O_APPEND;
fd = open(name, flags);
if(fd < 0) {
if(errno == ENXIO) warning(_("fifo '%s' is not ready"), name);
else warning(_("cannot open fifo '%s'"), name);
return FALSE;
}
if(temp) {
unlink(name);
free((char *) name); /* allocated by R_tmpnam */
}
this->fd = fd;
con->isopen = TRUE;
if(mlen >= 2 && con->mode[mlen-1] == 'b') con->text = FALSE;
else con->text = TRUE;
set_iconv(con);
con->save = -1000;
return TRUE;
}
static void fifo_close(Rconnection con)
{
close(((Rfifoconn)(con->private))->fd);
con->isopen = FALSE;
}
static int fifo_fgetc_internal(Rconnection con)
{
Rfifoconn this = con->private;
unsigned char c;
int n;
n = read(this->fd, (char *)&c, 1);
return (n == 1) ? c : R_EOF;
}
static size_t fifo_read(void *ptr, size_t size, size_t nitems,
Rconnection con)
{
Rfifoconn this = con->private;
/* uses 'size_t' for len */
if ((double) size * (double) nitems > SSIZE_MAX)
error(_("too large a block specified"));
return read(this->fd, ptr, size * nitems)/size;
}
static size_t fifo_write(const void *ptr, size_t size, size_t nitems,
Rconnection con)
{
Rfifoconn this = con->private;
/* uses 'size_t' for len */
if ((double) size * (double) nitems > SSIZE_MAX)
error(_("too large a block specified"));
return write(this->fd, ptr, size * nitems)/size;
}
static Rconnection newfifo(const char *description, const char *mode)
{
Rconnection new;
new = (Rconnection) malloc(sizeof(struct Rconn));
if(!new) error(_("allocation of fifo connection failed"));
new->class = (char *) malloc(strlen("fifo") + 1);
if(!new->class) {
free(new);
error(_("allocation of fifo connection failed"));
}
strcpy(new->class, "fifo");
new->description = (char *) malloc(strlen(description) + 1);
if(!new->description) {
free(new->class); free(new);
error(_("allocation of fifo connection failed"));
}
init_con(new, description, CE_NATIVE, mode);
new->open = &fifo_open;
new->close = &fifo_close;
new->vfprintf = &dummy_vfprintf;
new->fgetc_internal = &fifo_fgetc_internal;
new->fgetc = &dummy_fgetc;
new->seek = &null_seek;
new->truncate = &null_truncate;
new->fflush = &null_fflush;
new->read = &fifo_read;
new->write = &fifo_write;
new->private = (void *) malloc(sizeof(struct fifoconn));
if(!new->private) {
free(new->description); free(new->class); free(new);
error(_("allocation of fifo connection failed"));
}
return new;
}
#endif
SEXP attribute_hidden do_fifo(SEXP call, SEXP op, SEXP args, SEXP env)
{
#if defined(HAVE_MKFIFO) && defined(HAVE_FCNTL_H)
SEXP sfile, sopen, ans, class, enc;
const char *file, *open;
int ncon, block;
Rconnection con = NULL;
checkArity(op, args);
sfile = CAR(args);
if(!isString(sfile) || length(sfile) < 1)
error(_("invalid '%s' argument"), "description");
if(length(sfile) > 1)
warning(_("only first element of 'description' argument used"));
file = translateChar(STRING_ELT(sfile, 0)); /* for now, like fopen */
sopen = CADR(args);
if(!isString(sopen) || length(sopen) != 1)
error(_("invalid '%s' argument"), "open");
block = asLogical(CADDR(args));
if(block == NA_LOGICAL)
error(_("invalid '%s' argument"), "block");
enc = CADDDR(args);
if(!isString(enc) || length(enc) != 1 ||
strlen(CHAR(STRING_ELT(enc, 0))) > 100) /* ASCII */
error(_("invalid '%s' argument"), "encoding");
open = CHAR(STRING_ELT(sopen, 0)); /* ASCII */
if(strlen(file) == 0) {
if(!strlen(open)) open ="w+";
if(strcmp(open, "w+") != 0 && strcmp(open, "w+b") != 0) {
open ="w+";
warning(_("fifo(\"\") only supports open = \"w+\" and open = \"w+b\": using the former"));
}
}
ncon = NextConnection();
con = Connections[ncon] = newfifo(file, strlen(open) ? open : "r");
con->blocking = block;
strncpy(con->encname, CHAR(STRING_ELT(enc, 0)), 100); /* ASCII */
/* open it if desired */
if(strlen(open)) {
Rboolean success = con->open(con);
if(!success) {
con_destroy(ncon);
error(_("cannot open the connection"));
}
}
PROTECT(ans = ScalarInteger(ncon));
PROTECT(class = allocVector(STRSXP, 2));
SET_STRING_ELT(class, 0, mkChar("fifo"));
SET_STRING_ELT(class, 1, mkChar("connection"));
classgets(ans, class);
con->ex_ptr = R_MakeExternalPtr(con->id, install("connection"),
R_NilValue);
setAttrib(ans, install("conn_id"), con->ex_ptr);
R_RegisterCFinalizerEx(con->ex_ptr, conFinalizer, FALSE);