Exemplo n.º 1
0
/*
 * Return the first host and port in hostlist (setting *hostp and *portp).
 * Return value is an LDAP API error code (LDAP_SUCCESS if all goes well).
 * Note that a NULL or zero-length hostlist causes the host "127.0.0.1" to
 * be returned.
 */
int LDAP_CALL
ldap_x_hostlist_first( const char *hostlist, int defport, char **hostp,
    int *portp, struct ldap_x_hostlist_status **statusp )
{

	if ( NULL == hostp || NULL == portp || NULL == statusp ) {
		return( LDAP_PARAM_ERROR );
	}

	if ( NULL == hostlist || *hostlist == '\0' ) {
		*hostp = nsldapi_strdup( "127.0.0.1" );
		if ( NULL == *hostp ) {
			return( LDAP_NO_MEMORY );
		}
		*portp = defport;
		*statusp = NULL;
		return( LDAP_SUCCESS );
	}

	*statusp = NSLDAPI_CALLOC( 1, sizeof( struct ldap_x_hostlist_status ));
	if ( NULL == *statusp ) {
		return( LDAP_NO_MEMORY );
	}
	(*statusp)->lhs_hostlist = nsldapi_strdup( hostlist );
	if ( NULL == (*statusp)->lhs_hostlist ) {
		return( LDAP_NO_MEMORY );
	}
	(*statusp)->lhs_nexthost = (*statusp)->lhs_hostlist;
	(*statusp)->lhs_defport = defport;
	return( ldap_x_hostlist_next( hostp, portp, *statusp ));
}
Exemplo n.º 2
0
/*
 * Return the next host and port in hostlist (setting *hostp and *portp).
 * Return value is an LDAP API error code (LDAP_SUCCESS if all goes well).
 * If no more hosts are available, LDAP_SUCCESS is returned but *hostp is set
 * to NULL.
 */
int LDAP_CALL ldap_x_hostlist_next(char **hostp, int *portp,
                                   struct ldap_x_hostlist_status *status) {
  char *q;
  int squarebrackets = 0;

  if (NULL == hostp || NULL == portp) {
    return (LDAP_PARAM_ERROR);
  }

  if (NULL == status || NULL == status->lhs_nexthost) {
    *hostp = NULL;
    return (LDAP_SUCCESS);
  }

  /*
   * skip past leading '[' if present (IPv6 addresses may be surrounded
   * with square brackets, e.g., [fe80::a00:20ff:fee5:c0b4]:389
   */
  if (status->lhs_nexthost[0] == '[') {
    ++status->lhs_nexthost;
    squarebrackets = 1;
  }

  /* copy host into *hostp */
  if (NULL != (q = strchr(status->lhs_nexthost, ' '))) {
    size_t len = q - status->lhs_nexthost;
    *hostp = NSLDAPI_MALLOC(len + 1);
    if (NULL == *hostp) {
      return (LDAP_NO_MEMORY);
    }
    strncpy(*hostp, status->lhs_nexthost, len);
    (*hostp)[len] = '\0';
    status->lhs_nexthost += (len + 1);
  } else { /* last host */
    *hostp = nsldapi_strdup(status->lhs_nexthost);
    if (NULL == *hostp) {
      return (LDAP_NO_MEMORY);
    }
    status->lhs_nexthost = NULL;
  }

  /*
   * Look for closing ']' and skip past it before looking for port.
   */
  if (squarebrackets && NULL != (q = strchr(*hostp, ']'))) {
    *q++ = '\0';
  } else {
    q = *hostp;
  }

  /* determine and set port */
  if (NULL != (q = strchr(q, ':'))) {
    *q++ = '\0';
    *portp = atoi(q);
  } else {
    *portp = status->lhs_defport;
  }

  return (LDAP_SUCCESS);
}
Exemplo n.º 3
0
/* returns 0 if connection opened and -1 if an error occurs */
int
nsldapi_open_ldap_defconn( LDAP *ld )
{
	LDAPServer	*srv;

	if (( srv = (LDAPServer *)NSLDAPI_CALLOC( 1, sizeof( LDAPServer ))) ==
	    NULL || ( ld->ld_defhost != NULL && ( srv->lsrv_host =
	    nsldapi_strdup( ld->ld_defhost )) == NULL )) {
		LDAP_SET_LDERRNO( ld, LDAP_NO_MEMORY, NULL, NULL );
		return( -1 );
	}
	srv->lsrv_port = ld->ld_defport;

#ifdef LDAP_SSLIO_HOOKS
	if (( ld->ld_options & LDAP_BITOPT_SSL ) != 0 ) {
		srv->lsrv_options |= LDAP_SRV_OPT_SECURE;
	}
#endif

	if (( ld->ld_defconn = nsldapi_new_connection( ld, &srv, 1, 1, 0 ))
	    == NULL ) {
		if ( ld->ld_defhost != NULL ) {
			NSLDAPI_FREE( srv->lsrv_host );
		}
		NSLDAPI_FREE( (char *)srv );
		return( -1 );
	}
	++ld->ld_defconn->lconn_refcnt;	/* so it never gets closed/freed */

	return( 0 );
}
Exemplo n.º 4
0
/*
 * duplicate the contents of "ctrl_src" and place in "ctrl_dst"
 */
static int
/* LDAP_CALL */		/* keep this routine internal for now */
ldap_control_copy_contents( LDAPControl *ctrl_dst, LDAPControl *ctrl_src )
{
	size_t	len;

	if ( NULL == ctrl_dst || NULL == ctrl_src ) {
		return( LDAP_PARAM_ERROR );
	}

	ctrl_dst->ldctl_iscritical = ctrl_src->ldctl_iscritical;

	/* fill in the fields of this new control */
	if (( ctrl_dst->ldctl_oid = nsldapi_strdup( ctrl_src->ldctl_oid ))
	    == NULL ) {
		return( LDAP_NO_MEMORY );
	}

	len = (size_t)(ctrl_src->ldctl_value).bv_len;
	if ( ctrl_src->ldctl_value.bv_val == NULL || len <= 0 ) {
		ctrl_dst->ldctl_value.bv_len = 0;
		ctrl_dst->ldctl_value.bv_val = NULL;
	} else {
		ctrl_dst->ldctl_value.bv_len = len;
		if (( ctrl_dst->ldctl_value.bv_val = NSLDAPI_MALLOC( len ))
		    == NULL ) {
			NSLDAPI_FREE( ctrl_dst->ldctl_oid );
			return( LDAP_NO_MEMORY );
		}
		SAFEMEMCPY( ctrl_dst->ldctl_value.bv_val,
		    ctrl_src->ldctl_value.bv_val, len );
	}

	return ( LDAP_SUCCESS );
}
Exemplo n.º 5
0
LDAP_CALL
ldap_getfirstfilter( LDAPFiltDesc *lfdp, char *tagpat, char *value )
{
    LDAPFiltList	*flp;

    if ( lfdp == NULL || tagpat == NULL || value == NULL ) {
	return( NULL );	/* punt */
    }

    if ( lfdp->lfd_curvalcopy != NULL ) {
	NSLDAPI_FREE( lfdp->lfd_curvalcopy );
	NSLDAPI_FREE( lfdp->lfd_curvalwords );
    }

    NSLDAPI_FREE(lfdp->lfd_curval);
    if ((lfdp->lfd_curval = nsldapi_strdup(value)) == NULL) {
	return( NULL );
    }

    lfdp->lfd_curfip = NULL;

    for ( flp = lfdp->lfd_filtlist; flp != NULL; flp = flp->lfl_next ) {
	if ( re_comp( tagpat ) == NULL && re_exec( flp->lfl_tag ) == 1
		&& re_comp( flp->lfl_pattern ) == NULL
		&& re_exec( lfdp->lfd_curval ) == 1 ) {
	    lfdp->lfd_curfip = flp->lfl_ilist;
	    break;
	}
    }

    if ( lfdp->lfd_curfip == NULL ) {
	return( NULL );
    }

    if (( lfdp->lfd_curvalcopy = nsldapi_strdup( value )) == NULL ) {
	return( NULL );
    }

    if ( break_into_words( lfdp->lfd_curvalcopy, flp->lfl_delims,
		&lfdp->lfd_curvalwords ) < 0 ) {
	NSLDAPI_FREE( lfdp->lfd_curvalcopy );
	lfdp->lfd_curvalcopy = NULL;
	return( NULL );
    }

    return( ldap_getnextfilter( lfdp ));
}
Exemplo n.º 6
0
int LDAP_CALL ldap_set_filter_additions(LDAPFiltDesc *lfdp, char *prefix,
                                        char *suffix) {
  if (lfdp == NULL) {
    return (LDAP_PARAM_ERROR);
  }

  if (lfdp->lfd_filtprefix != NULL) {
    NSLDAPI_FREE(lfdp->lfd_filtprefix);
  }
  lfdp->lfd_filtprefix = (prefix == NULL) ? NULL : nsldapi_strdup(prefix);

  if (lfdp->lfd_filtsuffix != NULL) {
    NSLDAPI_FREE(lfdp->lfd_filtsuffix);
  }
  lfdp->lfd_filtsuffix = (suffix == NULL) ? NULL : nsldapi_strdup(suffix);

  return (LDAP_SUCCESS);
}
Exemplo n.º 7
0
static LBER_SOCKET
nsldapi_os_socket( LDAP *ld, int secure, int domain, int type, int protocol )
{
	int		s, invalid_socket;
	char		*errmsg = NULL;

	if ( secure ) {
		LDAP_SET_LDERRNO( ld, LDAP_LOCAL_ERROR, NULL,
			    nsldapi_strdup( dgettext(TEXT_DOMAIN,
				"secure mode not supported") ));
		return( -1 );
	}

	s = socket( domain, type, protocol );

	/*
	 * if the socket() call failed or it returned a socket larger
	 * than we can deal with, return a "local error."
	 */
	if ( NSLDAPI_INVALID_OS_SOCKET( s )) {
		errmsg = dgettext(TEXT_DOMAIN, "unable to create a socket");
		invalid_socket = 1;
	} else {	/* valid socket -- check for overflow */
		invalid_socket = 0;
#if !defined(NSLDAPI_HAVE_POLL) && !defined(_WINDOWS)
		/* not on Windows and do not have poll() */
		if ( s >= FD_SETSIZE ) {
			errmsg = "can't use socket >= FD_SETSIZE";
		}
#endif
	}

	if ( errmsg != NULL ) {	/* local socket error */
		if ( !invalid_socket ) {
			nsldapi_os_closesocket( s );
		}
		errmsg = nsldapi_strdup( errmsg );
		LDAP_SET_LDERRNO( ld, LDAP_LOCAL_ERROR, NULL, errmsg );
		return( -1 );
	}

	return( s );
}
Exemplo n.º 8
0
LDAP_CALL
ldap_explode_dns( const char *dn )
{
	int	ncomps, maxcomps;
	char	*s, *cpydn;
	char	**rdns;
#ifdef HAVE_STRTOK_R	/* defined in portable.h */
	char	*lasts;
#endif

	if ( dn == NULL ) {
		dn = "";
	}

	if ( (rdns = (char **)NSLDAPI_MALLOC( 8 * sizeof(char *) )) == NULL ) {
		return( NULL );
	}

	maxcomps = 8;
	ncomps = 0;
	cpydn = nsldapi_strdup( (char *)dn );
	for ( s = STRTOK( cpydn, "@.", &lasts ); s != NULL;
	    s = STRTOK( NULL, "@.", &lasts ) ) {
		if ( ncomps == maxcomps ) {
			maxcomps *= 2;
			if ( (rdns = (char **)NSLDAPI_REALLOC( rdns, maxcomps *
			    sizeof(char *) )) == NULL ) {
				NSLDAPI_FREE( cpydn );
				return( NULL );
			}
		}
		rdns[ncomps++] = nsldapi_strdup( s );
	}
	rdns[ncomps] = NULL;
	NSLDAPI_FREE( cpydn );

	return( rdns );
}
Exemplo n.º 9
0
/*
 * build an allocated LDAPv3 control.  Returns an LDAP error code.
 */
int
nsldapi_build_control( char *oid, BerElement *ber, int freeber, char iscritical,
    LDAPControl **ctrlp )
{
	int		rc;
	struct berval	*bvp;

	if ( ber == NULL ) {
		bvp = NULL;
	} else {
		/* allocate struct berval with contents of the BER encoding */
		rc = ber_flatten( ber, &bvp );
		if ( freeber ) {
			ber_free( ber, 1 );
		}
		if ( rc == -1 ) {
			return( LDAP_NO_MEMORY );
		}
	}

	/* allocate the new control structure */
	if (( *ctrlp = (LDAPControl *)NSLDAPI_MALLOC( sizeof(LDAPControl)))
	    == NULL ) {
		if ( bvp != NULL ) {
			ber_bvfree( bvp );
		}
		return( LDAP_NO_MEMORY );
	}

	/* fill in the fields of this new control */
	(*ctrlp)->ldctl_iscritical = iscritical;  
	if (( (*ctrlp)->ldctl_oid = nsldapi_strdup( oid )) == NULL ) {
		NSLDAPI_FREE( *ctrlp ); 
		if ( bvp != NULL ) {
			ber_bvfree( bvp );
		}
		return( LDAP_NO_MEMORY );
	}				

	if ( bvp == NULL ) {
		(*ctrlp)->ldctl_value.bv_len = 0;
		(*ctrlp)->ldctl_value.bv_val = NULL;
	} else {
		(*ctrlp)->ldctl_value = *bvp;	/* struct copy */
		NSLDAPI_FREE( bvp );	/* free container, not contents! */
	}

	return( LDAP_SUCCESS );
}
Exemplo n.º 10
0
LDAP_CALL
ldap_dn2ufn( const char *dn )
{
	char	*p, *ufn, *r;
	size_t	plen;
	int	state;

	LDAPDebug( LDAP_DEBUG_TRACE, "ldap_dn2ufn\n", 0, 0, 0 );

	if ( dn == NULL ) {
		dn = "";
	}

	if ( ldap_is_dns_dn( dn ) || ( p = strchr( dn, '=' )) == NULL )
		return( nsldapi_strdup( (char *)dn ));

	ufn = nsldapi_strdup( ++p );

#define INQUOTE		1
#define OUTQUOTE	2
	state = OUTQUOTE;
	for ( p = ufn, r = ufn; *p; p += plen ) {
	    plen = 1;
		switch ( *p ) {
		case '\\':
			if ( *++p == '\0' )
				plen=0;
			else {
				*r++ = '\\';
				r += (plen = LDAP_UTF8COPY(r,p));
			}
			break;
		case '"':
			if ( state == INQUOTE )
				state = OUTQUOTE;
			else
				state = INQUOTE;
			*r++ = *p;
			break;
		case ';':
		case ',':
			if ( state == OUTQUOTE )
				*r++ = ',';
			else
				*r++ = *p;
			break;
		case '=':
			if ( state == INQUOTE )
				*r++ = *p;
			else {
				char	*rsave = r;
				LDAP_UTF8DEC(r);
				*rsave = '\0';
				while ( !ldap_utf8isspace( r ) && *r != ';'
				    && *r != ',' && r > ufn )
					LDAP_UTF8DEC(r);
				LDAP_UTF8INC(r);

				if ( strcasecmp( r, "c" )
				    && strcasecmp( r, "o" )
				    && strcasecmp( r, "ou" )
				    && strcasecmp( r, "st" )
				    && strcasecmp( r, "l" )
				    && strcasecmp( r, "dc" )
				    && strcasecmp( r, "uid" )
				    && strcasecmp( r, "cn" ) ) {
					r = rsave;
					*r++ = '=';
				}
			}
			break;
		default:
			r += (plen = LDAP_UTF8COPY(r,p));
			break;
		}
	}
	*r = '\0';

	return( ufn );
}
Exemplo n.º 11
0
/* returns an LDAP error code and also sets it in ld */
int
nsldapi_build_search_req(
    LDAP		*ld, 
    const char		*base, 
    int			scope, 
    const char		*filter,
    char		**attrs, 
    int			attrsonly,
    LDAPControl		**serverctrls,
    LDAPControl		**clientctrls,	/* not used for anything yet */
    int			timelimit,	/* if -1, ld->ld_timelimit is used */
    int			sizelimit,	/* if -1, ld->ld_sizelimit is used */
    int			msgid,
    BerElement		**berp
)
{
	BerElement	*ber;
	int		err;
	char		*fdup;

	/*
	 * Create the search request.  It looks like this:
	 *	SearchRequest := [APPLICATION 3] SEQUENCE {
	 *		baseObject	DistinguishedName,
	 *		scope		ENUMERATED {
	 *			baseObject	(0),
	 *			singleLevel	(1),
	 *			wholeSubtree	(2)
	 *		},
	 *		derefAliases	ENUMERATED {
	 *			neverDerefaliases	(0),
	 *			derefInSearching	(1),
	 *			derefFindingBaseObj	(2),
	 *			alwaysDerefAliases	(3)
	 *		},
	 *		sizelimit	INTEGER (0 .. 65535),
	 *		timelimit	INTEGER (0 .. 65535),
	 *		attrsOnly	BOOLEAN,
	 *		filter		Filter,
	 *		attributes	SEQUENCE OF AttributeType
	 *	}
	 * wrapped in an ldap message.
	 */

	/* create a message to send */
	if (( err = nsldapi_alloc_ber_with_options( ld, &ber ))
	    != LDAP_SUCCESS ) {
		return( err );
	}

	if ( base == NULL ) {
	    base = "";
	}

	if ( sizelimit == -1 ) {
	    sizelimit = ld->ld_sizelimit;
	}

	if ( timelimit == -1 ) {
	    timelimit = ld->ld_timelimit;
	}

#ifdef CLDAP
	if ( ld->ld_sbp->sb_naddr > 0 ) {
	    err = ber_printf( ber, "{ist{seeiib", msgid,
		ld->ld_cldapdn, LDAP_REQ_SEARCH, base, scope, ld->ld_deref,
		sizelimit, timelimit, attrsonly );
	} else {
#endif /* CLDAP */
		err = ber_printf( ber, "{it{seeiib", msgid,
		    LDAP_REQ_SEARCH, base, scope, ld->ld_deref,
		    sizelimit, timelimit, attrsonly );
#ifdef CLDAP
	}
#endif /* CLDAP */

	if ( err == -1 ) {
		LDAP_SET_LDERRNO( ld, LDAP_ENCODING_ERROR, NULL, NULL );
		ber_free( ber, 1 );
		return( LDAP_ENCODING_ERROR );
	}

	fdup = nsldapi_strdup( filter );
	err = put_filter( ber, fdup );
	NSLDAPI_FREE( fdup );

	if ( err == -1 ) {
		LDAP_SET_LDERRNO( ld, LDAP_FILTER_ERROR, NULL, NULL );
		ber_free( ber, 1 );
		return( LDAP_FILTER_ERROR );
	}

	if ( ber_printf( ber, "{v}}", attrs ) == -1 ) {
		LDAP_SET_LDERRNO( ld, LDAP_ENCODING_ERROR, NULL, NULL );
		ber_free( ber, 1 );
		return( LDAP_ENCODING_ERROR );
	}

	if ( (err = nsldapi_put_controls( ld, serverctrls, 1, ber ))
	    != LDAP_SUCCESS ) {
		ber_free( ber, 1 );
		return( err );
	}

	*berp = ber;
	return( LDAP_SUCCESS );
}
Exemplo n.º 12
0
static int
put_simple_filter( BerElement *ber, char *str )
{
	char		*s, *s2, *s3, filterop;
	char		*value;
	unsigned long	ftype;
	int		rc, len;
	char		*oid;	/* for v3 extended filter */
	int		dnattr;	/* for v3 extended filter */

	LDAPDebug( LDAP_DEBUG_TRACE, "put_simple_filter \"%s\"\n", str, 0, 0 );

	rc = -1;	/* pessimistic */

	if (( str = nsldapi_strdup( str )) == NULL ) {
		return( rc );
	}

	if ( (s = strchr( str, '=' )) == NULL ) {
		goto free_and_return;
	}
	value = s + 1;
	*s-- = '\0';
	filterop = *s;
	if ( filterop == '<' || filterop == '>' || filterop == '~' ||
	    filterop == ':' ) {
		*s = '\0';
	}

	if ( ! is_valid_attr( str ) ) {
		goto free_and_return;
	}

	switch ( filterop ) {
	case '<':
		ftype = LDAP_FILTER_LE;
		break;
	case '>':
		ftype = LDAP_FILTER_GE;
		break;
	case '~':
		ftype = LDAP_FILTER_APPROX;
		break;
	case ':':	/* extended filter - v3 only */
		/*
		 * extended filter looks like this:
		 *
		 *	[type][':dn'][':'oid]':='value
		 *
		 * where one of type or :oid is required.
		 *
		 */
		ftype = LDAP_FILTER_EXTENDED;
		s2 = s3 = NULL;
		if ( (s2 = strrchr( str, ':' )) == NULL ) {
			goto free_and_return;
		}
		if ( strcasecmp( s2, ":dn" ) == 0 ) {
			oid = NULL;
			dnattr = 1;
			*s2 = '\0';
		} else {
			oid = s2 + 1;
			dnattr = 0;
			*s2 = '\0';
			if ( (s3 = strrchr( str, ':' )) != NULL ) {
				if ( strcasecmp( s3, ":dn" ) == 0 ) {
					dnattr = 1;
				} else {
					goto free_and_return;
				}
				*s3 = '\0';
			}
		}
		if ( (rc = ber_printf( ber, "t{", ftype )) == -1 ) {
			goto free_and_return;
		}
		if ( oid != NULL ) {
			if ( (rc = ber_printf( ber, "ts", LDAP_TAG_MRA_OID,
			    oid )) == -1 ) {
				goto free_and_return;
			}
		}
		if ( *str != '\0' ) {
			if ( (rc = ber_printf( ber, "ts",
			    LDAP_TAG_MRA_TYPE, str )) == -1 ) {
				goto free_and_return;
			}
		}
		if (( len = unescape_filterval( value )) < 0 ||
		    ( rc = ber_printf( ber, "totb}", LDAP_TAG_MRA_VALUE,
		    value, len, LDAP_TAG_MRA_DNATTRS, dnattr )) == -1 ) {
			goto free_and_return;
		}
		rc = 0;
		goto free_and_return;
		break;
	default:
		if ( find_star( value ) == NULL ) {
			ftype = LDAP_FILTER_EQUALITY;
		} else if ( strcmp( value, "*" ) == 0 ) {
			ftype = LDAP_FILTER_PRESENT;
		} else {
			rc = put_substring_filter( ber, str, value );
			goto free_and_return;
		}
		break;
	}

	if ( ftype == LDAP_FILTER_PRESENT ) {
		rc = ber_printf( ber, "ts", ftype, str );
	} else if (( len = unescape_filterval( value )) >= 0 ) {
		rc = ber_printf( ber, "t{so}", ftype, str, value, len );
	}
	if ( rc != -1 ) {
		rc = 0;
	}

free_and_return:
	NSLDAPI_FREE( str );
	return( rc );
}
Exemplo n.º 13
0
LDAP_CALL
ldap_init( const char *defhost, int defport )
{
	LDAP	*ld;

	if ( !nsldapi_initialized ) {
		nsldapi_initialize_defaults();
	}

	if ( defport < 0 || defport > LDAP_PORT_MAX ) {
	    LDAPDebug( LDAP_DEBUG_ANY,
		    "ldap_init: port %d is invalid (port numbers must range from 1 to %d)\n",
		    defport, LDAP_PORT_MAX, 0 );
#if !defined( macintosh ) && !defined( DOS )
	    errno = EINVAL;
#endif
	    return( NULL );
	}

	LDAPDebug( LDAP_DEBUG_TRACE, "ldap_init\n", 0, 0, 0 );

	if ( (ld = (LDAP*)NSLDAPI_MALLOC( sizeof(struct ldap) )) == NULL ) {
		return( NULL );
	}

	/* copy defaults */
	SAFEMEMCPY( ld, &nsldapi_ld_defaults, sizeof( struct ldap ));
	if ( nsldapi_ld_defaults.ld_io_fns_ptr != NULL ) {
		if (( ld->ld_io_fns_ptr = (struct ldap_io_fns *)NSLDAPI_MALLOC(
		    sizeof( struct ldap_io_fns ))) == NULL ) {
			NSLDAPI_FREE( (char *)ld );
			return( NULL );
		}
		/* struct copy */
		*(ld->ld_io_fns_ptr) = *(nsldapi_ld_defaults.ld_io_fns_ptr);
	}

	/* call the new handle I/O callback if one is defined */
	if ( ld->ld_extnewhandle_fn != NULL ) {
		/*
		 * We always pass the session extended I/O argument to
		 * the new handle callback.
		 */
		if ( ld->ld_extnewhandle_fn( ld, ld->ld_ext_session_arg )
		    != LDAP_SUCCESS ) {
			NSLDAPI_FREE( (char*)ld );
			return( NULL );
		}
	}

	/* allocate session-specific resources */
	if (( ld->ld_sbp = ber_sockbuf_alloc()) == NULL ||
	    ( defhost != NULL &&
	    ( ld->ld_defhost = nsldapi_strdup( defhost )) == NULL ) ||
	    ((ld->ld_mutex = (void **) NSLDAPI_CALLOC( LDAP_MAX_LOCK, sizeof(void *))) == NULL )) {
		if ( ld->ld_sbp != NULL ) {
			ber_sockbuf_free( ld->ld_sbp );
		}
		if( ld->ld_mutex != NULL ) {
			NSLDAPI_FREE( ld->ld_mutex );
		}
		NSLDAPI_FREE( (char*)ld );
		return( NULL );
	}

	/* install Sockbuf I/O functions if set in LDAP * */
	if ( ld->ld_extread_fn != NULL || ld->ld_extwrite_fn != NULL ) {
		struct lber_x_ext_io_fns lberiofns;

		memset( &lberiofns, 0, sizeof( lberiofns ));

		lberiofns.lbextiofn_size = LBER_X_EXTIO_FNS_SIZE;
		lberiofns.lbextiofn_read = ld->ld_extread_fn;
		lberiofns.lbextiofn_write = ld->ld_extwrite_fn;
		lberiofns.lbextiofn_writev = ld->ld_extwritev_fn;
		lberiofns.lbextiofn_socket_arg = NULL;
		ber_sockbuf_set_option( ld->ld_sbp, LBER_SOCKBUF_OPT_EXT_IO_FNS,
			(void *)&lberiofns );
	}

#ifdef _SOLARIS_SDK
	/* Install the functions for IPv6 support	*/
	/* code sequencing is critical from here to nsldapi_mutex_alloc_all */
        if ( prldap_install_thread_functions( ld, 1 ) != 0 ||
             prldap_install_io_functions( ld, 1 ) != 0 ||
             prldap_install_dns_functions( ld ) != 0 ) {
		/* go through ld and free resources */
		ldap_unbind( ld );
		ld = NULL;
		return( NULL );
        }
#else

	/* allocate mutexes */
	nsldapi_mutex_alloc_all( ld );
#endif

	/* set default port */
	ld->ld_defport = ( defport == 0 ) ? LDAP_PORT : defport;

	return( ld );
}
Exemplo n.º 14
0
/*
 * like ldap_url_parse() with a few exceptions:
 *   1) if dn_required is zero, a missing DN does not generate an error
 *	(we just leave the lud_dn field NULL)
 *   2) no defaults are set for lud_scope and lud_filter (they are set to -1
 *	and NULL respectively if no SCOPE or FILTER are present in the URL).
 *   3) when there is a zero-length DN in a URL we do not set lud_dn to NULL.
 *
 * note that LDAPv3 URL extensions are ignored unless they are marked
 * critical, in which case an LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION error
 * is returned.
 */
int
nsldapi_url_parse( const char *url, LDAPURLDesc **ludpp, int dn_required )
{

	LDAPURLDesc	*ludp;
	char		*urlcopy, *attrs, *scope, *extensions = NULL, *p, *q;
	int		enclosed, secure, i, nattrs, at_start;

	LDAPDebug( LDAP_DEBUG_TRACE, "nsldapi_url_parse(%s)\n", url, 0, 0 );

	if ( url == NULL || ludpp == NULL ) {
		return( LDAP_URL_ERR_PARAM );
	}

	*ludpp = NULL;	/* pessimistic */

	if ( !skip_url_prefix( &url, &enclosed, &secure )) {
		return( LDAP_URL_ERR_NOTLDAP );
	}

	/* allocate return struct */
	if (( ludp = (LDAPURLDesc *)NSLDAPI_CALLOC( 1, sizeof( LDAPURLDesc )))
	    == NULLLDAPURLDESC ) {
		return( LDAP_URL_ERR_MEM );
	}

	if ( secure ) {
		ludp->lud_options |= LDAP_URL_OPT_SECURE;
	}

	/* make working copy of the remainder of the URL */
	if (( urlcopy = nsldapi_strdup( url )) == NULL ) {
		ldap_free_urldesc( ludp );
		return( LDAP_URL_ERR_MEM );
	}

	if ( enclosed && *((p = urlcopy + strlen( urlcopy ) - 1)) == '>' ) {
		*p = '\0';
	}

	/* initialize scope and filter */
	ludp->lud_scope = -1;
	ludp->lud_filter = NULL;

	/* lud_string is the only malloc'd string space we use */
	ludp->lud_string = urlcopy;

	/* scan forward for '/' that marks end of hostport and begin. of dn */
	if (( ludp->lud_dn = strchr( urlcopy, '/' )) == NULL ) {
		if ( dn_required ) {
			ldap_free_urldesc( ludp );
			return( LDAP_URL_ERR_NODN );
		}
	} else {
		/* terminate hostport; point to start of dn */
		*ludp->lud_dn++ = '\0';
	}


	if ( *urlcopy == '\0' ) {
		ludp->lud_host = NULL;
	} else {
		ludp->lud_host = urlcopy;
		nsldapi_hex_unescape( ludp->lud_host );

		/*
		 * Locate and strip off optional port number (:#) in host
		 * portion of URL.
		 *
		 * If more than one space-separated host is listed, we only
		 * look for a port number within the right-most one since
		 * ldap_init() will handle host parameters that look like
		 * host:port anyway.
		 */
		if (( p = strrchr( ludp->lud_host, ' ' )) == NULL ) {
			p = ludp->lud_host;
		} else {
			++p;
		}
		if ( *p == '[' && ( q = strchr( p, ']' )) != NULL ) {
			 /* square brackets present -- skip past them */
			p = q++;
		}
		if (( p = strchr( p, ':' )) != NULL ) {
			*p++ = '\0';
			ludp->lud_port = atoi( p );
			if ( *ludp->lud_host == '\0' ) {
				ludp->lud_host = NULL;  /* no hostname */
			}
		}
	}

	/* scan for '?' that marks end of dn and beginning of attributes */
	attrs = NULL;
	if ( ludp->lud_dn != NULL &&
	    ( attrs = strchr( ludp->lud_dn, '?' )) != NULL ) {
		/* terminate dn; point to start of attrs. */
		*attrs++ = '\0';

		/* scan for '?' that marks end of attrs and begin. of scope */
		if (( p = strchr( attrs, '?' )) != NULL ) {
			/*
			 * terminate attrs; point to start of scope and scan for
			 * '?' that marks end of scope and begin. of filter
			 */
			*p++ = '\0';
			scope = p;

			if (( p = strchr( scope, '?' )) != NULL ) {
				/* terminate scope; point to start of filter */
				*p++ = '\0';
				if ( *p != '\0' ) {
					ludp->lud_filter = p;
					/*
					 * scan for the '?' that marks the end
					 * of the filter and the start of any
					 * extensions
					 */
					if (( p = strchr( ludp->lud_filter, '?' ))
					    != NULL ) {
						*p++ = '\0'; /* term. filter */
						extensions = p;
					}
					if ( *ludp->lud_filter == '\0' ) {
						ludp->lud_filter = NULL;
					} else {
						nsldapi_hex_unescape( ludp->lud_filter );
					}
				}
			}

			if ( strcasecmp( scope, "one" ) == 0 ) {
				ludp->lud_scope = LDAP_SCOPE_ONELEVEL;
			} else if ( strcasecmp( scope, "base" ) == 0 ) {
				ludp->lud_scope = LDAP_SCOPE_BASE;
			} else if ( strcasecmp( scope, "sub" ) == 0 ) {
				ludp->lud_scope = LDAP_SCOPE_SUBTREE;
			} else if ( *scope != '\0' ) {
				ldap_free_urldesc( ludp );
				return( LDAP_URL_ERR_BADSCOPE );
			}
		}
	}

	if ( ludp->lud_dn != NULL ) {
		nsldapi_hex_unescape( ludp->lud_dn );
	}

	/*
	 * if attrs list was included, turn it into a null-terminated array
	 */
	if ( attrs != NULL && *attrs != '\0' ) {
		nsldapi_hex_unescape( attrs );
		for ( nattrs = 1, p = attrs; *p != '\0'; ++p ) {
		    if ( *p == ',' ) {
			    ++nattrs;
		    }
		}

		if (( ludp->lud_attrs = (char **)NSLDAPI_CALLOC( nattrs + 1,
		    sizeof( char * ))) == NULL ) {
			ldap_free_urldesc( ludp );
			return( LDAP_URL_ERR_MEM );
		}

		for ( i = 0, p = attrs; i < nattrs; ++i ) {
			ludp->lud_attrs[ i ] = p;
			if (( p = strchr( p, ',' )) != NULL ) {
				*p++ ='\0';
			}
			nsldapi_hex_unescape( ludp->lud_attrs[ i ] );
		}
	}

	/* if extensions list was included, check for critical ones */
	if ( extensions != NULL && *extensions != '\0' ) {
		/* Note: at present, we do not recognize ANY extensions */
		at_start = 1;
		for ( p = extensions; *p != '\0'; ++p ) {
			if ( at_start ) {
				if ( *p == '!' ) {	/* critical extension */
					ldap_free_urldesc( ludp );
					return( LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION );
				}
				at_start = 0;
			} else if ( *p == ',' ) {
				at_start = 1;
			}
		}
	}

	*ludpp = ludp;

	return( 0 );
}
Exemplo n.º 15
0
/*
 * returns an LDAP error code
 *
 * XXXmcs: this function used to have #ifdef LDAP_DNS code in it but I
 *	removed it when I improved the parsing (we don't define LDAP_DNS
 *	here at Netscape).
 */
static int
chase_one_referral( LDAP *ld, LDAPRequest *lr, LDAPRequest *origreq,
    char *refurl, char *desc, int *unknownp )
{
	int		rc, tmprc, secure, msgid;
	LDAPServer	*srv;
	BerElement	*ber;
	LDAPURLDesc	*ludp;

	*unknownp = 0;
	ludp = NULLLDAPURLDESC;

	if ( nsldapi_url_parse( refurl, &ludp, 0 ) != 0 ) {
		LDAPDebug( LDAP_DEBUG_TRACE,
		    "ignoring unknown %s <%s>\n", desc, refurl, 0 );
		*unknownp = 1;
		rc = LDAP_SUCCESS;
		goto cleanup_and_return;
	}

	secure = (( ludp->lud_options & LDAP_URL_OPT_SECURE ) != 0 );

/* XXXmcs: can't tell if secure is supported by connect callback */
	if ( secure && ld->ld_extconnect_fn == NULL ) {
		LDAPDebug( LDAP_DEBUG_TRACE,
		    "ignoring LDAPS %s <%s>\n", desc, refurl, 0 );
		*unknownp = 1;
		rc = LDAP_SUCCESS;
		goto cleanup_and_return;
	}

	LDAPDebug( LDAP_DEBUG_TRACE, "chasing LDAP%s %s: <%s>\n",
	    secure ? "S" : "", desc, refurl );

	LDAP_MUTEX_LOCK( ld, LDAP_MSGID_LOCK );
	msgid = ++ld->ld_msgid;
	LDAP_MUTEX_UNLOCK( ld, LDAP_MSGID_LOCK );

	if (( tmprc = re_encode_request( ld, origreq->lr_ber, msgid,
	    ludp, &ber )) != LDAP_SUCCESS ) {
		rc = tmprc;
		goto cleanup_and_return;
	}

	if (( srv = (LDAPServer *)NSLDAPI_CALLOC( 1, sizeof( LDAPServer )))
	    == NULL ) {
		ber_free( ber, 1 );
		rc = LDAP_NO_MEMORY;
		goto cleanup_and_return;
	}

	if (ludp->lud_host == NULL && ld->ld_defhost == NULL) {
		srv->lsrv_host = NULL;
	} else {
		if (ludp->lud_host == NULL) {
			srv->lsrv_host =
			    nsldapi_strdup( origreq->lr_conn->lconn_server->lsrv_host );
			LDAPDebug(LDAP_DEBUG_TRACE,
			    "chase_one_referral: using hostname '%s' from original "
			    "request on new request\n",
			    srv->lsrv_host, 0, 0);
		} else {
			srv->lsrv_host = nsldapi_strdup(ludp->lud_host);
			LDAPDebug(LDAP_DEBUG_TRACE,
			    "chase_one_referral: using hostname '%s' as specified "
			    "on new request\n",
			    srv->lsrv_host, 0, 0);
		}

		if (srv->lsrv_host == NULL) {
			NSLDAPI_FREE((char *)srv);
			ber_free(ber, 1);
			rc = LDAP_NO_MEMORY;
			goto cleanup_and_return;
		}
	}

	/*
	 * According to our reading of RFCs 2255 and 1738, the
	 * following algorithm applies:
	 * - no hostport (no host, no port) provided in LDAP URL, use those
	 *   of previous request
	 * - no port but a host, use default LDAP port
	 * - else use given hostport
	 */
	if (ludp->lud_port == 0 && ludp->lud_host == NULL) {
		srv->lsrv_port = origreq->lr_conn->lconn_server->lsrv_port;
		LDAPDebug(LDAP_DEBUG_TRACE,
		    "chase_one_referral: using port (%d) from original "
		    "request on new request\n",
		    srv->lsrv_port, 0, 0);
	} else if (ludp->lud_port == 0 && ludp->lud_host != NULL) {
		srv->lsrv_port = (secure) ? LDAPS_PORT : LDAP_PORT;
		LDAPDebug(LDAP_DEBUG_TRACE,
		    "chase_one_referral: using default port (%d) \n",
		    srv->lsrv_port, 0, 0);
	} else {
		srv->lsrv_port = ludp->lud_port;
		LDAPDebug(LDAP_DEBUG_TRACE,
		    "chase_one_referral: using port (%d) as specified on "
		    "new request\n",
		    srv->lsrv_port, 0, 0);
	}

	if ( secure ) {
		srv->lsrv_options |= LDAP_SRV_OPT_SECURE;
	}

	if ( nsldapi_send_server_request( ld, ber, msgid,
	    lr, srv, NULL, NULL, 1 ) < 0 ) {
		rc = LDAP_GET_LDERRNO( ld, NULL, NULL );
		LDAPDebug( LDAP_DEBUG_ANY, "Unable to chase %s %s (%s)\n",
		    desc, refurl, ldap_err2string( rc ));
	} else {
		rc = LDAP_SUCCESS;
	}

cleanup_and_return:
	if ( ludp != NULLLDAPURLDESC ) {
		ldap_free_urldesc( ludp );
	}

	return( rc );
}
Exemplo n.º 16
0
static LDAPServer *
dn2servers( LDAP *ld, char *dn )	/* dn can also be a domain.... */
{
	char		*p, *domain, *host, *server_dn, **dxs;
	int		i, port;
	LDAPServer	*srvlist, *prevsrv, *srv;

	if (( domain = strrchr( dn, '@' )) != NULL ) {
		++domain;
	} else {
		domain = dn;
	}

	if (( dxs = nsldapi_getdxbyname( domain )) == NULL ) {
		LDAP_SET_LDERRNO( ld, LDAP_NO_MEMORY, NULL, NULL );
		return( NULL );
	}

	srvlist = NULL;

	for ( i = 0; dxs[ i ] != NULL; ++i ) {
		port = LDAP_PORT;
		server_dn = NULL;
		if ( strchr( dxs[ i ], ':' ) == NULL ) {
			host = dxs[ i ];
		} else if ( strlen( dxs[ i ] ) >= 7 &&
		    strncmp( dxs[ i ], "ldap://", 7 ) == 0 ) {
			host = dxs[ i ] + 7;
			if (( p = strchr( host, ':' )) == NULL ) {
				p = host;
			} else {
				*p++ = '\0';
				port = atoi( p );
			}
			if (( p = strchr( p, '/' )) != NULL ) {
				server_dn = ++p;
				if ( *server_dn == '\0' ) {
					server_dn = NULL;
				}
			}
		} else {
			host = NULL;
		}

		if ( host != NULL ) {	/* found a server we can use */
			if (( srv = (LDAPServer *)NSLDAPI_CALLOC( 1,
			    sizeof( LDAPServer ))) == NULL ) {
				free_servers( srvlist );
				srvlist = NULL;
				break;		/* exit loop & return */
			}

			/* add to end of list of servers */
			if ( srvlist == NULL ) {
				srvlist = srv;
			} else {
				prevsrv->lsrv_next = srv;
			}
			prevsrv = srv;
			
			/* copy in info. */
			if (( srv->lsrv_host = nsldapi_strdup( host )) == NULL
			    || ( server_dn != NULL && ( srv->lsrv_dn =
			    nsldapi_strdup( server_dn )) == NULL )) {
				free_servers( srvlist );
				srvlist = NULL;
				break;		/* exit loop & return */
			}
			srv->lsrv_port = port;
		}
	}

	ldap_value_free( dxs );

	if ( srvlist == NULL ) {
		LDAP_SET_LDERRNO( ld, LDAP_SERVER_DOWN, NULL, NULL );
	}

	return( srvlist );
}
Exemplo n.º 17
0
LDAPFiltDesc *LDAP_CALL ldap_init_getfilter_buf(char *buf, long buflen) {
  LDAPFiltDesc *lfdp;
  LDAPFiltList *flp, *nextflp;
  LDAPFiltInfo *fip, *nextfip;
  char *errmsg, *tag, **tok;
  int tokcnt, i;

  if ((buf == NULL) || (buflen < 0) ||
      (lfdp = (LDAPFiltDesc *)NSLDAPI_CALLOC(1, sizeof(LDAPFiltDesc))) ==
          NULL) {
    return (NULL);
  }

  flp = nextflp = NULL;
  fip = NULL;
  tag = NULL;

  while (buflen > 0 &&
         (tokcnt = nsldapi_next_line_tokens(&buf, &buflen, &tok)) > 0) {
    switch (tokcnt) {
      case 1: /* tag line */
        if (tag != NULL) {
          NSLDAPI_FREE(tag);
        }
        tag = tok[0];
        NSLDAPI_FREE(tok);
        break;
      case 4:
      case 5: /* start of filter info. list */
        if ((nextflp = (LDAPFiltList *)NSLDAPI_CALLOC(
                 1, sizeof(LDAPFiltList))) == NULL) {
          ldap_getfilter_free(lfdp);
          return (NULL);
        }
        nextflp->lfl_tag = nsldapi_strdup(tag);
        nextflp->lfl_pattern = tok[0];
        if ((errmsg = re_comp(nextflp->lfl_pattern)) != NULL) {
          char msg[512];
          ldap_getfilter_free(lfdp);
          snprintf(msg, sizeof(msg), "bad regular expression \"%s\" - %s\n",
                   nextflp->lfl_pattern, errmsg);
          ber_err_print(msg);
          nsldapi_free_strarray(tok);
          return (NULL);
        }

        nextflp->lfl_delims = tok[1];
        nextflp->lfl_ilist = NULL;
        nextflp->lfl_next = NULL;
        if (flp == NULL) { /* first one */
          lfdp->lfd_filtlist = nextflp;
        } else {
          flp->lfl_next = nextflp;
        }
        flp = nextflp;
        fip = NULL;
        for (i = 2; i < 5; ++i) {
          tok[i - 2] = tok[i];
        }
        /* fall through */

      case 2:
      case 3:                  /* filter, desc, and optional search scope */
        if (nextflp != NULL) { /* add to info list */
          if ((nextfip = (LDAPFiltInfo *)NSLDAPI_CALLOC(
                   1, sizeof(LDAPFiltInfo))) == NULL) {
            ldap_getfilter_free(lfdp);
            nsldapi_free_strarray(tok);
            return (NULL);
          }
          if (fip == NULL) { /* first one */
            nextflp->lfl_ilist = nextfip;
          } else {
            fip->lfi_next = nextfip;
          }
          fip = nextfip;
          nextfip->lfi_next = NULL;
          nextfip->lfi_filter = tok[0];
          nextfip->lfi_desc = tok[1];
          if (tok[2] != NULL) {
            if (strcasecmp(tok[2], "subtree") == 0) {
              nextfip->lfi_scope = LDAP_SCOPE_SUBTREE;
            } else if (strcasecmp(tok[2], "onelevel") == 0) {
              nextfip->lfi_scope = LDAP_SCOPE_ONELEVEL;
            } else if (strcasecmp(tok[2], "base") == 0) {
              nextfip->lfi_scope = LDAP_SCOPE_BASE;
            } else {
              nsldapi_free_strarray(tok);
              ldap_getfilter_free(lfdp);
              return (NULL);
            }
            NSLDAPI_FREE(tok[2]);
            tok[2] = NULL;
          } else {
            nextfip->lfi_scope = LDAP_SCOPE_SUBTREE; /* default */
          }
          nextfip->lfi_isexact =
              (strchr(tok[0], '*') == NULL && strchr(tok[0], '~') == NULL);
          NSLDAPI_FREE(tok);
        }
        break;

      default:
        nsldapi_free_strarray(tok);
        ldap_getfilter_free(lfdp);
        return (NULL);
    }
  }

  if (tag != NULL) {
    NSLDAPI_FREE(tag);
  }

  return (lfdp);
}
Exemplo n.º 18
0
int
LDAP_CALL
ldap_url_search( LDAP *ld, const char *url, int attrsonly )
{
	int		err, msgid;
	LDAPURLDesc	*ludp;
	BerElement	*ber;
	LDAPServer	*srv;
	char		*host;

	if ( !NSLDAPI_VALID_LDAP_POINTER( ld )) {
		return( -1 );		/* punt */
	}

	if ( ldap_url_parse( url, &ludp ) != 0 ) {
		LDAP_SET_LDERRNO( ld, LDAP_PARAM_ERROR, NULL, NULL );
		return( -1 );
	}

	LDAP_MUTEX_LOCK( ld, LDAP_MSGID_LOCK );
	msgid = ++ld->ld_msgid;
	LDAP_MUTEX_UNLOCK( ld, LDAP_MSGID_LOCK );

	if ( nsldapi_build_search_req( ld, ludp->lud_dn, ludp->lud_scope,
	    ludp->lud_filter, ludp->lud_attrs, attrsonly, NULL, NULL,
	    -1, -1, msgid, &ber ) != LDAP_SUCCESS ) {
		return( -1 );
	}

	err = 0;

	if ( ludp->lud_host == NULL ) {
		host = ld->ld_defhost;
	} else {
		host = ludp->lud_host;
	}

	if (( srv = (LDAPServer *)NSLDAPI_CALLOC( 1, sizeof( LDAPServer )))
	    == NULL || ( host != NULL &&
	    ( srv->lsrv_host = nsldapi_strdup( host )) == NULL )) {
		if ( srv != NULL ) {
			NSLDAPI_FREE( srv );
		}
		LDAP_SET_LDERRNO( ld, LDAP_NO_MEMORY, NULL, NULL );
		err = -1;
	} else {
		if ( ludp->lud_port == 0 ) {
			if (( ludp->lud_options & LDAP_URL_OPT_SECURE ) == 0 ) {
				srv->lsrv_port = LDAP_PORT;
			} else {
				srv->lsrv_port = LDAPS_PORT;
			}
		} else {
			 srv->lsrv_port = ludp->lud_port;
		}
	}

	if (( ludp->lud_options & LDAP_URL_OPT_SECURE ) != 0 ) {
		srv->lsrv_options |= LDAP_SRV_OPT_SECURE;
	}

	if ( err != 0 ) {
		ber_free( ber, 1 );
	} else {
		err = nsldapi_send_server_request( ld, ber, msgid, NULL, srv,
		    NULL, NULL, 1 );
	}

	ldap_free_urldesc( ludp );
	return( err );
}
Exemplo n.º 19
0
/* returns the message id of the request or -1 if an error occurs */
int
nsldapi_send_server_request(
    LDAP *ld,			/* session handle */
    BerElement *ber,		/* message to send */
    int msgid,			/* ID of message to send */
    LDAPRequest *parentreq,	/* non-NULL for referred requests */
    LDAPServer *srvlist,	/* servers to connect to (NULL for default) */
    LDAPConn *lc,		/* connection to use (NULL for default) */
    char *bindreqdn,		/* non-NULL for bind requests */
    int bind			/* perform a bind after opening new conn.? */
)
{
	LDAPRequest	*lr;
	int		err;
	int		incparent;	/* did we bump parent's ref count? */

	LDAPDebug( LDAP_DEBUG_TRACE, "nsldapi_send_server_request\n", 0, 0, 0 );

	incparent = 0;
	LDAP_MUTEX_LOCK( ld, LDAP_CONN_LOCK );
	if ( lc == NULL ) {
		if ( srvlist == NULL ) {
			if ( ld->ld_defconn == NULL ) {
				LDAP_MUTEX_LOCK( ld, LDAP_OPTION_LOCK );
				if ( bindreqdn == NULL && ( ld->ld_options
				    & LDAP_BITOPT_RECONNECT ) != 0 ) {
					LDAP_SET_LDERRNO( ld, LDAP_SERVER_DOWN,
					    NULL, NULL );
					ber_free( ber, 1 );
					LDAP_MUTEX_UNLOCK( ld, LDAP_OPTION_LOCK );
					LDAP_MUTEX_UNLOCK( ld, LDAP_CONN_LOCK );
					return( -1 );
				}
				LDAP_MUTEX_UNLOCK( ld, LDAP_OPTION_LOCK );

				if ( nsldapi_open_ldap_defconn( ld ) < 0 ) {
					ber_free( ber, 1 );
					LDAP_MUTEX_UNLOCK( ld, LDAP_CONN_LOCK );
					return( -1 );
				}
			}
			lc = ld->ld_defconn;
		} else {
			if (( lc = find_connection( ld, srvlist, 1 )) ==
			    NULL ) {
				if ( bind && (parentreq != NULL) ) {
					/* Remember the bind in the parent */
					incparent = 1;
					++parentreq->lr_outrefcnt;
				}

				lc = nsldapi_new_connection( ld, &srvlist, 0,
					1, bind );
			}
			free_servers( srvlist );
		}
	}


    /*
     * the logic here is:
     * if 
     * 1. no connections exists, 
     * or 
     * 2. if the connection is either not in the connected 
     *     or connecting state in an async io model
     * or 
     * 3. the connection is notin a connected state with normal (non async io)
     */
	if (   lc == NULL
		|| (  (ld->ld_options & LDAP_BITOPT_ASYNC 
               && lc->lconn_status != LDAP_CONNST_CONNECTING
		    && lc->lconn_status != LDAP_CONNST_CONNECTED)
              || (!(ld->ld_options & LDAP_BITOPT_ASYNC )
		    && lc->lconn_status != LDAP_CONNST_CONNECTED) ) ) {

		ber_free( ber, 1 );
		if ( lc != NULL ) {
			LDAP_SET_LDERRNO( ld, LDAP_SERVER_DOWN, NULL, NULL );
		}
		if ( incparent ) {
			/* Forget about the bind */
			--parentreq->lr_outrefcnt; 
		}
		LDAP_MUTEX_UNLOCK( ld, LDAP_CONN_LOCK );
		return( -1 );
	}

	use_connection( ld, lc );
	if (( lr = (LDAPRequest *)NSLDAPI_CALLOC( 1, sizeof( LDAPRequest ))) ==
	    NULL || ( bindreqdn != NULL && ( bindreqdn =
	    nsldapi_strdup( bindreqdn )) == NULL )) {
		if ( lr != NULL ) {
			NSLDAPI_FREE( lr );
		}
		LDAP_SET_LDERRNO( ld, LDAP_NO_MEMORY, NULL, NULL );
		nsldapi_free_connection( ld, lc, NULL, NULL, 0, 0 );
		ber_free( ber, 1 );
		if ( incparent ) {
			/* Forget about the bind */
			--parentreq->lr_outrefcnt; 
		}
		LDAP_MUTEX_UNLOCK( ld, LDAP_CONN_LOCK );
		return( -1 );
	} 
	lr->lr_binddn = bindreqdn;
	lr->lr_msgid = msgid;
	lr->lr_status = LDAP_REQST_INPROGRESS;
	lr->lr_res_errno = LDAP_SUCCESS;	/* optimistic */
	lr->lr_ber = ber;
	lr->lr_conn = lc;

	if ( parentreq != NULL ) {	/* sub-request */
		if ( !incparent ) { 
			/* Increment if we didn't do it before the bind */
			++parentreq->lr_outrefcnt;
		}
		lr->lr_origid = parentreq->lr_origid;
		lr->lr_parentcnt = parentreq->lr_parentcnt + 1;
		lr->lr_parent = parentreq;
		if ( parentreq->lr_child != NULL ) {
			lr->lr_sibling = parentreq->lr_child;
		}
		parentreq->lr_child = lr;
	} else {			/* original request */
		lr->lr_origid = lr->lr_msgid;
	}

	LDAP_MUTEX_LOCK( ld, LDAP_REQ_LOCK );
	if (( lr->lr_next = ld->ld_requests ) != NULL ) {
		lr->lr_next->lr_prev = lr;
	}
	ld->ld_requests = lr;
	lr->lr_prev = NULL;

	if (( err = nsldapi_ber_flush( ld, lc->lconn_sb, ber, 0, 1 )) != 0 ) {

		/* need to continue write later */
		if (ld->ld_options & LDAP_BITOPT_ASYNC && err == -2 ) {	
			lr->lr_status = LDAP_REQST_WRITING;
			nsldapi_iostatus_interest_write( ld, lc->lconn_sb );
		} else {

			LDAP_SET_LDERRNO( ld, LDAP_SERVER_DOWN, NULL, NULL );
			nsldapi_free_request( ld, lr, 0 );
			nsldapi_free_connection( ld, lc, NULL, NULL, 0, 0 );
			LDAP_MUTEX_UNLOCK( ld, LDAP_REQ_LOCK );
			LDAP_MUTEX_UNLOCK( ld, LDAP_CONN_LOCK );
			return( -1 );
		}

	} else {
		if ( parentreq == NULL ) {
			ber->ber_end = ber->ber_ptr;
			ber->ber_ptr = ber->ber_buf;
		}

		/* sent -- waiting for a response */
		if (ld->ld_options & LDAP_BITOPT_ASYNC) {
			lc->lconn_status = LDAP_CONNST_CONNECTED;
		}

		nsldapi_iostatus_interest_read( ld, lc->lconn_sb );
	}
	LDAP_MUTEX_UNLOCK( ld, LDAP_REQ_LOCK );
	LDAP_MUTEX_UNLOCK( ld, LDAP_CONN_LOCK );

	LDAP_SET_LDERRNO( ld, LDAP_SUCCESS, NULL, NULL );
	return( msgid );
}
Exemplo n.º 20
0
int
nsldapi_sasl_secprops(
        const char *in,
        sasl_security_properties_t *secprops )
{
        int i;
        char **props = NULL;
        char *inp;
        unsigned sflags = 0;
        sasl_ssf_t max_ssf = 0;
        sasl_ssf_t min_ssf = 0;
        unsigned maxbufsize = 0;
        int got_sflags = 0;
        int got_max_ssf = 0;
        int got_min_ssf = 0;
        int got_maxbufsize = 0;

        if (in == NULL) {
                return LDAP_PARAM_ERROR;
        }
        inp = nsldapi_strdup(in);
        if (inp == NULL) {
                return LDAP_PARAM_ERROR;
        }
        props = ldap_str2charray( inp, "," );
        NSLDAPI_FREE( inp );

        if( props == NULL || secprops == NULL ) {
                return LDAP_PARAM_ERROR;
        }

        for( i=0; props[i]; i++ ) {
                if( strcasecmp(props[i], "none") == 0 ) {
                        got_sflags++;

                } else if( strcasecmp(props[i], "noactive") == 0 ) {
                        got_sflags++;
                        sflags |= SASL_SEC_NOACTIVE;

                } else if( strcasecmp(props[i], "noanonymous") == 0 ) {
                        got_sflags++;
                        sflags |= SASL_SEC_NOANONYMOUS;

                } else if( strcasecmp(props[i], "nodict") == 0 ) {
                        got_sflags++;
                        sflags |= SASL_SEC_NODICTIONARY;

                } else if( strcasecmp(props[i], "noplain") == 0 ) {
                        got_sflags++;
                        sflags |= SASL_SEC_NOPLAINTEXT;

                } else if( strcasecmp(props[i], "forwardsec") == 0 ) {
                        got_sflags++;
                        sflags |= SASL_SEC_FORWARD_SECRECY;

                } else if( strcasecmp(props[i], "passcred") == 0 ) {
                        got_sflags++;
                        sflags |= SASL_SEC_PASS_CREDENTIALS;

                } else if( strncasecmp(props[i],
                        "minssf=", sizeof("minssf")) == 0 ) {
                        if( isdigit( props[i][sizeof("minssf")] ) ) {
                                got_min_ssf++;
                                min_ssf = atoi( &props[i][sizeof("minssf")] );
                        } else {
                                return LDAP_NOT_SUPPORTED;
                        }

                } else if( strncasecmp(props[i],
                        "maxssf=", sizeof("maxssf")) == 0 ) {
                        if( isdigit( props[i][sizeof("maxssf")] ) ) {
                                got_max_ssf++;
                                max_ssf = atoi( &props[i][sizeof("maxssf")] );
                        } else {
                                return LDAP_NOT_SUPPORTED;
                        }

                } else if( strncasecmp(props[i],
                        "maxbufsize=", sizeof("maxbufsize")) == 0 ) {
                        if( isdigit( props[i][sizeof("maxbufsize")] ) ) {
                                got_maxbufsize++;
                                maxbufsize = atoi( &props[i][sizeof("maxbufsize")] );
                                if( maxbufsize &&
                                    (( maxbufsize < SASL_MIN_BUFF_SIZE )
                                    || (maxbufsize > SASL_MAX_BUFF_SIZE ))) {
                                        return( LDAP_PARAM_ERROR );
                                }
                        } else {
                                return( LDAP_NOT_SUPPORTED );
                        }
                } else {
                        return( LDAP_NOT_SUPPORTED );
                }
        }

        if(got_sflags) {
                secprops->security_flags = sflags;
        }
        if(got_min_ssf) {
                secprops->min_ssf = min_ssf;
        }
        if(got_max_ssf) {
                secprops->max_ssf = max_ssf;
        }
        if(got_maxbufsize) {
                secprops->maxbufsize = maxbufsize;
        }

        ldap_charray_free( props );
        return( LDAP_SUCCESS );
}
Exemplo n.º 21
0
static int
nsldapi_sasl_do_bind( LDAP *ld, const char *dn,
        const char *mechs, unsigned flags,
        LDAP_SASL_INTERACT_PROC *callback, void *defaults,
        LDAPControl **sctrl, LDAPControl **cctrl, LDAPControl ***rctrl )
{
        sasl_interact_t *prompts = NULL;
        sasl_conn_t     *ctx = NULL;
        sasl_ssf_t      *ssf = NULL;
        const char      *mech = NULL;
        int             saslrc, rc;
        struct berval   ccred;
        unsigned        credlen;
        int stepnum = 1;
        char *sasl_username = NULL;

        if (rctrl) {
            /* init to NULL so we can call ldap_controls_free below */
            *rctrl = NULL;
        }

        if (NSLDAPI_LDAP_VERSION( ld ) < LDAP_VERSION3) {
                LDAP_SET_LDERRNO( ld, LDAP_NOT_SUPPORTED, NULL, NULL );
                return( LDAP_NOT_SUPPORTED );
        }

        /* shouldn't happen */
        if (callback == NULL) {
                return( LDAP_LOCAL_ERROR );
        }

        if ( (rc = nsldapi_sasl_open(ld, NULL, &ctx, 0)) != LDAP_SUCCESS ) {
            return( rc );
        }

        ccred.bv_val = NULL;
        ccred.bv_len = 0;

        LDAPDebug(LDAP_DEBUG_TRACE, "Starting SASL/%s authentication\n",
                  (mechs ? mechs : ""), 0, 0 );

        do {
                saslrc = sasl_client_start( ctx,
                        mechs,
                        &prompts,
                        (const char **)&ccred.bv_val,
                        &credlen,
                        &mech );

                LDAPDebug(LDAP_DEBUG_TRACE, "Doing step %d of client start for SASL/%s authentication\n",
                          stepnum, (mech ? mech : ""), 0 );
                stepnum++;

                if( saslrc == SASL_INTERACT &&
                    (callback)(ld, flags, defaults, prompts) != LDAP_SUCCESS ) {
                        break;
                }
        } while ( saslrc == SASL_INTERACT );

        ccred.bv_len = credlen;

        if ( (saslrc != SASL_OK) && (saslrc != SASL_CONTINUE) ) {
                return( nsldapi_sasl_cvterrno( ld, saslrc, nsldapi_strdup( sasl_errdetail( ctx ) ) ) );
        }

        stepnum = 1;

        do {
                struct berval *scred;
                int clientstepnum = 1;

                scred = NULL;

                if (rctrl) {
                    /* if we're looping again, we need to free any controls set
                       during the previous loop */
                    /* NOTE that this assumes we only care about the controls
                       returned by the last call to nsldapi_sasl_bind_s - if
                       we care about _all_ controls, we will have to figure out
                       some way to append them each loop go round */
                    ldap_controls_free(*rctrl);
                    *rctrl = NULL;
                }

                LDAPDebug(LDAP_DEBUG_TRACE, "Doing step %d of bind for SASL/%s authentication\n",
                          stepnum, (mech ? mech : ""), 0 );
                stepnum++;

                /* notify server of a sasl bind step */
                rc = nsldapi_sasl_bind_s(ld, dn, mech, &ccred,
                                      sctrl, cctrl, &scred, rctrl); 

                if ( ccred.bv_val != NULL ) {
                        ccred.bv_val = NULL;
                }

                if ( rc != LDAP_SUCCESS && rc != LDAP_SASL_BIND_IN_PROGRESS ) {
                        ber_bvfree( scred );
                        return( rc );
                }

                if( rc == LDAP_SUCCESS && saslrc == SASL_OK ) {
                        /* we're done, no need to step */
                        if( scred ) {
                            if ( scred->bv_len == 0 ) { /* MS AD sends back empty screds */
                                LDAPDebug(LDAP_DEBUG_ANY,
                                          "SASL BIND complete - ignoring empty credential response\n",
                                          0, 0, 0);
                                ber_bvfree( scred );
                            } else {
                                /* but server provided us with data! */
                                LDAPDebug(LDAP_DEBUG_TRACE,
                                          "SASL BIND complete but invalid because server responded with credentials - length [%u]\n",
                                          scred->bv_len, 0, 0);
                                ber_bvfree( scred );
                                LDAP_SET_LDERRNO( ld, LDAP_LOCAL_ERROR,
                                                  NULL, "Error during SASL handshake - invalid server credential response" );
                                return( LDAP_LOCAL_ERROR );
                            }
                        }
                        break;
                }

                /* perform the next step of the sasl bind */
                do {
                        LDAPDebug(LDAP_DEBUG_TRACE, "Doing client step %d of bind step %d for SASL/%s authentication\n",
                                  clientstepnum, stepnum, (mech ? mech : "") );
                        clientstepnum++;
                        saslrc = sasl_client_step( ctx,
                                (scred == NULL) ? NULL : scred->bv_val,
                                (scred == NULL) ? 0 : scred->bv_len,
                                &prompts,
                                (const char **)&ccred.bv_val,
                                &credlen );

                        if( saslrc == SASL_INTERACT &&
                            (callback)(ld, flags, defaults, prompts)
                                                        != LDAP_SUCCESS ) {
                                break;
                        }
                } while ( saslrc == SASL_INTERACT );

                ccred.bv_len = credlen;
                ber_bvfree( scred );

                if ( (saslrc != SASL_OK) && (saslrc != SASL_CONTINUE) ) {
                        return( nsldapi_sasl_cvterrno( ld, saslrc, nsldapi_strdup( sasl_errdetail( ctx ) ) ) );
                }
        } while ( rc == LDAP_SASL_BIND_IN_PROGRESS );

        if ( rc != LDAP_SUCCESS ) {
                return( rc );
        }

        if ( saslrc != SASL_OK ) {
                return( nsldapi_sasl_cvterrno( ld, saslrc, nsldapi_strdup( sasl_errdetail( ctx ) ) ) );
        }

        saslrc = sasl_getprop( ctx, SASL_USERNAME, (const void **) &sasl_username );
        if ( (saslrc == SASL_OK) && sasl_username ) {
                LDAPDebug(LDAP_DEBUG_TRACE, "SASL identity: %s\n", sasl_username, 0, 0);
        }

        saslrc = sasl_getprop( ctx, SASL_SSF, (const void **) &ssf );
        if( saslrc == SASL_OK ) {
                if( ssf && *ssf ) {
                        LDAPDebug(LDAP_DEBUG_TRACE,
                                "SASL install encryption, for SSF: %lu\n",
                                (unsigned long) *ssf, 0, 0 );
                        nsldapi_sasl_install( ld, NULL );
                }
        }

        return( rc );
}
Exemplo n.º 22
0
LDAP_CALL
ldap_tmplattrs( struct ldap_disptmpl *tmpl, char **includeattrs,
                int exclude, unsigned long syntaxmask )
{
    /*
     * this routine should filter out duplicate attributes...
     */
    struct ldap_tmplitem	*tirowp, *ticolp;
    int			i, attrcnt, memerr;
    char		**attrs;

    attrcnt = 0;
    memerr = 0;

    if (( attrs = (char **)NSLDAPI_MALLOC( sizeof( char * ))) == NULL ) {
        return( NULL );
    }

    if ( includeattrs != NULL ) {
        for ( i = 0; !memerr && includeattrs[ i ] != NULL; ++i ) {
            if (( attrs = (char **)NSLDAPI_REALLOC( attrs, ( attrcnt + 2 ) *
                                                    sizeof( char * ))) == NULL || ( attrs[ attrcnt++ ] =
                                                            nsldapi_strdup( includeattrs[ i ] )) == NULL ) {
                memerr = 1;
            } else {
                attrs[ attrcnt ] = NULL;
            }
        }
    }

    for ( tirowp = ldap_first_tmplrow( tmpl );
            !memerr && tirowp != NULLTMPLITEM;
            tirowp = ldap_next_tmplrow( tmpl, tirowp )) {
        for ( ticolp = ldap_first_tmplcol( tmpl, tirowp );
                ticolp != NULLTMPLITEM;
                ticolp = ldap_next_tmplcol( tmpl, tirowp, ticolp )) {

            if ( syntaxmask != 0 ) {
                if (( exclude &&
                        ( syntaxmask & ticolp->ti_syntaxid ) != 0 ) ||
                        ( !exclude &&
                          ( syntaxmask & ticolp->ti_syntaxid ) == 0 )) {
                    continue;
                }
            }

            if ( ticolp->ti_attrname != NULL ) {
                if (( attrs = (char **)NSLDAPI_REALLOC( attrs, ( attrcnt + 2 )
                                                        * sizeof( char * ))) == NULL || ( attrs[ attrcnt++ ] =
                                                                nsldapi_strdup( ticolp->ti_attrname )) == NULL ) {
                    memerr = 1;
                } else {
                    attrs[ attrcnt ] = NULL;
                }
            }
        }
    }

    if ( memerr || attrcnt == 0 ) {
        for ( i = 0; i < attrcnt; ++i ) {
            if ( attrs[ i ] != NULL ) {
                NSLDAPI_FREE( attrs[ i ] );
            }
        }

        NSLDAPI_FREE( (char *)attrs );
        return( NULL );
    }

    return( attrs );
}