1 /*
2 Author: James Bonfield
3 
4 Copyright (c) 2000-2001 MEDICAL RESEARCH COUNCIL
5 All rights reserved
6 
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9 
10    1. Redistributions of source code must retain the above copyright notice,
11 this list of conditions and the following disclaimer.
12 
13    2. Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
16 
17    3. Neither the name of the MEDICAL RESEARCH COUNCIL, THE LABORATORY OF
18 MOLECULAR BIOLOGY nor the names of its contributors may be used to endorse or
19 promote products derived from this software without specific prior written
20 permission.
21 
22 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
23 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
26 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
29 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 
34 /*
35 Copyright (c) 2008, 2009, 2013, 2014 Genome Research Ltd.
36 Author: James Bonfield <jkb@sanger.ac.uk>
37 
38 Redistribution and use in source and binary forms, with or without
39 modification, are permitted provided that the following conditions are met:
40 
41    1. Redistributions of source code must retain the above copyright notice,
42 this list of conditions and the following disclaimer.
43 
44    2. Redistributions in binary form must reproduce the above copyright notice,
45 this list of conditions and the following disclaimer in the documentation
46 and/or other materials provided with the distribution.
47 
48    3. Neither the names Genome Research Ltd and Wellcome Trust Sanger
49 Institute nor the names of its contributors may be used to endorse or promote
50 products derived from this software without specific prior written permission.
51 
52 THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS "AS IS" AND
53 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
54 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
55 DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH LTD OR CONTRIBUTORS BE LIABLE
56 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
58 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
59 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
60 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
61 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62 */
63 
64 #include <config.h>
65 
66 #include <stdlib.h>
67 #include <stdio.h>
68 #include <string.h>
69 #include <unistd.h>
70 #include <limits.h>
71 #include <errno.h>
72 #include <sys/types.h>
73 #include <sys/stat.h>
74 #include "cram/os.h"
75 #ifndef PATH_MAX
76 #  define PATH_MAX 1024
77 #endif
78 
79 #include "cram/open_trace_file.h"
80 #include "cram/misc.h"
81 #include "htslib/hfile.h"
82 #include "htslib/hts_log.h"
83 
84 /*
85  * Tokenises the search path splitting on colons (unix) or semicolons
86  * (windows).
87  * We also  explicitly add a "./" to the end of the search path
88  *
89  * Returns: A new search path with items separated by nul chars. Two nul
90  *          chars in a row represent the end of the tokenised path.
91  * Returns NULL for a failure.
92  *
93  * The returned data has been malloced. It is up to the caller to free this
94  * memory.
95  */
tokenise_search_path(char * searchpath)96 char *tokenise_search_path(char *searchpath) {
97     char *newsearch;
98     unsigned int i, j;
99     size_t len;
100 #ifdef _WIN32
101     char path_sep = ';';
102 #else
103     char path_sep = ':';
104 #endif
105 
106     if (!searchpath)
107         searchpath="";
108 
109     newsearch = (char *)malloc((len = strlen(searchpath))+5);
110     if (!newsearch)
111         return NULL;
112 
113     for (i = 0, j = 0; i < len; i++) {
114         /* "::" => ":". Used for escaping colons in http://foo */
115         if (i < len-1 && searchpath[i] == ':' && searchpath[i+1] == ':') {
116             newsearch[j++] = ':';
117             i++;
118             continue;
119         }
120 
121         /* Handle http:// and ftp:// too without :: */
122         if (path_sep == ':') {
123             if ((i == 0 || (i > 0 && searchpath[i-1] == ':')) &&
124                 (!strncmp(&searchpath[i], "http:",     5) ||
125                  !strncmp(&searchpath[i], "https:",    6) ||
126                  !strncmp(&searchpath[i], "ftp:",      4) ||
127                  !strncmp(&searchpath[i], "|http:",    6) ||
128                  !strncmp(&searchpath[i], "|https:",   7) ||
129                  !strncmp(&searchpath[i], "|ftp:",     5) ||
130                  !strncmp(&searchpath[i], "URL=http:", 9) ||
131                  !strncmp(&searchpath[i], "URL=https:",10)||
132                  !strncmp(&searchpath[i], "URL=ftp:",  8))) {
133                 do {
134                     newsearch[j++] = searchpath[i];
135                 } while (i<len && searchpath[i++] != ':');
136                 if (searchpath[i] == ':')
137                     i++;
138                 if (searchpath[i]=='/')
139                     newsearch[j++] = searchpath[i++];
140                 if (searchpath[i]=='/')
141                     newsearch[j++] = searchpath[i++];
142                 // Look for host:port
143                 do {
144                     newsearch[j++] = searchpath[i++];
145                 } while (i<len && searchpath[i] != ':' && searchpath[i] != '/');
146                 newsearch[j++] = searchpath[i++];
147                 if (searchpath[i] == ':')
148                     i++;
149             }
150         }
151 
152         if (searchpath[i] == path_sep) {
153             /* Skip blank path components */
154             if (j && newsearch[j-1] != 0)
155                 newsearch[j++] = 0;
156         } else {
157             newsearch[j++] = searchpath[i];
158         }
159     }
160 
161     if (j)
162         newsearch[j++] = 0;
163     newsearch[j++] = '.';
164     newsearch[j++] = '/';
165     newsearch[j++] = 0;
166     newsearch[j++] = 0;
167 
168     return newsearch;
169 }
170 
find_file_url(char * file,char * url)171 mFILE *find_file_url(char *file, char *url) {
172     char buf[8192], *cp;
173     mFILE *mf = NULL;
174     int maxlen = 8190 - strlen(file), len;
175     hFILE *hf;
176 
177     /* Expand %s for the trace name */
178     for (cp = buf; *url && cp - buf < maxlen; url++) {
179         if (*url == '%' && *(url+1) == 's') {
180             url++;
181             cp += strlen(strcpy(cp, file));
182         } else {
183             *cp++ = *url;
184         }
185     }
186     *cp++ = 0;
187 
188     if (!(hf = hopen(buf, "r"))) {
189         if (errno != ENOENT)
190             hts_log_warning("Failed to open reference \"%s\": %s", buf, strerror(errno));
191         return NULL;
192     }
193 
194     if (NULL == (mf = mfcreate(NULL, 0)))
195         return NULL;
196     while ((len = hread(hf, buf, 8192)) > 0) {
197         if (mfwrite(buf, len, 1, mf) <= 0) {
198             hclose_abruptly(hf);
199             mfdestroy(mf);
200             return NULL;
201         }
202     }
203     if (hclose(hf) < 0 || len < 0) {
204         mfdestroy(mf);
205         return NULL;
206     }
207 
208     mrewind(mf);
209     return mf;
210 }
211 
212 /*
213  * Takes a dirname possibly including % rules and appends the filename
214  * to it.
215  *
216  * Returns expanded pathname or NULL for malloc failure.
217  */
expand_path(char * file,char * dirname)218 static char *expand_path(char *file, char *dirname) {
219     size_t len = strlen(dirname);
220     size_t lenf = strlen(file);
221     char *cp, *path;
222 
223     path = malloc(len+lenf+2); // worst expansion DIR/FILE
224     if (!path)
225         return NULL;
226 
227     if (dirname[len-1] == '/')
228         len--;
229 
230     /* Special case for "./" or absolute filenames */
231     if (*file == '/' || (len==1 && *dirname == '.')) {
232         sprintf(path, "%s", file);
233     } else {
234         /* Handle %[0-9]*s expansions, if required */
235         char *path_end = path;
236         *path = 0;
237         while ((cp = strchr(dirname, '%'))) {
238             char *endp;
239             long l = strtol(cp+1, &endp, 10);
240             if (*endp != 's') {
241                 strncpy(path_end, dirname, (endp+1)-dirname);
242                 path_end += (endp+1)-dirname;
243                 dirname = endp+1;
244                 continue;
245             }
246 
247             strncpy(path_end, dirname, cp-dirname);
248             path_end += cp-dirname;
249             if (l) {
250                 strncpy(path_end, file, l);
251                 path_end += MIN(strlen(file), l);
252                 file     += MIN(strlen(file), l);
253             } else {
254                 strcpy(path_end, file);
255                 path_end += strlen(file);
256                 file     += strlen(file);
257             }
258             len -= (endp+1) - dirname;
259             dirname = endp+1;
260         }
261         strncpy(path_end, dirname, len);
262         path_end += MIN(strlen(dirname), len);
263         *path_end = 0;
264         if (*file) {
265             *path_end++ = '/';
266             strcpy(path_end, file);
267         }
268     }
269 
270     //fprintf(stderr, "*PATH=\"%s\"\n", path);
271     return path;
272 }
273 
274 /*
275  * Searches for file in the directory 'dirname'. If it finds it, it opens
276  * it. This also searches for compressed versions of the file in dirname
277  * too.
278  *
279  * Returns mFILE pointer if found
280  *         NULL if not
281  */
find_file_dir(char * file,char * dirname)282 static mFILE *find_file_dir(char *file, char *dirname) {
283     char *path;
284     mFILE *mf = NULL;
285 
286     path = expand_path(file, dirname);
287 
288     if (is_file(path))
289         mf = mfopen(path, "rbm");
290 
291     free(path);
292     return mf;
293 }
294 
295 /*
296  * ------------------------------------------------------------------------
297  * Public functions below.
298  */
299 
300 /*
301  * Opens a trace file named 'file'. This is initially looked for as a
302  * pathname relative to a file named "relative_to". This may (for
303  * example) be the name of an experiment file referencing the trace
304  * file. In this case by passing relative_to as the experiment file
305  * filename the trace file will be picked up in the same directory as
306  * the experiment file. Relative_to may be supplied as NULL.
307  *
308  * 'file' is looked for at relative_to, then the current directory, and then
309  * all of the locations listed in 'path' (which is a colon separated list).
310  * If 'path' is NULL it uses the RAWDATA environment variable instead.
311  *
312  * Returns a mFILE pointer when found.
313  *           NULL otherwise.
314  */
open_path_mfile(char * file,char * path,char * relative_to)315 mFILE *open_path_mfile(char *file, char *path, char *relative_to) {
316     char *newsearch;
317     char *ele;
318     mFILE *fp;
319 
320     /* Use path first */
321     if (!path)
322         path = getenv("RAWDATA");
323     if (NULL == (newsearch = tokenise_search_path(path)))
324         return NULL;
325 
326     /*
327      * Step through the search path testing out each component.
328      * We now look through each path element treating some prefixes as
329      * special, otherwise we treat the element as a directory.
330      */
331     for (ele = newsearch; *ele; ele += strlen(ele)+1) {
332         char *ele2;
333 
334         /*
335          * '|' prefixing a path component indicates that we do not
336          * wish to perform the compression extension searching in that
337          * location.
338          *
339          * NB: this has been removed from the htslib implementation.
340          */
341         if (*ele == '|') {
342             ele2 = ele+1;
343         } else {
344             ele2 = ele;
345         }
346 
347         if (0 == strncmp(ele2, "URL=", 4)) {
348             if ((fp = find_file_url(file, ele2+4))) {
349                 free(newsearch);
350                 return fp;
351             }
352         } else if (!strncmp(ele2, "http:", 5) ||
353                    !strncmp(ele2, "https:", 6) ||
354                    !strncmp(ele2, "ftp:", 4)) {
355             if ((fp = find_file_url(file, ele2))) {
356                 free(newsearch);
357                 return fp;
358             }
359         } else if ((fp = find_file_dir(file, ele2))) {
360             free(newsearch);
361             return fp;
362         }
363     }
364 
365     free(newsearch);
366 
367     /* Look in the same location as the incoming 'relative_to' filename */
368     if (relative_to) {
369         char *cp;
370         char relative_path[PATH_MAX+1];
371         strcpy(relative_path, relative_to);
372         if ((cp = strrchr(relative_path, '/')))
373             *cp = 0;
374         if ((fp = find_file_dir(file, relative_path)))
375             return fp;
376     }
377 
378     return NULL;
379 }
380 
381 
382 /*
383  * As per open_path_mfile, but searching only for local filenames.
384  * This is useful as we may avoid doing a full mfopen and loading
385  * the entire file into memory.
386  *
387  * Returns the expanded pathname if found.
388  *         NULL if not
389  */
find_path(char * file,char * path)390 char *find_path(char *file, char *path) {
391     char *newsearch;
392     char *ele;
393     char *outpath = NULL;
394 
395     /* Use path first */
396     if (!path)
397         path = getenv("RAWDATA");
398     if (NULL == (newsearch = tokenise_search_path(path)))
399         return NULL;
400 
401     for (ele = newsearch; *ele; ele += strlen(ele)+1) {
402         char *ele2 = (*ele == '|') ? ele+1 : ele;
403 
404         if (!strncmp(ele2, "URL=", 4) ||
405             !strncmp(ele2, "http:", 5) ||
406             !strncmp(ele2, "https:", 6) ||
407             !strncmp(ele2, "ftp:", 4)) {
408             continue;
409         } else {
410             outpath = expand_path(file, ele2);
411             if (is_file(outpath)) {
412                 free(newsearch);
413                 return outpath;
414             } else {
415                 free(outpath);
416             }
417         }
418     }
419 
420     free(newsearch);
421 
422     return NULL;
423 }
424