1 /* hfile_net.c -- network backend for low-level input/output streams.
3 Copyright (C) 2013-2015 Genome Research Ltd.
5 Author: John Marshall <jm18@sanger.ac.uk>
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 DEALINGS IN THE SOFTWARE. */
30 #include "hfile_internal.h"
32 #include "htslib/knetfile.h"
39 static int net_inited
= 0;
42 static void net_exit(void)
48 static int net_init(void)
51 if (knet_win32_init() != 0) return -1;
53 // In the unlikely event atexit() fails, it's better to succeed here and
54 // carry on and do the I/O; then eventually when the program exits, we'll
55 // merely have failed to clean up properly, as if we had aborted.
56 (void) atexit(net_exit
);
63 static ssize_t
net_read(hFILE
*fpv
, void *buffer
, size_t nbytes
)
65 hFILE_net
*fp
= (hFILE_net
*) fpv
;
66 return knet_read(fp
->netfp
, buffer
, nbytes
);
69 static off_t
net_seek(hFILE
*fpv
, off_t offset
, int whence
)
71 hFILE_net
*fp
= (hFILE_net
*) fpv
;
72 return knet_seek(fp
->netfp
, offset
, whence
);
75 static int net_close(hFILE
*fpv
)
77 hFILE_net
*fp
= (hFILE_net
*) fpv
;
78 return knet_close(fp
->netfp
);
81 static const struct hFILE_backend net_backend
=
83 net_read
, NULL
, net_seek
, NULL
, net_close
86 hFILE
*hopen_net(const char *filename
, const char *mode
)
90 // Do any networking initialisation if this is the first use.
91 if (! net_inited
) { if (net_init() < 0) return NULL
; }
93 fp
= (hFILE_net
*) hfile_init(sizeof (hFILE_net
), mode
, 0);
94 if (fp
== NULL
) return NULL
;
96 fp
->netfp
= knet_open(filename
, mode
);
97 if (fp
->netfp
== NULL
) { hfile_destroy((hFILE
*) fp
); return NULL
; }
99 fp
->base
.backend
= &net_backend
;
103 int hfile_plugin_init_net(struct hFILE_plugin
*self
)
105 static const struct hFILE_scheme_handler handler
=
106 { hopen_net
, hfile_always_remote
, "knetfile", 0 };
108 self
->name
= "knetfile";
109 hfile_add_scheme_handler("http", &handler
);
110 hfile_add_scheme_handler("ftp", &handler
);