1/* fetch.c - routines for fetching data at URLs */
2/* $OpenLDAP: pkg/ldap/libraries/liblutil/fetch.c,v 1.10.2.7 2010/04/13 20:23:05 kurt Exp $ */
3/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 *
5 * Copyright 1999-2010 The OpenLDAP Foundation.
6 * Portions Copyright 1999-2003 Kurt D. Zeilenga.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
11 * Public License.
12 *
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
16 */
17/* This work was initially developed by Kurt D. Zeilenga for
18 * inclusion in OpenLDAP Software.
19 */
20
21#include "portable.h"
22
23#include <stdio.h>
24
25#include <ac/stdlib.h>
26
27#include <ac/string.h>
28#include <ac/socket.h>
29#include <ac/time.h>
30
31#ifdef HAVE_FETCH
32#include <fetch.h>
33#endif
34
35#include "ldap_log.h"
36#include "lber_pvt.h"
37#include "ldap_pvt.h"
38#include "ldap_config.h"
39#include "ldif.h"
40
41FILE *
42ldif_open_url(
43	LDAP_CONST char *urlstr )
44{
45	FILE *url;
46
47	if( strncasecmp( "file:", urlstr, sizeof("file:")-1 ) == 0 ) {
48		char *p;
49		urlstr += sizeof("file:")-1;
50
51		/* we don't check for LDAP_DIRSEP since URLs should contain '/' */
52		if ( urlstr[0] == '/' && urlstr[1] == '/' ) {
53			urlstr += 2;
54			/* path must be absolute if authority is present */
55			if ( urlstr[0] != '/' )
56				return NULL;
57		}
58
59		p = ber_strdup( urlstr );
60
61		/* But we should convert to LDAP_DIRSEP before use */
62		if ( LDAP_DIRSEP[0] != '/' ) {
63			char *s = p;
64			while (( s = strchr( s, '/' )))
65				*s++ = LDAP_DIRSEP[0];
66		}
67
68		ldap_pvt_hex_unescape( p );
69
70		url = fopen( p, "rb" );
71
72		ber_memfree( p );
73	} else {
74#ifdef HAVE_FETCH
75		url = fetchGetURL( (char*) urlstr, "" );
76#else
77		url = NULL;
78#endif
79	}
80	return url;
81}
82
83int
84ldif_fetch_url(
85    LDAP_CONST char	*urlstr,
86    char	**valuep,
87    ber_len_t *vlenp )
88{
89	FILE *url;
90	char buffer[1024];
91	char *p = NULL;
92	size_t total;
93	size_t bytes;
94
95	*valuep = NULL;
96	*vlenp = 0;
97
98	url = ldif_open_url( urlstr );
99
100	if( url == NULL ) {
101		return -1;
102	}
103
104	total = 0;
105
106	while( (bytes = fread( buffer, 1, sizeof(buffer), url )) != 0 ) {
107		char *newp = ber_memrealloc( p, total + bytes + 1 );
108		if( newp == NULL ) {
109			ber_memfree( p );
110			fclose( url );
111			return -1;
112		}
113		p = newp;
114		AC_MEMCPY( &p[total], buffer, bytes );
115		total += bytes;
116	}
117
118	fclose( url );
119
120	if( total == 0 ) {
121		char *newp = ber_memrealloc( p, 1 );
122		if( newp == NULL ) {
123			ber_memfree( p );
124			return -1;
125		}
126		p = newp;
127	}
128
129	p[total] = '\0';
130	*valuep = p;
131	*vlenp = total;
132
133	return 0;
134}
135