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